diff --git a/.prettierignore b/.prettierignore index 768712900b8c2..761a3209faa0b 100644 --- a/.prettierignore +++ b/.prettierignore @@ -14,6 +14,8 @@ node_modules/ /solution/bash_problem_readme_template.md /solution/bash_problem_readme_template_en.md /solution/0100-0199/0177.Nth Highest Salary/Solution.sql +/solution/0100-0199/0178.Rank Scores/Solution2.sql +/solution/0500-0599/0586.Customer Placing the Largest Number of Orders/Solution2.sql /solution/1400-1499/1454.Active Users/Solution.sql /solution/1600-1699/1635.Hopper Company Queries I/Solution.sql /solution/2100-2199/2118.Build the Equation/Solution.sql diff --git a/basic/sorting/BubbleSort/Solution.cpp b/basic/sorting/BubbleSort/Solution.cpp new file mode 100644 index 0000000000000..6b81951fadf22 --- /dev/null +++ b/basic/sorting/BubbleSort/Solution.cpp @@ -0,0 +1,25 @@ +#include +#include + +using namespace std; + +void bubbleSort(vector& arr) { + int n = arr.size(); + for (int i = 0; i < n - 1; ++i) { + bool change = false; + for (int j = 0; j < n - i - 1; ++j) { + if (arr[j] > arr[j + 1]) { + swap(arr[j], arr[j + 1]); + change = true; + } + } + if (!change) break; + } +} + +int main() { + vector arr = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; + bubbleSort(arr); + for (int v : arr) cout << v << " "; + cout << endl; +} \ No newline at end of file diff --git a/basic/sorting/BubbleSort/Solution.cs b/basic/sorting/BubbleSort/Solution.cs new file mode 100644 index 0000000000000..d50279daa871b --- /dev/null +++ b/basic/sorting/BubbleSort/Solution.cs @@ -0,0 +1,45 @@ +using static System.Console; +namespace Pro; +public class Program +{ + public static void Main() + { + int[] test = new int[] { 56, 876, 34, 23, 45, 501, 2, 3, 4, 6, 5, 7, 8, 9, 11, 10, 12, 23, 34 }; + BubbleSortNums(test); + foreach (var item in test) + { + WriteLine(item); + } + ReadLine(); + } + public static void BubbleSortNums(int[] nums) + { + int numchange = 0; + for (int initial = 0; initial < nums.Length - numchange; initial++) + { + WriteLine($"{initial} start "); + // 记录此值 用于迭代开始位置 + bool changelog = false; + for (int second_sortnum = initial; second_sortnum < nums.Length - 1; second_sortnum++) + { + if (nums[second_sortnum] > nums[second_sortnum + 1]) + { + swap(ref nums[second_sortnum], ref nums[second_sortnum + 1]); + if (!changelog) + { + // 记录转换的位置,让initial开始位置从转换位置前开始 + initial = ((second_sortnum - 2) > 0) ? (second_sortnum - 2) : -1; + numchange += 1; + } + changelog = true; + } + } + } + } + private static void swap(ref int compare_left, ref int compare_right) + { + int temp = compare_left; + compare_left = compare_right; + compare_right = temp; + } +} diff --git a/basic/sorting/BubbleSort/Solution.go b/basic/sorting/BubbleSort/Solution.go new file mode 100644 index 0000000000000..1fe8862fe5d28 --- /dev/null +++ b/basic/sorting/BubbleSort/Solution.go @@ -0,0 +1,22 @@ +package main + +import "fmt" + +func bubbleSort(nums []int) { + hasChange := true + for i, n := 0, len(nums); i < n-1 && hasChange; i++ { + hasChange = false + for j := 0; j < n-i-1; j++ { + if nums[j] > nums[j+1] { + nums[j], nums[j+1] = nums[j+1], nums[j] + hasChange = true + } + } + } +} + +func main() { + nums := []int{1, 2, 7, 9, 5, 8} + bubbleSort(nums) + fmt.Println(nums) +} \ No newline at end of file diff --git a/basic/sorting/BubbleSort/Solution.java b/basic/sorting/BubbleSort/Solution.java new file mode 100644 index 0000000000000..2f224bdbf9e4b --- /dev/null +++ b/basic/sorting/BubbleSort/Solution.java @@ -0,0 +1,29 @@ +import java.util.Arrays; + +public class BubbleSort { + + private static void bubbleSort(int[] nums) { + boolean hasChange = true; + for (int i = 0, n = nums.length; i < n - 1 && hasChange; ++i) { + hasChange = false; + for (int j = 0; j < n - i - 1; ++j) { + if (nums[j] > nums[j + 1]) { + swap(nums, j, j + 1); + hasChange = true; + } + } + } + } + + private static void swap(int[] nums, int i, int j) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } + + public static void main(String[] args) { + int[] nums = {1, 2, 7, 9, 5, 8}; + bubbleSort(nums); + System.out.println(Arrays.toString(nums)); + } +} \ No newline at end of file diff --git a/basic/sorting/BubbleSort/Solution.js b/basic/sorting/BubbleSort/Solution.js new file mode 100644 index 0000000000000..7b3de254a0c88 --- /dev/null +++ b/basic/sorting/BubbleSort/Solution.js @@ -0,0 +1,22 @@ +function bubbleSort(inputArr) { + for (let i = inputArr.length - 1; i > 0; i--) { + let hasChange = false; + for (let j = 0; j < i; j++) { + if (inputArr[j] > inputArr[j + 1]) { + const temp = inputArr[j]; + inputArr[j] = inputArr[j + 1]; + inputArr[j + 1] = temp; + hasChange = true; + } + } + + if (!hasChange) { + break; + } + } + + return inputArr; +} + +const arr = [6, 3, 2, 1, 5]; +console.log(bubbleSort(arr)); diff --git a/basic/sorting/BubbleSort/Solution.py b/basic/sorting/BubbleSort/Solution.py new file mode 100644 index 0000000000000..5e41c4d9207ec --- /dev/null +++ b/basic/sorting/BubbleSort/Solution.py @@ -0,0 +1,26 @@ +def bubbleSort(arr): + n = len(arr) + # Iterate over all array elements + for i in range(n): + # Last i elements are already in place + for j in range(n - i - 1): + if arr[j] > arr[j + 1]: + arr[j], arr[j + 1] = arr[j + 1], arr[j] + + +# 改进版本 +def bubbleSort(arr): + n = len(arr) + for i in range(n - 1): + has_change = False + for j in range(n - i - 1): + if arr[j] > arr[j + 1]: + arr[j], arr[j + 1] = arr[j + 1], arr[j] + has_change = True + if not has_change: + break + + +arr = [64, 34, 25, 12, 22, 11, 90] +bubbleSort(arr) +print(arr) diff --git a/basic/sorting/BubbleSort/Solution.rs b/basic/sorting/BubbleSort/Solution.rs new file mode 100644 index 0000000000000..f552a2b72b8f0 --- /dev/null +++ b/basic/sorting/BubbleSort/Solution.rs @@ -0,0 +1,18 @@ +fn bubble_sort(nums: &mut Vec) { + let n = nums.len(); + for i in 0..n - 1 { + for j in i..n { + if nums[i] > nums[j] { + let temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } + } + } +} + +fn main() { + let mut nums = vec![1, 2, 7, 9, 5, 8]; + bubble_sort(&mut nums); + println!("{:?}", nums); +} diff --git a/basic/sorting/HeapSort/Solution.go b/basic/sorting/HeapSort/Solution.go new file mode 100644 index 0000000000000..fc0f3b834d72d --- /dev/null +++ b/basic/sorting/HeapSort/Solution.go @@ -0,0 +1,51 @@ +package main + +import "fmt" + +const N = 100010 + +var ( + size int + h []int +) + +func up(u int) { + for u/2 != 0 && h[u/2] > h[u] { //父节点比当前结点小 + h[u/2], h[u] = h[u], h[u/2] //交换 + u /= 2 + } +} +func down(u int) { + t := u //t 最小值 + if u*2 <= size && h[2*u] < h[t] { //左孩子存在且小于t + t = u * 2 + } + if u*2+1 <= size && h[2*u+1] < h[t] { //右孩子存在且小于t + t = 2*u + 1 + } + if u != t { + h[u], h[t] = h[t], h[u] + down(t) //递归处理 + } +} +func main() { + var n, m int + h = make([]int, N) + fmt.Scanf("%d%d", &n, &m) + //创建一维数组1 + for i := 1; i <= n; i++ { + fmt.Scanf("%d", &h[i]) + } + size = n + // 一维数组变为小根堆 + for i := n / 2; i != 0; i-- { + down(i) + } + + for ; m != 0; m-- { + fmt.Printf("%d ", h[1]) + h[1] = h[size] + size-- + down(1) + } +} \ No newline at end of file diff --git a/basic/sorting/HeapSort/Solution.java b/basic/sorting/HeapSort/Solution.java new file mode 100644 index 0000000000000..b4629f42d476a --- /dev/null +++ b/basic/sorting/HeapSort/Solution.java @@ -0,0 +1,50 @@ +import java.util.Scanner; + +public class Main { + private static int[] h = new int[100010]; + private static int size; + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(), m = sc.nextInt(); + for (int i = 1; i <= n; ++i) { + h[i] = sc.nextInt(); + } + size = n; + for (int i = n / 2; i > 0; --i) { + down(i); + } + while (m-- > 0) { + System.out.print(h[1] + " "); + h[1] = h[size--]; + down(1); + } + } + + public static void down(int u) { + int t = u; + if (u * 2 <= size && h[u * 2] < h[t]) { + t = u * 2; + } + if (u * 2 + 1 <= size && h[u * 2 + 1] < h[t]) { + t = u * 2 + 1; + } + if (t != u) { + swap(t, u); + down(t); + } + } + + public static void up(int u) { + while (u / 2 > 0 && h[u / 2] > h[u]) { + swap(u / 2, u); + u /= 2; + } + } + + public static void swap(int i, int j) { + int t = h[i]; + h[i] = h[j]; + h[j] = t; + } +} \ No newline at end of file diff --git a/basic/sorting/HeapSort/Solution.py b/basic/sorting/HeapSort/Solution.py new file mode 100644 index 0000000000000..1c3e64f830023 --- /dev/null +++ b/basic/sorting/HeapSort/Solution.py @@ -0,0 +1,34 @@ +n, m = list(map(int, input().split(" "))) +h = [0] + list(map(int, input().split(" "))) + +size = n + + +def down(u): + t = u + if u * 2 <= size and h[u * 2] < h[t]: + t = u * 2 + if u * 2 + 1 <= size and h[u * 2 + 1] < h[t]: + t = u * 2 + 1 + if t != u: + h[t], h[u] = h[u], h[t] + down(t) + + +def up(u): + while u // 2 > 0 and h[u // 2] > h[u]: + h[u // 2], h[u] = h[u], h[u // 2] + u //= 2 + + +for i in range(n // 2, 0, -1): + down(i) + +res = [] +for i in range(m): + res.append(h[1]) + h[1] = h[size] + size -= 1 + down(1) + +print(' '.join(list(map(str, res)))) diff --git a/basic/sorting/HeapSort/Solution.rs b/basic/sorting/HeapSort/Solution.rs new file mode 100644 index 0000000000000..ed0654aaff1b2 --- /dev/null +++ b/basic/sorting/HeapSort/Solution.rs @@ -0,0 +1,60 @@ +use std::io; + +fn heap_sort(nums: &mut Vec) { + let n = nums.len(); + for i in (0..n / 2).rev() { + sink(nums, i, n); + } + for i in (1..n).rev() { + let temp = nums[0]; + nums[0] = nums[i]; + nums[i] = temp; + sink(nums, 0, i); + } +} + +fn sink(nums: &mut Vec, mut i: usize, n: usize) { + loop { + let left = i * 2 + 1; + let right = left + 1; + let mut largest = i; + if left < n && nums[left] > nums[largest] { + largest = left; + } + if right < n && nums[right] > nums[largest] { + largest = right; + } + if largest == i { + break; + } + let temp = nums[i]; + nums[i] = nums[largest]; + nums[largest] = temp; + i = largest; + } +} + +fn main() -> io::Result<()> { + let mut s = String::new(); + io::stdin().read_line(&mut s)?; + let s: Vec = s + .split(' ') + .map(|s| s.trim().parse().unwrap()) + .collect(); + // let n = s[0]; + let m = s[1]; + + let mut nums = String::new(); + io::stdin().read_line(&mut nums)?; + let mut nums: Vec = nums + .split(' ') + .map(|s| s.trim().parse().unwrap()) + .collect(); + + heap_sort(&mut nums); + for num in nums.iter().take(m) { + print!("{} ", num); + } + + Ok(()) +} diff --git a/basic/sorting/InsertionSort/Solution.cpp b/basic/sorting/InsertionSort/Solution.cpp new file mode 100644 index 0000000000000..aa380423e44c5 --- /dev/null +++ b/basic/sorting/InsertionSort/Solution.cpp @@ -0,0 +1,36 @@ +#include +#include + +using namespace std; + +void printvec(const vector& vec, const string& strbegin = "", const string& strend = "") { + cout << strbegin << endl; + for (auto val : vec) { + cout << val << "\t"; + } + + cout << endl; + cout << strend << endl; +} + +void insertsort(vector& vec) { + for (int i = 1; i < vec.size(); i++) { + int j = i - 1; + int num = vec[i]; + for (; j >= 0 && vec[j] > num; j--) { + vec[j + 1] = vec[j]; + } + + vec[j + 1] = num; + } + + return; +} + +int main() { + vector vec = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; + printvec(vec); + insertsort(vec); + printvec(vec, "after insert sort"); + return (0); +} \ No newline at end of file diff --git a/basic/sorting/InsertionSort/Solution.cs b/basic/sorting/InsertionSort/Solution.cs new file mode 100644 index 0000000000000..165f9a07663ad --- /dev/null +++ b/basic/sorting/InsertionSort/Solution.cs @@ -0,0 +1,35 @@ +using System.Diagnostics; +using static System.Console; +namespace Pro; +public class Program +{ + public static void Main() + { + int[] test = new int[] { 31, 12, 10, 5, 6, 7, 8, 10, 23, 34, 56, 43, 32, 21 }; + InsertSortNums(test); + foreach (var item in test) + { + WriteLine(item); + } + } + public static void InsertSortNums(int[] nums) + { + for (int initial = 1; initial < nums.Length; initial++) + { + for (int second_sort = 0; second_sort < initial; second_sort++) + { + if (nums[second_sort] > nums[initial]) + { + swap(ref nums[second_sort], ref nums[initial]); + } + } + } + } + + private static void swap(ref int compare_left, ref int compare_right) + { + int temp = compare_left; + compare_left = compare_right; + compare_right = temp; + } +} diff --git a/basic/sorting/InsertionSort/Solution.go b/basic/sorting/InsertionSort/Solution.go new file mode 100644 index 0000000000000..a74f0e7a623af --- /dev/null +++ b/basic/sorting/InsertionSort/Solution.go @@ -0,0 +1,19 @@ +package main + +import "fmt" + +func insertionSort(nums []int) { + for i, n := 1, len(nums); i < n; i++ { + j, num := i-1, nums[i] + for ; j >= 0 && nums[j] > num; j-- { + nums[j+1] = nums[j] + } + nums[j+1] = num + } +} + +func main() { + nums := []int{1, 2, 7, 9, 5, 8} + insertionSort(nums) + fmt.Println(nums) +} \ No newline at end of file diff --git a/basic/sorting/InsertionSort/Solution.java b/basic/sorting/InsertionSort/Solution.java new file mode 100644 index 0000000000000..12294c68b023f --- /dev/null +++ b/basic/sorting/InsertionSort/Solution.java @@ -0,0 +1,20 @@ +import java.util.Arrays; + +public class InsertionSort { + + private static void insertionSort(int[] nums) { + for (int i = 1, j, n = nums.length; i < n; ++i) { + int num = nums[i]; + for (j = i - 1; j >= 0 && nums[j] > num; --j) { + nums[j + 1] = nums[j]; + } + nums[j + 1] = num; + } + } + + public static void main(String[] args) { + int[] nums = {1, 2, 7, 9, 5, 8}; + insertionSort(nums); + System.out.println(Arrays.toString(nums)); + } +} \ No newline at end of file diff --git a/basic/sorting/InsertionSort/Solution.js b/basic/sorting/InsertionSort/Solution.js new file mode 100644 index 0000000000000..95ec5e540a8d7 --- /dev/null +++ b/basic/sorting/InsertionSort/Solution.js @@ -0,0 +1,16 @@ +function insertionSort(inputArr) { + let len = inputArr.length; + for (let i = 1; i <= len - 1; i++) { + let temp = inputArr[i]; + let j = i - 1; + while (j >= 0 && inputArr[j] > temp) { + inputArr[j + 1] = inputArr[j]; + j--; + } + inputArr[j + 1] = temp; + } + return inputArr; +} + +let arr = [6, 3, 2, 1, 5]; +console.log(insertionSort(arr)); diff --git a/basic/sorting/InsertionSort/Solution.py b/basic/sorting/InsertionSort/Solution.py new file mode 100644 index 0000000000000..68a2de7e63eb7 --- /dev/null +++ b/basic/sorting/InsertionSort/Solution.py @@ -0,0 +1,14 @@ +def insertion_sort(array): + for i in range(len(array)): + cur_index = i + while array[cur_index - 1] > array[cur_index] and cur_index - 1 >= 0: + array[cur_index], array[cur_index - 1] = ( + array[cur_index - 1], + array[cur_index], + ) + cur_index -= 1 + return array + + +array = [10, 17, 50, 7, 30, 24, 27, 45, 15, 5, 36, 21] +print(insertion_sort(array)) diff --git a/basic/sorting/InsertionSort/Solution.rs b/basic/sorting/InsertionSort/Solution.rs new file mode 100644 index 0000000000000..842f5f8bfd2d2 --- /dev/null +++ b/basic/sorting/InsertionSort/Solution.rs @@ -0,0 +1,18 @@ +fn insertion_sort(nums: &mut Vec) { + let n = nums.len(); + for i in 1..n { + let mut j = i - 1; + let temp = nums[i]; + while j >= (0 as usize) && nums[j] > temp { + nums[j + 1] = nums[j]; + j -= 1; + } + nums[j + 1] = temp; + } +} + +fn main() { + let mut nums = vec![1, 2, 7, 9, 5, 8]; + insertion_sort(&mut nums); + println!("{:?}", nums); +} diff --git a/basic/sorting/MergeSort/Solution.cpp b/basic/sorting/MergeSort/Solution.cpp new file mode 100644 index 0000000000000..b7a64c234765e --- /dev/null +++ b/basic/sorting/MergeSort/Solution.cpp @@ -0,0 +1,34 @@ +#include + +using namespace std; + +const int N = 1e6 + 10; + +int n; +int nums[N]; +int tmp[N]; + +void merge_sort(int nums[], int left, int right) { + if (left >= right) return; + int mid = (left + right) >> 1; + merge_sort(nums, left, mid); + merge_sort(nums, mid + 1, right); + int i = left, j = mid + 1, k = 0; + while (i <= mid && j <= right) { + if (nums[i] <= nums[j]) + tmp[k++] = nums[i++]; + else + tmp[k++] = nums[j++]; + } + while (i <= mid) tmp[k++] = nums[i++]; + while (j <= right) tmp[k++] = nums[j++]; + for (i = left, j = 0; i <= right; ++i, ++j) nums[i] = tmp[j]; +} + +int main() { + int n; + scanf("%d", &n); + for (int i = 0; i < n; ++i) scanf("%d", &nums[i]); + merge_sort(nums, 0, n - 1); + for (int i = 0; i < n; ++i) printf("%d ", nums[i]); +} \ No newline at end of file diff --git a/basic/sorting/MergeSort/Solution.go b/basic/sorting/MergeSort/Solution.go new file mode 100644 index 0000000000000..931f15916cb2b --- /dev/null +++ b/basic/sorting/MergeSort/Solution.go @@ -0,0 +1,49 @@ +package main + +import "fmt" + +func mergeSort(nums []int, left, right int) { + if left >= right { + return + } + mid := (left + right) >> 1 + mergeSort(nums, left, mid) + mergeSort(nums, mid+1, right) + i, j := left, mid+1 + tmp := make([]int, 0) + for i <= mid && j <= right { + if nums[i] <= nums[j] { + tmp = append(tmp, nums[i]) + i++ + } else { + tmp = append(tmp, nums[j]) + j++ + } + } + for i <= mid { + tmp = append(tmp, nums[i]) + i++ + } + for j <= right { + tmp = append(tmp, nums[j]) + j++ + } + for i, j = left, 0; i <= right; i, j = i+1, j+1 { + nums[i] = tmp[j] + } +} + +func main() { + var n int + fmt.Scanf("%d\n", &n) + nums := make([]int, n) + for i := 0; i < n; i++ { + fmt.Scanf("%d", &nums[i]) + } + + mergeSort(nums, 0, n-1) + + for _, v := range nums { + fmt.Printf("%d ", v) + } +} \ No newline at end of file diff --git a/basic/sorting/MergeSort/Solution.java b/basic/sorting/MergeSort/Solution.java new file mode 100644 index 0000000000000..15d52831a8cda --- /dev/null +++ b/basic/sorting/MergeSort/Solution.java @@ -0,0 +1,44 @@ +import java.util.Scanner; + +public class Main { + private static int[] tmp = new int[100010]; + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + int[] nums = new int[n]; + for (int i = 0; i < n; ++i) { + nums[i] = sc.nextInt(); + } + mergeSort(nums, 0, n - 1); + for (int i = 0; i < n; ++i) { + System.out.printf("%d ", nums[i]); + } + } + + public static void mergeSort(int[] nums, int left, int right) { + if (left >= right) { + return; + } + int mid = (left + right) >>> 1; + mergeSort(nums, left, mid); + mergeSort(nums, mid + 1, right); + int i = left, j = mid + 1, k = 0; + while (i <= mid && j <= right) { + if (nums[i] <= nums[j]) { + tmp[k++] = nums[i++]; + } else { + tmp[k++] = nums[j++]; + } + } + while (i <= mid) { + tmp[k++] = nums[i++]; + } + while (j <= right) { + tmp[k++] = nums[j++]; + } + for (i = left, j = 0; i <= right; ++i, ++j) { + nums[i] = tmp[j]; + } + } +} \ No newline at end of file diff --git a/basic/sorting/MergeSort/Solution.js b/basic/sorting/MergeSort/Solution.js new file mode 100644 index 0000000000000..2ee3eaccd1316 --- /dev/null +++ b/basic/sorting/MergeSort/Solution.js @@ -0,0 +1,52 @@ +var buf = ''; + +process.stdin.on('readable', function () { + var chunk = process.stdin.read(); + if (chunk) buf += chunk.toString(); +}); + +let getInputArgs = line => { + return line + .split(' ') + .filter(s => s !== '') + .map(x => parseInt(x)); +}; + +function mergeSort(nums, left, right) { + if (left >= right) { + return; + } + + const mid = (left + right) >> 1; + mergeSort(nums, left, mid); + mergeSort(nums, mid + 1, right); + let i = left; + let j = mid + 1; + let tmp = []; + while (i <= mid && j <= right) { + if (nums[i] <= nums[j]) { + tmp.push(nums[i++]); + } else { + tmp.push(nums[j++]); + } + } + while (i <= mid) { + tmp.push(nums[i++]); + } + while (j <= right) { + tmp.push(nums[j++]); + } + for (i = left, j = 0; i <= right; ++i, ++j) { + nums[i] = tmp[j]; + } +} + +process.stdin.on('end', function () { + buf.split('\n').forEach(function (line, lineIdx) { + if (lineIdx % 2 === 1) { + nums = getInputArgs(line); + mergeSort(nums, 0, nums.length - 1); + console.log(nums.join(' ')); + } + }); +}); diff --git a/basic/sorting/MergeSort/Solution.py b/basic/sorting/MergeSort/Solution.py new file mode 100644 index 0000000000000..b6d51a68c8d91 --- /dev/null +++ b/basic/sorting/MergeSort/Solution.py @@ -0,0 +1,34 @@ +N = int(input()) +nums = list(map(int, input().split())) + + +def merge_sort(nums, left, right): + if left >= right: + return + mid = (left + right) >> 1 + merge_sort(nums, left, mid) + merge_sort(nums, mid + 1, right) + tmp = [] + i, j = left, mid + 1 + while i <= mid and j <= right: + if nums[i] <= nums[j]: + tmp.append(nums[i]) + i += 1 + else: + tmp.append(nums[j]) + j += 1 + while i <= mid: + tmp.append(nums[i]) + i += 1 + while j <= right: + tmp.append(nums[j]) + j += 1 + + j = 0 + for i in range(left, right + 1): + nums[i] = tmp[j] + j += 1 + + +merge_sort(nums, 0, N - 1) +print(' '.join(list(map(str, nums)))) diff --git a/basic/sorting/MergeSort/Solution.rs b/basic/sorting/MergeSort/Solution.rs new file mode 100644 index 0000000000000..9165da9ec0dd9 --- /dev/null +++ b/basic/sorting/MergeSort/Solution.rs @@ -0,0 +1,57 @@ +use std::io; + +fn merge_sort(nums: &mut Vec, left: usize, right: usize) { + if left >= right { + return; + } + + let mid = left + (right - left) / 2; + merge_sort(nums, left, mid); + merge_sort(nums, mid + 1, right); + + let mut temp = Vec::new(); + let mut i = left; + let mut j = mid + 1; + + while i <= mid && j <= right { + if nums[i] < nums[j] { + temp.push(nums[i]); + i += 1; + } else { + temp.push(nums[j]); + j += 1; + } + } + while i <= mid { + temp.push(nums[i]); + i += 1; + } + while j <= right { + temp.push(nums[j]); + j += 1; + } + + for i in left..=right { + nums[i] = temp[i - left]; + } +} + +fn main() -> io::Result<()> { + let mut n = String::new(); + io::stdin().read_line(&mut n)?; + let n = n.trim().parse::().unwrap(); + + let mut nums = String::new(); + io::stdin().read_line(&mut nums)?; + let mut nums: Vec = nums + .split(' ') + .map(|s| s.trim().parse().unwrap()) + .collect(); + + merge_sort(&mut nums, 0, n - 1); + for num in nums.iter() { + print!("{} ", num); + } + + Ok(()) +} diff --git a/basic/sorting/QuickSort/Solution.cpp b/basic/sorting/QuickSort/Solution.cpp new file mode 100644 index 0000000000000..3d939bde06a97 --- /dev/null +++ b/basic/sorting/QuickSort/Solution.cpp @@ -0,0 +1,31 @@ +#include + +using namespace std; + +const int N = 1e6 + 10; + +int n; +int nums[N]; + +void quick_sort(int nums[], int left, int right) { + if (left >= right) return; + int i = left - 1, j = right + 1; + int x = nums[left + right >> 1]; + while (i < j) { + while (nums[++i] < x) + ; + while (nums[--j] > x) + ; + if (i < j) swap(nums[i], nums[j]); + } + quick_sort(nums, left, j); + quick_sort(nums, j + 1, right); +} + +int main() { + int n; + scanf("%d", &n); + for (int i = 0; i < n; ++i) scanf("%d", &nums[i]); + quick_sort(nums, 0, n - 1); + for (int i = 0; i < n; ++i) printf("%d ", nums[i]); +} \ No newline at end of file diff --git a/basic/sorting/QuickSort/Solution.go b/basic/sorting/QuickSort/Solution.go new file mode 100644 index 0000000000000..7503ccb60757f --- /dev/null +++ b/basic/sorting/QuickSort/Solution.go @@ -0,0 +1,45 @@ +package main + +import "fmt" + +func quickSort(nums []int, left, right int) { + if left >= right { + return + } + i, j := left-1, right+1 + x := nums[(left+right)>>1] + for i < j { + for { + i++ + if nums[i] >= x { + break + } + } + for { + j-- + if nums[j] <= x { + break + } + } + if i < j { + nums[i], nums[j] = nums[j], nums[i] + } + } + quickSort(nums, left, j) + quickSort(nums, j+1, right) +} + +func main() { + var n int + fmt.Scanf("%d\n", &n) + nums := make([]int, n) + for i := 0; i < n; i++ { + fmt.Scanf("%d", &nums[i]) + } + + quickSort(nums, 0, n-1) + + for _, v := range nums { + fmt.Printf("%d ", v) + } +} \ No newline at end of file diff --git a/basic/sorting/QuickSort/Solution.java b/basic/sorting/QuickSort/Solution.java new file mode 100644 index 0000000000000..a339ddd60ef03 --- /dev/null +++ b/basic/sorting/QuickSort/Solution.java @@ -0,0 +1,37 @@ +import java.util.Scanner; + +public class Main { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + int[] nums = new int[n]; + for (int i = 0; i < n; ++i) { + nums[i] = sc.nextInt(); + } + quickSort(nums, 0, n - 1); + for (int i = 0; i < n; ++i) { + System.out.print(nums[i] + " "); + } + } + + public static void quickSort(int[] nums, int left, int right) { + if (left >= right) { + return; + } + int i = left - 1, j = right + 1; + int x = nums[(left + right) >> 1]; + while (i < j) { + while (nums[++i] < x) + ; + while (nums[--j] > x) + ; + if (i < j) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } + } + quickSort(nums, left, j); + quickSort(nums, j + 1, right); + } +} \ No newline at end of file diff --git a/basic/sorting/QuickSort/Solution.js b/basic/sorting/QuickSort/Solution.js new file mode 100644 index 0000000000000..4ceb2534da458 --- /dev/null +++ b/basic/sorting/QuickSort/Solution.js @@ -0,0 +1,44 @@ +var buf = ''; + +process.stdin.on('readable', function () { + var chunk = process.stdin.read(); + if (chunk) buf += chunk.toString(); +}); + +let getInputArgs = line => { + return line + .split(' ') + .filter(s => s !== '') + .map(x => parseInt(x)); +}; + +function quickSort(nums, left, right) { + if (left >= right) { + return; + } + + let i = left - 1; + let j = right + 1; + let x = nums[(left + right) >> 1]; + while (i < j) { + while (nums[++i] < x); + while (nums[--j] > x); + if (i < j) { + const t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } + } + quickSort(nums, left, j); + quickSort(nums, j + 1, right); +} + +process.stdin.on('end', function () { + buf.split('\n').forEach(function (line, lineIdx) { + if (lineIdx % 2 === 1) { + nums = getInputArgs(line); + quickSort(nums, 0, nums.length - 1); + console.log(nums.join(' ')); + } + }); +}); diff --git a/basic/sorting/QuickSort/Solution.py b/basic/sorting/QuickSort/Solution.py new file mode 100644 index 0000000000000..7684f58f5d015 --- /dev/null +++ b/basic/sorting/QuickSort/Solution.py @@ -0,0 +1,26 @@ +N = int(input()) +nums = list(map(int, input().split())) + + +def quick_sort(nums, left, right): + if left >= right: + return + i, j = left - 1, right + 1 + x = nums[(left + right) >> 1] + while i < j: + while 1: + i += 1 + if nums[i] >= x: + break + while 1: + j -= 1 + if nums[j] <= x: + break + if i < j: + nums[i], nums[j] = nums[j], nums[i] + quick_sort(nums, left, j) + quick_sort(nums, j + 1, right) + + +quick_sort(nums, 0, N - 1) +print(' '.join(list(map(str, nums)))) diff --git a/basic/sorting/QuickSort/Solution.rs b/basic/sorting/QuickSort/Solution.rs new file mode 100644 index 0000000000000..766e3579ae083 --- /dev/null +++ b/basic/sorting/QuickSort/Solution.rs @@ -0,0 +1,51 @@ +use rand::Rng; // 0.7.2 +use std::io; + +fn quick_sort(nums: &mut Vec, left: usize, right: usize) { + if left >= right { + return; + } + + let random_index = rand::thread_rng().gen_range(left, right + 1); + let temp = nums[random_index]; + nums[random_index] = nums[left]; + nums[left] = temp; + + let pivot = nums[left]; + let mut i = left; + let mut j = right; + while i < j { + while i < j && nums[j] >= pivot { + j -= 1; + } + nums[i] = nums[j]; + while i < j && nums[i] < pivot { + i += 1; + } + nums[j] = nums[i]; + } + nums[i] = pivot; + + quick_sort(nums, left, i); + quick_sort(nums, i + 1, right); +} + +fn main() -> io::Result<()> { + let mut n = String::new(); + io::stdin().read_line(&mut n)?; + let n = n.trim().parse::().unwrap(); + + let mut nums = String::new(); + io::stdin().read_line(&mut nums)?; + let mut nums: Vec = nums + .split(' ') + .map(|s| s.trim().parse().unwrap()) + .collect(); + + quick_sort(&mut nums, 0, n - 1); + for num in nums.iter() { + print!("{} ", num); + } + + Ok(()) +} diff --git a/basic/sorting/SelectionSort/Solution.cpp b/basic/sorting/SelectionSort/Solution.cpp new file mode 100644 index 0000000000000..f2351faf69b0e --- /dev/null +++ b/basic/sorting/SelectionSort/Solution.cpp @@ -0,0 +1,35 @@ +#include +#include + +using namespace std; + +void printvec(const vector& vec, const string& strbegin = "", const string& strend = "") { + cout << strbegin << endl; + for (auto val : vec) { + cout << val << "\t"; + } + + cout << endl; + cout << strend << endl; +} + +void selectsort(vector& vec) { + for (int i = 0; i < vec.size() - 1; i++) { + int minidx = i; + for (int j = i + 1; j < vec.size(); j++) { + if (vec[minidx] > vec[j]) { + minidx = j; + } + } + + swap(vec[i], vec[minidx]); + } +} + +int main(void) { + vector vec = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; + printvec(vec); + selectsort(vec); + printvec(vec, "after insert sort"); + return (0); +} \ No newline at end of file diff --git a/basic/sorting/SelectionSort/Solution.cs b/basic/sorting/SelectionSort/Solution.cs new file mode 100644 index 0000000000000..1b1ef72bf44a7 --- /dev/null +++ b/basic/sorting/SelectionSort/Solution.cs @@ -0,0 +1,37 @@ +using static System.Console; +namespace Pro; +public class Program +{ + public static void Main() + { + int[] test = new int[] {90, 12, 77, 9, 0, 2, 23, 23, 3, 57, 80}; + SelectionSortNums(test); + foreach (var item in test) + { + WriteLine(item); + } + } + public static void SelectionSortNums(int[] nums) + { + for (int initial = 0; initial < nums.Length; initial++) + { + for (int second_sort = initial; second_sort < nums.Length; second_sort++) + { + if (nums[initial] > nums[second_sort]) + { + swap(ref nums[initial], ref nums[second_sort]); + } + } + } + + } + + private static void swap(ref int compare_left, ref int compare_right) + { + int temp = compare_left; + compare_left = compare_right; + compare_right = temp; + } + +} + diff --git a/basic/sorting/SelectionSort/Solution.go b/basic/sorting/SelectionSort/Solution.go new file mode 100644 index 0000000000000..da89b176c4977 --- /dev/null +++ b/basic/sorting/SelectionSort/Solution.go @@ -0,0 +1,21 @@ +package main + +import "fmt" + +func selectionSort(nums []int) { + for i, n := 0, len(nums); i < n-1; i++ { + minIndex := i + for j := i + 1; j < n; j++ { + if nums[j] < nums[minIndex] { + minIndex = j + } + } + nums[minIndex], nums[i] = nums[i], nums[minIndex] + } +} + +func main() { + nums := []int{1, 2, 7, 9, 5, 8} + selectionSort(nums) + fmt.Println(nums) +} \ No newline at end of file diff --git a/basic/sorting/SelectionSort/Solution.java b/basic/sorting/SelectionSort/Solution.java new file mode 100644 index 0000000000000..e809969da0462 --- /dev/null +++ b/basic/sorting/SelectionSort/Solution.java @@ -0,0 +1,28 @@ +import java.util.Arrays; + +public class SelectionSort { + + private static void selectionSort(int[] nums) { + for (int i = 0, n = nums.length; i < n - 1; ++i) { + int minIndex = i; + for (int j = i; j < n; ++j) { + if (nums[j] < nums[minIndex]) { + minIndex = j; + } + } + swap(nums, minIndex, i); + } + } + + private static void swap(int[] nums, int i, int j) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } + + public static void main(String[] args) { + int[] nums = {1, 2, 7, 9, 5, 8}; + selectionSort(nums); + System.out.println(Arrays.toString(nums)); + } +} \ No newline at end of file diff --git a/basic/sorting/SelectionSort/Solution.js b/basic/sorting/SelectionSort/Solution.js new file mode 100644 index 0000000000000..102936743c5ef --- /dev/null +++ b/basic/sorting/SelectionSort/Solution.js @@ -0,0 +1,18 @@ +function selectionSort(inputArr) { + let len = inputArr.length; + for (let i = 0; i <= len - 2; i++) { + let j = i; + let min = j; + while (j <= len - 1) { + if (inputArr[j] < inputArr[min]) min = j; + j++; + } + let temp = inputArr[i]; + inputArr[i] = inputArr[min]; + inputArr[min] = temp; + } + return inputArr; +} + +let arr = [6, 3, 2, 1, 5]; +console.log(selectionSort(arr)); diff --git a/basic/sorting/SelectionSort/Solution.py b/basic/sorting/SelectionSort/Solution.py new file mode 100644 index 0000000000000..867de42c2a401 --- /dev/null +++ b/basic/sorting/SelectionSort/Solution.py @@ -0,0 +1,13 @@ +def selection_sort(arr): + n = len(arr) + for i in range(n - 1): + min_index = i + for j in range(i + 1, n): + if arr[j] < arr[min_index]: + min_index = j + arr[min_index], arr[i] = arr[i], arr[min_index] + + +arr = [26, 11, 99, 33, 69, 77, 55, 56, 67] +selection_sort(arr) +print(arr) diff --git a/basic/sorting/SelectionSort/Solution.rs b/basic/sorting/SelectionSort/Solution.rs new file mode 100644 index 0000000000000..a952088f7394a --- /dev/null +++ b/basic/sorting/SelectionSort/Solution.rs @@ -0,0 +1,20 @@ +fn selection_sort(nums: &mut Vec) { + let n = nums.len(); + for i in 0..n - 1 { + let mut min_index = i; + for j in i..n { + if nums[j] < nums[min_index] { + min_index = j; + } + } + let temp = nums[min_index]; + nums[min_index] = nums[i]; + nums[i] = temp; + } +} + +fn main() { + let mut nums = vec![1, 2, 7, 9, 5, 8]; + selection_sort(&mut nums); + println!("{:?}", nums); +} diff --git a/basic/sorting/ShellSort/Solution.go b/basic/sorting/ShellSort/Solution.go new file mode 100644 index 0000000000000..d3aa71a109524 --- /dev/null +++ b/basic/sorting/ShellSort/Solution.go @@ -0,0 +1,22 @@ +package main + +import "fmt" + +func shellSort(nums []int) { + n := len(nums) + for gap := n / 2; gap > 0; gap /= 2 { + for i := gap; i < n; i++ { + j, num := i-gap, nums[i] + for ; j >= 0 && nums[j] > num; j -= gap { + nums[j+gap] = nums[j] + } + nums[j+gap] = num + } + } +} + +func main() { + nums := []int{1, 2, 7, 9, 5, 8} + shellSort(nums) + fmt.Println(nums) +} \ No newline at end of file diff --git a/basic/sorting/ShellSort/Solution.java b/basic/sorting/ShellSort/Solution.java new file mode 100644 index 0000000000000..b2a12cbd34f92 --- /dev/null +++ b/basic/sorting/ShellSort/Solution.java @@ -0,0 +1,25 @@ +import java.util.Arrays; + +public class ShellSort { + + private static int[] shellSort(int[] arr) { + int n = arr.length; + + for (int gap = n / 2; gap > 0; gap /= 2) { + for (int i = gap; i < n; i++) { + int key = arr[i]; + int j = i; + while (j >= gap && arr[j - gap] > key) { + arr[j] = arr[j - gap]; + j -= gap; + } + arr[j] = key; + } + } + return arr; + } + + public static void main(String[] args) { + System.out.println(Arrays.toString(shellSort(new int[] {1, 2, 7, 9, 5, 8}))); + } +} \ No newline at end of file diff --git a/basic/sorting/ShellSort/Solution.js b/basic/sorting/ShellSort/Solution.js new file mode 100644 index 0000000000000..91b3ee645167a --- /dev/null +++ b/basic/sorting/ShellSort/Solution.js @@ -0,0 +1,21 @@ +function shellSort(arr) { + var len = arr.length; + var gapSize = Math.floor(len / 2); + while (gapSize > 0) { + for (var i = gapSize; i < len; i++) { + var temp = arr[i]; + var j = i; + + while (j >= gapSize && arr[j - gapSize] > temp) { + arr[j] = arr[j - gapSize]; + j -= gapSize; + } + arr[j] = temp; + } + gapSize = Math.floor(gapSize / 2); + } + return arr; +} + +let arr = [6, 3, 2, 1, 5]; +console.log(shellSort(arr)); diff --git a/basic/sorting/ShellSort/Solution.rs b/basic/sorting/ShellSort/Solution.rs new file mode 100644 index 0000000000000..5c0fc19806394 --- /dev/null +++ b/basic/sorting/ShellSort/Solution.rs @@ -0,0 +1,22 @@ +fn shell_sort(nums: &mut Vec) { + let n = nums.len(); + let mut gap = n / 2; + while gap > 0 { + for i in gap..n { + let mut j = i - gap; + let temp = nums[i]; + while j >= (0 as usize) && nums[j] > temp { + nums[j + gap] = nums[j]; + j -= gap; + } + nums[j + gap] = temp; + } + gap /= 2; + } +} + +fn main() { + let mut nums = vec![1, 2, 7, 9, 5, 8]; + shell_sort(&mut nums); + println!("{:?}", nums); +} diff --git a/lcci/01.02.Check Permutation/Solution.java b/lcci/01.02.Check Permutation/Solution.java index 9e7358a89066b..b72ba2e139e1f 100644 --- a/lcci/01.02.Check Permutation/Solution.java +++ b/lcci/01.02.Check Permutation/Solution.java @@ -1,5 +1,8 @@ class Solution { public boolean CheckPermutation(String s1, String s2) { + if (s1.length() != s2.length()) { + return false; + } int[] cnt = new int[26]; for (char c : s1.toCharArray()) { ++cnt[c - 'a']; diff --git a/lcci/01.02.Check Permutation/Solution.rs b/lcci/01.02.Check Permutation/Solution.rs index a5b2dbea7b8d9..efe963a0130f2 100644 --- a/lcci/01.02.Check Permutation/Solution.rs +++ b/lcci/01.02.Check Permutation/Solution.rs @@ -1,9 +1,18 @@ +use std::collections::HashMap; impl Solution { pub fn check_permutation(s1: String, s2: String) -> bool { - let mut s1: Vec = s1.chars().collect(); - let mut s2: Vec = s2.chars().collect(); - s1.sort(); - s2.sort(); - s1 == s2 + let n = s1.len(); + let m = s2.len(); + if n != m { + return false; + } + let s1 = s1.as_bytes(); + let s2 = s2.as_bytes(); + let mut map = HashMap::new(); + for i in 0..n { + *map.entry(s1[i]).or_insert(0) += 1; + *map.entry(s2[i]).or_insert(0) -= 1; + } + map.values().all(|i| *i == 0) } } diff --git a/lcci/01.02.Check Permutation/Solution.ts b/lcci/01.02.Check Permutation/Solution.ts index da323deac37f4..65f0c434d61b9 100644 --- a/lcci/01.02.Check Permutation/Solution.ts +++ b/lcci/01.02.Check Permutation/Solution.ts @@ -1,3 +1,18 @@ function CheckPermutation(s1: string, s2: string): boolean { - return [...s1].sort().join('') === [...s2].sort().join(''); + const n = s1.length; + const m = s2.length; + if (n !== m) { + return false; + } + const map = new Map(); + for (let i = 0; i < n; i++) { + map.set(s1[i], (map.get(s1[i]) ?? 0) + 1); + map.set(s2[i], (map.get(s2[i]) ?? 0) - 1); + } + for (const v of map.values()) { + if (v !== 0) { + return false; + } + } + return true; } diff --git a/lcci/01.02.Check Permutation/Solution2.cpp b/lcci/01.02.Check Permutation/Solution2.cpp new file mode 100644 index 0000000000000..70c67c68db593 --- /dev/null +++ b/lcci/01.02.Check Permutation/Solution2.cpp @@ -0,0 +1,8 @@ +class Solution { +public: + bool CheckPermutation(string s1, string s2) { + sort(s1.begin(), s1.end()); + sort(s2.begin(), s2.end()); + return s1 == s2; + } +}; \ No newline at end of file diff --git a/lcci/01.02.Check Permutation/Solution2.go b/lcci/01.02.Check Permutation/Solution2.go new file mode 100644 index 0000000000000..2fbb6049b852b --- /dev/null +++ b/lcci/01.02.Check Permutation/Solution2.go @@ -0,0 +1,6 @@ +func CheckPermutation(s1 string, s2 string) bool { + cs1, cs2 := []byte(s1), []byte(s2) + sort.Slice(cs1, func(i, j int) bool { return cs1[i] < cs1[j] }) + sort.Slice(cs2, func(i, j int) bool { return cs2[i] < cs2[j] }) + return string(cs1) == string(cs2) +} \ No newline at end of file diff --git a/lcci/01.02.Check Permutation/Solution2.java b/lcci/01.02.Check Permutation/Solution2.java new file mode 100644 index 0000000000000..0f28ef37abf4e --- /dev/null +++ b/lcci/01.02.Check Permutation/Solution2.java @@ -0,0 +1,9 @@ +class Solution { + public boolean CheckPermutation(String s1, String s2) { + char[] cs1 = s1.toCharArray(); + char[] cs2 = s2.toCharArray(); + Arrays.sort(cs1); + Arrays.sort(cs2); + return Arrays.equals(cs1, cs2); + } +} \ No newline at end of file diff --git a/lcci/01.02.Check Permutation/Solution2.py b/lcci/01.02.Check Permutation/Solution2.py new file mode 100644 index 0000000000000..66fa0192dcd3f --- /dev/null +++ b/lcci/01.02.Check Permutation/Solution2.py @@ -0,0 +1,3 @@ +class Solution: + def CheckPermutation(self, s1: str, s2: str) -> bool: + return sorted(s1) == sorted(s2) diff --git a/lcci/01.02.Check Permutation/Solution2.rs b/lcci/01.02.Check Permutation/Solution2.rs new file mode 100644 index 0000000000000..a5b2dbea7b8d9 --- /dev/null +++ b/lcci/01.02.Check Permutation/Solution2.rs @@ -0,0 +1,9 @@ +impl Solution { + pub fn check_permutation(s1: String, s2: String) -> bool { + let mut s1: Vec = s1.chars().collect(); + let mut s2: Vec = s2.chars().collect(); + s1.sort(); + s2.sort(); + s1 == s2 + } +} diff --git a/lcci/01.02.Check Permutation/Solution2.ts b/lcci/01.02.Check Permutation/Solution2.ts new file mode 100644 index 0000000000000..da323deac37f4 --- /dev/null +++ b/lcci/01.02.Check Permutation/Solution2.ts @@ -0,0 +1,3 @@ +function CheckPermutation(s1: string, s2: string): boolean { + return [...s1].sort().join('') === [...s2].sort().join(''); +} diff --git a/lcci/01.03.String to URL/Solution2.py b/lcci/01.03.String to URL/Solution2.py new file mode 100644 index 0000000000000..e64fda706fc0c --- /dev/null +++ b/lcci/01.03.String to URL/Solution2.py @@ -0,0 +1,3 @@ +class Solution: + def replaceSpaces(self, S: str, length: int) -> str: + return ''.join(['%20' if c == ' ' else c for c in S[:length]]) diff --git a/lcci/01.03.String to URL/Solution2.rs b/lcci/01.03.String to URL/Solution2.rs new file mode 100644 index 0000000000000..2ef9f1bb8b9db --- /dev/null +++ b/lcci/01.03.String to URL/Solution2.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn replace_spaces(s: String, length: i32) -> String { + s.chars() + .take(length as usize) + .map(|c| { + if c == ' ' { "%20".to_string() } else { c.to_string() } + }) + .collect() + } +} diff --git a/lcci/01.04.Palindrome Permutation/Solution2.cpp b/lcci/01.04.Palindrome Permutation/Solution2.cpp new file mode 100644 index 0000000000000..d492216b86066 --- /dev/null +++ b/lcci/01.04.Palindrome Permutation/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + bool canPermutePalindrome(string s) { + unordered_set vis; + for (auto& c : s) { + if (vis.count(c)) { + vis.erase(c); + } else { + vis.insert(c); + } + } + return vis.size() < 2; + } +}; \ No newline at end of file diff --git a/lcci/01.04.Palindrome Permutation/Solution2.java b/lcci/01.04.Palindrome Permutation/Solution2.java new file mode 100644 index 0000000000000..2923022ddc24d --- /dev/null +++ b/lcci/01.04.Palindrome Permutation/Solution2.java @@ -0,0 +1,12 @@ +class Solution { + public boolean canPermutePalindrome(String s) { + Set vis = new HashSet<>(); + for (int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if (!vis.add(c)) { + vis.remove(c); + } + } + return vis.size() < 2; + } +} \ No newline at end of file diff --git a/lcci/01.04.Palindrome Permutation/Solution2.py b/lcci/01.04.Palindrome Permutation/Solution2.py new file mode 100644 index 0000000000000..617cd88e6777f --- /dev/null +++ b/lcci/01.04.Palindrome Permutation/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def canPermutePalindrome(self, s: str) -> bool: + vis = set() + for c in s: + if c in vis: + vis.remove(c) + else: + vis.add(c) + return len(vis) < 2 diff --git a/lcci/01.05.One Away/Solution.cpp b/lcci/01.05.One Away/Solution.cpp index 63cd48c0494e8..83138f9b88d7c 100644 --- a/lcci/01.05.One Away/Solution.cpp +++ b/lcci/01.05.One Away/Solution.cpp @@ -1,31 +1,31 @@ -class Solution { -public: - bool oneEditAway(std::string first, std::string second) { - int m = first.length(), n = second.length(); - if (m < n) { - return oneEditAway(second, first); - } - if (m - n > 1) { - return false; - } - int cnt = 0; - if (m == n) { - for (int i = 0; i < n; ++i) { - if (first[i] != second[i]) { - if (++cnt > 1) { - return false; - } - } - } - return true; - } - for (int i = 0, j = 0; i < m; ++i) { - if (j == n || (j < n && first[i] != second[j])) { - ++cnt; - } else { - ++j; - } - } - return cnt < 2; - } +class Solution { +public: + bool oneEditAway(std::string first, std::string second) { + int m = first.length(), n = second.length(); + if (m < n) { + return oneEditAway(second, first); + } + if (m - n > 1) { + return false; + } + int cnt = 0; + if (m == n) { + for (int i = 0; i < n; ++i) { + if (first[i] != second[i]) { + if (++cnt > 1) { + return false; + } + } + } + return true; + } + for (int i = 0, j = 0; i < m; ++i) { + if (j == n || (j < n && first[i] != second[j])) { + ++cnt; + } else { + ++j; + } + } + return cnt < 2; + } }; \ No newline at end of file diff --git a/lcci/01.05.One Away/Solution.java b/lcci/01.05.One Away/Solution.java index b7b519bca9098..054bf4c37833d 100644 --- a/lcci/01.05.One Away/Solution.java +++ b/lcci/01.05.One Away/Solution.java @@ -1,30 +1,30 @@ -class Solution { - public boolean oneEditAway(String first, String second) { - int m = first.length(), n = second.length(); - if (m < n) { - return oneEditAway(second, first); - } - if (m - n > 1) { - return false; - } - int cnt = 0; - if (m == n) { - for (int i = 0; i < n; ++i) { - if (first.charAt(i) != second.charAt(i)) { - if (++cnt > 1) { - return false; - } - } - } - return true; - } - for (int i = 0, j = 0; i < m; ++i) { - if (j == n || (j < n && first.charAt(i) != second.charAt(j))) { - ++cnt; - } else { - ++j; - } - } - return cnt < 2; - } +class Solution { + public boolean oneEditAway(String first, String second) { + int m = first.length(), n = second.length(); + if (m < n) { + return oneEditAway(second, first); + } + if (m - n > 1) { + return false; + } + int cnt = 0; + if (m == n) { + for (int i = 0; i < n; ++i) { + if (first.charAt(i) != second.charAt(i)) { + if (++cnt > 1) { + return false; + } + } + } + return true; + } + for (int i = 0, j = 0; i < m; ++i) { + if (j == n || (j < n && first.charAt(i) != second.charAt(j))) { + ++cnt; + } else { + ++j; + } + } + return cnt < 2; + } } \ No newline at end of file diff --git a/lcci/01.05.One Away/Solution.py b/lcci/01.05.One Away/Solution.py index c668638540941..543a3a3ae1679 100644 --- a/lcci/01.05.One Away/Solution.py +++ b/lcci/01.05.One Away/Solution.py @@ -1,17 +1,17 @@ -class Solution: - def oneEditAway(self, first: str, second: str) -> bool: - m, n = len(first), len(second) - if m < n: - return self.oneEditAway(second, first) - if m - n > 1: - return False - if m == n: - return sum(a != b for a, b in zip(first, second)) < 2 - i = j = cnt = 0 - while i < m: - if j == n or (j < n and first[i] != second[j]): - cnt += 1 - else: - j += 1 - i += 1 - return cnt < 2 +class Solution: + def oneEditAway(self, first: str, second: str) -> bool: + m, n = len(first), len(second) + if m < n: + return self.oneEditAway(second, first) + if m - n > 1: + return False + if m == n: + return sum(a != b for a, b in zip(first, second)) < 2 + i = j = cnt = 0 + while i < m: + if j == n or (j < n and first[i] != second[j]): + cnt += 1 + else: + j += 1 + i += 1 + return cnt < 2 diff --git a/lcci/01.06.Compress String/Solution.cpp b/lcci/01.06.Compress String/Solution.cpp index b98486c6cdf6e..b1a6613865a2c 100644 --- a/lcci/01.06.Compress String/Solution.cpp +++ b/lcci/01.06.Compress String/Solution.cpp @@ -1,17 +1,17 @@ -class Solution { -public: - string compressString(string S) { - int n = S.size(); - string t; - for (int i = 0; i < n;) { - int j = i + 1; - while (j < n && S[j] == S[i]) { - ++j; - } - t += S[i]; - t += to_string(j - i); - i = j; - } - return t.size() < n ? t : S; - } +class Solution { +public: + string compressString(string S) { + int n = S.size(); + string t; + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && S[j] == S[i]) { + ++j; + } + t += S[i]; + t += to_string(j - i); + i = j; + } + return t.size() < n ? t : S; + } }; \ No newline at end of file diff --git a/lcci/01.06.Compress String/Solution.java b/lcci/01.06.Compress String/Solution.java index 0dd24f426c6cd..f65166d1c4308 100644 --- a/lcci/01.06.Compress String/Solution.java +++ b/lcci/01.06.Compress String/Solution.java @@ -1,16 +1,16 @@ -class Solution { - public String compressString(String S) { - int n = S.length(); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < n;) { - int j = i + 1; - while (j < n && S.charAt(j) == S.charAt(i)) { - ++j; - } - sb.append(S.charAt(i)).append(j - i); - i = j; - } - String t = sb.toString(); - return t.length() < n ? t : S; - } +class Solution { + public String compressString(String S) { + int n = S.length(); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && S.charAt(j) == S.charAt(i)) { + ++j; + } + sb.append(S.charAt(i)).append(j - i); + i = j; + } + String t = sb.toString(); + return t.length() < n ? t : S; + } } \ No newline at end of file diff --git a/lcci/01.06.Compress String/Solution.py b/lcci/01.06.Compress String/Solution.py index acfffae31ec3e..3f6eaad080978 100644 --- a/lcci/01.06.Compress String/Solution.py +++ b/lcci/01.06.Compress String/Solution.py @@ -1,4 +1,4 @@ -class Solution: - def compressString(self, S: str) -> str: - t = "".join(a + str(len(list(b))) for a, b in groupby(S)) - return min(S, t, key=len) +class Solution: + def compressString(self, S: str) -> str: + t = "".join(a + str(len(list(b))) for a, b in groupby(S)) + return min(S, t, key=len) diff --git a/lcci/01.06.Compress String/Solution2.py b/lcci/01.06.Compress String/Solution2.py new file mode 100644 index 0000000000000..d3bc1c1aab18d --- /dev/null +++ b/lcci/01.06.Compress String/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def compressString(self, S: str) -> str: + t = [] + i, n = 0, len(S) + while i < n: + j = i + 1 + while j < n and S[j] == S[i]: + j += 1 + t.append(S[i] + str(j - i)) + i = j + return min(S, "".join(t), key=len) diff --git a/lcci/01.07.Rotate Matrix/Solution.cpp b/lcci/01.07.Rotate Matrix/Solution.cpp index a769be400f3fc..2224adfa92a2a 100644 --- a/lcci/01.07.Rotate Matrix/Solution.cpp +++ b/lcci/01.07.Rotate Matrix/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - void rotate(vector>& matrix) { - int n = matrix.size(); - for (int i = 0; i < n >> 1; ++i) { - for (int j = 0; j < n; ++j) { - swap(matrix[i][j], matrix[n - i - 1][j]); - } - } - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - swap(matrix[i][j], matrix[j][i]); - } - } - } +class Solution { +public: + void rotate(vector>& matrix) { + int n = matrix.size(); + for (int i = 0; i < n >> 1; ++i) { + for (int j = 0; j < n; ++j) { + swap(matrix[i][j], matrix[n - i - 1][j]); + } + } + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + swap(matrix[i][j], matrix[j][i]); + } + } + } }; \ No newline at end of file diff --git a/lcci/01.07.Rotate Matrix/Solution.cs b/lcci/01.07.Rotate Matrix/Solution.cs index ede95719d847d..571e30b896365 100644 --- a/lcci/01.07.Rotate Matrix/Solution.cs +++ b/lcci/01.07.Rotate Matrix/Solution.cs @@ -1,19 +1,19 @@ -public class Solution { - public void Rotate(int[][] matrix) { - int n = matrix.Length; - for (int i = 0; i < n >> 1; ++i) { - for (int j = 0; j < n; ++j) { - int t = matrix[i][j]; - matrix[i][j] = matrix[n - i - 1][j]; - matrix[n - i - 1][j] = t; - } - } - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - int t = matrix[i][j]; - matrix[i][j] = matrix[j][i]; - matrix[j][i] = t; - } - } - } -} \ No newline at end of file +public class Solution { + public void Rotate(int[][] matrix) { + int n = matrix.Length; + for (int i = 0; i < n >> 1; ++i) { + for (int j = 0; j < n; ++j) { + int t = matrix[i][j]; + matrix[i][j] = matrix[n - i - 1][j]; + matrix[n - i - 1][j] = t; + } + } + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + int t = matrix[i][j]; + matrix[i][j] = matrix[j][i]; + matrix[j][i] = t; + } + } + } +} diff --git a/lcci/01.07.Rotate Matrix/Solution.java b/lcci/01.07.Rotate Matrix/Solution.java index 54162c23dc0aa..61a6944d23397 100644 --- a/lcci/01.07.Rotate Matrix/Solution.java +++ b/lcci/01.07.Rotate Matrix/Solution.java @@ -1,19 +1,19 @@ -class Solution { - public void rotate(int[][] matrix) { - int n = matrix.length; - for (int i = 0; i < n >> 1; ++i) { - for (int j = 0; j < n; ++j) { - int t = matrix[i][j]; - matrix[i][j] = matrix[n - i - 1][j]; - matrix[n - i - 1][j] = t; - } - } - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - int t = matrix[i][j]; - matrix[i][j] = matrix[j][i]; - matrix[j][i] = t; - } - } - } +class Solution { + public void rotate(int[][] matrix) { + int n = matrix.length; + for (int i = 0; i < n >> 1; ++i) { + for (int j = 0; j < n; ++j) { + int t = matrix[i][j]; + matrix[i][j] = matrix[n - i - 1][j]; + matrix[n - i - 1][j] = t; + } + } + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + int t = matrix[i][j]; + matrix[i][j] = matrix[j][i]; + matrix[j][i] = t; + } + } + } } \ No newline at end of file diff --git a/lcci/01.07.Rotate Matrix/Solution.py b/lcci/01.07.Rotate Matrix/Solution.py index d8eb627b11a86..dde2a0dffe278 100644 --- a/lcci/01.07.Rotate Matrix/Solution.py +++ b/lcci/01.07.Rotate Matrix/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def rotate(self, matrix: List[List[int]]) -> None: - n = len(matrix) - for i in range(n >> 1): - for j in range(n): - matrix[i][j], matrix[n - i - 1][j] = matrix[n - i - 1][j], matrix[i][j] - for i in range(n): - for j in range(i): - matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] +class Solution: + def rotate(self, matrix: List[List[int]]) -> None: + n = len(matrix) + for i in range(n >> 1): + for j in range(n): + matrix[i][j], matrix[n - i - 1][j] = matrix[n - i - 1][j], matrix[i][j] + for i in range(n): + for j in range(i): + matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] diff --git a/lcci/01.08.Zero Matrix/Solution.c b/lcci/01.08.Zero Matrix/Solution.c index b313eb85a58a6..ce5e40a16fd36 100644 --- a/lcci/01.08.Zero Matrix/Solution.c +++ b/lcci/01.08.Zero Matrix/Solution.c @@ -1,43 +1,25 @@ void setZeroes(int** matrix, int matrixSize, int* matrixColSize) { int m = matrixSize; int n = matrixColSize[0]; - int l0 = 0; - int r0 = 0; + int* rows = (int*) malloc(sizeof(int) * m); + int* cols = (int*) malloc(sizeof(int) * n); + memset(rows, 0, sizeof(int) * m); + memset(cols, 0, sizeof(int) * n); for (int i = 0; i < m; i++) { - if (matrix[i][0] == 0) { - l0 = 1; - break; - } - } - for (int j = 0; j < n; j++) { - if (matrix[0][j] == 0) { - r0 = 1; - break; - } - } - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { + for (int j = 0; j < n; ++j) { if (matrix[i][j] == 0) { - matrix[i][0] = 0; - matrix[0][j] = 0; + rows[i] = 1; + cols[j] = 1; } } } - for (int i = 1; i < m; i++) { - for (int j = 1; j < n; j++) { - if (matrix[i][0] == 0 || matrix[0][j] == 0) { + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; ++j) { + if (rows[i] || cols[j]) { matrix[i][j] = 0; } } } - if (l0) { - for (int i = 0; i < m; i++) { - matrix[i][0] = 0; - } - } - if (r0) { - for (int j = 0; j < n; j++) { - matrix[0][j] = 0; - } - } -} + free(rows); + free(cols); +} \ No newline at end of file diff --git a/lcci/01.08.Zero Matrix/Solution.rs b/lcci/01.08.Zero Matrix/Solution.rs index d1168977a6bad..631e1bf701d63 100644 --- a/lcci/01.08.Zero Matrix/Solution.rs +++ b/lcci/01.08.Zero Matrix/Solution.rs @@ -2,50 +2,22 @@ impl Solution { pub fn set_zeroes(matrix: &mut Vec>) { let m = matrix.len(); let n = matrix[0].len(); - let l0 = { - let mut res = false; - for j in 0..n { - if matrix[0][j] == 0 { - res = true; - break; - } - } - res - }; - let r0 = { - let mut res = false; - for i in 0..m { - if matrix[i][0] == 0 { - res = true; - break; - } - } - res - }; + let mut rows = vec![false; m]; + let mut cols = vec![false; n]; for i in 0..m { for j in 0..n { if matrix[i][j] == 0 { - matrix[i][0] = 0; - matrix[0][j] = 0; + rows[i] = true; + cols[j] = true; } } } - for i in 1..m { - for j in 1..n { - if matrix[i][0] == 0 || matrix[0][j] == 0 { + for i in 0..m { + for j in 0..n { + if rows[i] || cols[j] { matrix[i][j] = 0; } } } - if l0 { - for j in 0..n { - matrix[0][j] = 0; - } - } - if r0 { - for i in 0..m { - matrix[i][0] = 0; - } - } } } diff --git a/lcci/01.08.Zero Matrix/Solution.ts b/lcci/01.08.Zero Matrix/Solution.ts index cae9b1ded9555..9ffd42ff60559 100644 --- a/lcci/01.08.Zero Matrix/Solution.ts +++ b/lcci/01.08.Zero Matrix/Solution.ts @@ -4,43 +4,21 @@ function setZeroes(matrix: number[][]): void { const m = matrix.length; const n = matrix[0].length; - let l0 = false; - let r0 = false; - for (let i = 0; i < m; i++) { - if (matrix[i][0] === 0) { - l0 = true; - break; - } - } - for (let j = 0; j < n; j++) { - if (matrix[0][j] === 0) { - r0 = true; - break; - } - } + const rows = new Array(m).fill(false); + const cols = new Array(n).fill(false); for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { if (matrix[i][j] === 0) { - matrix[i][0] = 0; - matrix[0][j] = 0; + rows[i] = true; + cols[j] = true; } } } - for (let i = 1; i < m; i++) { - for (let j = 1; j < n; j++) { - if (matrix[i][0] === 0 || matrix[0][j] === 0) { + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (rows[i] || cols[j]) { matrix[i][j] = 0; } } } - if (l0) { - for (let i = 0; i < m; i++) { - matrix[i][0] = 0; - } - } - if (r0) { - for (let j = 0; j < n; j++) { - matrix[0][j] = 0; - } - } } diff --git a/lcci/01.08.Zero Matrix/Solution2.c b/lcci/01.08.Zero Matrix/Solution2.c new file mode 100644 index 0000000000000..6afafa3ee3aa2 --- /dev/null +++ b/lcci/01.08.Zero Matrix/Solution2.c @@ -0,0 +1,43 @@ +void setZeroes(int** matrix, int matrixSize, int* matrixColSize) { + int m = matrixSize; + int n = matrixColSize[0]; + int l0 = 0; + int r0 = 0; + for (int i = 0; i < m; i++) { + if (matrix[i][0] == 0) { + l0 = 1; + break; + } + } + for (int j = 0; j < n; j++) { + if (matrix[0][j] == 0) { + r0 = 1; + break; + } + } + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (matrix[i][j] == 0) { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + } + } + for (int i = 1; i < m; i++) { + for (int j = 1; j < n; j++) { + if (matrix[i][0] == 0 || matrix[0][j] == 0) { + matrix[i][j] = 0; + } + } + } + if (l0) { + for (int i = 0; i < m; i++) { + matrix[i][0] = 0; + } + } + if (r0) { + for (int j = 0; j < n; j++) { + matrix[0][j] = 0; + } + } +} \ No newline at end of file diff --git a/lcci/01.08.Zero Matrix/Solution2.cpp b/lcci/01.08.Zero Matrix/Solution2.cpp new file mode 100644 index 0000000000000..35fb03beee932 --- /dev/null +++ b/lcci/01.08.Zero Matrix/Solution2.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + void setZeroes(vector>& matrix) { + int m = matrix.size(), n = matrix[0].size(); + bool i0 = false, j0 = false; + for (int j = 0; j < n; ++j) { + if (matrix[0][j] == 0) { + i0 = true; + break; + } + } + for (int i = 0; i < m; ++i) { + if (matrix[i][0] == 0) { + j0 = true; + break; + } + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (matrix[i][j] == 0) { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + } + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (matrix[i][0] == 0 || matrix[0][j] == 0) { + matrix[i][j] = 0; + } + } + } + if (i0) { + for (int j = 0; j < n; ++j) { + matrix[0][j] = 0; + } + } + if (j0) { + for (int i = 0; i < m; ++i) { + matrix[i][0] = 0; + } + } + } +}; \ No newline at end of file diff --git a/lcci/01.08.Zero Matrix/Solution2.go b/lcci/01.08.Zero Matrix/Solution2.go new file mode 100644 index 0000000000000..563745744194b --- /dev/null +++ b/lcci/01.08.Zero Matrix/Solution2.go @@ -0,0 +1,40 @@ +func setZeroes(matrix [][]int) { + m, n := len(matrix), len(matrix[0]) + i0, j0 := false, false + for j := 0; j < n; j++ { + if matrix[0][j] == 0 { + i0 = true + break + } + } + for i := 0; i < m; i++ { + if matrix[i][0] == 0 { + j0 = true + break + } + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + if matrix[i][j] == 0 { + matrix[i][0], matrix[0][j] = 0, 0 + } + } + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + if matrix[i][0] == 0 || matrix[0][j] == 0 { + matrix[i][j] = 0 + } + } + } + if i0 { + for j := 0; j < n; j++ { + matrix[0][j] = 0 + } + } + if j0 { + for i := 0; i < m; i++ { + matrix[i][0] = 0 + } + } +} \ No newline at end of file diff --git a/lcci/01.08.Zero Matrix/Solution2.java b/lcci/01.08.Zero Matrix/Solution2.java new file mode 100644 index 0000000000000..dc71ae3359d35 --- /dev/null +++ b/lcci/01.08.Zero Matrix/Solution2.java @@ -0,0 +1,43 @@ +class Solution { + public void setZeroes(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + boolean i0 = false, j0 = false; + for (int j = 0; j < n; ++j) { + if (matrix[0][j] == 0) { + i0 = true; + break; + } + } + for (int i = 0; i < m; ++i) { + if (matrix[i][0] == 0) { + j0 = true; + break; + } + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (matrix[i][j] == 0) { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + } + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (matrix[i][0] == 0 || matrix[0][j] == 0) { + matrix[i][j] = 0; + } + } + } + if (i0) { + for (int j = 0; j < n; ++j) { + matrix[0][j] = 0; + } + } + if (j0) { + for (int i = 0; i < m; ++i) { + matrix[i][0] = 0; + } + } + } +} \ No newline at end of file diff --git a/lcci/01.08.Zero Matrix/Solution2.js b/lcci/01.08.Zero Matrix/Solution2.js new file mode 100644 index 0000000000000..88961eaf80b75 --- /dev/null +++ b/lcci/01.08.Zero Matrix/Solution2.js @@ -0,0 +1,41 @@ +/** + * @param {number[][]} matrix + * @return {void} Do not return anything, modify matrix in-place instead. + */ +var setZeroes = function (matrix) { + const m = matrix.length; + const n = matrix[0].length; + let i0 = matrix[0].some(v => v == 0); + let j0 = false; + for (let i = 0; i < m; ++i) { + if (matrix[i][0] == 0) { + j0 = true; + break; + } + } + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + if (matrix[i][j] == 0) { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + } + } + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + if (matrix[i][0] == 0 || matrix[0][j] == 0) { + matrix[i][j] = 0; + } + } + } + if (i0) { + for (let j = 0; j < n; ++j) { + matrix[0][j] = 0; + } + } + if (j0) { + for (let i = 0; i < m; ++i) { + matrix[i][0] = 0; + } + } +}; diff --git a/lcci/01.08.Zero Matrix/Solution2.py b/lcci/01.08.Zero Matrix/Solution2.py new file mode 100644 index 0000000000000..ec6ae77626f2a --- /dev/null +++ b/lcci/01.08.Zero Matrix/Solution2.py @@ -0,0 +1,19 @@ +class Solution: + def setZeroes(self, matrix: List[List[int]]) -> None: + m, n = len(matrix), len(matrix[0]) + i0 = any(v == 0 for v in matrix[0]) + j0 = any(matrix[i][0] == 0 for i in range(m)) + for i in range(1, m): + for j in range(1, n): + if matrix[i][j] == 0: + matrix[i][0] = matrix[0][j] = 0 + for i in range(1, m): + for j in range(1, n): + if matrix[i][0] == 0 or matrix[0][j] == 0: + matrix[i][j] = 0 + if i0: + for j in range(n): + matrix[0][j] = 0 + if j0: + for i in range(m): + matrix[i][0] = 0 diff --git a/lcci/01.08.Zero Matrix/Solution2.rs b/lcci/01.08.Zero Matrix/Solution2.rs new file mode 100644 index 0000000000000..d1168977a6bad --- /dev/null +++ b/lcci/01.08.Zero Matrix/Solution2.rs @@ -0,0 +1,51 @@ +impl Solution { + pub fn set_zeroes(matrix: &mut Vec>) { + let m = matrix.len(); + let n = matrix[0].len(); + let l0 = { + let mut res = false; + for j in 0..n { + if matrix[0][j] == 0 { + res = true; + break; + } + } + res + }; + let r0 = { + let mut res = false; + for i in 0..m { + if matrix[i][0] == 0 { + res = true; + break; + } + } + res + }; + for i in 0..m { + for j in 0..n { + if matrix[i][j] == 0 { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + } + } + for i in 1..m { + for j in 1..n { + if matrix[i][0] == 0 || matrix[0][j] == 0 { + matrix[i][j] = 0; + } + } + } + if l0 { + for j in 0..n { + matrix[0][j] = 0; + } + } + if r0 { + for i in 0..m { + matrix[i][0] = 0; + } + } + } +} diff --git a/lcci/01.08.Zero Matrix/Solution2.ts b/lcci/01.08.Zero Matrix/Solution2.ts new file mode 100644 index 0000000000000..cae9b1ded9555 --- /dev/null +++ b/lcci/01.08.Zero Matrix/Solution2.ts @@ -0,0 +1,46 @@ +/** + Do not return anything, modify matrix in-place instead. + */ +function setZeroes(matrix: number[][]): void { + const m = matrix.length; + const n = matrix[0].length; + let l0 = false; + let r0 = false; + for (let i = 0; i < m; i++) { + if (matrix[i][0] === 0) { + l0 = true; + break; + } + } + for (let j = 0; j < n; j++) { + if (matrix[0][j] === 0) { + r0 = true; + break; + } + } + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (matrix[i][j] === 0) { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + } + } + for (let i = 1; i < m; i++) { + for (let j = 1; j < n; j++) { + if (matrix[i][0] === 0 || matrix[0][j] === 0) { + matrix[i][j] = 0; + } + } + } + if (l0) { + for (let i = 0; i < m; i++) { + matrix[i][0] = 0; + } + } + if (r0) { + for (let j = 0; j < n; j++) { + matrix[0][j] = 0; + } + } +} diff --git a/lcci/01.09.String Rotation/Solution2.rs b/lcci/01.09.String Rotation/Solution2.rs new file mode 100644 index 0000000000000..56f1489dcc677 --- /dev/null +++ b/lcci/01.09.String Rotation/Solution2.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn is_fliped_string(s1: String, s2: String) -> bool { + if s1 == s2 { + return true; + } + if s1.len() != s2.len() { + return false; + } + let s2: Vec = (s2.clone() + &s2).chars().collect(); + let n = s1.len(); + let m = s2.len(); + for i in 0..m - n { + let mut is_pass = true; + for (j, c) in s1.chars().enumerate() { + if c != s2[i + j] { + is_pass = false; + break; + } + } + if is_pass { + return true; + } + } + false + } +} diff --git a/lcci/02.01.Remove Duplicate Node/Solution2.ts b/lcci/02.01.Remove Duplicate Node/Solution2.ts new file mode 100644 index 0000000000000..6074af6cc05cf --- /dev/null +++ b/lcci/02.01.Remove Duplicate Node/Solution2.ts @@ -0,0 +1,27 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function removeDuplicateNodes(head: ListNode | null): ListNode | null { + let n1 = head; + while (n1 != null) { + let n2 = n1; + while (n2.next != null) { + if (n1.val === n2.next.val) { + n2.next = n2.next.next; + } else { + n2 = n2.next; + } + } + n1 = n1.next; + } + return head; +} diff --git a/lcci/02.05.Sum Lists/Solution.java b/lcci/02.05.Sum Lists/Solution.java index e0fd988930406..1d8176d7c6c0f 100644 --- a/lcci/02.05.Sum Lists/Solution.java +++ b/lcci/02.05.Sum Lists/Solution.java @@ -8,14 +8,14 @@ */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { - ListNode dummy = new ListNode(0); - ListNode cur = dummy; int carry = 0; - while (l1 != null || l2 != null || carry > 0) { - carry += (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val); - cur.next = new ListNode(carry % 10); + ListNode dummy = new ListNode(-1); + ListNode cur = dummy; + while (l1 != null || l2 != null || carry != 0) { + int s = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; + carry = s / 10; + cur.next = new ListNode(s % 10); cur = cur.next; - carry /= 10; l1 = l1 == null ? null : l1.next; l2 = l2 == null ? null : l2.next; } diff --git a/lcci/02.06.Palindrome Linked List/Solution.cs b/lcci/02.06.Palindrome Linked List/Solution.cs index 235bc2036f168..47f9d260e262f 100644 --- a/lcci/02.06.Palindrome Linked List/Solution.cs +++ b/lcci/02.06.Palindrome Linked List/Solution.cs @@ -43,4 +43,4 @@ public bool IsPalindrome(ListNode head) { } return true; } -} \ No newline at end of file +} diff --git a/lcci/02.06.Palindrome Linked List/Solution2.ts b/lcci/02.06.Palindrome Linked List/Solution2.ts new file mode 100644 index 0000000000000..4088bd0df53ff --- /dev/null +++ b/lcci/02.06.Palindrome Linked List/Solution2.ts @@ -0,0 +1,26 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function isPalindrome(head: ListNode | null): boolean { + let root = head; + const dfs = (node: ListNode | null): boolean => { + if (node == null) { + return true; + } + if (dfs(node.next) && node.val === root.val) { + root = root.next; + return true; + } + return false; + }; + return dfs(head); +} diff --git a/lcci/03.01.Three in One/Solution.java b/lcci/03.01.Three in One/Solution.java index bf6d0b6a8d2e3..19916ea47f1f3 100644 --- a/lcci/03.01.Three in One/Solution.java +++ b/lcci/03.01.Three in One/Solution.java @@ -32,8 +32,10 @@ public boolean isEmpty(int stackNum) { } /** - * Your TripleInOne object will be instantiated and called as such: TripleInOne - * obj = new TripleInOne(stackSize); obj.push(stackNum,value); int param_2 = - * obj.pop(stackNum); int param_3 = obj.peek(stackNum); boolean param_4 = - * obj.isEmpty(stackNum); + * Your TripleInOne object will be instantiated and called as such: + * TripleInOne obj = new TripleInOne(stackSize); + * obj.push(stackNum,value); + * int param_2 = obj.pop(stackNum); + * int param_3 = obj.peek(stackNum); + * boolean param_4 = obj.isEmpty(stackNum); */ \ No newline at end of file diff --git a/lcci/03.02.Min Stack/Solution.cs b/lcci/03.02.Min Stack/Solution.cs index f56c4b3b07bd8..23c1cf7a8d41c 100644 --- a/lcci/03.02.Min Stack/Solution.cs +++ b/lcci/03.02.Min Stack/Solution.cs @@ -6,21 +6,21 @@ public class MinStack { public MinStack() { stk2.Push(int.MaxValue); } - + public void Push(int x) { stk1.Push(x); stk2.Push(Math.Min(x, GetMin())); } - + public void Pop() { stk1.Pop(); stk2.Pop(); } - + public int Top() { return stk1.Peek(); } - + public int GetMin() { return stk2.Peek(); } @@ -33,4 +33,4 @@ public int GetMin() { * obj.Pop(); * int param_3 = obj.Top(); * int param_4 = obj.GetMin(); - */ \ No newline at end of file + */ diff --git a/lcci/03.02.Min Stack/Solution.py b/lcci/03.02.Min Stack/Solution.py index 6d088cd10e860..a96818e41b3d4 100644 --- a/lcci/03.02.Min Stack/Solution.py +++ b/lcci/03.02.Min Stack/Solution.py @@ -1,26 +1,29 @@ class MinStack: def __init__(self): - self.stk1 = [] - self.stk2 = [inf] + """ + initialize your data structure here. + """ + self.s = [] + self.mins = [inf] - def push(self, x: int) -> None: - self.stk1.append(x) - self.stk2.append(min(x, self.stk2[-1])) + def push(self, val: int) -> None: + self.s.append(val) + self.mins.append(min(self.mins[-1], val)) def pop(self) -> None: - self.stk1.pop() - self.stk2.pop() + self.s.pop() + self.mins.pop() def top(self) -> int: - return self.stk1[-1] + return self.s[-1] def getMin(self) -> int: - return self.stk2[-1] + return self.mins[-1] # Your MinStack object will be instantiated and called as such: # obj = MinStack() -# obj.push(x) +# obj.push(val) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin() diff --git a/lcci/03.02.Min Stack/Solution.ts b/lcci/03.02.Min Stack/Solution.ts index 091a296221328..aa6dafc3fba70 100644 --- a/lcci/03.02.Min Stack/Solution.ts +++ b/lcci/03.02.Min Stack/Solution.ts @@ -1,28 +1,27 @@ class MinStack { - stk1: number[]; - stk2: number[]; - + stack: number[]; + mins: number[]; constructor() { - this.stk1 = []; - this.stk2 = [Infinity]; + this.stack = []; + this.mins = []; } push(x: number): void { - this.stk1.push(x); - this.stk2.push(Math.min(x, this.stk2[this.stk2.length - 1])); + this.stack.push(x); + this.mins.push(Math.min(this.getMin(), x)); } pop(): void { - this.stk1.pop(); - this.stk2.pop(); + this.stack.pop(); + this.mins.pop(); } top(): number { - return this.stk1[this.stk1.length - 1]; + return this.stack[this.stack.length - 1]; } getMin(): number { - return this.stk2[this.stk2.length - 1]; + return this.mins.length == 0 ? Infinity : this.mins[this.mins.length - 1]; } } diff --git a/lcci/03.03.Stack of Plates/Solution.ts b/lcci/03.03.Stack of Plates/Solution.ts index 7bcb51f05baac..4ffaea5bd89f1 100644 --- a/lcci/03.03.Stack of Plates/Solution.ts +++ b/lcci/03.03.Stack of Plates/Solution.ts @@ -1,12 +1,10 @@ class StackOfPlates { private cap: number; private stacks: number[][]; - constructor(cap: number) { this.cap = cap; this.stacks = []; } - push(val: number): void { if (this.cap === 0) { return; @@ -19,7 +17,6 @@ class StackOfPlates { stack.push(val); } } - pop(): number { const n = this.stacks.length; if (n === 0) { @@ -32,7 +29,6 @@ class StackOfPlates { } return res; } - popAt(index: number): number { if (index >= this.stacks.length) { return -1; @@ -45,7 +41,6 @@ class StackOfPlates { return res; } } - /** * Your StackOfPlates object will be instantiated and called as such: * var obj = new StackOfPlates(cap) diff --git a/lcci/03.05.Sort of Stacks/Solution2.ts b/lcci/03.05.Sort of Stacks/Solution2.ts new file mode 100644 index 0000000000000..3ca6e4c9c0eb2 --- /dev/null +++ b/lcci/03.05.Sort of Stacks/Solution2.ts @@ -0,0 +1,39 @@ +class SortedStack { + private stack: number[]; + + constructor() { + this.stack = []; + } + + push(val: number): void { + if (this.isEmpty() || this.peek() > val) { + this.stack.push(val); + return; + } + + const tmp = this.stack.pop(); + this.push(val); + this.stack.push(tmp); + } + + pop(): void { + this.stack.pop(); + } + + peek(): number { + return this.stack[this.stack.length - 1] ?? -1; + } + + isEmpty(): boolean { + return this.stack.length === 0; + } +} + +/** + * Your SortedStack object will be instantiated and called as such: + * var obj = new SortedStack() + * obj.push(val) + * obj.pop() + * var param_3 = obj.peek() + * var param_4 = obj.isEmpty() + */ diff --git a/lcci/04.01.Route Between Nodes/Solution.cpp b/lcci/04.01.Route Between Nodes/Solution.cpp index ea6f0c9fc3d4c..ff4932ba6ffb0 100644 --- a/lcci/04.01.Route Between Nodes/Solution.cpp +++ b/lcci/04.01.Route Between Nodes/Solution.cpp @@ -3,17 +3,16 @@ class Solution { bool findWhetherExistsPath(int n, vector>& graph, int start, int target) { unordered_map> g; for (auto& e : graph) g[e[0]].push_back(e[1]); - queue q{{start}}; unordered_set vis{{start}}; - while (!q.empty()) { - int u = q.front(); - if (u == target) return true; - q.pop(); - for (int v : g[u]) { - if (!vis.count(v)) { - vis.insert(v); - q.push(v); - } + return dfs(start, target, g, vis); + } + + bool dfs(int u, int& target, unordered_map>& g, unordered_set& vis) { + if (u == target) return true; + for (int& v : g[u]) { + if (!vis.count(v)) { + vis.insert(v); + if (dfs(v, target, g, vis)) return true; } } return false; diff --git a/lcci/04.01.Route Between Nodes/Solution.go b/lcci/04.01.Route Between Nodes/Solution.go index e38482dc19af0..a3cd970dd14aa 100644 --- a/lcci/04.01.Route Between Nodes/Solution.go +++ b/lcci/04.01.Route Between Nodes/Solution.go @@ -4,20 +4,21 @@ func findWhetherExistsPath(n int, graph [][]int, start int, target int) bool { u, v := e[0], e[1] g[u] = append(g[u], v) } - q := []int{start} vis := map[int]bool{start: true} - for len(q) > 0 { - u := q[0] + var dfs func(int) bool + dfs = func(u int) bool { if u == target { return true } - q = q[1:] for _, v := range g[u] { if !vis[v] { vis[v] = true - q = append(q, v) + if dfs(v) { + return true + } } } + return false } - return false + return dfs(start) } \ No newline at end of file diff --git a/lcci/04.01.Route Between Nodes/Solution.java b/lcci/04.01.Route Between Nodes/Solution.java index 958c95d8256e9..3437933773c01 100644 --- a/lcci/04.01.Route Between Nodes/Solution.java +++ b/lcci/04.01.Route Between Nodes/Solution.java @@ -4,19 +4,20 @@ public boolean findWhetherExistsPath(int n, int[][] graph, int start, int target for (int[] e : graph) { g.computeIfAbsent(e[0], k -> new ArrayList<>()).add(e[1]); } - Deque q = new ArrayDeque<>(); - q.offer(start); Set vis = new HashSet<>(); vis.add(start); - while (!q.isEmpty()) { - int u = q.poll(); - if (u == target) { - return true; - } - for (int v : g.getOrDefault(u, Collections.emptyList())) { - if (!vis.contains(v)) { - vis.add(v); - q.offer(v); + return dfs(start, target, g, vis); + } + + private boolean dfs(int u, int target, Map> g, Set vis) { + if (u == target) { + return true; + } + for (int v : g.getOrDefault(u, Collections.emptyList())) { + if (!vis.contains(v)) { + vis.add(v); + if (dfs(v, target, g, vis)) { + return true; } } } diff --git a/lcci/04.01.Route Between Nodes/Solution.py b/lcci/04.01.Route Between Nodes/Solution.py index 22db981ccfcd1..03bd2d58b8303 100644 --- a/lcci/04.01.Route Between Nodes/Solution.py +++ b/lcci/04.01.Route Between Nodes/Solution.py @@ -2,17 +2,18 @@ class Solution: def findWhetherExistsPath( self, n: int, graph: List[List[int]], start: int, target: int ) -> bool: - g = defaultdict(list) - for u, v in graph: - g[u].append(v) - q = deque([start]) - vis = {start} - while q: - u = q.popleft() + def dfs(u): if u == target: return True for v in g[u]: if v not in vis: vis.add(v) - q.append(v) - return False + if dfs(v): + return True + return False + + g = defaultdict(list) + for u, v in graph: + g[u].append(v) + vis = {start} + return dfs(start) diff --git a/lcci/04.01.Route Between Nodes/Solution2.cpp b/lcci/04.01.Route Between Nodes/Solution2.cpp new file mode 100644 index 0000000000000..ea6f0c9fc3d4c --- /dev/null +++ b/lcci/04.01.Route Between Nodes/Solution2.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + bool findWhetherExistsPath(int n, vector>& graph, int start, int target) { + unordered_map> g; + for (auto& e : graph) g[e[0]].push_back(e[1]); + queue q{{start}}; + unordered_set vis{{start}}; + while (!q.empty()) { + int u = q.front(); + if (u == target) return true; + q.pop(); + for (int v : g[u]) { + if (!vis.count(v)) { + vis.insert(v); + q.push(v); + } + } + } + return false; + } +}; \ No newline at end of file diff --git a/lcci/04.01.Route Between Nodes/Solution2.go b/lcci/04.01.Route Between Nodes/Solution2.go new file mode 100644 index 0000000000000..e38482dc19af0 --- /dev/null +++ b/lcci/04.01.Route Between Nodes/Solution2.go @@ -0,0 +1,23 @@ +func findWhetherExistsPath(n int, graph [][]int, start int, target int) bool { + g := map[int][]int{} + for _, e := range graph { + u, v := e[0], e[1] + g[u] = append(g[u], v) + } + q := []int{start} + vis := map[int]bool{start: true} + for len(q) > 0 { + u := q[0] + if u == target { + return true + } + q = q[1:] + for _, v := range g[u] { + if !vis[v] { + vis[v] = true + q = append(q, v) + } + } + } + return false +} \ No newline at end of file diff --git a/lcci/04.01.Route Between Nodes/Solution2.java b/lcci/04.01.Route Between Nodes/Solution2.java new file mode 100644 index 0000000000000..958c95d8256e9 --- /dev/null +++ b/lcci/04.01.Route Between Nodes/Solution2.java @@ -0,0 +1,25 @@ +class Solution { + public boolean findWhetherExistsPath(int n, int[][] graph, int start, int target) { + Map> g = new HashMap<>(); + for (int[] e : graph) { + g.computeIfAbsent(e[0], k -> new ArrayList<>()).add(e[1]); + } + Deque q = new ArrayDeque<>(); + q.offer(start); + Set vis = new HashSet<>(); + vis.add(start); + while (!q.isEmpty()) { + int u = q.poll(); + if (u == target) { + return true; + } + for (int v : g.getOrDefault(u, Collections.emptyList())) { + if (!vis.contains(v)) { + vis.add(v); + q.offer(v); + } + } + } + return false; + } +} \ No newline at end of file diff --git a/lcci/04.01.Route Between Nodes/Solution2.py b/lcci/04.01.Route Between Nodes/Solution2.py new file mode 100644 index 0000000000000..22db981ccfcd1 --- /dev/null +++ b/lcci/04.01.Route Between Nodes/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def findWhetherExistsPath( + self, n: int, graph: List[List[int]], start: int, target: int + ) -> bool: + g = defaultdict(list) + for u, v in graph: + g[u].append(v) + q = deque([start]) + vis = {start} + while q: + u = q.popleft() + if u == target: + return True + for v in g[u]: + if v not in vis: + vis.add(v) + q.append(v) + return False diff --git a/lcci/04.02.Minimum Height Tree/Solution.java b/lcci/04.02.Minimum Height Tree/Solution.java index b05dace659ffe..2e281a440e485 100644 --- a/lcci/04.02.Minimum Height Tree/Solution.java +++ b/lcci/04.02.Minimum Height Tree/Solution.java @@ -15,17 +15,11 @@ public TreeNode sortedArrayToBST(int[] nums) { return dfs(0, nums.length - 1); } - private TreeNode dfs(int i, int j) { - if (i > j) { + private TreeNode dfs(int l, int r) { + if (l > r) { return null; } - if (i == j) { - return new TreeNode(nums[i]); - } - int mid = (i + j) >>> 1; - TreeNode node = new TreeNode(nums[mid]); - node.left = dfs(i, mid - 1); - node.right = dfs(mid + 1, j); - return node; + int mid = (l + r) >> 1; + return new TreeNode(nums[mid], dfs(l, mid - 1), dfs(mid + 1, r)); } } \ No newline at end of file diff --git a/lcci/04.04.Check Balance/Solution.py b/lcci/04.04.Check Balance/Solution.py index 3667394cc7464..40fa1113909f4 100644 --- a/lcci/04.04.Check Balance/Solution.py +++ b/lcci/04.04.Check Balance/Solution.py @@ -10,10 +10,9 @@ class Solution: def isBalanced(self, root: TreeNode) -> bool: def dfs(root: TreeNode): if root is None: - return 0 - l, r = dfs(root.left), dfs(root.right) - if l == -1 or r == -1 or abs(l - r) > 1: - return -1 - return max(l, r) + 1 + return 0, True + a, b = dfs(root.left) + c, d = dfs(root.right) + return max(a, c) + 1, abs(a - c) <= 1 and b and d - return dfs(root) >= 0 + return dfs(root)[1] diff --git a/lcci/04.04.Check Balance/Solution2.py b/lcci/04.04.Check Balance/Solution2.py new file mode 100644 index 0000000000000..3667394cc7464 --- /dev/null +++ b/lcci/04.04.Check Balance/Solution2.py @@ -0,0 +1,19 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution: + def isBalanced(self, root: TreeNode) -> bool: + def dfs(root: TreeNode): + if root is None: + return 0 + l, r = dfs(root.left), dfs(root.right) + if l == -1 or r == -1 or abs(l - r) > 1: + return -1 + return max(l, r) + 1 + + return dfs(root) >= 0 diff --git a/lcci/04.05.Legal Binary Search Tree/Solution.go b/lcci/04.05.Legal Binary Search Tree/Solution.go index 36ec44dc85b02..aedd74b56e121 100644 --- a/lcci/04.05.Legal Binary Search Tree/Solution.go +++ b/lcci/04.05.Legal Binary Search Tree/Solution.go @@ -1,34 +1,20 @@ func isValidBST(root *TreeNode) bool { - return check(root, math.MinInt64, math.MaxInt64) -} - -func check(node *TreeNode, lower, upper int) bool { - if node == nil { - return true + stack := make([]*TreeNode, 0) + var prev *TreeNode = nil + node := root + for len(stack) > 0 || node != nil { + for node != nil { + stack = append(stack, node) + node = node.Left + } + node = stack[len(stack)-1] + stack = stack[:len(stack)-1] + if prev == nil || node.Val > prev.Val { + prev = node + } else { + return false + } + node = node.Right } - if node.Val <= lower || node.Val >= upper { - return false - } - return check(node.Left, lower, node.Val) && check(node.Right, node.Val, upper) -} - -// func isValidBST(root *TreeNode) bool { -// stack := make([]*TreeNode, 0) -// var prev *TreeNode = nil -// node := root -// for len(stack) > 0 || node != nil { -// for node != nil { -// stack = append(stack, node) -// node = node.Left -// } -// node = stack[len(stack)-1] -// stack = stack[:len(stack)-1] -// if prev == nil || node.Val > prev.Val { -// prev = node -// } else { -// return false -// } -// node = node.Right -// } -// return true -// } \ No newline at end of file + return true +} \ No newline at end of file diff --git a/lcci/04.05.Legal Binary Search Tree/Solution2.go b/lcci/04.05.Legal Binary Search Tree/Solution2.go new file mode 100644 index 0000000000000..3b33a98772bd4 --- /dev/null +++ b/lcci/04.05.Legal Binary Search Tree/Solution2.go @@ -0,0 +1,13 @@ +func isValidBST(root *TreeNode) bool { + return check(root, math.MinInt64, math.MaxInt64) +} + +func check(node *TreeNode, lower, upper int) bool { + if node == nil { + return true + } + if node.Val <= lower || node.Val >= upper { + return false + } + return check(node.Left, lower, node.Val) && check(node.Right, node.Val, upper) +} \ No newline at end of file diff --git a/lcci/04.05.Legal Binary Search Tree/Solution2.ts b/lcci/04.05.Legal Binary Search Tree/Solution2.ts new file mode 100644 index 0000000000000..2d831aa8d57f4 --- /dev/null +++ b/lcci/04.05.Legal Binary Search Tree/Solution2.ts @@ -0,0 +1,31 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function isValidBST(root: TreeNode | null): boolean { + if (root == null) { + return true; + } + const { val, left, right } = root; + const dfs = (root: TreeNode | null, min: number, max: number) => { + if (root == null) { + return true; + } + const { val, left, right } = root; + if (val <= min || val >= max) { + return false; + } + return dfs(left, min, Math.min(val, max)) && dfs(right, Math.max(val, min), max); + }; + return dfs(left, -Infinity, val) && dfs(right, val, Infinity); +} diff --git a/lcci/04.06.Successor/Solution2.cpp b/lcci/04.06.Successor/Solution2.cpp new file mode 100644 index 0000000000000..3bca6ead22e7d --- /dev/null +++ b/lcci/04.06.Successor/Solution2.cpp @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { + stack stk; + TreeNode* cur = root; + while (cur != nullptr || !stk.empty()) { + if (cur == nullptr) { + cur = stk.top(); + stk.pop(); + if (cur->val > p->val) { + return cur; + } + cur = cur->right; + } else { + stk.push(cur); + cur = cur->left; + } + } + return cur; + } +}; \ No newline at end of file diff --git a/lcci/04.06.Successor/Solution2.js b/lcci/04.06.Successor/Solution2.js new file mode 100644 index 0000000000000..3dd723e651175 --- /dev/null +++ b/lcci/04.06.Successor/Solution2.js @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} p + * @return {TreeNode} + */ +var inorderSuccessor = function (root, p) { + const stack = []; + let cur = root; + while (cur != null || stack.length !== 0) { + if (cur == null) { + cur = stack.pop(); + if (cur.val > p.val) { + return cur; + } + cur = cur.right; + } else { + stack.push(cur); + cur = cur.left; + } + } + return cur; +}; diff --git a/lcci/04.12.Paths with Sum/Solution.cpp b/lcci/04.12.Paths with Sum/Solution.cpp index 38017b4d754bc..72e43d0c492c0 100644 --- a/lcci/04.12.Paths with Sum/Solution.cpp +++ b/lcci/04.12.Paths with Sum/Solution.cpp @@ -1,29 +1,29 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - int pathSum(TreeNode* root, int sum) { - unordered_map cnt; - cnt[0] = 1; - function dfs = [&](TreeNode* root, long long s) { - if (!root) { - return 0; - } - s += root->val; - int ans = cnt[s - sum]; - ++cnt[s]; - ans += dfs(root->left, s); - ans += dfs(root->right, s); - --cnt[s]; - return ans; - }; - return dfs(root, 0); - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + int pathSum(TreeNode* root, int sum) { + unordered_map cnt; + cnt[0] = 1; + function dfs = [&](TreeNode* root, long long s) { + if (!root) { + return 0; + } + s += root->val; + int ans = cnt[s - sum]; + ++cnt[s]; + ans += dfs(root->left, s); + ans += dfs(root->right, s); + --cnt[s]; + return ans; + }; + return dfs(root, 0); + } }; \ No newline at end of file diff --git a/lcci/04.12.Paths with Sum/Solution.java b/lcci/04.12.Paths with Sum/Solution.java index 9a10048683e88..fe5baf9efb33a 100644 --- a/lcci/04.12.Paths with Sum/Solution.java +++ b/lcci/04.12.Paths with Sum/Solution.java @@ -1,32 +1,32 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -class Solution { - private Map cnt = new HashMap<>(); - private int target; - - public int pathSum(TreeNode root, int sum) { - cnt.put(0L, 1); - target = sum; - return dfs(root, 0); - } - - private int dfs(TreeNode root, long s) { - if (root == null) { - return 0; - } - s += root.val; - int ans = cnt.getOrDefault(s - target, 0); - cnt.merge(s, 1, Integer::sum); - ans += dfs(root.left, s); - ans += dfs(root.right, s); - cnt.merge(s, -1, Integer::sum); - return ans; - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + private Map cnt = new HashMap<>(); + private int target; + + public int pathSum(TreeNode root, int sum) { + cnt.put(0L, 1); + target = sum; + return dfs(root, 0); + } + + private int dfs(TreeNode root, long s) { + if (root == null) { + return 0; + } + s += root.val; + int ans = cnt.getOrDefault(s - target, 0); + cnt.merge(s, 1, Integer::sum); + ans += dfs(root.left, s); + ans += dfs(root.right, s); + cnt.merge(s, -1, Integer::sum); + return ans; + } } \ No newline at end of file diff --git a/lcci/04.12.Paths with Sum/Solution.py b/lcci/04.12.Paths with Sum/Solution.py index d7341ad78231f..096e03e07552b 100644 --- a/lcci/04.12.Paths with Sum/Solution.py +++ b/lcci/04.12.Paths with Sum/Solution.py @@ -1,23 +1,23 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None - - -class Solution: - def pathSum(self, root: TreeNode, sum: int) -> int: - def dfs(root: TreeNode, s: int): - if root is None: - return 0 - s += root.val - ans = cnt[s - sum] - cnt[s] += 1 - ans += dfs(root.left, s) - ans += dfs(root.right, s) - cnt[s] -= 1 - return ans - - cnt = Counter({0: 1}) - return dfs(root, 0) +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution: + def pathSum(self, root: TreeNode, sum: int) -> int: + def dfs(root: TreeNode, s: int): + if root is None: + return 0 + s += root.val + ans = cnt[s - sum] + cnt[s] += 1 + ans += dfs(root.left, s) + ans += dfs(root.right, s) + cnt[s] -= 1 + return ans + + cnt = Counter({0: 1}) + return dfs(root, 0) diff --git a/lcci/05.01.Insert Into Bits/Solution.cpp b/lcci/05.01.Insert Into Bits/Solution.cpp index 6cc0e83414ca1..7cb1f27609138 100644 --- a/lcci/05.01.Insert Into Bits/Solution.cpp +++ b/lcci/05.01.Insert Into Bits/Solution.cpp @@ -1,9 +1,9 @@ -class Solution { -public: - int insertBits(int N, int M, int i, int j) { - for (int k = i; k <= j; ++k) { - N &= ~(1 << k); - } - return N | M << i; - } +class Solution { +public: + int insertBits(int N, int M, int i, int j) { + for (int k = i; k <= j; ++k) { + N &= ~(1 << k); + } + return N | M << i; + } }; \ No newline at end of file diff --git a/lcci/05.01.Insert Into Bits/Solution.java b/lcci/05.01.Insert Into Bits/Solution.java index 609c0a97670e9..19b892fff2f64 100644 --- a/lcci/05.01.Insert Into Bits/Solution.java +++ b/lcci/05.01.Insert Into Bits/Solution.java @@ -1,8 +1,8 @@ -class Solution { - public int insertBits(int N, int M, int i, int j) { - for (int k = i; k <= j; ++k) { - N &= ~(1 << k); - } - return N | M << i; - } +class Solution { + public int insertBits(int N, int M, int i, int j) { + for (int k = i; k <= j; ++k) { + N &= ~(1 << k); + } + return N | M << i; + } } \ No newline at end of file diff --git a/lcci/05.01.Insert Into Bits/Solution.py b/lcci/05.01.Insert Into Bits/Solution.py index 061270ea598a2..45a78a33338f3 100644 --- a/lcci/05.01.Insert Into Bits/Solution.py +++ b/lcci/05.01.Insert Into Bits/Solution.py @@ -1,5 +1,5 @@ -class Solution: - def insertBits(self, N: int, M: int, i: int, j: int) -> int: - for k in range(i, j + 1): - N &= ~(1 << k) - return N | M << i +class Solution: + def insertBits(self, N: int, M: int, i: int, j: int) -> int: + for k in range(i, j + 1): + N &= ~(1 << k) + return N | M << i diff --git a/lcci/05.04.Closed Number/Solution.cpp b/lcci/05.04.Closed Number/Solution.cpp index 8484edb2a2f04..f351e78c41268 100644 --- a/lcci/05.04.Closed Number/Solution.cpp +++ b/lcci/05.04.Closed Number/Solution.cpp @@ -1,33 +1,33 @@ -class Solution { -public: - vector findClosedNumbers(int num) { - vector ans(2, -1); - int dirs[3] = {0, 1, 0}; - for (int p = 0; p < 2; ++p) { - int a = dirs[p], b = dirs[p + 1]; - int x = num; - for (int i = 1; i < 31; ++i) { - if ((x >> i & 1) == a && (x >> (i - 1) & 1) == b) { - x ^= 1 << i; - x ^= 1 << (i - 1); - int j = 0, k = i - 2; - while (j < k) { - while (j < k && (x >> j & 1) == b) { - ++j; - } - while (j < k && (x >> k & 1) == a) { - --k; - } - if (j < k) { - x ^= 1 << j; - x ^= 1 << k; - } - } - ans[p] = x; - break; - } - } - } - return ans; - } +class Solution { +public: + vector findClosedNumbers(int num) { + vector ans(2, -1); + int dirs[3] = {0, 1, 0}; + for (int p = 0; p < 2; ++p) { + int a = dirs[p], b = dirs[p + 1]; + int x = num; + for (int i = 1; i < 31; ++i) { + if ((x >> i & 1) == a && (x >> (i - 1) & 1) == b) { + x ^= 1 << i; + x ^= 1 << (i - 1); + int j = 0, k = i - 2; + while (j < k) { + while (j < k && (x >> j & 1) == b) { + ++j; + } + while (j < k && (x >> k & 1) == a) { + --k; + } + if (j < k) { + x ^= 1 << j; + x ^= 1 << k; + } + } + ans[p] = x; + break; + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/lcci/05.04.Closed Number/Solution.java b/lcci/05.04.Closed Number/Solution.java index 54c55251696dc..75c87d0ecd172 100644 --- a/lcci/05.04.Closed Number/Solution.java +++ b/lcci/05.04.Closed Number/Solution.java @@ -1,32 +1,32 @@ -class Solution { - public int[] findClosedNumbers(int num) { - int[] ans = {-1, -1}; - int[] dirs = {0, 1, 0}; - for (int p = 0; p < 2; ++p) { - int a = dirs[p], b = dirs[p + 1]; - int x = num; - for (int i = 1; i < 31; ++i) { - if ((x >> i & 1) == a && (x >> (i - 1) & 1) == b) { - x ^= 1 << i; - x ^= 1 << (i - 1); - int j = 0, k = i - 2; - while (j < k) { - while (j < k && (x >> j & 1) == b) { - ++j; - } - while (j < k && (x >> k & 1) == a) { - --k; - } - if (j < k) { - x ^= 1 << j; - x ^= 1 << k; - } - } - ans[p] = x; - break; - } - } - } - return ans; - } +class Solution { + public int[] findClosedNumbers(int num) { + int[] ans = {-1, -1}; + int[] dirs = {0, 1, 0}; + for (int p = 0; p < 2; ++p) { + int a = dirs[p], b = dirs[p + 1]; + int x = num; + for (int i = 1; i < 31; ++i) { + if ((x >> i & 1) == a && (x >> (i - 1) & 1) == b) { + x ^= 1 << i; + x ^= 1 << (i - 1); + int j = 0, k = i - 2; + while (j < k) { + while (j < k && (x >> j & 1) == b) { + ++j; + } + while (j < k && (x >> k & 1) == a) { + --k; + } + if (j < k) { + x ^= 1 << j; + x ^= 1 << k; + } + } + ans[p] = x; + break; + } + } + } + return ans; + } } \ No newline at end of file diff --git a/lcci/05.04.Closed Number/Solution.py b/lcci/05.04.Closed Number/Solution.py index f5a97bf1d2219..3381a9784da8b 100644 --- a/lcci/05.04.Closed Number/Solution.py +++ b/lcci/05.04.Closed Number/Solution.py @@ -1,23 +1,23 @@ -class Solution: - def findClosedNumbers(self, num: int) -> List[int]: - ans = [-1] * 2 - dirs = (0, 1, 0) - for p in range(2): - a, b = dirs[p], dirs[p + 1] - x = num - for i in range(1, 31): - if (x >> i & 1) == a and (x >> (i - 1) & 1) == b: - x ^= 1 << i - x ^= 1 << (i - 1) - j, k = 0, i - 2 - while j < k: - while j < k and (x >> j & 1) == b: - j += 1 - while j < k and (x >> k & 1) == a: - k -= 1 - if j < k: - x ^= 1 << j - x ^= 1 << k - ans[p] = x - break - return ans +class Solution: + def findClosedNumbers(self, num: int) -> List[int]: + ans = [-1] * 2 + dirs = (0, 1, 0) + for p in range(2): + a, b = dirs[p], dirs[p + 1] + x = num + for i in range(1, 31): + if (x >> i & 1) == a and (x >> (i - 1) & 1) == b: + x ^= 1 << i + x ^= 1 << (i - 1) + j, k = 0, i - 2 + while j < k: + while j < k and (x >> j & 1) == b: + j += 1 + while j < k and (x >> k & 1) == a: + k -= 1 + if j < k: + x ^= 1 << j + x ^= 1 << k + ans[p] = x + break + return ans diff --git a/lcci/05.07.Exchange/Solution.cpp b/lcci/05.07.Exchange/Solution.cpp index 2b0b443c35f09..b0158ec5e00b9 100644 --- a/lcci/05.07.Exchange/Solution.cpp +++ b/lcci/05.07.Exchange/Solution.cpp @@ -1,6 +1,6 @@ -class Solution { -public: - int exchangeBits(int num) { - return ((num & 0x55555555) << 1) | ((num & 0xaaaaaaaa)) >> 1; - } +class Solution { +public: + int exchangeBits(int num) { + return ((num & 0x55555555) << 1) | ((num & 0xaaaaaaaa)) >> 1; + } }; \ No newline at end of file diff --git a/lcci/05.07.Exchange/Solution.java b/lcci/05.07.Exchange/Solution.java index dfd561144f6a3..fe66579e0e0d6 100644 --- a/lcci/05.07.Exchange/Solution.java +++ b/lcci/05.07.Exchange/Solution.java @@ -1,5 +1,5 @@ -class Solution { - public int exchangeBits(int num) { - return ((num & 0x55555555) << 1) | ((num & 0xaaaaaaaa)) >> 1; - } +class Solution { + public int exchangeBits(int num) { + return ((num & 0x55555555) << 1) | ((num & 0xaaaaaaaa)) >> 1; + } } \ No newline at end of file diff --git a/lcci/05.07.Exchange/Solution.py b/lcci/05.07.Exchange/Solution.py index f56cf488e207b..1ebd7c1a45b98 100644 --- a/lcci/05.07.Exchange/Solution.py +++ b/lcci/05.07.Exchange/Solution.py @@ -1,3 +1,3 @@ -class Solution: - def exchangeBits(self, num: int) -> int: - return ((num & 0x55555555) << 1) | ((num & 0xAAAAAAAA) >> 1) +class Solution: + def exchangeBits(self, num: int) -> int: + return ((num & 0x55555555) << 1) | ((num & 0xAAAAAAAA) >> 1) diff --git a/lcci/08.01.Three Steps Problem/Solution.c b/lcci/08.01.Three Steps Problem/Solution.c index acadb8f9c1537..dfaddfd5b3189 100644 --- a/lcci/08.01.Three Steps Problem/Solution.c +++ b/lcci/08.01.Three Steps Problem/Solution.c @@ -1,11 +1,11 @@ -int waysToStep(int n) { - const int mod = 1e9 + 7; - int a = 1, b = 2, c = 4; - for (int i = 1; i < n; ++i) { - int t = a; - a = b; - b = c; - c = (((a + b) % mod) + t) % mod; - } - return a; +int waysToStep(int n) { + const int mod = 1e9 + 7; + int a = 1, b = 2, c = 4; + for (int i = 1; i < n; ++i) { + int t = a; + a = b; + b = c; + c = (((a + b) % mod) + t) % mod; + } + return a; } \ No newline at end of file diff --git a/lcci/08.01.Three Steps Problem/Solution.cpp b/lcci/08.01.Three Steps Problem/Solution.cpp index 624aa921c5aa0..26f6f352b2579 100644 --- a/lcci/08.01.Three Steps Problem/Solution.cpp +++ b/lcci/08.01.Three Steps Problem/Solution.cpp @@ -1,43 +1,14 @@ -class Solution { -public: - int waysToStep(int n) { - if (n < 4) { - return pow(2, n - 1); - } - vector> a = {{1, 1, 0}, {1, 0, 1}, {1, 0, 0}}; - vector> res = qpow(a, n - 4); - ll ans = 0; - for (ll x : res[0]) { - ans = (ans + x) % mod; - } - return ans; - } - -private: - using ll = long long; - const int mod = 1e9 + 7; - vector> mul(vector>& a, vector>& b) { - int m = a.size(), n = b[0].size(); - vector> c(m, vector(n)); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - for (int k = 0; k < b.size(); ++k) { - c[i][j] = (c[i][j] + a[i][k] * b[k][j] % mod) % mod; - } - } - } - return c; - } - - vector> qpow(vector>& a, int n) { - vector> res = {{4, 2, 1}}; - while (n) { - if (n & 1) { - res = mul(res, a); - } - a = mul(a, a); - n >>= 1; - } - return res; - } +class Solution { +public: + int waysToStep(int n) { + const int mod = 1e9 + 7; + int a = 1, b = 2, c = 4; + for (int i = 1; i < n; ++i) { + int t = a; + a = b; + b = c; + c = (((a + b) % mod) + t) % mod; + } + return a; + } }; \ No newline at end of file diff --git a/lcci/08.01.Three Steps Problem/Solution.go b/lcci/08.01.Three Steps Problem/Solution.go index 905e5ead86930..c1ff57807c924 100644 --- a/lcci/08.01.Three Steps Problem/Solution.go +++ b/lcci/08.01.Three Steps Problem/Solution.go @@ -1,41 +1,8 @@ -const mod = 1e9 + 7 - -func waysToStep(n int) (ans int) { - if n < 4 { - return int(math.Pow(2, float64(n-1))) +func waysToStep(n int) int { + const mod int = 1e9 + 7 + a, b, c := 1, 2, 4 + for i := 1; i < n; i++ { + a, b, c = b, c, (a+b+c)%mod } - a := [][]int{{1, 1, 0}, {1, 0, 1}, {1, 0, 0}} - res := pow(a, n-4) - for _, x := range res[0] { - ans = (ans + x) % mod - } - return -} - -func mul(a, b [][]int) [][]int { - m, n := len(a), len(b[0]) - c := make([][]int, m) - for i := range c { - c[i] = make([]int, n) - } - for i := 0; i < m; i++ { - for j := 0; j < n; j++ { - for k := 0; k < len(b); k++ { - c[i][j] = (c[i][j] + a[i][k]*b[k][j]%mod) % mod - } - } - } - return c -} - -func pow(a [][]int, n int) [][]int { - res := [][]int{{4, 2, 1}} - for n > 0 { - if n&1 == 1 { - res = mul(res, a) - } - a = mul(a, a) - n >>= 1 - } - return res + return a } \ No newline at end of file diff --git a/lcci/08.01.Three Steps Problem/Solution.java b/lcci/08.01.Three Steps Problem/Solution.java index 01d877b28ceb7..23e7d230c7ad0 100644 --- a/lcci/08.01.Three Steps Problem/Solution.java +++ b/lcci/08.01.Three Steps Problem/Solution.java @@ -1,41 +1,13 @@ -class Solution { - private final int mod = (int) 1e9 + 7; - - public int waysToStep(int n) { - if (n < 4) { - return (int) Math.pow(2, n - 1); - } - long[][] a = {{1, 1, 0}, {1, 0, 1}, {1, 0, 0}}; - long[][] res = pow(a, n - 4); - long ans = 0; - for (long x : res[0]) { - ans = (ans + x) % mod; - } - return (int) ans; - } - - private long[][] mul(long[][] a, long[][] b) { - int m = a.length, n = b[0].length; - long[][] c = new long[m][n]; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - for (int k = 0; k < b.length; ++k) { - c[i][j] = (c[i][j] + a[i][k] * b[k][j] % mod) % mod; - } - } - } - return c; - } - - private long[][] pow(long[][] a, int n) { - long[][] res = {{4, 2, 1}}; - while (n > 0) { - if ((n & 1) == 1) { - res = mul(res, a); - } - a = mul(a, a); - n >>= 1; - } - return res; - } +class Solution { + public int waysToStep(int n) { + final int mod = (int) 1e9 + 7; + int a = 1, b = 2, c = 4; + for (int i = 1; i < n; ++i) { + int t = a; + a = b; + b = c; + c = (((a + b) % mod) + t) % mod; + } + return a; + } } \ No newline at end of file diff --git a/lcci/08.01.Three Steps Problem/Solution.js b/lcci/08.01.Three Steps Problem/Solution.js index c72c9b3227922..a7e516a3bf725 100644 --- a/lcci/08.01.Three Steps Problem/Solution.js +++ b/lcci/08.01.Three Steps Problem/Solution.js @@ -2,48 +2,11 @@ * @param {number} n * @return {number} */ - -const mod = 1e9 + 7; - var waysToStep = function (n) { - if (n < 4) { - return Math.pow(2, n - 1); + let [a, b, c] = [1, 2, 4]; + const mod = 1e9 + 7; + for (let i = 1; i < n; ++i) { + [a, b, c] = [b, c, (a + b + c) % mod]; } - const a = [ - [1, 1, 0], - [1, 0, 1], - [1, 0, 0], - ]; - let ans = 0; - const res = pow(a, n - 4); - for (const x of res[0]) { - ans = (ans + x) % mod; - } - return ans; + return a; }; - -function mul(a, b) { - const [m, n] = [a.length, b[0].length]; - const c = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - for (let k = 0; k < b.length; ++k) { - c[i][j] = - (c[i][j] + Number((BigInt(a[i][k]) * BigInt(b[k][j])) % BigInt(mod))) % mod; - } - } - } - return c; -} - -function pow(a, n) { - let res = [[4, 2, 1]]; - while (n) { - if (n & 1) { - res = mul(res, a); - } - a = mul(a, a); - n >>= 1; - } - return res; -} diff --git a/lcci/08.01.Three Steps Problem/Solution.py b/lcci/08.01.Three Steps Problem/Solution.py index 5881de452de2d..41b8500d5f509 100644 --- a/lcci/08.01.Three Steps Problem/Solution.py +++ b/lcci/08.01.Three Steps Problem/Solution.py @@ -1,17 +1,7 @@ -import numpy as np - - -class Solution: - def waysToStep(self, n: int) -> int: - if n < 4: - return 2 ** (n - 1) - mod = 10**9 + 7 - factor = np.mat([(1, 1, 0), (1, 0, 1), (1, 0, 0)], np.dtype("O")) - res = np.mat([(4, 2, 1)], np.dtype("O")) - n -= 4 - while n: - if n & 1: - res = res * factor % mod - factor = factor * factor % mod - n >>= 1 - return res.sum() % mod +class Solution: + def waysToStep(self, n: int) -> int: + a, b, c = 1, 2, 4 + mod = 10**9 + 7 + for _ in range(n - 1): + a, b, c = b, c, (a + b + c) % mod + return a diff --git a/lcci/08.01.Three Steps Problem/Solution2.cpp b/lcci/08.01.Three Steps Problem/Solution2.cpp new file mode 100644 index 0000000000000..0ea6601a423e1 --- /dev/null +++ b/lcci/08.01.Three Steps Problem/Solution2.cpp @@ -0,0 +1,43 @@ +class Solution { +public: + int waysToStep(int n) { + if (n < 4) { + return pow(2, n - 1); + } + vector> a = {{1, 1, 0}, {1, 0, 1}, {1, 0, 0}}; + vector> res = qpow(a, n - 4); + ll ans = 0; + for (ll x : res[0]) { + ans = (ans + x) % mod; + } + return ans; + } + +private: + using ll = long long; + const int mod = 1e9 + 7; + vector> mul(vector>& a, vector>& b) { + int m = a.size(), n = b[0].size(); + vector> c(m, vector(n)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k < b.size(); ++k) { + c[i][j] = (c[i][j] + a[i][k] * b[k][j] % mod) % mod; + } + } + } + return c; + } + + vector> qpow(vector>& a, int n) { + vector> res = {{4, 2, 1}}; + while (n) { + if (n & 1) { + res = mul(res, a); + } + a = mul(a, a); + n >>= 1; + } + return res; + } +}; \ No newline at end of file diff --git a/lcci/08.01.Three Steps Problem/Solution2.go b/lcci/08.01.Three Steps Problem/Solution2.go new file mode 100644 index 0000000000000..905e5ead86930 --- /dev/null +++ b/lcci/08.01.Three Steps Problem/Solution2.go @@ -0,0 +1,41 @@ +const mod = 1e9 + 7 + +func waysToStep(n int) (ans int) { + if n < 4 { + return int(math.Pow(2, float64(n-1))) + } + a := [][]int{{1, 1, 0}, {1, 0, 1}, {1, 0, 0}} + res := pow(a, n-4) + for _, x := range res[0] { + ans = (ans + x) % mod + } + return +} + +func mul(a, b [][]int) [][]int { + m, n := len(a), len(b[0]) + c := make([][]int, m) + for i := range c { + c[i] = make([]int, n) + } + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + for k := 0; k < len(b); k++ { + c[i][j] = (c[i][j] + a[i][k]*b[k][j]%mod) % mod + } + } + } + return c +} + +func pow(a [][]int, n int) [][]int { + res := [][]int{{4, 2, 1}} + for n > 0 { + if n&1 == 1 { + res = mul(res, a) + } + a = mul(a, a) + n >>= 1 + } + return res +} \ No newline at end of file diff --git a/lcci/08.01.Three Steps Problem/Solution2.java b/lcci/08.01.Three Steps Problem/Solution2.java new file mode 100644 index 0000000000000..92cf4105d1edc --- /dev/null +++ b/lcci/08.01.Three Steps Problem/Solution2.java @@ -0,0 +1,41 @@ +class Solution { + private final int mod = (int) 1e9 + 7; + + public int waysToStep(int n) { + if (n < 4) { + return (int) Math.pow(2, n - 1); + } + long[][] a = {{1, 1, 0}, {1, 0, 1}, {1, 0, 0}}; + long[][] res = pow(a, n - 4); + long ans = 0; + for (long x : res[0]) { + ans = (ans + x) % mod; + } + return (int) ans; + } + + private long[][] mul(long[][] a, long[][] b) { + int m = a.length, n = b[0].length; + long[][] c = new long[m][n]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k < b.length; ++k) { + c[i][j] = (c[i][j] + a[i][k] * b[k][j] % mod) % mod; + } + } + } + return c; + } + + private long[][] pow(long[][] a, int n) { + long[][] res = {{4, 2, 1}}; + while (n > 0) { + if ((n & 1) == 1) { + res = mul(res, a); + } + a = mul(a, a); + n >>= 1; + } + return res; + } +} \ No newline at end of file diff --git a/lcci/08.01.Three Steps Problem/Solution2.js b/lcci/08.01.Three Steps Problem/Solution2.js new file mode 100644 index 0000000000000..c72c9b3227922 --- /dev/null +++ b/lcci/08.01.Three Steps Problem/Solution2.js @@ -0,0 +1,49 @@ +/** + * @param {number} n + * @return {number} + */ + +const mod = 1e9 + 7; + +var waysToStep = function (n) { + if (n < 4) { + return Math.pow(2, n - 1); + } + const a = [ + [1, 1, 0], + [1, 0, 1], + [1, 0, 0], + ]; + let ans = 0; + const res = pow(a, n - 4); + for (const x of res[0]) { + ans = (ans + x) % mod; + } + return ans; +}; + +function mul(a, b) { + const [m, n] = [a.length, b[0].length]; + const c = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + for (let k = 0; k < b.length; ++k) { + c[i][j] = + (c[i][j] + Number((BigInt(a[i][k]) * BigInt(b[k][j])) % BigInt(mod))) % mod; + } + } + } + return c; +} + +function pow(a, n) { + let res = [[4, 2, 1]]; + while (n) { + if (n & 1) { + res = mul(res, a); + } + a = mul(a, a); + n >>= 1; + } + return res; +} diff --git a/lcci/08.01.Three Steps Problem/Solution2.py b/lcci/08.01.Three Steps Problem/Solution2.py new file mode 100644 index 0000000000000..47973c3c6b40d --- /dev/null +++ b/lcci/08.01.Three Steps Problem/Solution2.py @@ -0,0 +1,26 @@ +class Solution: + def waysToStep(self, n: int) -> int: + mod = 10**9 + 7 + + def mul(a: List[List[int]], b: List[List[int]]) -> List[List[int]]: + m, n = len(a), len(b[0]) + c = [[0] * n for _ in range(m)] + for i in range(m): + for j in range(n): + for k in range(len(a[0])): + c[i][j] = (c[i][j] + a[i][k] * b[k][j] % mod) % mod + return c + + def pow(a: List[List[int]], n: int) -> List[List[int]]: + res = [[4, 2, 1]] + while n: + if n & 1: + res = mul(res, a) + n >>= 1 + a = mul(a, a) + return res + + if n < 4: + return 2 ** (n - 1) + a = [[1, 1, 0], [1, 0, 1], [1, 0, 0]] + return sum(pow(a, n - 4)[0]) % mod diff --git a/lcci/08.01.Three Steps Problem/Solution3.py b/lcci/08.01.Three Steps Problem/Solution3.py new file mode 100644 index 0000000000000..7ee79117fbbaa --- /dev/null +++ b/lcci/08.01.Three Steps Problem/Solution3.py @@ -0,0 +1,17 @@ +import numpy as np + + +class Solution: + def waysToStep(self, n: int) -> int: + if n < 4: + return 2 ** (n - 1) + mod = 10**9 + 7 + factor = np.mat([(1, 1, 0), (1, 0, 1), (1, 0, 0)], np.dtype("O")) + res = np.mat([(4, 2, 1)], np.dtype("O")) + n -= 4 + while n: + if n & 1: + res = res * factor % mod + factor = factor * factor % mod + n >>= 1 + return res.sum() % mod diff --git a/lcci/08.03.Magic Index/Solution.rs b/lcci/08.03.Magic Index/Solution.rs index cd13572072eff..f5674a654709a 100644 --- a/lcci/08.03.Magic Index/Solution.rs +++ b/lcci/08.03.Magic Index/Solution.rs @@ -1,14 +1,22 @@ impl Solution { - pub fn find_magic_index(nums: Vec) -> i32 { - let n = nums.len(); - let mut i = 0 as i32; - while (i as usize) < n { - let num = nums[i as usize]; - if num == i { - return i; + fn find(nums: &Vec, l: usize, r: usize) -> i32 { + if l >= r || nums[r - 1] < 0 { + return -1; + } + let mid = l + (r - l) / 2; + if nums[mid] >= (l as i32) { + let res = Self::find(nums, l, mid); + if res != -1 { + return res; } - i = num.max(i + 1); } - -1 + if nums[mid] == (mid as i32) { + return mid as i32; + } + Self::find(nums, mid + 1, r) + } + + pub fn find_magic_index(nums: Vec) -> i32 { + Self::find(&nums, 0, nums.len()) } } diff --git a/lcci/08.03.Magic Index/Solution.ts b/lcci/08.03.Magic Index/Solution.ts index 09a988aa75c36..74db52ca16bf0 100644 --- a/lcci/08.03.Magic Index/Solution.ts +++ b/lcci/08.03.Magic Index/Solution.ts @@ -1,11 +1,20 @@ function findMagicIndex(nums: number[]): number { const n = nums.length; - let i = 0; - while (i < n) { - if (nums[i] === i) { - return i; + const find = (l: number, r: number): number => { + if (l > r || nums[r] < 0) { + return -1; } - i = Math.max(nums[i], i + 1); - } - return -1; + const mid = l + Math.floor((r - l) / 2); + if (nums[mid] >= l) { + const res = find(l, mid - 1); + if (res !== -1) { + return res; + } + } + if (nums[mid] === mid) { + return mid; + } + return find(mid + 1, r); + }; + return find(0, n - 1); } diff --git a/lcci/08.03.Magic Index/Solution2.rs b/lcci/08.03.Magic Index/Solution2.rs new file mode 100644 index 0000000000000..cd13572072eff --- /dev/null +++ b/lcci/08.03.Magic Index/Solution2.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn find_magic_index(nums: Vec) -> i32 { + let n = nums.len(); + let mut i = 0 as i32; + while (i as usize) < n { + let num = nums[i as usize]; + if num == i { + return i; + } + i = num.max(i + 1); + } + -1 + } +} diff --git a/lcci/08.03.Magic Index/Solution2.ts b/lcci/08.03.Magic Index/Solution2.ts new file mode 100644 index 0000000000000..09a988aa75c36 --- /dev/null +++ b/lcci/08.03.Magic Index/Solution2.ts @@ -0,0 +1,11 @@ +function findMagicIndex(nums: number[]): number { + const n = nums.length; + let i = 0; + while (i < n) { + if (nums[i] === i) { + return i; + } + i = Math.max(nums[i], i + 1); + } + return -1; +} diff --git a/lcci/08.04.Power Set/Solution.cpp b/lcci/08.04.Power Set/Solution.cpp index 06b20c1afb02b..46e0677f2c149 100644 --- a/lcci/08.04.Power Set/Solution.cpp +++ b/lcci/08.04.Power Set/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - vector> subsets(vector& nums) { - vector> ans; - vector t; - dfs(0, nums, t, ans); - return ans; - } - - void dfs(int u, vector& nums, vector& t, vector>& ans) { - if (u == nums.size()) { - ans.push_back(t); - return; - } - dfs(u + 1, nums, t, ans); - t.push_back(nums[u]); - dfs(u + 1, nums, t, ans); - t.pop_back(); - } +class Solution { +public: + vector> subsets(vector& nums) { + vector> ans; + vector t; + dfs(0, nums, t, ans); + return ans; + } + + void dfs(int u, vector& nums, vector& t, vector>& ans) { + if (u == nums.size()) { + ans.push_back(t); + return; + } + dfs(u + 1, nums, t, ans); + t.push_back(nums[u]); + dfs(u + 1, nums, t, ans); + t.pop_back(); + } }; \ No newline at end of file diff --git a/lcci/08.04.Power Set/Solution.java b/lcci/08.04.Power Set/Solution.java index ae9595bf98f77..0bb08413a151c 100644 --- a/lcci/08.04.Power Set/Solution.java +++ b/lcci/08.04.Power Set/Solution.java @@ -1,21 +1,21 @@ -class Solution { - private List> ans = new ArrayList<>(); - private int[] nums; - - public List> subsets(int[] nums) { - this.nums = nums; - dfs(0, new ArrayList<>()); - return ans; - } - - private void dfs(int u, List t) { - if (u == nums.length) { - ans.add(new ArrayList<>(t)); - return; - } - dfs(u + 1, t); - t.add(nums[u]); - dfs(u + 1, t); - t.remove(t.size() - 1); - } +class Solution { + private List> ans = new ArrayList<>(); + private int[] nums; + + public List> subsets(int[] nums) { + this.nums = nums; + dfs(0, new ArrayList<>()); + return ans; + } + + private void dfs(int u, List t) { + if (u == nums.length) { + ans.add(new ArrayList<>(t)); + return; + } + dfs(u + 1, t); + t.add(nums[u]); + dfs(u + 1, t); + t.remove(t.size() - 1); + } } \ No newline at end of file diff --git a/lcci/08.04.Power Set/Solution.py b/lcci/08.04.Power Set/Solution.py index cc8a44878889d..884162448f700 100644 --- a/lcci/08.04.Power Set/Solution.py +++ b/lcci/08.04.Power Set/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def subsets(self, nums: List[int]) -> List[List[int]]: - def dfs(u, t): - if u == len(nums): - ans.append(t[:]) - return - t.append(nums[u]) - dfs(u + 1, t) - t.pop() - dfs(u + 1, t) - - ans = [] - dfs(0, []) - return ans +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: + def dfs(u, t): + if u == len(nums): + ans.append(t[:]) + return + dfs(u + 1, t) + t.append(nums[u]) + dfs(u + 1, t) + t.pop() + + ans = [] + dfs(0, []) + return ans diff --git a/lcci/08.04.Power Set/Solution.rs b/lcci/08.04.Power Set/Solution.rs index a7523d370fc9c..70c964d892208 100644 --- a/lcci/08.04.Power Set/Solution.rs +++ b/lcci/08.04.Power Set/Solution.rs @@ -1,18 +1,12 @@ impl Solution { - fn dfs(nums: &Vec, i: usize, res: &mut Vec>, list: &mut Vec) { - if i == nums.len() { - res.push(list.clone()); - return; - } - list.push(nums[i]); - Self::dfs(nums, i + 1, res, list); - list.pop(); - Self::dfs(nums, i + 1, res, list); - } - pub fn subsets(nums: Vec) -> Vec> { - let mut res = vec![]; - Self::dfs(&nums, 0, &mut res, &mut vec![]); + let n = nums.len(); + let mut res: Vec> = vec![vec![]]; + for i in 0..n { + for j in 0..res.len() { + res.push(vec![..res[j].clone(), vec![nums[i]]].concat()); + } + } res } } diff --git a/lcci/08.04.Power Set/Solution.ts b/lcci/08.04.Power Set/Solution.ts index 1b908e9c8a6e2..06cca054dfac3 100644 --- a/lcci/08.04.Power Set/Solution.ts +++ b/lcci/08.04.Power Set/Solution.ts @@ -1,17 +1,9 @@ function subsets(nums: number[]): number[][] { - const n = nums.length; - const res = []; - const list = []; - const dfs = (i: number) => { - if (i === n) { - res.push([...list]); - return; - } - list.push(nums[i]); - dfs(i + 1); - list.pop(); - dfs(i + 1); - }; - dfs(0); + const res = [[]]; + nums.forEach(num => { + res.forEach(item => { + res.push(item.concat(num)); + }); + }); return res; } diff --git a/lcci/08.04.Power Set/Solution2.cpp b/lcci/08.04.Power Set/Solution2.cpp new file mode 100644 index 0000000000000..2b01f1ac8c99b --- /dev/null +++ b/lcci/08.04.Power Set/Solution2.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + vector> subsets(vector& nums) { + vector> ans; + vector t; + int n = nums.size(); + for (int mask = 0; mask < 1 << n; ++mask) { + t.clear(); + for (int i = 0; i < n; ++i) { + if ((mask >> i) & 1) { + t.push_back(nums[i]); + } + } + ans.push_back(t); + } + return ans; + } +}; \ No newline at end of file diff --git a/lcci/08.04.Power Set/Solution2.go b/lcci/08.04.Power Set/Solution2.go new file mode 100644 index 0000000000000..d1bd6248c887d --- /dev/null +++ b/lcci/08.04.Power Set/Solution2.go @@ -0,0 +1,14 @@ +func subsets(nums []int) [][]int { + var ans [][]int + n := len(nums) + for mask := 0; mask < 1<> i) & 1) == 1 { + t = append(t, v) + } + } + ans = append(ans, t) + } + return ans +} \ No newline at end of file diff --git a/lcci/08.04.Power Set/Solution2.java b/lcci/08.04.Power Set/Solution2.java new file mode 100644 index 0000000000000..8a20bcc9d3fb7 --- /dev/null +++ b/lcci/08.04.Power Set/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public List> subsets(int[] nums) { + int n = nums.length; + List> ans = new ArrayList<>(); + for (int mask = 0; mask < 1 << n; ++mask) { + List t = new ArrayList<>(); + for (int i = 0; i < n; ++i) { + if (((mask >> i) & 1) == 1) { + t.add(nums[i]); + } + } + ans.add(t); + } + return ans; + } +} \ No newline at end of file diff --git a/lcci/08.04.Power Set/Solution2.py b/lcci/08.04.Power Set/Solution2.py new file mode 100644 index 0000000000000..41c7ac3946cfe --- /dev/null +++ b/lcci/08.04.Power Set/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: + ans = [] + for mask in range(1 << len(nums)): + t = [] + for i, v in enumerate(nums): + if (mask >> i) & 1: + t.append(v) + ans.append(t) + return ans diff --git a/lcci/08.04.Power Set/Solution2.rs b/lcci/08.04.Power Set/Solution2.rs new file mode 100644 index 0000000000000..a7523d370fc9c --- /dev/null +++ b/lcci/08.04.Power Set/Solution2.rs @@ -0,0 +1,18 @@ +impl Solution { + fn dfs(nums: &Vec, i: usize, res: &mut Vec>, list: &mut Vec) { + if i == nums.len() { + res.push(list.clone()); + return; + } + list.push(nums[i]); + Self::dfs(nums, i + 1, res, list); + list.pop(); + Self::dfs(nums, i + 1, res, list); + } + + pub fn subsets(nums: Vec) -> Vec> { + let mut res = vec![]; + Self::dfs(&nums, 0, &mut res, &mut vec![]); + res + } +} diff --git a/lcci/08.04.Power Set/Solution2.ts b/lcci/08.04.Power Set/Solution2.ts new file mode 100644 index 0000000000000..1b908e9c8a6e2 --- /dev/null +++ b/lcci/08.04.Power Set/Solution2.ts @@ -0,0 +1,17 @@ +function subsets(nums: number[]): number[][] { + const n = nums.length; + const res = []; + const list = []; + const dfs = (i: number) => { + if (i === n) { + res.push([...list]); + return; + } + list.push(nums[i]); + dfs(i + 1); + list.pop(); + dfs(i + 1); + }; + dfs(0); + return res; +} diff --git a/lcci/08.05.Recursive Mulitply/Solution.cpp b/lcci/08.05.Recursive Mulitply/Solution.cpp index 62f178bfc7009..dfb2001e4e347 100644 --- a/lcci/08.05.Recursive Mulitply/Solution.cpp +++ b/lcci/08.05.Recursive Mulitply/Solution.cpp @@ -1,12 +1,12 @@ -class Solution { -public: - int multiply(int A, int B) { - if (B == 1) { - return A; - } - if ((B & 1) == 1) { - return (multiply(A, B >> 1) << 1) + A; - } - return multiply(A, B >> 1) << 1; - } +class Solution { +public: + int multiply(int A, int B) { + if (B == 1) { + return A; + } + if ((B & 1) == 1) { + return (multiply(A, B >> 1) << 1) + A; + } + return multiply(A, B >> 1) << 1; + } }; \ No newline at end of file diff --git a/lcci/08.05.Recursive Mulitply/Solution.java b/lcci/08.05.Recursive Mulitply/Solution.java index eaff95d582eee..8c36b376a41a6 100644 --- a/lcci/08.05.Recursive Mulitply/Solution.java +++ b/lcci/08.05.Recursive Mulitply/Solution.java @@ -1,11 +1,11 @@ -class Solution { - public int multiply(int A, int B) { - if (B == 1) { - return A; - } - if ((B & 1) == 1) { - return (multiply(A, B >> 1) << 1) + A; - } - return multiply(A, B >> 1) << 1; - } +class Solution { + public int multiply(int A, int B) { + if (B == 1) { + return A; + } + if ((B & 1) == 1) { + return (multiply(A, B >> 1) << 1) + A; + } + return multiply(A, B >> 1) << 1; + } } \ No newline at end of file diff --git a/lcci/08.05.Recursive Mulitply/Solution.py b/lcci/08.05.Recursive Mulitply/Solution.py index c5de60ade14e7..5e769c1436f92 100644 --- a/lcci/08.05.Recursive Mulitply/Solution.py +++ b/lcci/08.05.Recursive Mulitply/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def multiply(self, A: int, B: int) -> int: - if B == 1: - return A - if B & 1: - return (self.multiply(A, B >> 1) << 1) + A - return self.multiply(A, B >> 1) << 1 +class Solution: + def multiply(self, A: int, B: int) -> int: + if B == 1: + return A + if B & 1: + return (self.multiply(A, B >> 1) << 1) + A + return self.multiply(A, B >> 1) << 1 diff --git a/lcci/08.06.Hanota/Solution.cpp b/lcci/08.06.Hanota/Solution.cpp index 7ccd65344cbc2..7cf7ad9647324 100644 --- a/lcci/08.06.Hanota/Solution.cpp +++ b/lcci/08.06.Hanota/Solution.cpp @@ -1,26 +1,17 @@ -struct Task { - int n; - vector* a; - vector* b; - vector* c; -}; - -class Solution { -public: - void hanota(vector& A, vector& B, vector& C) { - stack stk; - stk.push({(int) A.size(), &A, &B, &C}); - while (!stk.empty()) { - Task task = stk.top(); - stk.pop(); - if (task.n == 1) { - task.c->push_back(task.a->back()); - task.a->pop_back(); - } else { - stk.push({task.n - 1, task.b, task.a, task.c}); - stk.push({1, task.a, task.b, task.c}); - stk.push({task.n - 1, task.a, task.c, task.b}); - } - } - } +class Solution { +public: + void hanota(vector& A, vector& B, vector& C) { + function&, vector&, vector&)> dfs = [&](int n, vector& a, vector& b, vector& c) { + if (n == 1) { + c.push_back(a.back()); + a.pop_back(); + return; + } + dfs(n - 1, a, c, b); + c.push_back(a.back()); + a.pop_back(); + dfs(n - 1, b, a, c); + }; + dfs(A.size(), A, B, C); + } }; \ No newline at end of file diff --git a/lcci/08.06.Hanota/Solution.go b/lcci/08.06.Hanota/Solution.go index 957252408c120..bfefce79f26e1 100644 --- a/lcci/08.06.Hanota/Solution.go +++ b/lcci/08.06.Hanota/Solution.go @@ -1,21 +1,16 @@ func hanota(A []int, B []int, C []int) []int { - stk := []Task{{len(A), &A, &B, &C}} - for len(stk) > 0 { - task := stk[len(stk)-1] - stk = stk[:len(stk)-1] - if task.n == 1 { - *task.c = append(*task.c, (*task.a)[len(*task.a)-1]) - *task.a = (*task.a)[:len(*task.a)-1] - } else { - stk = append(stk, Task{task.n - 1, task.b, task.a, task.c}) - stk = append(stk, Task{1, task.a, task.b, task.c}) - stk = append(stk, Task{task.n - 1, task.a, task.c, task.b}) + var dfs func(n int, a, b, c *[]int) + dfs = func(n int, a, b, c *[]int) { + if n == 1 { + *c = append(*c, (*a)[len(*a)-1]) + *a = (*a)[:len(*a)-1] + return } + dfs(n-1, a, c, b) + *c = append(*c, (*a)[len(*a)-1]) + *a = (*a)[:len(*a)-1] + dfs(n-1, b, a, c) } + dfs(len(A), &A, &B, &C) return C -} - -type Task struct { - n int - a, b, c *[]int } \ No newline at end of file diff --git a/lcci/08.06.Hanota/Solution.java b/lcci/08.06.Hanota/Solution.java index 66cb5e5a50235..c30b9d4be2c86 100644 --- a/lcci/08.06.Hanota/Solution.java +++ b/lcci/08.06.Hanota/Solution.java @@ -1,34 +1,15 @@ -class Solution { - public void hanota(List A, List B, List C) { - Deque stk = new ArrayDeque<>(); - stk.push(new Task(A.size(), A, B, C)); - while (stk.size() > 0) { - Task task = stk.pop(); - int n = task.n; - List a = task.a; - List b = task.b; - List c = task.c; - if (n == 1) { - c.add(a.remove(a.size() - 1)); - } else { - stk.push(new Task(n - 1, b, a, c)); - stk.push(new Task(1, a, b, c)); - stk.push(new Task(n - 1, a, c, b)); - } - } - } -} - -class Task { - int n; - List a; - List b; - List c; - - public Task(int n, List a, List b, List c) { - this.n = n; - this.a = a; - this.b = b; - this.c = c; - } +class Solution { + public void hanota(List A, List B, List C) { + dfs(A.size(), A, B, C); + } + + private void dfs(int n, List a, List b, List c) { + if (n == 1) { + c.add(a.remove(a.size() - 1)); + return; + } + dfs(n - 1, a, c, b); + c.add(a.remove(a.size() - 1)); + dfs(n - 1, b, a, c); + } } \ No newline at end of file diff --git a/lcci/08.06.Hanota/Solution.py b/lcci/08.06.Hanota/Solution.py index 844370b74044e..363f2a20dfcf1 100644 --- a/lcci/08.06.Hanota/Solution.py +++ b/lcci/08.06.Hanota/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def hanota(self, A: List[int], B: List[int], C: List[int]) -> None: - stk = [(len(A), A, B, C)] - while stk: - n, a, b, c = stk.pop() - if n == 1: - c.append(a.pop()) - else: - stk.append((n - 1, b, a, c)) - stk.append((1, a, b, c)) - stk.append((n - 1, a, c, b)) +class Solution: + def hanota(self, A: List[int], B: List[int], C: List[int]) -> None: + def dfs(n, a, b, c): + if n == 1: + c.append(a.pop()) + return + dfs(n - 1, a, c, b) + c.append(a.pop()) + dfs(n - 1, b, a, c) + + dfs(len(A), A, B, C) diff --git a/lcci/08.06.Hanota/Solution.ts b/lcci/08.06.Hanota/Solution.ts index b549082b53f91..9af439ab17a81 100644 --- a/lcci/08.06.Hanota/Solution.ts +++ b/lcci/08.06.Hanota/Solution.ts @@ -2,15 +2,14 @@ Do not return anything, modify C in-place instead. */ function hanota(A: number[], B: number[], C: number[]): void { - const stk: any[] = [[A.length, A, B, C]]; - while (stk.length) { - const [n, a, b, c] = stk.pop()!; + const dfs = (n: number, a: number[], b: number[], c: number[]) => { if (n === 1) { - c.push(a.pop()); - } else { - stk.push([n - 1, b, a, c]); - stk.push([1, a, b, c]); - stk.push([n - 1, a, c, b]); + c.push(a.pop()!); + return; } - } + dfs(n - 1, a, c, b); + c.push(a.pop()!); + dfs(n - 1, b, a, c); + }; + dfs(A.length, A, B, C); } diff --git a/lcci/08.06.Hanota/Solution2.cpp b/lcci/08.06.Hanota/Solution2.cpp new file mode 100644 index 0000000000000..dac7dd3bcb3de --- /dev/null +++ b/lcci/08.06.Hanota/Solution2.cpp @@ -0,0 +1,26 @@ +struct Task { + int n; + vector* a; + vector* b; + vector* c; +}; + +class Solution { +public: + void hanota(vector& A, vector& B, vector& C) { + stack stk; + stk.push({(int) A.size(), &A, &B, &C}); + while (!stk.empty()) { + Task task = stk.top(); + stk.pop(); + if (task.n == 1) { + task.c->push_back(task.a->back()); + task.a->pop_back(); + } else { + stk.push({task.n - 1, task.b, task.a, task.c}); + stk.push({1, task.a, task.b, task.c}); + stk.push({task.n - 1, task.a, task.c, task.b}); + } + } + } +}; \ No newline at end of file diff --git a/lcci/08.06.Hanota/Solution2.go b/lcci/08.06.Hanota/Solution2.go new file mode 100644 index 0000000000000..957252408c120 --- /dev/null +++ b/lcci/08.06.Hanota/Solution2.go @@ -0,0 +1,21 @@ +func hanota(A []int, B []int, C []int) []int { + stk := []Task{{len(A), &A, &B, &C}} + for len(stk) > 0 { + task := stk[len(stk)-1] + stk = stk[:len(stk)-1] + if task.n == 1 { + *task.c = append(*task.c, (*task.a)[len(*task.a)-1]) + *task.a = (*task.a)[:len(*task.a)-1] + } else { + stk = append(stk, Task{task.n - 1, task.b, task.a, task.c}) + stk = append(stk, Task{1, task.a, task.b, task.c}) + stk = append(stk, Task{task.n - 1, task.a, task.c, task.b}) + } + } + return C +} + +type Task struct { + n int + a, b, c *[]int +} \ No newline at end of file diff --git a/lcci/08.06.Hanota/Solution2.java b/lcci/08.06.Hanota/Solution2.java new file mode 100644 index 0000000000000..74278ce31a67f --- /dev/null +++ b/lcci/08.06.Hanota/Solution2.java @@ -0,0 +1,34 @@ +class Solution { + public void hanota(List A, List B, List C) { + Deque stk = new ArrayDeque<>(); + stk.push(new Task(A.size(), A, B, C)); + while (stk.size() > 0) { + Task task = stk.pop(); + int n = task.n; + List a = task.a; + List b = task.b; + List c = task.c; + if (n == 1) { + c.add(a.remove(a.size() - 1)); + } else { + stk.push(new Task(n - 1, b, a, c)); + stk.push(new Task(1, a, b, c)); + stk.push(new Task(n - 1, a, c, b)); + } + } + } +} + +class Task { + int n; + List a; + List b; + List c; + + public Task(int n, List a, List b, List c) { + this.n = n; + this.a = a; + this.b = b; + this.c = c; + } +} \ No newline at end of file diff --git a/lcci/08.06.Hanota/Solution2.py b/lcci/08.06.Hanota/Solution2.py new file mode 100644 index 0000000000000..831269c9a1544 --- /dev/null +++ b/lcci/08.06.Hanota/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def hanota(self, A: List[int], B: List[int], C: List[int]) -> None: + stk = [(len(A), A, B, C)] + while stk: + n, a, b, c = stk.pop() + if n == 1: + c.append(a.pop()) + else: + stk.append((n - 1, b, a, c)) + stk.append((1, a, b, c)) + stk.append((n - 1, a, c, b)) diff --git a/lcci/08.06.Hanota/Solution2.ts b/lcci/08.06.Hanota/Solution2.ts new file mode 100644 index 0000000000000..b549082b53f91 --- /dev/null +++ b/lcci/08.06.Hanota/Solution2.ts @@ -0,0 +1,16 @@ +/** + Do not return anything, modify C in-place instead. + */ +function hanota(A: number[], B: number[], C: number[]): void { + const stk: any[] = [[A.length, A, B, C]]; + while (stk.length) { + const [n, a, b, c] = stk.pop()!; + if (n === 1) { + c.push(a.pop()); + } else { + stk.push([n - 1, b, a, c]); + stk.push([1, a, b, c]); + stk.push([n - 1, a, c, b]); + } + } +} diff --git a/lcci/08.07.Permutation I/Solution.cpp b/lcci/08.07.Permutation I/Solution.cpp index 380f09189a528..efec2b97d3bd0 100644 --- a/lcci/08.07.Permutation I/Solution.cpp +++ b/lcci/08.07.Permutation I/Solution.cpp @@ -1,25 +1,25 @@ -class Solution { -public: - vector permutation(string S) { - unordered_set vis; - vector ans; - string t = ""; - dfs(0, S, t, ans, vis); - return ans; - } - - void dfs(int u, string& S, string& t, vector& ans, unordered_set& vis) { - if (u == S.size()) { - ans.push_back(t); - return; - } - for (char& c : S) { - if (vis.count(c)) continue; - vis.insert(c); - t.push_back(c); - dfs(u + 1, S, t, ans, vis); - vis.erase(c); - t.pop_back(); - } - } +class Solution { +public: + vector permutation(string S) { + unordered_set vis; + vector ans; + string t = ""; + dfs(0, S, t, ans, vis); + return ans; + } + + void dfs(int u, string& S, string& t, vector& ans, unordered_set& vis) { + if (u == S.size()) { + ans.push_back(t); + return; + } + for (char& c : S) { + if (vis.count(c)) continue; + vis.insert(c); + t.push_back(c); + dfs(u + 1, S, t, ans, vis); + vis.erase(c); + t.pop_back(); + } + } }; \ No newline at end of file diff --git a/lcci/08.07.Permutation I/Solution.java b/lcci/08.07.Permutation I/Solution.java index 2ef169fb78b6f..0dc4c679e8202 100644 --- a/lcci/08.07.Permutation I/Solution.java +++ b/lcci/08.07.Permutation I/Solution.java @@ -1,26 +1,26 @@ -class Solution { - public String[] permutation(String S) { - Set vis = new HashSet<>(); - List ans = new ArrayList<>(); - StringBuilder t = new StringBuilder(); - dfs(0, S, t, ans, vis); - return ans.toArray(new String[0]); - } - - private void dfs(int u, String S, StringBuilder t, List ans, Set vis) { - if (u == S.length()) { - ans.add(t.toString()); - return; - } - for (char c : S.toCharArray()) { - if (vis.contains(c)) { - continue; - } - vis.add(c); - t.append(c); - dfs(u + 1, S, t, ans, vis); - t.deleteCharAt(t.length() - 1); - vis.remove(c); - } - } +class Solution { + public String[] permutation(String S) { + Set vis = new HashSet<>(); + List ans = new ArrayList<>(); + StringBuilder t = new StringBuilder(); + dfs(0, S, t, ans, vis); + return ans.toArray(new String[0]); + } + + private void dfs(int u, String S, StringBuilder t, List ans, Set vis) { + if (u == S.length()) { + ans.add(t.toString()); + return; + } + for (char c : S.toCharArray()) { + if (vis.contains(c)) { + continue; + } + vis.add(c); + t.append(c); + dfs(u + 1, S, t, ans, vis); + t.deleteCharAt(t.length() - 1); + vis.remove(c); + } + } } \ No newline at end of file diff --git a/lcci/08.07.Permutation I/Solution.py b/lcci/08.07.Permutation I/Solution.py index 6e08bfdbda01b..86e9be8496d31 100644 --- a/lcci/08.07.Permutation I/Solution.py +++ b/lcci/08.07.Permutation I/Solution.py @@ -1,20 +1,20 @@ -class Solution: - def permutation(self, S: str) -> List[str]: - def dfs(u, t): - if u == n: - ans.append(''.join(t)) - return - for i in range(n): - if vis[i]: - continue - vis[i] = True - t.append(S[i]) - dfs(u + 1, t) - t.pop() - vis[i] = False - - n = len(S) - vis = [False] * n - ans = [] - dfs(0, []) - return ans +class Solution: + def permutation(self, S: str) -> List[str]: + def dfs(u, t): + if u == n: + ans.append(''.join(t)) + return + for i in range(n): + if vis[i]: + continue + vis[i] = True + t.append(S[i]) + dfs(u + 1, t) + t.pop() + vis[i] = False + + n = len(S) + vis = [False] * n + ans = [] + dfs(0, []) + return ans diff --git a/lcci/08.08.Permutation II/Solution.cpp b/lcci/08.08.Permutation II/Solution.cpp index 89418c7dd37e3..c706c3df751b9 100644 --- a/lcci/08.08.Permutation II/Solution.cpp +++ b/lcci/08.08.Permutation II/Solution.cpp @@ -1,29 +1,29 @@ -class Solution { -public: - vector permutation(string S) { - vector cs(S.begin(), S.end()); - sort(cs.begin(), cs.end()); - int n = cs.size(); - vector ans; - vector vis(n); - string t; - function dfs = [&](int i) { - if (i == n) { - ans.push_back(t); - return; - } - for (int j = 0; j < n; ++j) { - if (vis[j] || (j && !vis[j - 1] && cs[j] == cs[j - 1])) { - continue; - } - vis[j] = true; - t.push_back(cs[j]); - dfs(i + 1); - t.pop_back(); - vis[j] = false; - } - }; - dfs(0); - return ans; - } +class Solution { +public: + vector permutation(string S) { + vector cs(S.begin(), S.end()); + sort(cs.begin(), cs.end()); + int n = cs.size(); + vector ans; + vector vis(n); + string t; + function dfs = [&](int i) { + if (i == n) { + ans.push_back(t); + return; + } + for (int j = 0; j < n; ++j) { + if (vis[j] || (j && !vis[j - 1] && cs[j] == cs[j - 1])) { + continue; + } + vis[j] = true; + t.push_back(cs[j]); + dfs(i + 1); + t.pop_back(); + vis[j] = false; + } + }; + dfs(0); + return ans; + } }; \ No newline at end of file diff --git a/lcci/08.08.Permutation II/Solution.java b/lcci/08.08.Permutation II/Solution.java index ca44d0d3d3023..e0dffd2d0cfae 100644 --- a/lcci/08.08.Permutation II/Solution.java +++ b/lcci/08.08.Permutation II/Solution.java @@ -1,33 +1,33 @@ -class Solution { - private int n; - private char[] cs; - private List ans = new ArrayList<>(); - private boolean[] vis; - private StringBuilder t = new StringBuilder(); - - public String[] permutation(String S) { - cs = S.toCharArray(); - n = cs.length; - Arrays.sort(cs); - vis = new boolean[n]; - dfs(0); - return ans.toArray(new String[0]); - } - - private void dfs(int i) { - if (i == n) { - ans.add(t.toString()); - return; - } - for (int j = 0; j < n; ++j) { - if (vis[j] || (j > 0 && !vis[j - 1] && cs[j] == cs[j - 1])) { - continue; - } - vis[j] = true; - t.append(cs[j]); - dfs(i + 1); - t.deleteCharAt(t.length() - 1); - vis[j] = false; - } - } +class Solution { + private int n; + private char[] cs; + private List ans = new ArrayList<>(); + private boolean[] vis; + private StringBuilder t = new StringBuilder(); + + public String[] permutation(String S) { + cs = S.toCharArray(); + n = cs.length; + Arrays.sort(cs); + vis = new boolean[n]; + dfs(0); + return ans.toArray(new String[0]); + } + + private void dfs(int i) { + if (i == n) { + ans.add(t.toString()); + return; + } + for (int j = 0; j < n; ++j) { + if (vis[j] || (j > 0 && !vis[j - 1] && cs[j] == cs[j - 1])) { + continue; + } + vis[j] = true; + t.append(cs[j]); + dfs(i + 1); + t.deleteCharAt(t.length() - 1); + vis[j] = false; + } + } } \ No newline at end of file diff --git a/lcci/08.08.Permutation II/Solution.py b/lcci/08.08.Permutation II/Solution.py index 5731468cfdea6..e6b19ccba395a 100644 --- a/lcci/08.08.Permutation II/Solution.py +++ b/lcci/08.08.Permutation II/Solution.py @@ -1,21 +1,21 @@ -class Solution: - def permutation(self, S: str) -> List[str]: - def dfs(i: int): - if i == n: - ans.append("".join(t)) - return - for j in range(n): - if vis[j] or (j and cs[j] == cs[j - 1] and not vis[j - 1]): - continue - t[i] = cs[j] - vis[j] = True - dfs(i + 1) - vis[j] = False - - cs = sorted(S) - n = len(cs) - ans = [] - t = [None] * n - vis = [False] * n - dfs(0) - return ans +class Solution: + def permutation(self, S: str) -> List[str]: + def dfs(i: int): + if i == n: + ans.append("".join(t)) + return + for j in range(n): + if vis[j] or (j and cs[j] == cs[j - 1] and not vis[j - 1]): + continue + t[i] = cs[j] + vis[j] = True + dfs(i + 1) + vis[j] = False + + cs = sorted(S) + n = len(cs) + ans = [] + t = [None] * n + vis = [False] * n + dfs(0) + return ans diff --git a/lcci/08.08.Permutation II/Solution.ts b/lcci/08.08.Permutation II/Solution.ts index 44aed97be109c..747891e4cfff0 100644 --- a/lcci/08.08.Permutation II/Solution.ts +++ b/lcci/08.08.Permutation II/Solution.ts @@ -1,14 +1,10 @@ -/** - * @param {string} S - * @return {string[]} - */ -var permutation = function (S) { - const cs = S.split('').sort(); - const ans = []; +function permutation(S: string): string[] { + const cs: string[] = S.split('').sort(); + const ans: string[] = []; const n = cs.length; - const vis = Array(n).fill(false); - const t = []; - const dfs = i => { + const vis: boolean[] = Array(n).fill(false); + const t: string[] = []; + const dfs = (i: number) => { if (i === n) { ans.push(t.join('')); return; @@ -26,4 +22,4 @@ var permutation = function (S) { }; dfs(0); return ans; -}; +} diff --git a/lcci/08.10.Color Fill/Solution2.cpp b/lcci/08.10.Color Fill/Solution2.cpp new file mode 100644 index 0000000000000..7bce414cbe762 --- /dev/null +++ b/lcci/08.10.Color Fill/Solution2.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + vector> floodFill(vector>& image, int sr, int sc, int newColor) { + if (image[sr][sc] == newColor) return image; + int oc = image[sr][sc]; + image[sr][sc] = newColor; + queue> q; + q.push({sr, sc}); + int dirs[5] = {-1, 0, 1, 0, -1}; + while (!q.empty()) { + auto [a, b] = q.front(); + q.pop(); + for (int k = 0; k < 4; ++k) { + int x = a + dirs[k]; + int y = b + dirs[k + 1]; + if (x >= 0 && x < image.size() && y >= 0 && y < image[0].size() && image[x][y] == oc) { + q.push({x, y}); + image[x][y] = newColor; + } + } + } + return image; + } +}; \ No newline at end of file diff --git a/lcci/08.10.Color Fill/Solution2.go b/lcci/08.10.Color Fill/Solution2.go new file mode 100644 index 0000000000000..defd4e9ca83ca --- /dev/null +++ b/lcci/08.10.Color Fill/Solution2.go @@ -0,0 +1,21 @@ +func floodFill(image [][]int, sr int, sc int, newColor int) [][]int { + if image[sr][sc] == newColor { + return image + } + oc := image[sr][sc] + q := [][]int{[]int{sr, sc}} + image[sr][sc] = newColor + dirs := []int{-1, 0, 1, 0, -1} + for len(q) > 0 { + p := q[0] + q = q[1:] + for k := 0; k < 4; k++ { + x, y := p[0]+dirs[k], p[1]+dirs[k+1] + if x >= 0 && x < len(image) && y >= 0 && y < len(image[0]) && image[x][y] == oc { + q = append(q, []int{x, y}) + image[x][y] = newColor + } + } + } + return image +} \ No newline at end of file diff --git a/lcci/08.10.Color Fill/Solution2.java b/lcci/08.10.Color Fill/Solution2.java new file mode 100644 index 0000000000000..8e3f5737cffc0 --- /dev/null +++ b/lcci/08.10.Color Fill/Solution2.java @@ -0,0 +1,25 @@ +class Solution { + public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { + if (image[sr][sc] == newColor) { + return image; + } + Deque q = new ArrayDeque<>(); + q.offer(new int[] {sr, sc}); + int oc = image[sr][sc]; + image[sr][sc] = newColor; + int[] dirs = {-1, 0, 1, 0, -1}; + while (!q.isEmpty()) { + int[] p = q.poll(); + int i = p[0], j = p[1]; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < image.length && y >= 0 && y < image[0].length + && image[x][y] == oc) { + q.offer(new int[] {x, y}); + image[x][y] = newColor; + } + } + } + return image; + } +} \ No newline at end of file diff --git a/lcci/08.10.Color Fill/Solution2.py b/lcci/08.10.Color Fill/Solution2.py new file mode 100644 index 0000000000000..4897977ff04a0 --- /dev/null +++ b/lcci/08.10.Color Fill/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def floodFill( + self, image: List[List[int]], sr: int, sc: int, newColor: int + ) -> List[List[int]]: + if image[sr][sc] == newColor: + return image + q = deque([(sr, sc)]) + oc = image[sr][sc] + image[sr][sc] = newColor + dirs = (-1, 0, 1, 0, -1) + while q: + i, j = q.popleft() + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < len(image) and 0 <= y < len(image[0]) and image[x][y] == oc: + q.append((x, y)) + image[x][y] = newColor + return image diff --git a/lcci/08.11.Coin/Solution.cpp b/lcci/08.11.Coin/Solution.cpp index 03262e61c881f..f68c0fb247c21 100644 --- a/lcci/08.11.Coin/Solution.cpp +++ b/lcci/08.11.Coin/Solution.cpp @@ -1,16 +1,19 @@ -class Solution { -public: - int waysToChange(int n) { - const int mod = 1e9 + 7; - vector coins = {25, 10, 5, 1}; - int f[n + 1]; - memset(f, 0, sizeof(f)); - f[0] = 1; - for (int c : coins) { - for (int j = c; j <= n; ++j) { - f[j] = (f[j] + f[j - c]) % mod; - } - } - return f[n]; - } +class Solution { +public: + int waysToChange(int n) { + const int mod = 1e9 + 7; + vector coins = {25, 10, 5, 1}; + int f[5][n + 1]; + memset(f, 0, sizeof(f)); + f[0][0] = 1; + for (int i = 1; i <= 4; ++i) { + for (int j = 0; j <= n; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= coins[i - 1]) { + f[i][j] = (f[i][j] + f[i][j - coins[i - 1]]) % mod; + } + } + } + return f[4][n]; + } }; \ No newline at end of file diff --git a/lcci/08.11.Coin/Solution.go b/lcci/08.11.Coin/Solution.go index f6f0a1ee5f625..7376b5f21005c 100644 --- a/lcci/08.11.Coin/Solution.go +++ b/lcci/08.11.Coin/Solution.go @@ -1,12 +1,18 @@ func waysToChange(n int) int { const mod int = 1e9 + 7 coins := []int{25, 10, 5, 1} - f := make([]int, n+1) - f[0] = 1 - for _, c := range coins { - for j := c; j <= n; j++ { - f[j] = (f[j] + f[j-c]) % mod + f := make([][]int, 5) + for i := range f { + f[i] = make([]int, n+1) + } + f[0][0] = 1 + for i := 1; i <= 4; i++ { + for j := 0; j <= n; j++ { + f[i][j] = f[i-1][j] + if j >= coins[i-1] { + f[i][j] = (f[i][j] + f[i][j-coins[i-1]]) % mod + } } } - return f[n] + return f[4][n] } \ No newline at end of file diff --git a/lcci/08.11.Coin/Solution.java b/lcci/08.11.Coin/Solution.java index 12fee50a7a83f..bd860cc2316c6 100644 --- a/lcci/08.11.Coin/Solution.java +++ b/lcci/08.11.Coin/Solution.java @@ -1,14 +1,17 @@ -class Solution { - public int waysToChange(int n) { - final int mod = (int) 1e9 + 7; - int[] coins = {25, 10, 5, 1}; - int[] f = new int[n + 1]; - f[0] = 1; - for (int c : coins) { - for (int j = c; j <= n; ++j) { - f[j] = (f[j] + f[j - c]) % mod; - } - } - return f[n]; - } +class Solution { + public int waysToChange(int n) { + final int mod = (int) 1e9 + 7; + int[] coins = {25, 10, 5, 1}; + int[][] f = new int[5][n + 1]; + f[0][0] = 1; + for (int i = 1; i <= 4; ++i) { + for (int j = 0; j <= n; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= coins[i - 1]) { + f[i][j] = (f[i][j] + f[i][j - coins[i - 1]]) % mod; + } + } + } + return f[4][n]; + } } \ No newline at end of file diff --git a/lcci/08.11.Coin/Solution.py b/lcci/08.11.Coin/Solution.py index b433ce4c26892..923c006d39056 100644 --- a/lcci/08.11.Coin/Solution.py +++ b/lcci/08.11.Coin/Solution.py @@ -1,9 +1,12 @@ -class Solution: - def waysToChange(self, n: int) -> int: - mod = 10**9 + 7 - coins = [25, 10, 5, 1] - f = [1] + [0] * n - for c in coins: - for j in range(c, n + 1): - f[j] = (f[j] + f[j - c]) % mod - return f[n] +class Solution: + def waysToChange(self, n: int) -> int: + mod = 10**9 + 7 + coins = [25, 10, 5, 1] + f = [[0] * (n + 1) for _ in range(5)] + f[0][0] = 1 + for i, c in enumerate(coins, 1): + for j in range(n + 1): + f[i][j] = f[i - 1][j] + if j >= c: + f[i][j] = (f[i][j] + f[i][j - c]) % mod + return f[-1][n] diff --git a/lcci/08.11.Coin/Solution.ts b/lcci/08.11.Coin/Solution.ts index d35339fae7f8b..238cbb63a5e67 100644 --- a/lcci/08.11.Coin/Solution.ts +++ b/lcci/08.11.Coin/Solution.ts @@ -1,12 +1,17 @@ function waysToChange(n: number): number { const mod = 10 ** 9 + 7; const coins: number[] = [25, 10, 5, 1]; - const f: number[] = new Array(n + 1).fill(0); - f[0] = 1; - for (const c of coins) { - for (let i = c; i <= n; ++i) { - f[i] = (f[i] + f[i - c]) % mod; + const f: number[][] = Array(5) + .fill(0) + .map(() => Array(n + 1).fill(0)); + f[0][0] = 1; + for (let i = 1; i <= 4; ++i) { + for (let j = 0; j <= n; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= coins[i - 1]) { + f[i][j] = (f[i][j] + f[i][j - coins[i - 1]]) % mod; + } } } - return f[n]; + return f[4][n]; } diff --git a/lcci/08.11.Coin/Solution2.cpp b/lcci/08.11.Coin/Solution2.cpp new file mode 100644 index 0000000000000..9abb79757810c --- /dev/null +++ b/lcci/08.11.Coin/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int waysToChange(int n) { + const int mod = 1e9 + 7; + vector coins = {25, 10, 5, 1}; + int f[n + 1]; + memset(f, 0, sizeof(f)); + f[0] = 1; + for (int c : coins) { + for (int j = c; j <= n; ++j) { + f[j] = (f[j] + f[j - c]) % mod; + } + } + return f[n]; + } +}; \ No newline at end of file diff --git a/lcci/08.11.Coin/Solution2.go b/lcci/08.11.Coin/Solution2.go new file mode 100644 index 0000000000000..f6f0a1ee5f625 --- /dev/null +++ b/lcci/08.11.Coin/Solution2.go @@ -0,0 +1,12 @@ +func waysToChange(n int) int { + const mod int = 1e9 + 7 + coins := []int{25, 10, 5, 1} + f := make([]int, n+1) + f[0] = 1 + for _, c := range coins { + for j := c; j <= n; j++ { + f[j] = (f[j] + f[j-c]) % mod + } + } + return f[n] +} \ No newline at end of file diff --git a/lcci/08.11.Coin/Solution2.java b/lcci/08.11.Coin/Solution2.java new file mode 100644 index 0000000000000..680062762d6ff --- /dev/null +++ b/lcci/08.11.Coin/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public int waysToChange(int n) { + final int mod = (int) 1e9 + 7; + int[] coins = {25, 10, 5, 1}; + int[] f = new int[n + 1]; + f[0] = 1; + for (int c : coins) { + for (int j = c; j <= n; ++j) { + f[j] = (f[j] + f[j - c]) % mod; + } + } + return f[n]; + } +} \ No newline at end of file diff --git a/lcci/08.11.Coin/Solution2.py b/lcci/08.11.Coin/Solution2.py new file mode 100644 index 0000000000000..814724155b2f7 --- /dev/null +++ b/lcci/08.11.Coin/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def waysToChange(self, n: int) -> int: + mod = 10**9 + 7 + coins = [25, 10, 5, 1] + f = [1] + [0] * n + for c in coins: + for j in range(c, n + 1): + f[j] = (f[j] + f[j - c]) % mod + return f[n] diff --git a/lcci/08.11.Coin/Solution2.ts b/lcci/08.11.Coin/Solution2.ts new file mode 100644 index 0000000000000..d35339fae7f8b --- /dev/null +++ b/lcci/08.11.Coin/Solution2.ts @@ -0,0 +1,12 @@ +function waysToChange(n: number): number { + const mod = 10 ** 9 + 7; + const coins: number[] = [25, 10, 5, 1]; + const f: number[] = new Array(n + 1).fill(0); + f[0] = 1; + for (const c of coins) { + for (let i = c; i <= n; ++i) { + f[i] = (f[i] + f[i - c]) % mod; + } + } + return f[n]; +} diff --git a/lcci/08.12.Eight Queens/Solution.java b/lcci/08.12.Eight Queens/Solution.java index 937ef424ced10..d28752036a628 100644 --- a/lcci/08.12.Eight Queens/Solution.java +++ b/lcci/08.12.Eight Queens/Solution.java @@ -7,9 +7,13 @@ public List> solveNQueens(int n) { Arrays.fill(t, "."); g[i] = t; } + // 列是否已经有值 boolean[] col = new boolean[n]; + // 斜线是否已经有值 boolean[] dg = new boolean[2 * n]; + // 反斜线是否已经有值 boolean[] udg = new boolean[2 * n]; + // 从第一行开始搜索 dfs(0, n, col, dg, udg, g, res); return res; } diff --git a/lcci/08.13.Pile Box/Solution.cpp b/lcci/08.13.Pile Box/Solution.cpp index 9ca9b457b575b..7c6523b4dda30 100644 --- a/lcci/08.13.Pile Box/Solution.cpp +++ b/lcci/08.13.Pile Box/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - int pileBox(vector>& box) { - sort(box.begin(), box.end(), [](const vector& a, const vector& b) { - return a[0] < b[0] || (a[0] == b[0] && b[1] < a[1]); - }); - int n = box.size(); - int f[n]; - memset(f, 0, sizeof(f)); - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (box[j][1] < box[i][1] && box[j][2] < box[i][2]) { - f[i] = max(f[i], f[j]); - } - } - f[i] += box[i][2]; - } - return *max_element(f, f + n); - } +class Solution { +public: + int pileBox(vector>& box) { + sort(box.begin(), box.end(), [](const vector& a, const vector& b) { + return a[0] < b[0] || (a[0] == b[0] && b[1] < a[1]); + }); + int n = box.size(); + int f[n]; + memset(f, 0, sizeof(f)); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (box[j][1] < box[i][1] && box[j][2] < box[i][2]) { + f[i] = max(f[i], f[j]); + } + } + f[i] += box[i][2]; + } + return *max_element(f, f + n); + } }; \ No newline at end of file diff --git a/lcci/08.13.Pile Box/Solution.java b/lcci/08.13.Pile Box/Solution.java index 52cc367e67220..687f768da7627 100644 --- a/lcci/08.13.Pile Box/Solution.java +++ b/lcci/08.13.Pile Box/Solution.java @@ -1,18 +1,18 @@ -class Solution { - public int pileBox(int[][] box) { - Arrays.sort(box, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); - int n = box.length; - int[] f = new int[n]; - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (box[j][1] < box[i][1] && box[j][2] < box[i][2]) { - f[i] = Math.max(f[i], f[j]); - } - } - f[i] += box[i][2]; - ans = Math.max(ans, f[i]); - } - return ans; - } +class Solution { + public int pileBox(int[][] box) { + Arrays.sort(box, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); + int n = box.length; + int[] f = new int[n]; + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (box[j][1] < box[i][1] && box[j][2] < box[i][2]) { + f[i] = Math.max(f[i], f[j]); + } + } + f[i] += box[i][2]; + ans = Math.max(ans, f[i]); + } + return ans; + } } \ No newline at end of file diff --git a/lcci/08.13.Pile Box/Solution.py b/lcci/08.13.Pile Box/Solution.py index 04538c822d68d..2e730e4144ce1 100644 --- a/lcci/08.13.Pile Box/Solution.py +++ b/lcci/08.13.Pile Box/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def pileBox(self, box: List[List[int]]) -> int: - box.sort(key=lambda x: (x[0], -x[1])) - n = len(box) - f = [0] * n - for i in range(n): - for j in range(i): - if box[j][1] < box[i][1] and box[j][2] < box[i][2]: - f[i] = max(f[i], f[j]) - f[i] += box[i][2] - return max(f) +class Solution: + def pileBox(self, box: List[List[int]]) -> int: + box.sort(key=lambda x: (x[0], -x[1])) + n = len(box) + f = [0] * n + for i in range(n): + for j in range(i): + if box[j][1] < box[i][1] and box[j][2] < box[i][2]: + f[i] = max(f[i], f[j]) + f[i] += box[i][2] + return max(f) diff --git a/lcci/10.03.Search Rotate Array/Solution.cpp b/lcci/10.03.Search Rotate Array/Solution.cpp index 7a28ef0a075de..476772fc4ba38 100644 --- a/lcci/10.03.Search Rotate Array/Solution.cpp +++ b/lcci/10.03.Search Rotate Array/Solution.cpp @@ -1,28 +1,28 @@ -class Solution { -public: - int search(vector& arr, int target) { - int l = 0, r = arr.size() - 1; - while (arr[l] == arr[r]) { - --r; - } - while (l < r) { - int mid = (l + r) >> 1; - if (arr[mid] > arr[r]) { - if (arr[l] <= target && target <= arr[mid]) { - r = mid; - } else { - l = mid + 1; - } - } else if (arr[mid] < arr[r]) { - if (arr[mid] < target && target <= arr[r]) { - l = mid + 1; - } else { - r = mid; - } - } else { - --r; - } - } - return arr[l] == target ? l : -1; - } +class Solution { +public: + int search(vector& arr, int target) { + int l = 0, r = arr.size() - 1; + while (arr[l] == arr[r]) { + --r; + } + while (l < r) { + int mid = (l + r) >> 1; + if (arr[mid] > arr[r]) { + if (arr[l] <= target && target <= arr[mid]) { + r = mid; + } else { + l = mid + 1; + } + } else if (arr[mid] < arr[r]) { + if (arr[mid] < target && target <= arr[r]) { + l = mid + 1; + } else { + r = mid; + } + } else { + --r; + } + } + return arr[l] == target ? l : -1; + } }; \ No newline at end of file diff --git a/lcci/10.03.Search Rotate Array/Solution.java b/lcci/10.03.Search Rotate Array/Solution.java index c1d9089277322..b0eaa996faef1 100644 --- a/lcci/10.03.Search Rotate Array/Solution.java +++ b/lcci/10.03.Search Rotate Array/Solution.java @@ -1,27 +1,27 @@ -class Solution { - public int search(int[] arr, int target) { - int l = 0, r = arr.length - 1; - while (arr[l] == arr[r]) { - --r; - } - while (l < r) { - int mid = (l + r) >> 1; - if (arr[mid] > arr[r]) { - if (arr[l] <= target && target <= arr[mid]) { - r = mid; - } else { - l = mid + 1; - } - } else if (arr[mid] < arr[r]) { - if (arr[mid] < target && target <= arr[r]) { - l = mid + 1; - } else { - r = mid; - } - } else { - --r; - } - } - return arr[l] == target ? l : -1; - } +class Solution { + public int search(int[] arr, int target) { + int l = 0, r = arr.length - 1; + while (arr[l] == arr[r]) { + --r; + } + while (l < r) { + int mid = (l + r) >> 1; + if (arr[mid] > arr[r]) { + if (arr[l] <= target && target <= arr[mid]) { + r = mid; + } else { + l = mid + 1; + } + } else if (arr[mid] < arr[r]) { + if (arr[mid] < target && target <= arr[r]) { + l = mid + 1; + } else { + r = mid; + } + } else { + --r; + } + } + return arr[l] == target ? l : -1; + } } \ No newline at end of file diff --git a/lcci/10.03.Search Rotate Array/Solution.py b/lcci/10.03.Search Rotate Array/Solution.py index c88723a3ff098..463fec8d23e7e 100644 --- a/lcci/10.03.Search Rotate Array/Solution.py +++ b/lcci/10.03.Search Rotate Array/Solution.py @@ -1,20 +1,20 @@ -class Solution: - def search(self, arr: List[int], target: int) -> int: - l, r = 0, len(arr) - 1 - while arr[l] == arr[r]: - r -= 1 - while l < r: - mid = (l + r) >> 1 - if arr[mid] > arr[r]: - if arr[l] <= target <= arr[mid]: - r = mid - else: - l = mid + 1 - elif arr[mid] < arr[r]: - if arr[mid] < target <= arr[r]: - l = mid + 1 - else: - r = mid - else: - r -= 1 - return l if arr[l] == target else -1 +class Solution: + def search(self, arr: List[int], target: int) -> int: + l, r = 0, len(arr) - 1 + while arr[l] == arr[r]: + r -= 1 + while l < r: + mid = (l + r) >> 1 + if arr[mid] > arr[r]: + if arr[l] <= target <= arr[mid]: + r = mid + else: + l = mid + 1 + elif arr[mid] < arr[r]: + if arr[mid] < target <= arr[r]: + l = mid + 1 + else: + r = mid + else: + r -= 1 + return l if arr[l] == target else -1 diff --git a/lcci/10.11.Peaks and Valleys/Solution.cpp b/lcci/10.11.Peaks and Valleys/Solution.cpp index d9b0897c0d24b..51c54103e21a8 100644 --- a/lcci/10.11.Peaks and Valleys/Solution.cpp +++ b/lcci/10.11.Peaks and Valleys/Solution.cpp @@ -1,10 +1,10 @@ -class Solution { -public: - void wiggleSort(vector& nums) { - sort(nums.begin(), nums.end()); - int n = nums.size(); - for (int i = 0; i < n - 1; i += 2) { - swap(nums[i], nums[i + 1]); - } - } +class Solution { +public: + void wiggleSort(vector& nums) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + for (int i = 0; i < n - 1; i += 2) { + swap(nums[i], nums[i + 1]); + } + } }; \ No newline at end of file diff --git a/lcci/10.11.Peaks and Valleys/Solution.java b/lcci/10.11.Peaks and Valleys/Solution.java index 8486ae1b5c647..a09a65340ed16 100644 --- a/lcci/10.11.Peaks and Valleys/Solution.java +++ b/lcci/10.11.Peaks and Valleys/Solution.java @@ -1,11 +1,11 @@ -class Solution { - public void wiggleSort(int[] nums) { - Arrays.sort(nums); - int n = nums.length; - for (int i = 0; i < n - 1; i += 2) { - int t = nums[i]; - nums[i] = nums[i + 1]; - nums[i + 1] = t; - } - } +class Solution { + public void wiggleSort(int[] nums) { + Arrays.sort(nums); + int n = nums.length; + for (int i = 0; i < n - 1; i += 2) { + int t = nums[i]; + nums[i] = nums[i + 1]; + nums[i + 1] = t; + } + } } \ No newline at end of file diff --git a/lcci/10.11.Peaks and Valleys/Solution.py b/lcci/10.11.Peaks and Valleys/Solution.py index 9d8704ecd52c1..b41bf547b6802 100644 --- a/lcci/10.11.Peaks and Valleys/Solution.py +++ b/lcci/10.11.Peaks and Valleys/Solution.py @@ -1,5 +1,5 @@ -class Solution: - def wiggleSort(self, nums: List[int]) -> None: - nums.sort() - for i in range(0, len(nums), 2): - nums[i : i + 2] = nums[i : i + 2][::-1] +class Solution: + def wiggleSort(self, nums: List[int]) -> None: + nums.sort() + for i in range(0, len(nums), 2): + nums[i : i + 2] = nums[i : i + 2][::-1] diff --git a/lcci/16.01.Swap Numbers/Solution2.ts b/lcci/16.01.Swap Numbers/Solution2.ts new file mode 100644 index 0000000000000..52ddec9cb3dfe --- /dev/null +++ b/lcci/16.01.Swap Numbers/Solution2.ts @@ -0,0 +1,4 @@ +function swapNumbers(numbers: number[]): number[] { + [numbers[0], numbers[1]] = [numbers[1], numbers[0]]; + return numbers; +} diff --git a/lcci/16.02.Words Frequency/Solution.py b/lcci/16.02.Words Frequency/Solution.py index f4fa1f1747c74..68ed016d35bb9 100644 --- a/lcci/16.02.Words Frequency/Solution.py +++ b/lcci/16.02.Words Frequency/Solution.py @@ -1,11 +1,11 @@ -class WordsFrequency: - def __init__(self, book: List[str]): - self.cnt = Counter(book) - - def get(self, word: str) -> int: - return self.cnt[word] - - -# Your WordsFrequency object will be instantiated and called as such: -# obj = WordsFrequency(book) -# param_1 = obj.get(word) +class WordsFrequency: + def __init__(self, book: List[str]): + self.cnt = Counter(book) + + def get(self, word: str) -> int: + return self.cnt[word] + + +# Your WordsFrequency object will be instantiated and called as such: +# obj = WordsFrequency(book) +# param_1 = obj.get(word) diff --git a/lcci/16.05.Factorial Zeros/Solution.cpp b/lcci/16.05.Factorial Zeros/Solution.cpp index 54a7e93e3fffb..0548171db4c53 100644 --- a/lcci/16.05.Factorial Zeros/Solution.cpp +++ b/lcci/16.05.Factorial Zeros/Solution.cpp @@ -1,11 +1,11 @@ -class Solution { -public: - int trailingZeroes(int n) { - int ans = 0; - while (n) { - n /= 5; - ans += n; - } - return ans; - } +class Solution { +public: + int trailingZeroes(int n) { + int ans = 0; + while (n) { + n /= 5; + ans += n; + } + return ans; + } }; \ No newline at end of file diff --git a/lcci/16.05.Factorial Zeros/Solution.java b/lcci/16.05.Factorial Zeros/Solution.java index 030ddb17b63ee..1669c7dbf98d4 100644 --- a/lcci/16.05.Factorial Zeros/Solution.java +++ b/lcci/16.05.Factorial Zeros/Solution.java @@ -1,10 +1,10 @@ -class Solution { - public int trailingZeroes(int n) { - int ans = 0; - while (n > 0) { - n /= 5; - ans += n; - } - return ans; - } +class Solution { + public int trailingZeroes(int n) { + int ans = 0; + while (n > 0) { + n /= 5; + ans += n; + } + return ans; + } } \ No newline at end of file diff --git a/lcci/16.05.Factorial Zeros/Solution.py b/lcci/16.05.Factorial Zeros/Solution.py index 4f64e26ddaf49..159c3b331678f 100644 --- a/lcci/16.05.Factorial Zeros/Solution.py +++ b/lcci/16.05.Factorial Zeros/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def trailingZeroes(self, n: int) -> int: - ans = 0 - while n: - n //= 5 - ans += n - return ans +class Solution: + def trailingZeroes(self, n: int) -> int: + ans = 0 + while n: + n //= 5 + ans += n + return ans diff --git a/lcci/16.06.Smallest Difference/Solution.cpp b/lcci/16.06.Smallest Difference/Solution.cpp index 20da03808fc15..b28411c3e1b88 100644 --- a/lcci/16.06.Smallest Difference/Solution.cpp +++ b/lcci/16.06.Smallest Difference/Solution.cpp @@ -1,18 +1,17 @@ -class Solution { -public: - int smallestDifference(vector& a, vector& b) { - sort(a.begin(), a.end()); - sort(b.begin(), b.end()); - int i = 0, j = 0; - long long ans = LONG_LONG_MAX; - while (i < a.size() && j < b.size()) { - ans = min(ans, abs(1LL * a[i] - 1LL * b[j])); - if (a[i] < b[j]) { - ++i; - } else { - ++j; - } - } - return ans; - } +class Solution { +public: + int smallestDifference(vector& a, vector& b) { + sort(b.begin(), b.end()); + long long ans = LONG_LONG_MAX; + for (int x : a) { + auto it = lower_bound(b.begin(), b.end(), x); + if (it != b.end()) { + ans = min(ans, (long long) *it - x); + } + if (it != b.begin()) { + ans = min(ans, x - (long long) *prev(it)); + } + } + return ans; + } }; \ No newline at end of file diff --git a/lcci/16.06.Smallest Difference/Solution.go b/lcci/16.06.Smallest Difference/Solution.go index 916cdfcb9bc9d..eed5b6c697cdd 100644 --- a/lcci/16.06.Smallest Difference/Solution.go +++ b/lcci/16.06.Smallest Difference/Solution.go @@ -1,22 +1,14 @@ func smallestDifference(a []int, b []int) int { - sort.Ints(a) sort.Ints(b) - i, j := 0, 0 var ans int = 1e18 - for i < len(a) && j < len(b) { - ans = min(ans, abs(a[i]-b[j])) - if a[i] < b[j] { - i++ - } else { - j++ + for _, x := range a { + i := sort.SearchInts(b, x) + if i < len(b) { + ans = min(ans, b[i]-x) + } + if i > 0 { + ans = min(ans, x-b[i-1]) } } return ans -} - -func abs(a int) int { - if a < 0 { - return -a - } - return a } \ No newline at end of file diff --git a/lcci/16.06.Smallest Difference/Solution.java b/lcci/16.06.Smallest Difference/Solution.java index d52ce57673417..35be65b37faa9 100644 --- a/lcci/16.06.Smallest Difference/Solution.java +++ b/lcci/16.06.Smallest Difference/Solution.java @@ -1,17 +1,29 @@ -class Solution { - public int smallestDifference(int[] a, int[] b) { - Arrays.sort(a); - Arrays.sort(b); - int i = 0, j = 0; - long ans = Long.MAX_VALUE; - while (i < a.length && j < b.length) { - ans = Math.min(ans, Math.abs((long) a[i] - (long) b[j])); - if (a[i] < b[j]) { - ++i; - } else { - ++j; - } - } - return (int) ans; - } +class Solution { + public int smallestDifference(int[] a, int[] b) { + Arrays.sort(b); + long ans = Long.MAX_VALUE; + for (int x : a) { + int j = search(b, x); + if (j < b.length) { + ans = Math.min(ans, (long) b[j] - x); + } + if (j > 0) { + ans = Math.min(ans, (long) x - b[j - 1]); + } + } + return (int) ans; + } + + private int search(int[] nums, int x) { + int l = 0, r = nums.length; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } } \ No newline at end of file diff --git a/lcci/16.06.Smallest Difference/Solution.py b/lcci/16.06.Smallest Difference/Solution.py index af716e9044e3c..3a1fc78cb27fd 100644 --- a/lcci/16.06.Smallest Difference/Solution.py +++ b/lcci/16.06.Smallest Difference/Solution.py @@ -1,13 +1,12 @@ -class Solution: - def smallestDifference(self, a: List[int], b: List[int]) -> int: - a.sort() - b.sort() - i = j = 0 - ans = inf - while i < len(a) and j < len(b): - ans = min(ans, abs(a[i] - b[j])) - if a[i] < b[j]: - i += 1 - else: - j += 1 - return ans +class Solution: + def smallestDifference(self, a: List[int], b: List[int]) -> int: + b.sort() + ans = inf + n = len(b) + for x in a: + j = bisect_left(b, x) + if j < n: + ans = min(ans, b[j] - x) + if j: + ans = min(ans, x - b[j - 1]) + return ans diff --git a/lcci/16.06.Smallest Difference/Solution.ts b/lcci/16.06.Smallest Difference/Solution.ts index 8f848fcff7f39..bf967c41c2381 100644 --- a/lcci/16.06.Smallest Difference/Solution.ts +++ b/lcci/16.06.Smallest Difference/Solution.ts @@ -1,14 +1,25 @@ function smallestDifference(a: number[], b: number[]): number { - a.sort((a, b) => a - b); b.sort((a, b) => a - b); - let [i, j] = [0, 0]; let ans = Infinity; - while (i < a.length && j < b.length) { - ans = Math.min(ans, Math.abs(a[i] - b[j])); - if (a[i] < b[j]) { - ++i; - } else { - ++j; + const search = (nums: number[], x: number): number => { + let [l, r] = [0, nums.length]; + while (l < r) { + const mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + for (const x of a) { + const j = search(b, x); + if (j < b.length) { + ans = Math.min(ans, b[j] - x); + } + if (j > 0) { + ans = Math.min(ans, x - b[j - 1]); } } return ans; diff --git a/lcci/16.06.Smallest Difference/Solution2.cpp b/lcci/16.06.Smallest Difference/Solution2.cpp new file mode 100644 index 0000000000000..17dc7df3314f2 --- /dev/null +++ b/lcci/16.06.Smallest Difference/Solution2.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int smallestDifference(vector& a, vector& b) { + sort(a.begin(), a.end()); + sort(b.begin(), b.end()); + int i = 0, j = 0; + long long ans = LONG_LONG_MAX; + while (i < a.size() && j < b.size()) { + ans = min(ans, abs(1LL * a[i] - 1LL * b[j])); + if (a[i] < b[j]) { + ++i; + } else { + ++j; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/lcci/16.06.Smallest Difference/Solution2.go b/lcci/16.06.Smallest Difference/Solution2.go new file mode 100644 index 0000000000000..916cdfcb9bc9d --- /dev/null +++ b/lcci/16.06.Smallest Difference/Solution2.go @@ -0,0 +1,22 @@ +func smallestDifference(a []int, b []int) int { + sort.Ints(a) + sort.Ints(b) + i, j := 0, 0 + var ans int = 1e18 + for i < len(a) && j < len(b) { + ans = min(ans, abs(a[i]-b[j])) + if a[i] < b[j] { + i++ + } else { + j++ + } + } + return ans +} + +func abs(a int) int { + if a < 0 { + return -a + } + return a +} \ No newline at end of file diff --git a/lcci/16.06.Smallest Difference/Solution2.java b/lcci/16.06.Smallest Difference/Solution2.java new file mode 100644 index 0000000000000..713f3aefb8ab4 --- /dev/null +++ b/lcci/16.06.Smallest Difference/Solution2.java @@ -0,0 +1,17 @@ +class Solution { + public int smallestDifference(int[] a, int[] b) { + Arrays.sort(a); + Arrays.sort(b); + int i = 0, j = 0; + long ans = Long.MAX_VALUE; + while (i < a.length && j < b.length) { + ans = Math.min(ans, Math.abs((long) a[i] - (long) b[j])); + if (a[i] < b[j]) { + ++i; + } else { + ++j; + } + } + return (int) ans; + } +} \ No newline at end of file diff --git a/lcci/16.06.Smallest Difference/Solution2.py b/lcci/16.06.Smallest Difference/Solution2.py new file mode 100644 index 0000000000000..0d9aa3c785479 --- /dev/null +++ b/lcci/16.06.Smallest Difference/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def smallestDifference(self, a: List[int], b: List[int]) -> int: + a.sort() + b.sort() + i = j = 0 + ans = inf + while i < len(a) and j < len(b): + ans = min(ans, abs(a[i] - b[j])) + if a[i] < b[j]: + i += 1 + else: + j += 1 + return ans diff --git a/lcci/16.06.Smallest Difference/Solution2.ts b/lcci/16.06.Smallest Difference/Solution2.ts new file mode 100644 index 0000000000000..8f848fcff7f39 --- /dev/null +++ b/lcci/16.06.Smallest Difference/Solution2.ts @@ -0,0 +1,15 @@ +function smallestDifference(a: number[], b: number[]): number { + a.sort((a, b) => a - b); + b.sort((a, b) => a - b); + let [i, j] = [0, 0]; + let ans = Infinity; + while (i < a.length && j < b.length) { + ans = Math.min(ans, Math.abs(a[i] - b[j])); + if (a[i] < b[j]) { + ++i; + } else { + ++j; + } + } + return ans; +} diff --git a/lcci/16.07.Maximum/Solution.cpp b/lcci/16.07.Maximum/Solution.cpp index d37768a7d2dff..cd6df9d03a4fa 100644 --- a/lcci/16.07.Maximum/Solution.cpp +++ b/lcci/16.07.Maximum/Solution.cpp @@ -1,7 +1,7 @@ -class Solution { -public: - int maximum(int a, int b) { - int k = ((static_cast(a) - static_cast(b)) >> 63) & 1; - return a * (k ^ 1) + b * k; - } +class Solution { +public: + int maximum(int a, int b) { + int k = ((static_cast(a) - static_cast(b)) >> 63) & 1; + return a * (k ^ 1) + b * k; + } }; \ No newline at end of file diff --git a/lcci/16.07.Maximum/Solution.java b/lcci/16.07.Maximum/Solution.java index 2befc526919ca..aaa20bf4dc217 100644 --- a/lcci/16.07.Maximum/Solution.java +++ b/lcci/16.07.Maximum/Solution.java @@ -1,6 +1,6 @@ -class Solution { - public int maximum(int a, int b) { - int k = (int) (((long) a - (long) b) >> 63) & 1; - return a * (k ^ 1) + b * k; - } +class Solution { + public int maximum(int a, int b) { + int k = (int) (((long) a - (long) b) >> 63) & 1; + return a * (k ^ 1) + b * k; + } } \ No newline at end of file diff --git a/lcci/16.07.Maximum/Solution.py b/lcci/16.07.Maximum/Solution.py index 28d5d7cefe6a6..fd7cfe456005c 100644 --- a/lcci/16.07.Maximum/Solution.py +++ b/lcci/16.07.Maximum/Solution.py @@ -1,4 +1,4 @@ -class Solution: - def maximum(self, a: int, b: int) -> int: - k = (int(((a - b) & 0xFFFFFFFFFFFFFFFF) >> 63)) & 1 - return a * (k ^ 1) + b * k +class Solution: + def maximum(self, a: int, b: int) -> int: + k = (int(((a - b) & 0xFFFFFFFFFFFFFFFF) >> 63)) & 1 + return a * (k ^ 1) + b * k diff --git a/lcci/16.10.Living People/Solution.cpp b/lcci/16.10.Living People/Solution.cpp index 4631e89718cfb..78ca16966b9b1 100644 --- a/lcci/16.10.Living People/Solution.cpp +++ b/lcci/16.10.Living People/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - int maxAliveYear(vector& birth, vector& death) { - int base = 1900; - int d[102]{}; - for (int i = 0; i < birth.size(); ++i) { - int a = birth[i] - base; - int b = death[i] - base; - ++d[a]; - --d[b + 1]; - } - int s = 0, mx = 0; - int ans = 0; - for (int i = 0; i < 102; ++i) { - s += d[i]; - if (mx < s) { - mx = s; - ans = base + i; - } - } - return ans; - } +class Solution { +public: + int maxAliveYear(vector& birth, vector& death) { + int base = 1900; + int d[102]{}; + for (int i = 0; i < birth.size(); ++i) { + int a = birth[i] - base; + int b = death[i] - base; + ++d[a]; + --d[b + 1]; + } + int s = 0, mx = 0; + int ans = 0; + for (int i = 0; i < 102; ++i) { + s += d[i]; + if (mx < s) { + mx = s; + ans = base + i; + } + } + return ans; + } }; \ No newline at end of file diff --git a/lcci/16.10.Living People/Solution.java b/lcci/16.10.Living People/Solution.java index 6b442114cbc11..5180e1b6e633e 100644 --- a/lcci/16.10.Living People/Solution.java +++ b/lcci/16.10.Living People/Solution.java @@ -1,22 +1,22 @@ -class Solution { - public int maxAliveYear(int[] birth, int[] death) { - int base = 1900; - int[] d = new int[102]; - for (int i = 0; i < birth.length; ++i) { - int a = birth[i] - base; - int b = death[i] - base; - ++d[a]; - --d[b + 1]; - } - int s = 0, mx = 0; - int ans = 0; - for (int i = 0; i < d.length; ++i) { - s += d[i]; - if (mx < s) { - mx = s; - ans = base + i; - } - } - return ans; - } +class Solution { + public int maxAliveYear(int[] birth, int[] death) { + int base = 1900; + int[] d = new int[102]; + for (int i = 0; i < birth.length; ++i) { + int a = birth[i] - base; + int b = death[i] - base; + ++d[a]; + --d[b + 1]; + } + int s = 0, mx = 0; + int ans = 0; + for (int i = 0; i < d.length; ++i) { + s += d[i]; + if (mx < s) { + mx = s; + ans = base + i; + } + } + return ans; + } } \ No newline at end of file diff --git a/lcci/16.10.Living People/Solution.py b/lcci/16.10.Living People/Solution.py index be2b910ba7ed5..e6f6f9712d646 100644 --- a/lcci/16.10.Living People/Solution.py +++ b/lcci/16.10.Living People/Solution.py @@ -1,15 +1,15 @@ -class Solution: - def maxAliveYear(self, birth: List[int], death: List[int]) -> int: - base = 1900 - d = [0] * 102 - for a, b in zip(birth, death): - d[a - base] += 1 - d[b + 1 - base] -= 1 - s = mx = 0 - ans = 0 - for i, x in enumerate(d): - s += x - if mx < s: - mx = s - ans = base + i - return ans +class Solution: + def maxAliveYear(self, birth: List[int], death: List[int]) -> int: + base = 1900 + d = [0] * 102 + for a, b in zip(birth, death): + d[a - base] += 1 + d[b + 1 - base] -= 1 + s = mx = 0 + ans = 0 + for i, x in enumerate(d): + s += x + if mx < s: + mx = s + ans = base + i + return ans diff --git a/lcci/16.13.Bisect Squares/Solution.cpp b/lcci/16.13.Bisect Squares/Solution.cpp index 110a7f3462d1d..4a1e3b8d1ddf8 100644 --- a/lcci/16.13.Bisect Squares/Solution.cpp +++ b/lcci/16.13.Bisect Squares/Solution.cpp @@ -1,32 +1,32 @@ -class Solution { -public: - vector cutSquares(vector& square1, vector& square2) { - double x1 = square1[0] + square1[2] / 2.0; - double y1 = square1[1] + square1[2] / 2.0; - double x2 = square2[0] + square2[2] / 2.0; - double y2 = square2[1] + square2[2] / 2.0; - if (x1 == x2) { - double y3 = min(square1[1], square2[1]); - double y4 = max(square1[1] + square1[2], square2[1] + square2[2]); - return {x1, y3, x2, y4}; - } - double k = (y2 - y1) / (x2 - x1); - double b = y1 - k * x1; - if (abs(k) > 1) { - double y3 = min(square1[1], square2[1]); - double x3 = (y3 - b) / k; - double y4 = max(square1[1] + square1[2], square2[1] + square2[2]); - double x4 = (y4 - b) / k; - if (x3 > x4 || (x3 == x4 && y3 > y4)) { - return {x4, y4, x3, y3}; - } - return {x3, y3, x4, y4}; - } else { - double x3 = min(square1[0], square2[0]); - double y3 = k * x3 + b; - double x4 = max(square1[0] + square1[2], square2[0] + square2[2]); - double y4 = k * x4 + b; - return {x3, y3, x4, y4}; - } - } +class Solution { +public: + vector cutSquares(vector& square1, vector& square2) { + double x1 = square1[0] + square1[2] / 2.0; + double y1 = square1[1] + square1[2] / 2.0; + double x2 = square2[0] + square2[2] / 2.0; + double y2 = square2[1] + square2[2] / 2.0; + if (x1 == x2) { + double y3 = min(square1[1], square2[1]); + double y4 = max(square1[1] + square1[2], square2[1] + square2[2]); + return {x1, y3, x2, y4}; + } + double k = (y2 - y1) / (x2 - x1); + double b = y1 - k * x1; + if (abs(k) > 1) { + double y3 = min(square1[1], square2[1]); + double x3 = (y3 - b) / k; + double y4 = max(square1[1] + square1[2], square2[1] + square2[2]); + double x4 = (y4 - b) / k; + if (x3 > x4 || (x3 == x4 && y3 > y4)) { + return {x4, y4, x3, y3}; + } + return {x3, y3, x4, y4}; + } else { + double x3 = min(square1[0], square2[0]); + double y3 = k * x3 + b; + double x4 = max(square1[0] + square1[2], square2[0] + square2[2]); + double y4 = k * x4 + b; + return {x3, y3, x4, y4}; + } + } }; \ No newline at end of file diff --git a/lcci/16.13.Bisect Squares/Solution.java b/lcci/16.13.Bisect Squares/Solution.java index 433fa614af8b0..9dd6521c5e6bf 100644 --- a/lcci/16.13.Bisect Squares/Solution.java +++ b/lcci/16.13.Bisect Squares/Solution.java @@ -1,31 +1,31 @@ -class Solution { - public double[] cutSquares(int[] square1, int[] square2) { - double x1 = square1[0] + square1[2] / 2.0; - double y1 = square1[1] + square1[2] / 2.0; - double x2 = square2[0] + square2[2] / 2.0; - double y2 = square2[1] + square2[2] / 2.0; - if (x1 == x2) { - double y3 = Math.min(square1[1], square2[1]); - double y4 = Math.max(square1[1] + square1[2], square2[1] + square2[2]); - return new double[] {x1, y3, x2, y4}; - } - double k = (y2 - y1) / (x2 - x1); - double b = y1 - k * x1; - if (Math.abs(k) > 1) { - double y3 = Math.min(square1[1], square2[1]); - double x3 = (y3 - b) / k; - double y4 = Math.max(square1[1] + square1[2], square2[1] + square2[2]); - double x4 = (y4 - b) / k; - if (x3 > x4 || (x3 == x4 && y3 > y4)) { - return new double[] {x4, y4, x3, y3}; - } - return new double[] {x3, y3, x4, y4}; - } else { - double x3 = Math.min(square1[0], square2[0]); - double y3 = k * x3 + b; - double x4 = Math.max(square1[0] + square1[2], square2[0] + square2[2]); - double y4 = k * x4 + b; - return new double[] {x3, y3, x4, y4}; - } - } +class Solution { + public double[] cutSquares(int[] square1, int[] square2) { + double x1 = square1[0] + square1[2] / 2.0; + double y1 = square1[1] + square1[2] / 2.0; + double x2 = square2[0] + square2[2] / 2.0; + double y2 = square2[1] + square2[2] / 2.0; + if (x1 == x2) { + double y3 = Math.min(square1[1], square2[1]); + double y4 = Math.max(square1[1] + square1[2], square2[1] + square2[2]); + return new double[] {x1, y3, x2, y4}; + } + double k = (y2 - y1) / (x2 - x1); + double b = y1 - k * x1; + if (Math.abs(k) > 1) { + double y3 = Math.min(square1[1], square2[1]); + double x3 = (y3 - b) / k; + double y4 = Math.max(square1[1] + square1[2], square2[1] + square2[2]); + double x4 = (y4 - b) / k; + if (x3 > x4 || (x3 == x4 && y3 > y4)) { + return new double[] {x4, y4, x3, y3}; + } + return new double[] {x3, y3, x4, y4}; + } else { + double x3 = Math.min(square1[0], square2[0]); + double y3 = k * x3 + b; + double x4 = Math.max(square1[0] + square1[2], square2[0] + square2[2]); + double y4 = k * x4 + b; + return new double[] {x3, y3, x4, y4}; + } + } } \ No newline at end of file diff --git a/lcci/16.13.Bisect Squares/Solution.py b/lcci/16.13.Bisect Squares/Solution.py index 5fbe90850299a..dae272eb2adaf 100644 --- a/lcci/16.13.Bisect Squares/Solution.py +++ b/lcci/16.13.Bisect Squares/Solution.py @@ -1,23 +1,23 @@ -class Solution: - def cutSquares(self, square1: List[int], square2: List[int]) -> List[float]: - x1, y1 = square1[0] + square1[2] / 2, square1[1] + square1[2] / 2 - x2, y2 = square2[0] + square2[2] / 2, square2[1] + square2[2] / 2 - if x1 == x2: - y3 = min(square1[1], square2[1]) - y4 = max(square1[1] + square1[2], square2[1] + square2[2]) - return [x1, y3, x2, y4] - k = (y2 - y1) / (x2 - x1) - b = y1 - k * x1 - if abs(k) > 1: - y3 = min(square1[1], square2[1]) - x3 = (y3 - b) / k - y4 = max(square1[1] + square1[2], square2[1] + square2[2]) - x4 = (y4 - b) / k - if x3 > x4 or (x3 == x4 and y3 > y4): - x3, y3, x4, y4 = x4, y4, x3, y3 - else: - x3 = min(square1[0], square2[0]) - y3 = k * x3 + b - x4 = max(square1[0] + square1[2], square2[0] + square2[2]) - y4 = k * x4 + b - return [x3, y3, x4, y4] +class Solution: + def cutSquares(self, square1: List[int], square2: List[int]) -> List[float]: + x1, y1 = square1[0] + square1[2] / 2, square1[1] + square1[2] / 2 + x2, y2 = square2[0] + square2[2] / 2, square2[1] + square2[2] / 2 + if x1 == x2: + y3 = min(square1[1], square2[1]) + y4 = max(square1[1] + square1[2], square2[1] + square2[2]) + return [x1, y3, x2, y4] + k = (y2 - y1) / (x2 - x1) + b = y1 - k * x1 + if abs(k) > 1: + y3 = min(square1[1], square2[1]) + x3 = (y3 - b) / k + y4 = max(square1[1] + square1[2], square2[1] + square2[2]) + x4 = (y4 - b) / k + if x3 > x4 or (x3 == x4 and y3 > y4): + x3, y3, x4, y4 = x4, y4, x3, y3 + else: + x3 = min(square1[0], square2[0]) + y3 = k * x3 + b + x4 = max(square1[0] + square1[2], square2[0] + square2[2]) + y4 = k * x4 + b + return [x3, y3, x4, y4] diff --git a/lcci/16.14.Best Line/Solution.cpp b/lcci/16.14.Best Line/Solution.cpp index 7da3310b9f7f8..2a53ae53c2789 100644 --- a/lcci/16.14.Best Line/Solution.cpp +++ b/lcci/16.14.Best Line/Solution.cpp @@ -3,26 +3,25 @@ class Solution { vector bestLine(vector>& points) { int n = points.size(); int mx = 0; - pair ans = {0, 0}; + vector ans(2); for (int i = 0; i < n; ++i) { int x1 = points[i][0], y1 = points[i][1]; - unordered_map>> cnt; for (int j = i + 1; j < n; ++j) { int x2 = points[j][0], y2 = points[j][1]; - int dx = x2 - x1, dy = y2 - y1; - int g = gcd(dx, dy); - string k = to_string(dx / g) + "." + to_string(dy / g); - cnt[k].push_back({i, j}); - if (mx < cnt[k].size() || (mx == cnt[k].size() && ans > cnt[k][0])) { - mx = cnt[k].size(); - ans = cnt[k][0]; + int cnt = 2; + for (int k = j + 1; k < n; ++k) { + int x3 = points[k][0], y3 = points[k][1]; + long a = (long) (y2 - y1) * (x3 - x1); + long b = (long) (y3 - y1) * (x2 - x1); + cnt += a == b; + } + if (mx < cnt) { + mx = cnt; + ans[0] = i; + ans[1] = j; } } } - return vector{ans.first, ans.second}; - } - - int gcd(int a, int b) { - return b == 0 ? a : gcd(b, a % b); + return ans; } }; \ No newline at end of file diff --git a/lcci/16.14.Best Line/Solution.go b/lcci/16.14.Best Line/Solution.go index 8c94fcc409ed5..e74d21c3c34a9 100644 --- a/lcci/16.14.Best Line/Solution.go +++ b/lcci/16.14.Best Line/Solution.go @@ -1,29 +1,25 @@ func bestLine(points [][]int) []int { n := len(points) ans := make([]int, 2) - type pair struct{ i, j int } mx := 0 for i := 0; i < n; i++ { x1, y1 := points[i][0], points[i][1] - cnt := map[pair][]pair{} for j := i + 1; j < n; j++ { x2, y2 := points[j][0], points[j][1] - dx, dy := x2-x1, y2-y1 - g := gcd(dx, dy) - k := pair{dx / g, dy / g} - cnt[k] = append(cnt[k], pair{i, j}) - if mx < len(cnt[k]) || (mx == len(cnt[k]) && (ans[0] > cnt[k][0].i || (ans[0] == cnt[k][0].i && ans[1] > cnt[k][0].j))) { - mx = len(cnt[k]) - ans[0], ans[1] = cnt[k][0].i, cnt[k][0].j + cnt := 2 + for k := j + 1; k < n; k++ { + x3, y3 := points[k][0], points[k][1] + a := (y2 - y1) * (x3 - x1) + b := (y3 - y1) * (x2 - x1) + if a == b { + cnt++ + } + } + if mx < cnt { + mx = cnt + ans[0], ans[1] = i, j } } } return ans -} - -func gcd(a, b int) int { - if b == 0 { - return a - } - return gcd(b, a%b) } \ No newline at end of file diff --git a/lcci/16.14.Best Line/Solution.py b/lcci/16.14.Best Line/Solution.py index 4eba1489f3650..2ea483c9164b3 100644 --- a/lcci/16.14.Best Line/Solution.py +++ b/lcci/16.14.Best Line/Solution.py @@ -1,20 +1,18 @@ class Solution: def bestLine(self, points: List[List[int]]) -> List[int]: - def gcd(a, b): - return a if b == 0 else gcd(b, a % b) - n = len(points) mx = 0 for i in range(n): x1, y1 = points[i] - cnt = defaultdict(list) for j in range(i + 1, n): x2, y2 = points[j] - dx, dy = x2 - x1, y2 - y1 - g = gcd(dx, dy) - k = (dx // g, dy // g) - cnt[k].append((i, j)) - if mx < len(cnt[k]) or (mx == len(cnt[k]) and (x, y) > cnt[k][0]): - mx = len(cnt[k]) - x, y = cnt[k][0] + cnt = 2 + for k in range(j + 1, n): + x3, y3 = points[k] + a = (y2 - y1) * (x3 - x1) + b = (y3 - y1) * (x2 - x1) + cnt += a == b + if mx < cnt: + mx = cnt + x, y = i, j return [x, y] diff --git a/lcci/16.14.Best Line/Solution2.cpp b/lcci/16.14.Best Line/Solution2.cpp new file mode 100644 index 0000000000000..7da3310b9f7f8 --- /dev/null +++ b/lcci/16.14.Best Line/Solution2.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + vector bestLine(vector>& points) { + int n = points.size(); + int mx = 0; + pair ans = {0, 0}; + for (int i = 0; i < n; ++i) { + int x1 = points[i][0], y1 = points[i][1]; + unordered_map>> cnt; + for (int j = i + 1; j < n; ++j) { + int x2 = points[j][0], y2 = points[j][1]; + int dx = x2 - x1, dy = y2 - y1; + int g = gcd(dx, dy); + string k = to_string(dx / g) + "." + to_string(dy / g); + cnt[k].push_back({i, j}); + if (mx < cnt[k].size() || (mx == cnt[k].size() && ans > cnt[k][0])) { + mx = cnt[k].size(); + ans = cnt[k][0]; + } + } + } + return vector{ans.first, ans.second}; + } + + int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +}; \ No newline at end of file diff --git a/lcci/16.14.Best Line/Solution2.go b/lcci/16.14.Best Line/Solution2.go new file mode 100644 index 0000000000000..8c94fcc409ed5 --- /dev/null +++ b/lcci/16.14.Best Line/Solution2.go @@ -0,0 +1,29 @@ +func bestLine(points [][]int) []int { + n := len(points) + ans := make([]int, 2) + type pair struct{ i, j int } + mx := 0 + for i := 0; i < n; i++ { + x1, y1 := points[i][0], points[i][1] + cnt := map[pair][]pair{} + for j := i + 1; j < n; j++ { + x2, y2 := points[j][0], points[j][1] + dx, dy := x2-x1, y2-y1 + g := gcd(dx, dy) + k := pair{dx / g, dy / g} + cnt[k] = append(cnt[k], pair{i, j}) + if mx < len(cnt[k]) || (mx == len(cnt[k]) && (ans[0] > cnt[k][0].i || (ans[0] == cnt[k][0].i && ans[1] > cnt[k][0].j))) { + mx = len(cnt[k]) + ans[0], ans[1] = cnt[k][0].i, cnt[k][0].j + } + } + } + return ans +} + +func gcd(a, b int) int { + if b == 0 { + return a + } + return gcd(b, a%b) +} \ No newline at end of file diff --git a/lcci/16.14.Best Line/Solution2.java b/lcci/16.14.Best Line/Solution2.java new file mode 100644 index 0000000000000..ba04acbec2a17 --- /dev/null +++ b/lcci/16.14.Best Line/Solution2.java @@ -0,0 +1,31 @@ +class Solution { + public int[] bestLine(int[][] points) { + int n = points.length; + int mx = 0; + int[] ans = new int[2]; + for (int i = 0; i < n; ++i) { + int x1 = points[i][0], y1 = points[i][1]; + Map> cnt = new HashMap<>(); + for (int j = i + 1; j < n; ++j) { + int x2 = points[j][0], y2 = points[j][1]; + int dx = x2 - x1, dy = y2 - y1; + int g = gcd(dx, dy); + String key = (dx / g) + "." + (dy / g); + cnt.computeIfAbsent(key, k -> new ArrayList<>()).add(new int[] {i, j}); + if (mx < cnt.get(key).size() + || (mx == cnt.get(key).size() + && (ans[0] > cnt.get(key).get(0)[0] + || (ans[0] == cnt.get(key).get(0)[0] + && ans[1] > cnt.get(key).get(0)[1])))) { + mx = cnt.get(key).size(); + ans = cnt.get(key).get(0); + } + } + } + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} \ No newline at end of file diff --git a/lcci/16.14.Best Line/Solution2.py b/lcci/16.14.Best Line/Solution2.py new file mode 100644 index 0000000000000..4eba1489f3650 --- /dev/null +++ b/lcci/16.14.Best Line/Solution2.py @@ -0,0 +1,20 @@ +class Solution: + def bestLine(self, points: List[List[int]]) -> List[int]: + def gcd(a, b): + return a if b == 0 else gcd(b, a % b) + + n = len(points) + mx = 0 + for i in range(n): + x1, y1 = points[i] + cnt = defaultdict(list) + for j in range(i + 1, n): + x2, y2 = points[j] + dx, dy = x2 - x1, y2 - y1 + g = gcd(dx, dy) + k = (dx // g, dy // g) + cnt[k].append((i, j)) + if mx < len(cnt[k]) or (mx == len(cnt[k]) and (x, y) > cnt[k][0]): + mx = len(cnt[k]) + x, y = cnt[k][0] + return [x, y] diff --git a/lcci/16.16.Sub Sort/Solution.cpp b/lcci/16.16.Sub Sort/Solution.cpp index ba78bb2fc9cce..9abda889d7a39 100644 --- a/lcci/16.16.Sub Sort/Solution.cpp +++ b/lcci/16.16.Sub Sort/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - vector subSort(vector& array) { - int n = array.size(); - int mi = INT_MAX, mx = INT_MIN; - int left = -1, right = -1; - for (int i = 0; i < n; ++i) { - if (array[i] < mx) { - right = i; - } else { - mx = array[i]; - } - } - for (int i = n - 1; ~i; --i) { - if (array[i] > mi) { - left = i; - } else { - mi = array[i]; - } - } - return {left, right}; - } +class Solution { +public: + vector subSort(vector& array) { + int n = array.size(); + int mi = INT_MAX, mx = INT_MIN; + int left = -1, right = -1; + for (int i = 0; i < n; ++i) { + if (array[i] < mx) { + right = i; + } else { + mx = array[i]; + } + } + for (int i = n - 1; ~i; --i) { + if (array[i] > mi) { + left = i; + } else { + mi = array[i]; + } + } + return {left, right}; + } }; \ No newline at end of file diff --git a/lcci/16.16.Sub Sort/Solution.java b/lcci/16.16.Sub Sort/Solution.java index 079d86e0626c9..7f47159d6a9e5 100644 --- a/lcci/16.16.Sub Sort/Solution.java +++ b/lcci/16.16.Sub Sort/Solution.java @@ -1,22 +1,22 @@ -class Solution { - public int[] subSort(int[] array) { - int n = array.length; - int mi = Integer.MAX_VALUE, mx = Integer.MIN_VALUE; - int left = -1, right = -1; - for (int i = 0; i < n; ++i) { - if (array[i] < mx) { - right = i; - } else { - mx = array[i]; - } - } - for (int i = n - 1; i >= 0; --i) { - if (array[i] > mi) { - left = i; - } else { - mi = array[i]; - } - } - return new int[] {left, right}; - } +class Solution { + public int[] subSort(int[] array) { + int n = array.length; + int mi = Integer.MAX_VALUE, mx = Integer.MIN_VALUE; + int left = -1, right = -1; + for (int i = 0; i < n; ++i) { + if (array[i] < mx) { + right = i; + } else { + mx = array[i]; + } + } + for (int i = n - 1; i >= 0; --i) { + if (array[i] > mi) { + left = i; + } else { + mi = array[i]; + } + } + return new int[] {left, right}; + } } \ No newline at end of file diff --git a/lcci/16.16.Sub Sort/Solution.py b/lcci/16.16.Sub Sort/Solution.py index 6f559e26dca6c..97244eae8354e 100644 --- a/lcci/16.16.Sub Sort/Solution.py +++ b/lcci/16.16.Sub Sort/Solution.py @@ -1,16 +1,16 @@ -class Solution: - def subSort(self, array: List[int]) -> List[int]: - n = len(array) - mi, mx = inf, -inf - left = right = -1 - for i, x in enumerate(array): - if x < mx: - right = i - else: - mx = x - for i in range(n - 1, -1, -1): - if array[i] > mi: - left = i - else: - mi = array[i] - return [left, right] +class Solution: + def subSort(self, array: List[int]) -> List[int]: + n = len(array) + mi, mx = inf, -inf + left = right = -1 + for i, x in enumerate(array): + if x < mx: + right = i + else: + mx = x + for i in range(n - 1, -1, -1): + if array[i] > mi: + left = i + else: + mi = array[i] + return [left, right] diff --git a/lcci/16.17.Contiguous Sequence/Solution.cpp b/lcci/16.17.Contiguous Sequence/Solution.cpp index 65ddc133a9870..77ee22c40b144 100644 --- a/lcci/16.17.Contiguous Sequence/Solution.cpp +++ b/lcci/16.17.Contiguous Sequence/Solution.cpp @@ -1,11 +1,11 @@ -class Solution { -public: - int maxSubArray(vector& nums) { - int ans = INT_MIN, f = INT_MIN; - for (int x : nums) { - f = max(f, 0) + x; - ans = max(ans, f); - } - return ans; - } +class Solution { +public: + int maxSubArray(vector& nums) { + int ans = INT_MIN, f = INT_MIN; + for (int x : nums) { + f = max(f, 0) + x; + ans = max(ans, f); + } + return ans; + } }; \ No newline at end of file diff --git a/lcci/16.17.Contiguous Sequence/Solution.java b/lcci/16.17.Contiguous Sequence/Solution.java index c4ca0298d29ab..005c55bbe0fe5 100644 --- a/lcci/16.17.Contiguous Sequence/Solution.java +++ b/lcci/16.17.Contiguous Sequence/Solution.java @@ -1,10 +1,10 @@ -class Solution { - public int maxSubArray(int[] nums) { - int ans = Integer.MIN_VALUE, f = Integer.MIN_VALUE; - for (int x : nums) { - f = Math.max(f, 0) + x; - ans = Math.max(ans, f); - } - return ans; - } +class Solution { + public int maxSubArray(int[] nums) { + int ans = Integer.MIN_VALUE, f = Integer.MIN_VALUE; + for (int x : nums) { + f = Math.max(f, 0) + x; + ans = Math.max(ans, f); + } + return ans; + } } \ No newline at end of file diff --git a/lcci/16.17.Contiguous Sequence/Solution.py b/lcci/16.17.Contiguous Sequence/Solution.py index 2ac17f23e4ef0..693d3a42211b8 100644 --- a/lcci/16.17.Contiguous Sequence/Solution.py +++ b/lcci/16.17.Contiguous Sequence/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def maxSubArray(self, nums: List[int]) -> int: - ans = f = -inf - for x in nums: - f = max(f, 0) + x - ans = max(ans, f) - return ans +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + ans = f = -inf + for x in nums: + f = max(f, 0) + x + ans = max(ans, f) + return ans diff --git a/lcci/16.18.Pattern Matching/Solution.cpp b/lcci/16.18.Pattern Matching/Solution.cpp index 8b3c00c642f9e..b71d1a7925e22 100644 --- a/lcci/16.18.Pattern Matching/Solution.cpp +++ b/lcci/16.18.Pattern Matching/Solution.cpp @@ -1,56 +1,56 @@ -class Solution { -public: - bool patternMatching(string pattern, string value) { - int n = value.size(); - int cnt[2]{}; - for (char c : pattern) { - cnt[c - 'a']++; - } - if (cnt[0] == 0) { - return n % cnt[1] == 0 && repeat(value.substr(0, n / cnt[1]), cnt[1]) == value; - } - if (cnt[1] == 0) { - return n % cnt[0] == 0 && repeat(value.substr(0, n / cnt[0]), cnt[0]) == value; - } - auto check = [&](int la, int lb) { - int i = 0; - string a, b; - for (char c : pattern) { - if (c == 'a') { - if (!a.empty() && a != value.substr(i, la)) { - return false; - } - a = value.substr(i, la); - i += la; - } else { - if (!b.empty() && b != value.substr(i, lb)) { - return false; - } - b = value.substr(i, lb); - i += lb; - } - } - return a != b; - }; - for (int la = 0; la <= n; ++la) { - if (la * cnt[0] > n) { - break; - } - if ((n - la * cnt[0]) % cnt[1] == 0) { - int lb = (n - la * cnt[0]) / cnt[1]; - if (check(la, lb)) { - return true; - } - } - } - return false; - } - - string repeat(string s, int n) { - string ans; - while (n--) { - ans += s; - } - return ans; - } +class Solution { +public: + bool patternMatching(string pattern, string value) { + int n = value.size(); + int cnt[2]{}; + for (char c : pattern) { + cnt[c - 'a']++; + } + if (cnt[0] == 0) { + return n % cnt[1] == 0 && repeat(value.substr(0, n / cnt[1]), cnt[1]) == value; + } + if (cnt[1] == 0) { + return n % cnt[0] == 0 && repeat(value.substr(0, n / cnt[0]), cnt[0]) == value; + } + auto check = [&](int la, int lb) { + int i = 0; + string a, b; + for (char c : pattern) { + if (c == 'a') { + if (!a.empty() && a != value.substr(i, la)) { + return false; + } + a = value.substr(i, la); + i += la; + } else { + if (!b.empty() && b != value.substr(i, lb)) { + return false; + } + b = value.substr(i, lb); + i += lb; + } + } + return a != b; + }; + for (int la = 0; la <= n; ++la) { + if (la * cnt[0] > n) { + break; + } + if ((n - la * cnt[0]) % cnt[1] == 0) { + int lb = (n - la * cnt[0]) / cnt[1]; + if (check(la, lb)) { + return true; + } + } + } + return false; + } + + string repeat(string s, int n) { + string ans; + while (n--) { + ans += s; + } + return ans; + } }; \ No newline at end of file diff --git a/lcci/16.18.Pattern Matching/Solution.java b/lcci/16.18.Pattern Matching/Solution.java index 0f6c1815e3ddb..9cbd98126f5f2 100644 --- a/lcci/16.18.Pattern Matching/Solution.java +++ b/lcci/16.18.Pattern Matching/Solution.java @@ -1,53 +1,53 @@ -class Solution { - private String pattern; - private String value; - - public boolean patternMatching(String pattern, String value) { - this.pattern = pattern; - this.value = value; - int[] cnt = new int[2]; - for (char c : pattern.toCharArray()) { - ++cnt[c - 'a']; - } - int n = value.length(); - if (cnt[0] == 0) { - return n % cnt[1] == 0 && value.substring(0, n / cnt[1]).repeat(cnt[1]).equals(value); - } - if (cnt[1] == 0) { - return n % cnt[0] == 0 && value.substring(0, n / cnt[0]).repeat(cnt[0]).equals(value); - } - for (int la = 0; la <= n; ++la) { - if (la * cnt[0] > n) { - break; - } - if ((n - la * cnt[0]) % cnt[1] == 0) { - int lb = (n - la * cnt[0]) / cnt[1]; - if (check(la, lb)) { - return true; - } - } - } - return false; - } - - private boolean check(int la, int lb) { - int i = 0; - String a = null, b = null; - for (char c : pattern.toCharArray()) { - if (c == 'a') { - if (a != null && !a.equals(value.substring(i, i + la))) { - return false; - } - a = value.substring(i, i + la); - i += la; - } else { - if (b != null && !b.equals(value.substring(i, i + lb))) { - return false; - } - b = value.substring(i, i + lb); - i += lb; - } - } - return !a.equals(b); - } +class Solution { + private String pattern; + private String value; + + public boolean patternMatching(String pattern, String value) { + this.pattern = pattern; + this.value = value; + int[] cnt = new int[2]; + for (char c : pattern.toCharArray()) { + ++cnt[c - 'a']; + } + int n = value.length(); + if (cnt[0] == 0) { + return n % cnt[1] == 0 && value.substring(0, n / cnt[1]).repeat(cnt[1]).equals(value); + } + if (cnt[1] == 0) { + return n % cnt[0] == 0 && value.substring(0, n / cnt[0]).repeat(cnt[0]).equals(value); + } + for (int la = 0; la <= n; ++la) { + if (la * cnt[0] > n) { + break; + } + if ((n - la * cnt[0]) % cnt[1] == 0) { + int lb = (n - la * cnt[0]) / cnt[1]; + if (check(la, lb)) { + return true; + } + } + } + return false; + } + + private boolean check(int la, int lb) { + int i = 0; + String a = null, b = null; + for (char c : pattern.toCharArray()) { + if (c == 'a') { + if (a != null && !a.equals(value.substring(i, i + la))) { + return false; + } + a = value.substring(i, i + la); + i += la; + } else { + if (b != null && !b.equals(value.substring(i, i + lb))) { + return false; + } + b = value.substring(i, i + lb); + i += lb; + } + } + return !a.equals(b); + } } \ No newline at end of file diff --git a/lcci/16.18.Pattern Matching/Solution.py b/lcci/16.18.Pattern Matching/Solution.py index 3d05b768dd19f..1119b02bd07bf 100644 --- a/lcci/16.18.Pattern Matching/Solution.py +++ b/lcci/16.18.Pattern Matching/Solution.py @@ -1,32 +1,32 @@ -class Solution: - def patternMatching(self, pattern: str, value: str) -> bool: - def check(la: int, lb: int) -> bool: - i = 0 - a, b = "", "" - for c in pattern: - if c == "a": - if a and value[i : i + la] != a: - return False - a = value[i : i + la] - i += la - else: - if b and value[i : i + lb] != b: - return False - b = value[i : i + lb] - i += lb - return a != b - - n = len(value) - cnt = Counter(pattern) - if cnt["a"] == 0: - return n % cnt["b"] == 0 and value[: n // cnt["b"]] * cnt["b"] == value - if cnt["b"] == 0: - return n % cnt["a"] == 0 and value[: n // cnt["a"]] * cnt["a"] == value - - for la in range(n + 1): - if la * cnt["a"] > n: - break - lb, mod = divmod(n - la * cnt["a"], cnt["b"]) - if mod == 0 and check(la, lb): - return True - return False +class Solution: + def patternMatching(self, pattern: str, value: str) -> bool: + def check(la: int, lb: int) -> bool: + i = 0 + a, b = "", "" + for c in pattern: + if c == "a": + if a and value[i : i + la] != a: + return False + a = value[i : i + la] + i += la + else: + if b and value[i : i + lb] != b: + return False + b = value[i : i + lb] + i += lb + return a != b + + n = len(value) + cnt = Counter(pattern) + if cnt["a"] == 0: + return n % cnt["b"] == 0 and value[: n // cnt["b"]] * cnt["b"] == value + if cnt["b"] == 0: + return n % cnt["a"] == 0 and value[: n // cnt["a"]] * cnt["a"] == value + + for la in range(n + 1): + if la * cnt["a"] > n: + break + lb, mod = divmod(n - la * cnt["a"], cnt["b"]) + if mod == 0 and check(la, lb): + return True + return False diff --git a/lcci/16.20.T9/Solution.py b/lcci/16.20.T9/Solution.py index db5cd911b00cd..be9edfdd55774 100644 --- a/lcci/16.20.T9/Solution.py +++ b/lcci/16.20.T9/Solution.py @@ -1,4 +1,7 @@ class Solution: def getValidT9Words(self, num: str, words: List[str]) -> List[str]: - trans = str.maketrans(ascii_lowercase, "22233344455566677778889999") - return [w for w in words if w.translate(trans) == num] + def check(w: str) -> bool: + return all(d[c] == num[i] for i, c in enumerate(w)) + + d = {c: d for c, d in zip(ascii_lowercase, "22233344455566677778889999")} + return [w for w in words if check(w)] diff --git a/lcci/16.20.T9/Solution2.py b/lcci/16.20.T9/Solution2.py new file mode 100644 index 0000000000000..db5cd911b00cd --- /dev/null +++ b/lcci/16.20.T9/Solution2.py @@ -0,0 +1,4 @@ +class Solution: + def getValidT9Words(self, num: str, words: List[str]) -> List[str]: + trans = str.maketrans(ascii_lowercase, "22233344455566677778889999") + return [w for w in words if w.translate(trans) == num] diff --git a/lcci/16.21.Sum Swap/Solution.cpp b/lcci/16.21.Sum Swap/Solution.cpp index 4e593a3cd61bb..3c6a8827e8f54 100644 --- a/lcci/16.21.Sum Swap/Solution.cpp +++ b/lcci/16.21.Sum Swap/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - vector findSwapValues(vector& array1, vector& array2) { - long long s1 = accumulate(array1.begin(), array1.end(), 0LL); - long long s2 = accumulate(array2.begin(), array2.end(), 0LL); - long long diff = s1 - s2; - if (diff & 1) { - return {}; - } - diff >>= 1; - unordered_set s(array2.begin(), array2.end()); - for (int x : array1) { - int y = x - diff; - if (s.count(y)) { - return {x, y}; - } - } - return {}; - } +class Solution { +public: + vector findSwapValues(vector& array1, vector& array2) { + long long s1 = accumulate(array1.begin(), array1.end(), 0LL); + long long s2 = accumulate(array2.begin(), array2.end(), 0LL); + long long diff = s1 - s2; + if (diff & 1) { + return {}; + } + diff >>= 1; + unordered_set s(array2.begin(), array2.end()); + for (int x : array1) { + int y = x - diff; + if (s.count(y)) { + return {x, y}; + } + } + return {}; + } }; \ No newline at end of file diff --git a/lcci/16.21.Sum Swap/Solution.java b/lcci/16.21.Sum Swap/Solution.java index d2510130f6dd1..d37e040e017d2 100644 --- a/lcci/16.21.Sum Swap/Solution.java +++ b/lcci/16.21.Sum Swap/Solution.java @@ -1,25 +1,25 @@ -class Solution { - public int[] findSwapValues(int[] array1, int[] array2) { - long s1 = 0, s2 = 0; - Set s = new HashSet<>(); - for (int x : array1) { - s1 += x; - } - for (int x : array2) { - s2 += x; - s.add(x); - } - long diff = s1 - s2; - if (diff % 2 != 0) { - return new int[0]; - } - diff /= 2; - for (int a : array1) { - int b = (int) (a - diff); - if (s.contains(b)) { - return new int[] {a, b}; - } - } - return new int[0]; - } +class Solution { + public int[] findSwapValues(int[] array1, int[] array2) { + long s1 = 0, s2 = 0; + Set s = new HashSet<>(); + for (int x : array1) { + s1 += x; + } + for (int x : array2) { + s2 += x; + s.add(x); + } + long diff = s1 - s2; + if (diff % 2 != 0) { + return new int[0]; + } + diff /= 2; + for (int a : array1) { + int b = (int) (a - diff); + if (s.contains(b)) { + return new int[] {a, b}; + } + } + return new int[0]; + } } \ No newline at end of file diff --git a/lcci/16.21.Sum Swap/Solution.py b/lcci/16.21.Sum Swap/Solution.py index 355d0207eabcd..d621aa8b66054 100644 --- a/lcci/16.21.Sum Swap/Solution.py +++ b/lcci/16.21.Sum Swap/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def findSwapValues(self, array1: List[int], array2: List[int]) -> List[int]: - diff = sum(array1) - sum(array2) - if diff & 1: - return [] - diff >>= 1 - s = set(array2) - for a in array1: - if (b := (a - diff)) in s: - return [a, b] - return [] +class Solution: + def findSwapValues(self, array1: List[int], array2: List[int]) -> List[int]: + diff = sum(array1) - sum(array2) + if diff & 1: + return [] + diff >>= 1 + s = set(array2) + for a in array1: + if (b := (a - diff)) in s: + return [a, b] + return [] diff --git a/lcci/16.22.Langtons Ant/Solution.cpp b/lcci/16.22.Langtons Ant/Solution.cpp index ea244f5160783..2666104aab151 100644 --- a/lcci/16.22.Langtons Ant/Solution.cpp +++ b/lcci/16.22.Langtons Ant/Solution.cpp @@ -1,33 +1,33 @@ -class Solution { -public: - vector printKMoves(int K) { - int x1 = 0, y1 = 0, x2 = 0, y2 = 0; - int dirs[5] = {0, 1, 0, -1, 0}; - string d = "RDLU"; - int x = 0, y = 0, p = 0; - set> black; - while (K--) { - auto t = make_pair(x, y); - if (black.count(t)) { - black.erase(t); - p = (p + 3) % 4; - } else { - black.insert(t); - p = (p + 1) % 4; - } - x += dirs[p]; - y += dirs[p + 1]; - x1 = min(x1, x); - y1 = min(y1, y); - x2 = max(x2, x); - y2 = max(y2, y); - } - int m = x2 - x1 + 1, n = y2 - y1 + 1; - vector g(m, string(n, '_')); - for (auto& [i, j] : black) { - g[i - x1][j - y1] = 'X'; - } - g[x - x1][y - y1] = d[p]; - return g; - } +class Solution { +public: + vector printKMoves(int K) { + int x1 = 0, y1 = 0, x2 = 0, y2 = 0; + int dirs[5] = {0, 1, 0, -1, 0}; + string d = "RDLU"; + int x = 0, y = 0, p = 0; + set> black; + while (K--) { + auto t = make_pair(x, y); + if (black.count(t)) { + black.erase(t); + p = (p + 3) % 4; + } else { + black.insert(t); + p = (p + 1) % 4; + } + x += dirs[p]; + y += dirs[p + 1]; + x1 = min(x1, x); + y1 = min(y1, y); + x2 = max(x2, x); + y2 = max(y2, y); + } + int m = x2 - x1 + 1, n = y2 - y1 + 1; + vector g(m, string(n, '_')); + for (auto& [i, j] : black) { + g[i - x1][j - y1] = 'X'; + } + g[x - x1][y - y1] = d[p]; + return g; + } }; \ No newline at end of file diff --git a/lcci/16.22.Langtons Ant/Solution.java b/lcci/16.22.Langtons Ant/Solution.java index 2e5c728b17da3..e805373d5c189 100644 --- a/lcci/16.22.Langtons Ant/Solution.java +++ b/lcci/16.22.Langtons Ant/Solution.java @@ -1,41 +1,41 @@ -class Solution { - public List printKMoves(int K) { - int x1 = 0, y1 = 0, x2 = 0, y2 = 0; - int[] dirs = {0, 1, 0, -1, 0}; - String d = "RDLU"; - int x = 0, y = 0, p = 0; - Set> black = new HashSet<>(); - while (K-- > 0) { - List t = List.of(x, y); - if (black.add(t)) { - p = (p + 1) % 4; - } else { - black.remove(t); - p = (p + 3) % 4; - } - x += dirs[p]; - y += dirs[p + 1]; - x1 = Math.min(x1, x); - y1 = Math.min(y1, y); - x2 = Math.max(x2, x); - y2 = Math.max(y2, y); - } - int m = x2 - x1 + 1; - int n = y2 - y1 + 1; - char[][] g = new char[m][n]; - for (char[] row : g) { - Arrays.fill(row, '_'); - } - for (List t : black) { - int i = t.get(0) - x1; - int j = t.get(1) - y1; - g[i][j] = 'X'; - } - g[x - x1][y - y1] = d.charAt(p); - List ans = new ArrayList<>(); - for (char[] row : g) { - ans.add(String.valueOf(row)); - } - return ans; - } +class Solution { + public List printKMoves(int K) { + int x1 = 0, y1 = 0, x2 = 0, y2 = 0; + int[] dirs = {0, 1, 0, -1, 0}; + String d = "RDLU"; + int x = 0, y = 0, p = 0; + Set> black = new HashSet<>(); + while (K-- > 0) { + List t = List.of(x, y); + if (black.add(t)) { + p = (p + 1) % 4; + } else { + black.remove(t); + p = (p + 3) % 4; + } + x += dirs[p]; + y += dirs[p + 1]; + x1 = Math.min(x1, x); + y1 = Math.min(y1, y); + x2 = Math.max(x2, x); + y2 = Math.max(y2, y); + } + int m = x2 - x1 + 1; + int n = y2 - y1 + 1; + char[][] g = new char[m][n]; + for (char[] row : g) { + Arrays.fill(row, '_'); + } + for (List t : black) { + int i = t.get(0) - x1; + int j = t.get(1) - y1; + g[i][j] = 'X'; + } + g[x - x1][y - y1] = d.charAt(p); + List ans = new ArrayList<>(); + for (char[] row : g) { + ans.add(String.valueOf(row)); + } + return ans; + } } \ No newline at end of file diff --git a/lcci/16.22.Langtons Ant/Solution.py b/lcci/16.22.Langtons Ant/Solution.py index 47cde462353cd..e147bbc07f1bd 100644 --- a/lcci/16.22.Langtons Ant/Solution.py +++ b/lcci/16.22.Langtons Ant/Solution.py @@ -1,27 +1,27 @@ -class Solution: - def printKMoves(self, K: int) -> List[str]: - x1 = y1 = x2 = y2 = 0 - dirs = (0, 1, 0, -1, 0) - d = "RDLU" - x = y = 0 - p = 0 - black = set() - for _ in range(K): - if (x, y) in black: - black.remove((x, y)) - p = (p + 3) % 4 - else: - black.add((x, y)) - p = (p + 1) % 4 - x += dirs[p] - y += dirs[p + 1] - x1 = min(x1, x) - y1 = min(y1, y) - x2 = max(x2, x) - y2 = max(y2, y) - m, n = x2 - x1 + 1, y2 - y1 + 1 - g = [["_"] * n for _ in range(m)] - for i, j in black: - g[i - x1][j - y1] = "X" - g[x - x1][y - y1] = d[p] - return ["".join(row) for row in g] +class Solution: + def printKMoves(self, K: int) -> List[str]: + x1 = y1 = x2 = y2 = 0 + dirs = (0, 1, 0, -1, 0) + d = "RDLU" + x = y = 0 + p = 0 + black = set() + for _ in range(K): + if (x, y) in black: + black.remove((x, y)) + p = (p + 3) % 4 + else: + black.add((x, y)) + p = (p + 1) % 4 + x += dirs[p] + y += dirs[p + 1] + x1 = min(x1, x) + y1 = min(y1, y) + x2 = max(x2, x) + y2 = max(y2, y) + m, n = x2 - x1 + 1, y2 - y1 + 1 + g = [["_"] * n for _ in range(m)] + for i, j in black: + g[i - x1][j - y1] = "X" + g[x - x1][y - y1] = d[p] + return ["".join(row) for row in g] diff --git a/lcci/16.26.Calculator/Solution.cpp b/lcci/16.26.Calculator/Solution.cpp index 143453c0e385d..c688646a1d4b0 100644 --- a/lcci/16.26.Calculator/Solution.cpp +++ b/lcci/16.26.Calculator/Solution.cpp @@ -1,38 +1,38 @@ -class Solution { -public: - int calculate(string s) { - int n = s.size(); - int x = 0; - char sign = '+'; - stack stk; - for (int i = 0; i < n; ++i) { - char c = s[i]; - if (isdigit(c)) { - x = x * 10 + (c - '0'); - } - if (i == n - 1 || !isdigit(c) && c != ' ') { - if (sign == '+') { - stk.push(x); - } else if (sign == '-') { - stk.push(-x); - } else if (sign == '*') { - int y = stk.top(); - stk.pop(); - stk.push(y * x); - } else if (sign == '/') { - int y = stk.top(); - stk.pop(); - stk.push(y / x); - } - x = 0; - sign = c; - } - } - int ans = 0; - while (!stk.empty()) { - ans += stk.top(); - stk.pop(); - } - return ans; - } +class Solution { +public: + int calculate(string s) { + int n = s.size(); + int x = 0; + char sign = '+'; + stack stk; + for (int i = 0; i < n; ++i) { + char c = s[i]; + if (isdigit(c)) { + x = x * 10 + (c - '0'); + } + if (i == n - 1 || !isdigit(c) && c != ' ') { + if (sign == '+') { + stk.push(x); + } else if (sign == '-') { + stk.push(-x); + } else if (sign == '*') { + int y = stk.top(); + stk.pop(); + stk.push(y * x); + } else if (sign == '/') { + int y = stk.top(); + stk.pop(); + stk.push(y / x); + } + x = 0; + sign = c; + } + } + int ans = 0; + while (!stk.empty()) { + ans += stk.top(); + stk.pop(); + } + return ans; + } }; \ No newline at end of file diff --git a/lcci/16.26.Calculator/Solution.java b/lcci/16.26.Calculator/Solution.java index ca9dac83933d4..0aa1cfd2023f2 100644 --- a/lcci/16.26.Calculator/Solution.java +++ b/lcci/16.26.Calculator/Solution.java @@ -1,29 +1,29 @@ -class Solution { - public int calculate(String s) { - int n = s.length(); - int x = 0; - char sign = '+'; - Deque stk = new ArrayDeque<>(); - for (int i = 0; i < n; ++i) { - char c = s.charAt(i); - if (Character.isDigit(c)) { - x = x * 10 + (c - '0'); - } - if (i == n - 1 || !Character.isDigit(c) && c != ' ') { - switch (sign) { - case '+' -> stk.push(x); - case '-' -> stk.push(-x); - case '*' -> stk.push(stk.pop() * x); - case '/' -> stk.push(stk.pop() / x); - } - x = 0; - sign = c; - } - } - int ans = 0; - while (!stk.isEmpty()) { - ans += stk.pop(); - } - return ans; - } +class Solution { + public int calculate(String s) { + int n = s.length(); + int x = 0; + char sign = '+'; + Deque stk = new ArrayDeque<>(); + for (int i = 0; i < n; ++i) { + char c = s.charAt(i); + if (Character.isDigit(c)) { + x = x * 10 + (c - '0'); + } + if (i == n - 1 || !Character.isDigit(c) && c != ' ') { + switch (sign) { + case '+' -> stk.push(x); + case '-' -> stk.push(-x); + case '*' -> stk.push(stk.pop() * x); + case '/' -> stk.push(stk.pop() / x); + } + x = 0; + sign = c; + } + } + int ans = 0; + while (!stk.isEmpty()) { + ans += stk.pop(); + } + return ans; + } } \ No newline at end of file diff --git a/lcci/16.26.Calculator/Solution.py b/lcci/16.26.Calculator/Solution.py index 6f60853aee359..51e11f95ad2cb 100644 --- a/lcci/16.26.Calculator/Solution.py +++ b/lcci/16.26.Calculator/Solution.py @@ -1,22 +1,22 @@ -class Solution: - def calculate(self, s: str) -> int: - n = len(s) - x = 0 - sign = "+" - stk = [] - for i, c in enumerate(s): - if c.isdigit(): - x = x * 10 + ord(c) - ord("0") - if i == n - 1 or c in "+-*/": - match sign: - case "+": - stk.append(x) - case "-": - stk.append(-x) - case "*": - stk.append(stk.pop() * x) - case "/": - stk.append(int(stk.pop() / x)) - x = 0 - sign = c - return sum(stk) +class Solution: + def calculate(self, s: str) -> int: + n = len(s) + x = 0 + sign = "+" + stk = [] + for i, c in enumerate(s): + if c.isdigit(): + x = x * 10 + ord(c) - ord("0") + if i == n - 1 or c in "+-*/": + match sign: + case "+": + stk.append(x) + case "-": + stk.append(-x) + case "*": + stk.append(stk.pop() * x) + case "/": + stk.append(int(stk.pop() / x)) + x = 0 + sign = c + return sum(stk) diff --git a/lcci/17.04.Missing Number/Solution.cpp b/lcci/17.04.Missing Number/Solution.cpp index 96d0ba0c974c3..ad6f9e87af285 100644 --- a/lcci/17.04.Missing Number/Solution.cpp +++ b/lcci/17.04.Missing Number/Solution.cpp @@ -1,10 +1,13 @@ class Solution { public: int missingNumber(vector& nums) { - int ans = 0; - for (int i = 1; i <= nums.size(); ++i) { - ans ^= i ^ nums[i - 1]; + sort(nums.begin(), nums.end()); + int n = nums.size(); + for (int i = 0; i < n; ++i) { + if (i != nums[i]) { + return i; + } } - return ans; + return n; } }; \ No newline at end of file diff --git a/lcci/17.04.Missing Number/Solution.go b/lcci/17.04.Missing Number/Solution.go index d770b9b9d8eec..57032a9a84a1c 100644 --- a/lcci/17.04.Missing Number/Solution.go +++ b/lcci/17.04.Missing Number/Solution.go @@ -1,6 +1,9 @@ -func missingNumber(nums []int) (ans int) { +func missingNumber(nums []int) int { + sort.Ints(nums) for i, x := range nums { - ans ^= (i + 1) ^ x + if i != x { + return i + } } - return + return len(nums) } \ No newline at end of file diff --git a/lcci/17.04.Missing Number/Solution.java b/lcci/17.04.Missing Number/Solution.java index 464ad9d878c45..cc7665ab52b41 100644 --- a/lcci/17.04.Missing Number/Solution.java +++ b/lcci/17.04.Missing Number/Solution.java @@ -1,9 +1,12 @@ class Solution { public int missingNumber(int[] nums) { - int ans = 0; - for (int i = 1; i <= nums.length; ++i) { - ans ^= i ^ nums[i - 1]; + Arrays.sort(nums); + int n = nums.length; + for (int i = 0; i < n; ++i) { + if (i != nums[i]) { + return i; + } } - return ans; + return n; } } \ No newline at end of file diff --git a/lcci/17.04.Missing Number/Solution.js b/lcci/17.04.Missing Number/Solution.js index 97cdfeb04d9bc..c344b6c7fb1ed 100644 --- a/lcci/17.04.Missing Number/Solution.js +++ b/lcci/17.04.Missing Number/Solution.js @@ -3,9 +3,12 @@ * @return {number} */ var missingNumber = function (nums) { - let ans = 0; - for (let i = 1; i <= nums.length; ++i) { - ans ^= i ^ nums[i - 1]; + nums.sort((a, b) => a - b); + const n = nums.length; + for (let i = 0; i < n; ++i) { + if (i != nums[i]) { + return i; + } } - return ans; + return n; }; diff --git a/lcci/17.04.Missing Number/Solution.py b/lcci/17.04.Missing Number/Solution.py index 2f3cfea9a5145..e2d2c4d814035 100644 --- a/lcci/17.04.Missing Number/Solution.py +++ b/lcci/17.04.Missing Number/Solution.py @@ -1,6 +1,7 @@ class Solution: def missingNumber(self, nums: List[int]) -> int: - ans = 0 - for i, x in enumerate(nums, 1): - ans ^= i ^ x - return ans + nums.sort() + for i, x in enumerate(nums): + if i != x: + return i + return len(nums) diff --git a/lcci/17.04.Missing Number/Solution.rs b/lcci/17.04.Missing Number/Solution.rs index 255bded97307c..0cc2852038a22 100644 --- a/lcci/17.04.Missing Number/Solution.rs +++ b/lcci/17.04.Missing Number/Solution.rs @@ -1,10 +1,12 @@ impl Solution { - pub fn missing_number(nums: Vec) -> i32 { - let mut res = 0; - let n = nums.len(); + pub fn missing_number(mut nums: Vec) -> i32 { + nums.sort(); + let n = nums.len() as i32; for i in 0..n { - res ^= nums[i] ^ ((i + 1) as i32); + if i != nums[i as usize] { + return i; + } } - res + n } } diff --git a/lcci/17.04.Missing Number/Solution2.cpp b/lcci/17.04.Missing Number/Solution2.cpp new file mode 100644 index 0000000000000..7e575d48ade94 --- /dev/null +++ b/lcci/17.04.Missing Number/Solution2.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int missingNumber(vector& nums) { + int n = nums.size(); + int ans = n; + for (int i = 0; i < n; ++i) { + ans += i - nums[i]; + } + return ans; + } +}; \ No newline at end of file diff --git a/lcci/17.04.Missing Number/Solution2.go b/lcci/17.04.Missing Number/Solution2.go new file mode 100644 index 0000000000000..1f237ed37263b --- /dev/null +++ b/lcci/17.04.Missing Number/Solution2.go @@ -0,0 +1,7 @@ +func missingNumber(nums []int) (ans int) { + ans = len(nums) + for i, x := range nums { + ans += i - x + } + return +} \ No newline at end of file diff --git a/lcci/17.04.Missing Number/Solution2.java b/lcci/17.04.Missing Number/Solution2.java new file mode 100644 index 0000000000000..1a59f9eb87dd9 --- /dev/null +++ b/lcci/17.04.Missing Number/Solution2.java @@ -0,0 +1,10 @@ +class Solution { + public int missingNumber(int[] nums) { + int n = nums.length; + int ans = n; + for (int i = 0; i < n; ++i) { + ans += i - nums[i]; + } + return ans; + } +} \ No newline at end of file diff --git a/lcci/17.04.Missing Number/Solution2.js b/lcci/17.04.Missing Number/Solution2.js new file mode 100644 index 0000000000000..de7e7a8d29e70 --- /dev/null +++ b/lcci/17.04.Missing Number/Solution2.js @@ -0,0 +1,12 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var missingNumber = function (nums) { + const n = nums.length; + let ans = n; + for (let i = 0; i < n; ++i) { + ans += i - nums[i]; + } + return ans; +}; diff --git a/lcci/17.04.Missing Number/Solution2.py b/lcci/17.04.Missing Number/Solution2.py new file mode 100644 index 0000000000000..08d6570703c14 --- /dev/null +++ b/lcci/17.04.Missing Number/Solution2.py @@ -0,0 +1,3 @@ +class Solution: + def missingNumber(self, nums: List[int]) -> int: + return sum(range(len(nums) + 1)) - sum(nums) diff --git a/lcci/17.04.Missing Number/Solution2.rs b/lcci/17.04.Missing Number/Solution2.rs new file mode 100644 index 0000000000000..22c712c6a12a6 --- /dev/null +++ b/lcci/17.04.Missing Number/Solution2.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn missing_number(nums: Vec) -> i32 { + let n = nums.len() as i32; + let mut sum = 0; + let mut max = 0; + for num in nums { + sum += num; + max = max.max(num); + } + if max == n { + ((1 + max) * max) / 2 - sum + } else { + n + } + } +} diff --git a/lcci/17.04.Missing Number/Solution3.cpp b/lcci/17.04.Missing Number/Solution3.cpp new file mode 100644 index 0000000000000..96d0ba0c974c3 --- /dev/null +++ b/lcci/17.04.Missing Number/Solution3.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + int missingNumber(vector& nums) { + int ans = 0; + for (int i = 1; i <= nums.size(); ++i) { + ans ^= i ^ nums[i - 1]; + } + return ans; + } +}; \ No newline at end of file diff --git a/lcci/17.04.Missing Number/Solution3.go b/lcci/17.04.Missing Number/Solution3.go new file mode 100644 index 0000000000000..d770b9b9d8eec --- /dev/null +++ b/lcci/17.04.Missing Number/Solution3.go @@ -0,0 +1,6 @@ +func missingNumber(nums []int) (ans int) { + for i, x := range nums { + ans ^= (i + 1) ^ x + } + return +} \ No newline at end of file diff --git a/lcci/17.04.Missing Number/Solution3.java b/lcci/17.04.Missing Number/Solution3.java new file mode 100644 index 0000000000000..464ad9d878c45 --- /dev/null +++ b/lcci/17.04.Missing Number/Solution3.java @@ -0,0 +1,9 @@ +class Solution { + public int missingNumber(int[] nums) { + int ans = 0; + for (int i = 1; i <= nums.length; ++i) { + ans ^= i ^ nums[i - 1]; + } + return ans; + } +} \ No newline at end of file diff --git a/lcci/17.04.Missing Number/Solution3.js b/lcci/17.04.Missing Number/Solution3.js new file mode 100644 index 0000000000000..97cdfeb04d9bc --- /dev/null +++ b/lcci/17.04.Missing Number/Solution3.js @@ -0,0 +1,11 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var missingNumber = function (nums) { + let ans = 0; + for (let i = 1; i <= nums.length; ++i) { + ans ^= i ^ nums[i - 1]; + } + return ans; +}; diff --git a/lcci/17.04.Missing Number/Solution3.py b/lcci/17.04.Missing Number/Solution3.py new file mode 100644 index 0000000000000..2f3cfea9a5145 --- /dev/null +++ b/lcci/17.04.Missing Number/Solution3.py @@ -0,0 +1,6 @@ +class Solution: + def missingNumber(self, nums: List[int]) -> int: + ans = 0 + for i, x in enumerate(nums, 1): + ans ^= i ^ x + return ans diff --git a/lcci/17.04.Missing Number/Solution3.rs b/lcci/17.04.Missing Number/Solution3.rs new file mode 100644 index 0000000000000..255bded97307c --- /dev/null +++ b/lcci/17.04.Missing Number/Solution3.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn missing_number(nums: Vec) -> i32 { + let mut res = 0; + let n = nums.len(); + for i in 0..n { + res ^= nums[i] ^ ((i + 1) as i32); + } + res + } +} diff --git a/lcci/17.09.Get Kth Magic Number/Solution.c b/lcci/17.09.Get Kth Magic Number/Solution.c index daccac29e4cf2..154a618820ae5 100644 --- a/lcci/17.09.Get Kth Magic Number/Solution.c +++ b/lcci/17.09.Get Kth Magic Number/Solution.c @@ -23,4 +23,4 @@ int getKthMagicNumber(int k) { int res = dp[k - 1]; free(dp); return res; -} +} \ No newline at end of file diff --git a/lcci/17.09.Get Kth Magic Number/Solution.cpp b/lcci/17.09.Get Kth Magic Number/Solution.cpp index b481139f7cae3..c09f98a068110 100644 --- a/lcci/17.09.Get Kth Magic Number/Solution.cpp +++ b/lcci/17.09.Get Kth Magic Number/Solution.cpp @@ -1,22 +1,23 @@ class Solution { public: + const vector factors = {3, 5, 7}; + int getKthMagicNumber(int k) { - vector dp(k + 1, 1); - int p3 = 1, p5 = 1, p7 = 1; - for (int i = 2; i <= k; ++i) { - int a = dp[p3] * 3, b = dp[p5] * 5, c = dp[p7] * 7; - int v = min(min(a, b), c); - dp[i] = v; - if (v == a) { - ++p3; - } - if (v == b) { - ++p5; - } - if (v == c) { - ++p7; + priority_queue, greater> q; + unordered_set vis; + q.push(1l); + vis.insert(1l); + for (int i = 0; i < k - 1; ++i) { + long cur = q.top(); + q.pop(); + for (int f : factors) { + long nxt = cur * f; + if (!vis.count(nxt)) { + vis.insert(nxt); + q.push(nxt); + } } } - return dp[k]; + return (int) q.top(); } }; \ No newline at end of file diff --git a/lcci/17.09.Get Kth Magic Number/Solution.go b/lcci/17.09.Get Kth Magic Number/Solution.go index b3bafeda26d55..72b659560c520 100644 --- a/lcci/17.09.Get Kth Magic Number/Solution.go +++ b/lcci/17.09.Get Kth Magic Number/Solution.go @@ -1,20 +1,25 @@ func getKthMagicNumber(k int) int { - dp := make([]int, k+1) - dp[1] = 1 - p3, p5, p7 := 1, 1, 1 - for i := 2; i <= k; i++ { - a, b, c := dp[p3]*3, dp[p5]*5, dp[p7]*7 - v := min(min(a, b), c) - dp[i] = v - if v == a { - p3++ - } - if v == b { - p5++ - } - if v == c { - p7++ + q := hp{[]int{1}} + vis := map[int]bool{1: true} + for i := 0; i < k-1; i++ { + cur := heap.Pop(&q).(int) + for _, f := range []int{3, 5, 7} { + nxt := cur * f + if !vis[nxt] { + vis[nxt] = true + heap.Push(&q, nxt) + } } } - return dp[k] + return q.IntSlice[0] +} + +type hp struct{ sort.IntSlice } + +func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) } +func (h *hp) Pop() any { + a := h.IntSlice + v := a[len(a)-1] + h.IntSlice = a[:len(a)-1] + return v } \ No newline at end of file diff --git a/lcci/17.09.Get Kth Magic Number/Solution.java b/lcci/17.09.Get Kth Magic Number/Solution.java index d5c5f5f4afeb3..8d1f8903a6f57 100644 --- a/lcci/17.09.Get Kth Magic Number/Solution.java +++ b/lcci/17.09.Get Kth Magic Number/Solution.java @@ -1,22 +1,22 @@ class Solution { + private static final int[] FACTORS = new int[] {3, 5, 7}; + public int getKthMagicNumber(int k) { - int[] dp = new int[k + 1]; - Arrays.fill(dp, 1); - int p3 = 1, p5 = 1, p7 = 1; - for (int i = 2; i <= k; ++i) { - int a = dp[p3] * 3, b = dp[p5] * 5, c = dp[p7] * 7; - int v = Math.min(Math.min(a, b), c); - dp[i] = v; - if (v == a) { - ++p3; - } - if (v == b) { - ++p5; - } - if (v == c) { - ++p7; + PriorityQueue q = new PriorityQueue<>(); + Set vis = new HashSet<>(); + q.offer(1L); + vis.add(1L); + while (--k > 0) { + long cur = q.poll(); + for (int f : FACTORS) { + long nxt = cur * f; + if (!vis.contains(nxt)) { + q.offer(nxt); + vis.add(nxt); + } } } - return dp[k]; + long ans = q.poll(); + return (int) ans; } } \ No newline at end of file diff --git a/lcci/17.09.Get Kth Magic Number/Solution.py b/lcci/17.09.Get Kth Magic Number/Solution.py index daf89757fcf08..cb012b03c87dc 100644 --- a/lcci/17.09.Get Kth Magic Number/Solution.py +++ b/lcci/17.09.Get Kth Magic Number/Solution.py @@ -1,15 +1,11 @@ class Solution: def getKthMagicNumber(self, k: int) -> int: - dp = [1] * (k + 1) - p3 = p5 = p7 = 1 - for i in range(2, k + 1): - a, b, c = dp[p3] * 3, dp[p5] * 5, dp[p7] * 7 - v = min(a, b, c) - dp[i] = v - if v == a: - p3 += 1 - if v == b: - p5 += 1 - if v == c: - p7 += 1 - return dp[k] + h = [1] + vis = {1} + for _ in range(k - 1): + cur = heappop(h) + for f in (3, 5, 7): + if (nxt := cur * f) not in vis: + vis.add(nxt) + heappush(h, nxt) + return h[0] diff --git a/lcci/17.09.Get Kth Magic Number/Solution2.cpp b/lcci/17.09.Get Kth Magic Number/Solution2.cpp new file mode 100644 index 0000000000000..b481139f7cae3 --- /dev/null +++ b/lcci/17.09.Get Kth Magic Number/Solution2.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int getKthMagicNumber(int k) { + vector dp(k + 1, 1); + int p3 = 1, p5 = 1, p7 = 1; + for (int i = 2; i <= k; ++i) { + int a = dp[p3] * 3, b = dp[p5] * 5, c = dp[p7] * 7; + int v = min(min(a, b), c); + dp[i] = v; + if (v == a) { + ++p3; + } + if (v == b) { + ++p5; + } + if (v == c) { + ++p7; + } + } + return dp[k]; + } +}; \ No newline at end of file diff --git a/lcci/17.09.Get Kth Magic Number/Solution2.go b/lcci/17.09.Get Kth Magic Number/Solution2.go new file mode 100644 index 0000000000000..b3bafeda26d55 --- /dev/null +++ b/lcci/17.09.Get Kth Magic Number/Solution2.go @@ -0,0 +1,20 @@ +func getKthMagicNumber(k int) int { + dp := make([]int, k+1) + dp[1] = 1 + p3, p5, p7 := 1, 1, 1 + for i := 2; i <= k; i++ { + a, b, c := dp[p3]*3, dp[p5]*5, dp[p7]*7 + v := min(min(a, b), c) + dp[i] = v + if v == a { + p3++ + } + if v == b { + p5++ + } + if v == c { + p7++ + } + } + return dp[k] +} \ No newline at end of file diff --git a/lcci/17.09.Get Kth Magic Number/Solution2.java b/lcci/17.09.Get Kth Magic Number/Solution2.java new file mode 100644 index 0000000000000..d5c5f5f4afeb3 --- /dev/null +++ b/lcci/17.09.Get Kth Magic Number/Solution2.java @@ -0,0 +1,22 @@ +class Solution { + public int getKthMagicNumber(int k) { + int[] dp = new int[k + 1]; + Arrays.fill(dp, 1); + int p3 = 1, p5 = 1, p7 = 1; + for (int i = 2; i <= k; ++i) { + int a = dp[p3] * 3, b = dp[p5] * 5, c = dp[p7] * 7; + int v = Math.min(Math.min(a, b), c); + dp[i] = v; + if (v == a) { + ++p3; + } + if (v == b) { + ++p5; + } + if (v == c) { + ++p7; + } + } + return dp[k]; + } +} \ No newline at end of file diff --git a/lcci/17.09.Get Kth Magic Number/Solution2.py b/lcci/17.09.Get Kth Magic Number/Solution2.py new file mode 100644 index 0000000000000..daf89757fcf08 --- /dev/null +++ b/lcci/17.09.Get Kth Magic Number/Solution2.py @@ -0,0 +1,15 @@ +class Solution: + def getKthMagicNumber(self, k: int) -> int: + dp = [1] * (k + 1) + p3 = p5 = p7 = 1 + for i in range(2, k + 1): + a, b, c = dp[p3] * 3, dp[p5] * 5, dp[p7] * 7 + v = min(a, b, c) + dp[i] = v + if v == a: + p3 += 1 + if v == b: + p5 += 1 + if v == c: + p7 += 1 + return dp[k] diff --git a/lcci/17.10.Find Majority Element/Solution.cs b/lcci/17.10.Find Majority Element/Solution.cs index d01a07197aa99..e48a175c2ced2 100644 --- a/lcci/17.10.Find Majority Element/Solution.cs +++ b/lcci/17.10.Find Majority Element/Solution.cs @@ -23,4 +23,4 @@ public int MajorityElement(int[] nums) { } return cnt > nums.Length / 2 ? m : -1; } -} \ No newline at end of file +} diff --git a/lcci/17.11.Find Closest/Solution.cpp b/lcci/17.11.Find Closest/Solution.cpp index 9dfedf9467f3a..9f23dd4e392bf 100644 --- a/lcci/17.11.Find Closest/Solution.cpp +++ b/lcci/17.11.Find Closest/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - int findClosest(vector& words, string word1, string word2) { - int i = 1e5, j = -1e5, ans = 1e5; - for (int k = 0; k < words.size(); ++k) { - string word = words[k]; - if (word == word1) - i = k; - else if (word == word2) - j = k; - ans = min(ans, abs(i - j)); - } - return ans; - } +class Solution { +public: + int findClosest(vector& words, string word1, string word2) { + int i = 1e5, j = -1e5, ans = 1e5; + for (int k = 0; k < words.size(); ++k) { + string word = words[k]; + if (word == word1) + i = k; + else if (word == word2) + j = k; + ans = min(ans, abs(i - j)); + } + return ans; + } }; \ No newline at end of file diff --git a/lcci/17.11.Find Closest/Solution.java b/lcci/17.11.Find Closest/Solution.java index 84df1d4dcf926..ed2f1fc0cfb3c 100644 --- a/lcci/17.11.Find Closest/Solution.java +++ b/lcci/17.11.Find Closest/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public int findClosest(String[] words, String word1, String word2) { - int i = 100000, j = -100000, ans = 100000; - for (int k = 0; k < words.length; ++k) { - String word = words[k]; - if (word.equals(word1)) { - i = k; - } else if (word.equals(word2)) { - j = k; - } - ans = Math.min(ans, Math.abs(i - j)); - } - return ans; - } +class Solution { + public int findClosest(String[] words, String word1, String word2) { + int i = 100000, j = -100000, ans = 100000; + for (int k = 0; k < words.length; ++k) { + String word = words[k]; + if (word.equals(word1)) { + i = k; + } else if (word.equals(word2)) { + j = k; + } + ans = Math.min(ans, Math.abs(i - j)); + } + return ans; + } } \ No newline at end of file diff --git a/lcci/17.11.Find Closest/Solution.py b/lcci/17.11.Find Closest/Solution.py index dc372a1ab3ad6..008368a2ece9f 100644 --- a/lcci/17.11.Find Closest/Solution.py +++ b/lcci/17.11.Find Closest/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def findClosest(self, words: List[str], word1: str, word2: str) -> int: - i, j, ans = 1e5, -1e5, 1e5 - for k, word in enumerate(words): - if word == word1: - i = k - elif word == word2: - j = k - ans = min(ans, abs(i - j)) - return ans +class Solution: + def findClosest(self, words: List[str], word1: str, word2: str) -> int: + i, j, ans = 1e5, -1e5, 1e5 + for k, word in enumerate(words): + if word == word1: + i = k + elif word == word2: + j = k + ans = min(ans, abs(i - j)) + return ans diff --git a/lcci/17.11.Find Closest/Solution2.cpp b/lcci/17.11.Find Closest/Solution2.cpp new file mode 100644 index 0000000000000..0a0d906ee4007 --- /dev/null +++ b/lcci/17.11.Find Closest/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int findClosest(vector& words, string word1, string word2) { + unordered_map> d; + for (int i = 0; i < words.size(); ++i) d[words[i]].push_back(i); + vector idx1 = d[word1], idx2 = d[word2]; + int i = 0, j = 0, m = idx1.size(), n = idx2.size(); + int ans = 1e5; + while (i < m && j < n) { + int t = abs(idx1[i] - idx2[j]); + ans = min(ans, t); + if (idx1[i] < idx2[j]) + ++i; + else + ++j; + } + return ans; + } +}; \ No newline at end of file diff --git a/lcci/17.11.Find Closest/Solution2.go b/lcci/17.11.Find Closest/Solution2.go new file mode 100644 index 0000000000000..6800c7155a146 --- /dev/null +++ b/lcci/17.11.Find Closest/Solution2.go @@ -0,0 +1,28 @@ +func findClosest(words []string, word1 string, word2 string) int { + d := map[string][]int{} + for i, w := range words { + d[w] = append(d[w], i) + } + idx1, idx2 := d[word1], d[word2] + i, j, m, n := 0, 0, len(idx1), len(idx2) + ans := 100000 + for i < m && j < n { + t := abs(idx1[i] - idx2[j]) + if t < ans { + ans = t + } + if idx1[i] < idx2[j] { + i++ + } else { + j++ + } + } + return ans +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} \ No newline at end of file diff --git a/lcci/17.11.Find Closest/Solution2.java b/lcci/17.11.Find Closest/Solution2.java new file mode 100644 index 0000000000000..86159704762d4 --- /dev/null +++ b/lcci/17.11.Find Closest/Solution2.java @@ -0,0 +1,21 @@ +class Solution { + public int findClosest(String[] words, String word1, String word2) { + Map> d = new HashMap<>(); + for (int i = 0; i < words.length; ++i) { + d.computeIfAbsent(words[i], k -> new ArrayList<>()).add(i); + } + List idx1 = d.get(word1), idx2 = d.get(word2); + int i = 0, j = 0, m = idx1.size(), n = idx2.size(); + int ans = 100000; + while (i < m && j < n) { + int t = Math.abs(idx1.get(i) - idx2.get(j)); + ans = Math.min(ans, t); + if (idx1.get(i) < idx2.get(j)) { + ++i; + } else { + ++j; + } + } + return ans; + } +} \ No newline at end of file diff --git a/lcci/17.11.Find Closest/Solution2.py b/lcci/17.11.Find Closest/Solution2.py new file mode 100644 index 0000000000000..aafc2eac3ff5f --- /dev/null +++ b/lcci/17.11.Find Closest/Solution2.py @@ -0,0 +1,15 @@ +class Solution: + def findClosest(self, words: List[str], word1: str, word2: str) -> int: + d = defaultdict(list) + for i, w in enumerate(words): + d[w].append(i) + ans = 1e5 + idx1, idx2 = d[word1], d[word2] + i, j, m, n = 0, 0, len(idx1), len(idx2) + while i < m and j < n: + ans = min(ans, abs(idx1[i] - idx2[j])) + if idx1[i] < idx2[j]: + i += 1 + else: + j += 1 + return ans diff --git a/lcci/17.12.BiNode/Solution.cpp b/lcci/17.12.BiNode/Solution.cpp index 36b487b40347a..8ba4ee63bbfb7 100644 --- a/lcci/17.12.BiNode/Solution.cpp +++ b/lcci/17.12.BiNode/Solution.cpp @@ -1,29 +1,29 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - TreeNode* prev; - - TreeNode* convertBiNode(TreeNode* root) { - TreeNode* dummy = new TreeNode(0, nullptr, root); - prev = dummy; - dfs(root); - return dummy->right; - } - - void dfs(TreeNode* root) { - if (!root) return; - dfs(root->left); - prev->right = root; - root->left = nullptr; - prev = root; - dfs(root->right); - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* prev; + + TreeNode* convertBiNode(TreeNode* root) { + TreeNode* dummy = new TreeNode(0, nullptr, root); + prev = dummy; + dfs(root); + return dummy->right; + } + + void dfs(TreeNode* root) { + if (!root) return; + dfs(root->left); + prev->right = root; + root->left = nullptr; + prev = root; + dfs(root->right); + } }; \ No newline at end of file diff --git a/lcci/17.12.BiNode/Solution.java b/lcci/17.12.BiNode/Solution.java index a963435d4af00..8071c2ab28cbb 100644 --- a/lcci/17.12.BiNode/Solution.java +++ b/lcci/17.12.BiNode/Solution.java @@ -1,30 +1,30 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -class Solution { - private TreeNode prev; - - public TreeNode convertBiNode(TreeNode root) { - TreeNode dummy = new TreeNode(0, null, root); - prev = dummy; - dfs(root); - return dummy.right; - } - - private void dfs(TreeNode root) { - if (root == null) { - return; - } - dfs(root.left); - prev.right = root; - root.left = null; - prev = root; - dfs(root.right); - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + private TreeNode prev; + + public TreeNode convertBiNode(TreeNode root) { + TreeNode dummy = new TreeNode(0, null, root); + prev = dummy; + dfs(root); + return dummy.right; + } + + private void dfs(TreeNode root) { + if (root == null) { + return; + } + dfs(root.left); + prev.right = root; + root.left = null; + prev = root; + dfs(root.right); + } } \ No newline at end of file diff --git a/lcci/17.12.BiNode/Solution.py b/lcci/17.12.BiNode/Solution.py index 95973cc792cb9..d5e78f34aea8f 100644 --- a/lcci/17.12.BiNode/Solution.py +++ b/lcci/17.12.BiNode/Solution.py @@ -1,24 +1,24 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None - - -class Solution: - def convertBiNode(self, root: TreeNode) -> TreeNode: - def dfs(root): - if root is None: - return - nonlocal prev - dfs(root.left) - prev.right = root - root.left = None - prev = root - dfs(root.right) - - dummy = TreeNode(val=0, right=root) - prev = dummy - dfs(root) - return dummy.right +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution: + def convertBiNode(self, root: TreeNode) -> TreeNode: + def dfs(root): + if root is None: + return + nonlocal prev + dfs(root.left) + prev.right = root + root.left = None + prev = root + dfs(root.right) + + dummy = TreeNode(val=0, right=root) + prev = dummy + dfs(root) + return dummy.right diff --git a/lcci/17.14.Smallest K/Solution2.cpp b/lcci/17.14.Smallest K/Solution2.cpp new file mode 100644 index 0000000000000..5863101c073bc --- /dev/null +++ b/lcci/17.14.Smallest K/Solution2.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + vector smallestK(vector& arr, int k) { + priority_queue q; + for (int& v : arr) { + q.push(v); + if (q.size() > k) { + q.pop(); + } + } + vector ans; + while (q.size()) { + ans.push_back(q.top()); + q.pop(); + } + return ans; + } +}; \ No newline at end of file diff --git a/lcci/17.14.Smallest K/Solution2.go b/lcci/17.14.Smallest K/Solution2.go new file mode 100644 index 0000000000000..bb53d84201dd1 --- /dev/null +++ b/lcci/17.14.Smallest K/Solution2.go @@ -0,0 +1,25 @@ +func smallestK(arr []int, k int) []int { + q := hp{} + for _, v := range arr { + heap.Push(&q, v) + if q.Len() > k { + heap.Pop(&q) + } + } + ans := make([]int, k) + for i := range ans { + ans[i] = heap.Pop(&q).(int) + } + return ans +} + +type hp struct{ sort.IntSlice } + +func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } +func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) } +func (h *hp) Pop() any { + a := h.IntSlice + v := a[len(a)-1] + h.IntSlice = a[:len(a)-1] + return v +} \ No newline at end of file diff --git a/lcci/17.14.Smallest K/Solution2.java b/lcci/17.14.Smallest K/Solution2.java new file mode 100644 index 0000000000000..1b0b45b6bf7d2 --- /dev/null +++ b/lcci/17.14.Smallest K/Solution2.java @@ -0,0 +1,17 @@ +class Solution { + public int[] smallestK(int[] arr, int k) { + PriorityQueue q = new PriorityQueue<>((a, b) -> b - a); + for (int v : arr) { + q.offer(v); + if (q.size() > k) { + q.poll(); + } + } + int[] ans = new int[k]; + int i = 0; + while (!q.isEmpty()) { + ans[i++] = q.poll(); + } + return ans; + } +} \ No newline at end of file diff --git a/lcci/17.14.Smallest K/Solution2.py b/lcci/17.14.Smallest K/Solution2.py new file mode 100644 index 0000000000000..d66bca954b345 --- /dev/null +++ b/lcci/17.14.Smallest K/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def smallestK(self, arr: List[int], k: int) -> List[int]: + h = [] + for v in arr: + heappush(h, -v) + if len(h) > k: + heappop(h) + return [-v for v in h] diff --git a/lcci/17.17.Multi Search/Solution.cpp b/lcci/17.17.Multi Search/Solution.cpp index 862bd155ebe5a..ecd3a31d8b3cd 100644 --- a/lcci/17.17.Multi Search/Solution.cpp +++ b/lcci/17.17.Multi Search/Solution.cpp @@ -1,48 +1,48 @@ -class Trie { -private: - vector children; - int idx; - -public: - Trie() - : children(26) - , idx(-1) {} - - void insert(string word, int i) { - Trie* node = this; - for (char c : word) { - int idx = c - 'a'; - if (!node->children[idx]) node->children[idx] = new Trie(); - node = node->children[idx]; - } - node->idx = i; - } - - vector search(string word) { - Trie* node = this; - vector res; - for (char c : word) { - int idx = c - 'a'; - if (!node->children[idx]) return res; - node = node->children[idx]; - if (node->idx != -1) res.push_back(node->idx); - } - return res; - } -}; - -class Solution { -public: - vector> multiSearch(string big, vector& smalls) { - Trie* tree = new Trie(); - int n = smalls.size(); - for (int i = 0; i < n; ++i) tree->insert(smalls[i], i); - vector> ans(n); - for (int i = 0, m = big.size(); i < m; ++i) { - string s = big.substr(i, m - i); - vector t = tree->search(s); - for (int& idx : t) ans[idx].push_back(i); - } - return ans; - } +class Trie { +private: + vector children; + int idx; + +public: + Trie() + : children(26) + , idx(-1) {} + + void insert(string word, int i) { + Trie* node = this; + for (char c : word) { + int idx = c - 'a'; + if (!node->children[idx]) node->children[idx] = new Trie(); + node = node->children[idx]; + } + node->idx = i; + } + + vector search(string word) { + Trie* node = this; + vector res; + for (char c : word) { + int idx = c - 'a'; + if (!node->children[idx]) return res; + node = node->children[idx]; + if (node->idx != -1) res.push_back(node->idx); + } + return res; + } +}; + +class Solution { +public: + vector> multiSearch(string big, vector& smalls) { + Trie* tree = new Trie(); + int n = smalls.size(); + for (int i = 0; i < n; ++i) tree->insert(smalls[i], i); + vector> ans(n); + for (int i = 0, m = big.size(); i < m; ++i) { + string s = big.substr(i, m - i); + vector t = tree->search(s); + for (int& idx : t) ans[idx].push_back(i); + } + return ans; + } }; \ No newline at end of file diff --git a/lcci/17.17.Multi Search/Solution.java b/lcci/17.17.Multi Search/Solution.java index b8548c567b493..d00eff79635a3 100644 --- a/lcci/17.17.Multi Search/Solution.java +++ b/lcci/17.17.Multi Search/Solution.java @@ -1,63 +1,63 @@ -class Solution { - public int[][] multiSearch(String big, String[] smalls) { - Trie tree = new Trie(); - int n = smalls.length; - for (int i = 0; i < n; ++i) { - tree.insert(smalls[i], i); - } - List> res = new ArrayList<>(); - for (int i = 0; i < n; ++i) { - res.add(new ArrayList<>()); - } - for (int i = 0; i < big.length(); ++i) { - String s = big.substring(i); - List t = tree.search(s); - for (int idx : t) { - res.get(idx).add(i); - } - } - int[][] ans = new int[n][]; - for (int i = 0; i < n; ++i) { - ans[i] = res.get(i).stream().mapToInt(Integer::intValue).toArray(); - } - return ans; - } -} - -class Trie { - private int idx; - private Trie[] children; - - public Trie() { - idx = -1; - children = new Trie[26]; - } - - public void insert(String word, int i) { - Trie node = this; - for (char c : word.toCharArray()) { - c -= 'a'; - if (node.children[c] == null) { - node.children[c] = new Trie(); - } - node = node.children[c]; - } - node.idx = i; - } - - public List search(String word) { - Trie node = this; - List res = new ArrayList<>(); - for (char c : word.toCharArray()) { - c -= 'a'; - if (node.children[c] == null) { - return res; - } - node = node.children[c]; - if (node.idx != -1) { - res.add(node.idx); - } - } - return res; - } +class Solution { + public int[][] multiSearch(String big, String[] smalls) { + Trie tree = new Trie(); + int n = smalls.length; + for (int i = 0; i < n; ++i) { + tree.insert(smalls[i], i); + } + List> res = new ArrayList<>(); + for (int i = 0; i < n; ++i) { + res.add(new ArrayList<>()); + } + for (int i = 0; i < big.length(); ++i) { + String s = big.substring(i); + List t = tree.search(s); + for (int idx : t) { + res.get(idx).add(i); + } + } + int[][] ans = new int[n][]; + for (int i = 0; i < n; ++i) { + ans[i] = res.get(i).stream().mapToInt(Integer::intValue).toArray(); + } + return ans; + } +} + +class Trie { + private int idx; + private Trie[] children; + + public Trie() { + idx = -1; + children = new Trie[26]; + } + + public void insert(String word, int i) { + Trie node = this; + for (char c : word.toCharArray()) { + c -= 'a'; + if (node.children[c] == null) { + node.children[c] = new Trie(); + } + node = node.children[c]; + } + node.idx = i; + } + + public List search(String word) { + Trie node = this; + List res = new ArrayList<>(); + for (char c : word.toCharArray()) { + c -= 'a'; + if (node.children[c] == null) { + return res; + } + node = node.children[c]; + if (node.idx != -1) { + res.add(node.idx); + } + } + return res; + } } \ No newline at end of file diff --git a/lcci/17.17.Multi Search/Solution.py b/lcci/17.17.Multi Search/Solution.py index 1683c90098218..2759a1ce347de 100644 --- a/lcci/17.17.Multi Search/Solution.py +++ b/lcci/17.17.Multi Search/Solution.py @@ -1,39 +1,39 @@ -class Trie: - def __init__(self): - self.idx = -1 - self.children = [None] * 26 - - def insert(self, word, i): - node = self - for c in word: - idx = ord(c) - ord('a') - if node.children[idx] is None: - node.children[idx] = Trie() - node = node.children[idx] - node.idx = i - - def search(self, word): - res = [] - node = self - for c in word: - idx = ord(c) - ord('a') - if node.children[idx] is None: - return res - node = node.children[idx] - if node.idx != -1: - res.append(node.idx) - return res - - -class Solution: - def multiSearch(self, big: str, smalls: List[str]) -> List[List[int]]: - tree = Trie() - for i, s in enumerate(smalls): - tree.insert(s, i) - n = len(smalls) - ans = [[] for _ in range(n)] - for i in range(len(big)): - s = big[i:] - for idx in tree.search(s): - ans[idx].append(i) - return ans +class Trie: + def __init__(self): + self.idx = -1 + self.children = [None] * 26 + + def insert(self, word, i): + node = self + for c in word: + idx = ord(c) - ord('a') + if node.children[idx] is None: + node.children[idx] = Trie() + node = node.children[idx] + node.idx = i + + def search(self, word): + res = [] + node = self + for c in word: + idx = ord(c) - ord('a') + if node.children[idx] is None: + return res + node = node.children[idx] + if node.idx != -1: + res.append(node.idx) + return res + + +class Solution: + def multiSearch(self, big: str, smalls: List[str]) -> List[List[int]]: + tree = Trie() + for i, s in enumerate(smalls): + tree.insert(s, i) + n = len(smalls) + ans = [[] for _ in range(n)] + for i in range(len(big)): + s = big[i:] + for idx in tree.search(s): + ans[idx].append(i) + return ans diff --git a/lcci/17.18.Shortest Supersequence/Solution.cpp b/lcci/17.18.Shortest Supersequence/Solution.cpp index 0232b0e96176d..f8e0c370fa42d 100644 --- a/lcci/17.18.Shortest Supersequence/Solution.cpp +++ b/lcci/17.18.Shortest Supersequence/Solution.cpp @@ -1,32 +1,32 @@ -class Solution { -public: - vector shortestSeq(vector& big, vector& small) { - int cnt = small.size(); - unordered_map need; - unordered_map window; - for (int x : small) { - need[x] = 1; - } - int k = -1, mi = 1 << 30; - for (int i = 0, j = 0; i < big.size(); ++i) { - window[big[i]]++; - if (need[big[i]] >= window[big[i]]) { - --cnt; - } - while (cnt == 0) { - if (i - j + 1 < mi) { - mi = i - j + 1; - k = j; - } - if (need[big[j]] >= window[big[j]]) { - ++cnt; - } - window[big[j++]]--; - } - } - if (k < 0) { - return {}; - } - return {k, k + mi - 1}; - } +class Solution { +public: + vector shortestSeq(vector& big, vector& small) { + int cnt = small.size(); + unordered_map need; + unordered_map window; + for (int x : small) { + need[x] = 1; + } + int k = -1, mi = 1 << 30; + for (int i = 0, j = 0; i < big.size(); ++i) { + window[big[i]]++; + if (need[big[i]] >= window[big[i]]) { + --cnt; + } + while (cnt == 0) { + if (i - j + 1 < mi) { + mi = i - j + 1; + k = j; + } + if (need[big[j]] >= window[big[j]]) { + ++cnt; + } + window[big[j++]]--; + } + } + if (k < 0) { + return {}; + } + return {k, k + mi - 1}; + } }; \ No newline at end of file diff --git a/lcci/17.18.Shortest Supersequence/Solution.java b/lcci/17.18.Shortest Supersequence/Solution.java index 59049a887c7e1..9ae848f3eaee3 100644 --- a/lcci/17.18.Shortest Supersequence/Solution.java +++ b/lcci/17.18.Shortest Supersequence/Solution.java @@ -1,28 +1,28 @@ -class Solution { - public int[] shortestSeq(int[] big, int[] small) { - int cnt = small.length; - Map need = new HashMap<>(cnt); - Map window = new HashMap<>(cnt); - for (int x : small) { - need.put(x, 1); - } - int k = -1, mi = 1 << 30; - for (int i = 0, j = 0; i < big.length; ++i) { - window.merge(big[i], 1, Integer::sum); - if (need.getOrDefault(big[i], 0) >= window.get(big[i])) { - --cnt; - } - while (cnt == 0) { - if (i - j + 1 < mi) { - mi = i - j + 1; - k = j; - } - if (need.getOrDefault(big[j], 0) >= window.get(big[j])) { - ++cnt; - } - window.merge(big[j++], -1, Integer::sum); - } - } - return k < 0 ? new int[0] : new int[] {k, k + mi - 1}; - } +class Solution { + public int[] shortestSeq(int[] big, int[] small) { + int cnt = small.length; + Map need = new HashMap<>(cnt); + Map window = new HashMap<>(cnt); + for (int x : small) { + need.put(x, 1); + } + int k = -1, mi = 1 << 30; + for (int i = 0, j = 0; i < big.length; ++i) { + window.merge(big[i], 1, Integer::sum); + if (need.getOrDefault(big[i], 0) >= window.get(big[i])) { + --cnt; + } + while (cnt == 0) { + if (i - j + 1 < mi) { + mi = i - j + 1; + k = j; + } + if (need.getOrDefault(big[j], 0) >= window.get(big[j])) { + ++cnt; + } + window.merge(big[j++], -1, Integer::sum); + } + } + return k < 0 ? new int[0] : new int[] {k, k + mi - 1}; + } } \ No newline at end of file diff --git a/lcci/17.18.Shortest Supersequence/Solution.py b/lcci/17.18.Shortest Supersequence/Solution.py index 549ef7c2f74b3..c4f6d5d888520 100644 --- a/lcci/17.18.Shortest Supersequence/Solution.py +++ b/lcci/17.18.Shortest Supersequence/Solution.py @@ -1,18 +1,18 @@ -class Solution: - def shortestSeq(self, big: List[int], small: List[int]) -> List[int]: - need = Counter(small) - window = Counter() - cnt, j, k, mi = len(small), 0, -1, inf - for i, x in enumerate(big): - window[x] += 1 - if need[x] >= window[x]: - cnt -= 1 - while cnt == 0: - if i - j + 1 < mi: - mi = i - j + 1 - k = j - if need[big[j]] >= window[big[j]]: - cnt += 1 - window[big[j]] -= 1 - j += 1 - return [] if k < 0 else [k, k + mi - 1] +class Solution: + def shortestSeq(self, big: List[int], small: List[int]) -> List[int]: + need = Counter(small) + window = Counter() + cnt, j, k, mi = len(small), 0, -1, inf + for i, x in enumerate(big): + window[x] += 1 + if need[x] >= window[x]: + cnt -= 1 + while cnt == 0: + if i - j + 1 < mi: + mi = i - j + 1 + k = j + if need[big[j]] >= window[big[j]]: + cnt += 1 + window[big[j]] -= 1 + j += 1 + return [] if k < 0 else [k, k + mi - 1] diff --git a/lcci/17.21.Volume of Histogram/Solution.cpp b/lcci/17.21.Volume of Histogram/Solution.cpp index 1786894bdebb3..70daa53350ed4 100644 --- a/lcci/17.21.Volume of Histogram/Solution.cpp +++ b/lcci/17.21.Volume of Histogram/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - int trap(vector& height) { - int n = height.size(); - if (n < 3) { - return 0; - } - int left[n], right[n]; - left[0] = height[0]; - right[n - 1] = height[n - 1]; - for (int i = 1; i < n; ++i) { - left[i] = max(left[i - 1], height[i]); - right[n - i - 1] = max(right[n - i], height[n - i - 1]); - } - int ans = 0; - for (int i = 0; i < n; ++i) { - ans += min(left[i], right[i]) - height[i]; - } - return ans; - } +class Solution { +public: + int trap(vector& height) { + int n = height.size(); + if (n < 3) { + return 0; + } + int left[n], right[n]; + left[0] = height[0]; + right[n - 1] = height[n - 1]; + for (int i = 1; i < n; ++i) { + left[i] = max(left[i - 1], height[i]); + right[n - i - 1] = max(right[n - i], height[n - i - 1]); + } + int ans = 0; + for (int i = 0; i < n; ++i) { + ans += min(left[i], right[i]) - height[i]; + } + return ans; + } }; \ No newline at end of file diff --git a/lcci/17.21.Volume of Histogram/Solution.cs b/lcci/17.21.Volume of Histogram/Solution.cs index 9edcb60ecd6e9..6671c2680ce43 100644 --- a/lcci/17.21.Volume of Histogram/Solution.cs +++ b/lcci/17.21.Volume of Histogram/Solution.cs @@ -1,21 +1,21 @@ -public class Solution { - public int Trap(int[] height) { - int n = height.Length; - if (n < 3) { - return 0; - } - int[] left = new int[n]; - int[] right = new int[n]; - left[0] = height[0]; - right[n - 1] = height[n - 1]; - for (int i = 1; i < n; ++i) { - left[i] = Math.Max(left[i - 1], height[i]); - right[n - i - 1] = Math.Max(right[n - i], height[n - i - 1]); - } - int ans = 0; - for (int i = 0; i < n; ++i) { - ans += Math.Min(left[i], right[i]) - height[i]; - } - return ans; - } -} \ No newline at end of file +public class Solution { + public int Trap(int[] height) { + int n = height.Length; + if (n < 3) { + return 0; + } + int[] left = new int[n]; + int[] right = new int[n]; + left[0] = height[0]; + right[n - 1] = height[n - 1]; + for (int i = 1; i < n; ++i) { + left[i] = Math.Max(left[i - 1], height[i]); + right[n - i - 1] = Math.Max(right[n - i], height[n - i - 1]); + } + int ans = 0; + for (int i = 0; i < n; ++i) { + ans += Math.Min(left[i], right[i]) - height[i]; + } + return ans; + } +} diff --git a/lcci/17.21.Volume of Histogram/Solution.java b/lcci/17.21.Volume of Histogram/Solution.java index 43cd3597ac560..b20ddb814bb14 100644 --- a/lcci/17.21.Volume of Histogram/Solution.java +++ b/lcci/17.21.Volume of Histogram/Solution.java @@ -1,21 +1,21 @@ -class Solution { - public int trap(int[] height) { - int n = height.length; - if (n < 3) { - return 0; - } - int[] left = new int[n]; - int[] right = new int[n]; - left[0] = height[0]; - right[n - 1] = height[n - 1]; - for (int i = 1; i < n; ++i) { - left[i] = Math.max(left[i - 1], height[i]); - right[n - i - 1] = Math.max(right[n - i], height[n - i - 1]); - } - int ans = 0; - for (int i = 0; i < n; ++i) { - ans += Math.min(left[i], right[i]) - height[i]; - } - return ans; - } +class Solution { + public int trap(int[] height) { + int n = height.length; + if (n < 3) { + return 0; + } + int[] left = new int[n]; + int[] right = new int[n]; + left[0] = height[0]; + right[n - 1] = height[n - 1]; + for (int i = 1; i < n; ++i) { + left[i] = Math.max(left[i - 1], height[i]); + right[n - i - 1] = Math.max(right[n - i], height[n - i - 1]); + } + int ans = 0; + for (int i = 0; i < n; ++i) { + ans += Math.min(left[i], right[i]) - height[i]; + } + return ans; + } } \ No newline at end of file diff --git a/lcci/17.21.Volume of Histogram/Solution.py b/lcci/17.21.Volume of Histogram/Solution.py index fe957d05b37b8..19c87191e9fc8 100644 --- a/lcci/17.21.Volume of Histogram/Solution.py +++ b/lcci/17.21.Volume of Histogram/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def trap(self, height: List[int]) -> int: - n = len(height) - if n < 3: - return 0 - left = [height[0]] * n - right = [height[-1]] * n - for i in range(1, n): - left[i] = max(left[i - 1], height[i]) - right[n - i - 1] = max(right[n - i], height[n - i - 1]) - return sum(min(l, r) - h for l, r, h in zip(left, right, height)) +class Solution: + def trap(self, height: List[int]) -> int: + n = len(height) + if n < 3: + return 0 + left = [height[0]] * n + right = [height[-1]] * n + for i in range(1, n): + left[i] = max(left[i - 1], height[i]) + right[n - i - 1] = max(right[n - i], height[n - i - 1]) + return sum(min(l, r) - h for l, r, h in zip(left, right, height)) diff --git a/lcci/17.24.Max Submatrix/Solution.py b/lcci/17.24.Max Submatrix/Solution.py index d5d40b4846e02..abadd07c2c619 100644 --- a/lcci/17.24.Max Submatrix/Solution.py +++ b/lcci/17.24.Max Submatrix/Solution.py @@ -4,6 +4,7 @@ def getMaxMatrix(self, matrix: List[List[int]]) -> List[int]: s = [[0] * n for _ in range(m + 1)] for i in range(m): for j in range(n): + # 构造列前缀和 s[i + 1][j] = s[i][j] + matrix[i][j] mx = matrix[0][0] diff --git a/lcci/17.25.Word Rectangle/Solution.cpp b/lcci/17.25.Word Rectangle/Solution.cpp index e1aecf0ca153b..8680501133239 100644 --- a/lcci/17.25.Word Rectangle/Solution.cpp +++ b/lcci/17.25.Word Rectangle/Solution.cpp @@ -1,81 +1,81 @@ -class Trie { -public: - vector children; - bool is_end; - - Trie() { - children = vector(26, nullptr); - is_end = false; - } - - void insert(const string& word) { - Trie* cur = this; - for (char c : word) { - c -= 'a'; - if (cur->children[c] == nullptr) { - cur->children[c] = new Trie; - } - cur = cur->children[c]; - } - cur->is_end = true; - } -}; - -class Solution { -public: - vector maxRectangle(vector& words) { - unordered_map> d; - int maxL = 0, maxS = 0; - vector ans; - vector t; - Trie* trie = new Trie(); - for (auto& w : words) { - maxL = max(maxL, (int) w.size()); - d[w.size()].emplace_back(w); - trie->insert(w); - } - auto check = [&](vector& mat) { - int m = mat.size(), n = mat[0].size(); - int ans = 1; - for (int j = 0; j < n; ++j) { - Trie* node = trie; - for (int i = 0; i < m; ++i) { - int idx = mat[i][j] - 'a'; - if (!node->children[idx]) { - return 0; - } - node = node->children[idx]; - } - if (!node->is_end) { - ans = 2; - } - } - return ans; - }; - - function&)> dfs = [&](vector& ws) { - if (ws[0].size() * maxL <= maxS || t.size() >= maxL) { - return; - } - for (auto& w : ws) { - t.emplace_back(w); - int st = check(t); - if (st == 0) { - t.pop_back(); - continue; - } - if (st == 1 && maxS < t.size() * t[0].size()) { - maxS = t.size() * t[0].size(); - ans = t; - } - dfs(ws); - t.pop_back(); - } - }; - for (auto& [_, ws] : d) { - t.clear(); - dfs(ws); - } - return ans; - } +class Trie { +public: + vector children; + bool is_end; + + Trie() { + children = vector(26, nullptr); + is_end = false; + } + + void insert(const string& word) { + Trie* cur = this; + for (char c : word) { + c -= 'a'; + if (cur->children[c] == nullptr) { + cur->children[c] = new Trie; + } + cur = cur->children[c]; + } + cur->is_end = true; + } +}; + +class Solution { +public: + vector maxRectangle(vector& words) { + unordered_map> d; + int maxL = 0, maxS = 0; + vector ans; + vector t; + Trie* trie = new Trie(); + for (auto& w : words) { + maxL = max(maxL, (int) w.size()); + d[w.size()].emplace_back(w); + trie->insert(w); + } + auto check = [&](vector& mat) { + int m = mat.size(), n = mat[0].size(); + int ans = 1; + for (int j = 0; j < n; ++j) { + Trie* node = trie; + for (int i = 0; i < m; ++i) { + int idx = mat[i][j] - 'a'; + if (!node->children[idx]) { + return 0; + } + node = node->children[idx]; + } + if (!node->is_end) { + ans = 2; + } + } + return ans; + }; + + function&)> dfs = [&](vector& ws) { + if (ws[0].size() * maxL <= maxS || t.size() >= maxL) { + return; + } + for (auto& w : ws) { + t.emplace_back(w); + int st = check(t); + if (st == 0) { + t.pop_back(); + continue; + } + if (st == 1 && maxS < t.size() * t[0].size()) { + maxS = t.size() * t[0].size(); + ans = t; + } + dfs(ws); + t.pop_back(); + } + }; + for (auto& [_, ws] : d) { + t.clear(); + dfs(ws); + } + return ans; + } }; \ No newline at end of file diff --git a/lcci/17.25.Word Rectangle/Solution.java b/lcci/17.25.Word Rectangle/Solution.java index fd97227c988a2..956b3c91901a8 100644 --- a/lcci/17.25.Word Rectangle/Solution.java +++ b/lcci/17.25.Word Rectangle/Solution.java @@ -1,77 +1,77 @@ -class Trie { - Trie[] children = new Trie[26]; - boolean isEnd; - - void insert(String word) { - Trie node = this; - for (char c : word.toCharArray()) { - c -= 'a'; - if (node.children[c] == null) { - node.children[c] = new Trie(); - } - node = node.children[c]; - } - node.isEnd = true; - } -} - -class Solution { - private int maxL; - private int maxS; - private String[] ans; - private Trie trie = new Trie(); - private List t = new ArrayList<>(); - - public String[] maxRectangle(String[] words) { - Map> d = new HashMap<>(100); - for (String w : words) { - maxL = Math.max(maxL, w.length()); - trie.insert(w); - d.computeIfAbsent(w.length(), k -> new ArrayList<>()).add(w); - } - for (List ws : d.values()) { - t.clear(); - dfs(ws); - } - return ans; - } - - private void dfs(List ws) { - if (ws.get(0).length() * maxL <= maxS || t.size() >= maxL) { - return; - } - for (String w : ws) { - t.add(w); - int st = check(t); - if (st == 0) { - t.remove(t.size() - 1); - continue; - } - if (st == 1 && maxS < t.size() * t.get(0).length()) { - maxS = t.size() * t.get(0).length(); - ans = t.toArray(new String[0]); - } - dfs(ws); - t.remove(t.size() - 1); - } - } - - private int check(List mat) { - int m = mat.size(), n = mat.get(0).length(); - int ans = 1; - for (int j = 0; j < n; ++j) { - Trie node = trie; - for (int i = 0; i < m; ++i) { - int idx = mat.get(i).charAt(j) - 'a'; - if (node.children[idx] == null) { - return 0; - } - node = node.children[idx]; - } - if (!node.isEnd) { - ans = 2; - } - } - return ans; - } +class Trie { + Trie[] children = new Trie[26]; + boolean isEnd; + + void insert(String word) { + Trie node = this; + for (char c : word.toCharArray()) { + c -= 'a'; + if (node.children[c] == null) { + node.children[c] = new Trie(); + } + node = node.children[c]; + } + node.isEnd = true; + } +} + +class Solution { + private int maxL; + private int maxS; + private String[] ans; + private Trie trie = new Trie(); + private List t = new ArrayList<>(); + + public String[] maxRectangle(String[] words) { + Map> d = new HashMap<>(100); + for (String w : words) { + maxL = Math.max(maxL, w.length()); + trie.insert(w); + d.computeIfAbsent(w.length(), k -> new ArrayList<>()).add(w); + } + for (List ws : d.values()) { + t.clear(); + dfs(ws); + } + return ans; + } + + private void dfs(List ws) { + if (ws.get(0).length() * maxL <= maxS || t.size() >= maxL) { + return; + } + for (String w : ws) { + t.add(w); + int st = check(t); + if (st == 0) { + t.remove(t.size() - 1); + continue; + } + if (st == 1 && maxS < t.size() * t.get(0).length()) { + maxS = t.size() * t.get(0).length(); + ans = t.toArray(new String[0]); + } + dfs(ws); + t.remove(t.size() - 1); + } + } + + private int check(List mat) { + int m = mat.size(), n = mat.get(0).length(); + int ans = 1; + for (int j = 0; j < n; ++j) { + Trie node = trie; + for (int i = 0; i < m; ++i) { + int idx = mat.get(i).charAt(j) - 'a'; + if (node.children[idx] == null) { + return 0; + } + node = node.children[idx]; + } + if (!node.isEnd) { + ans = 2; + } + } + return ans; + } } \ No newline at end of file diff --git a/lcci/17.25.Word Rectangle/Solution.py b/lcci/17.25.Word Rectangle/Solution.py index 9fc31723b4fbd..4b59de546cfb6 100644 --- a/lcci/17.25.Word Rectangle/Solution.py +++ b/lcci/17.25.Word Rectangle/Solution.py @@ -1,62 +1,62 @@ -class Trie: - def __init__(self): - self.children = [None] * 26 - self.is_end = False - - def insert(self, w): - node = self - for c in w: - idx = ord(c) - ord("a") - if node.children[idx] is None: - node.children[idx] = Trie() - node = node.children[idx] - node.is_end = True - - -class Solution: - def maxRectangle(self, words: List[str]) -> List[str]: - def check(mat): - m, n = len(mat), len(mat[0]) - ans = 1 - for j in range(n): - node = trie - for i in range(m): - idx = ord(mat[i][j]) - ord("a") - if node.children[idx] is None: - return 0 - node = node.children[idx] - if not node.is_end: - ans = 2 - return ans - - def dfs(ws): - nonlocal ans, max_s, max_l - if len(ws[0]) * max_l <= max_s or len(t) >= max_l: - return - - for w in ws: - t.append(w) - st = check(t) - if st == 0: - t.pop() - continue - if st == 1 and max_s < len(t) * len(t[0]): - ans = t[:] - max_s = len(t) * len(t[0]) - dfs(ws) - t.pop() - - d = defaultdict(list) - trie = Trie() - max_l = 0 - for w in words: - trie.insert(w) - max_l = max(max_l, len(w)) - d[len(w)].append(w) - - max_s = 0 - ans = [] - for ws in d.values(): - t = [] - dfs(ws) - return ans +class Trie: + def __init__(self): + self.children = [None] * 26 + self.is_end = False + + def insert(self, w): + node = self + for c in w: + idx = ord(c) - ord("a") + if node.children[idx] is None: + node.children[idx] = Trie() + node = node.children[idx] + node.is_end = True + + +class Solution: + def maxRectangle(self, words: List[str]) -> List[str]: + def check(mat): + m, n = len(mat), len(mat[0]) + ans = 1 + for j in range(n): + node = trie + for i in range(m): + idx = ord(mat[i][j]) - ord("a") + if node.children[idx] is None: + return 0 + node = node.children[idx] + if not node.is_end: + ans = 2 + return ans + + def dfs(ws): + nonlocal ans, max_s, max_l + if len(ws[0]) * max_l <= max_s or len(t) >= max_l: + return + + for w in ws: + t.append(w) + st = check(t) + if st == 0: + t.pop() + continue + if st == 1 and max_s < len(t) * len(t[0]): + ans = t[:] + max_s = len(t) * len(t[0]) + dfs(ws) + t.pop() + + d = defaultdict(list) + trie = Trie() + max_l = 0 + for w in words: + trie.insert(w) + max_l = max(max_l, len(w)) + d[len(w)].append(w) + + max_s = 0 + ans = [] + for ws in d.values(): + t = [] + dfs(ws) + return ans diff --git "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.cpp" index af7eff7e5a15f..5b30758a2b2d7 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.cpp" +++ "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.cpp" @@ -1,13 +1,10 @@ class Solution { public: int findRepeatNumber(vector& nums) { + sort(nums.begin(), nums.end()); for (int i = 0;; ++i) { - while (nums[i] != i) { - int j = nums[i]; - if (nums[j] == j) { - return j; - } - swap(nums[i], nums[j]); + if (nums[i] == nums[i + 1]) { + return nums[i]; } } } diff --git "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.cs" index 76d700dc00d60..ffa7c2ee7468d 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.cs" @@ -1,15 +1,15 @@ -public class Solution { - public int FindRepeatNumber(int[] nums) { - for (int i = 0; ; ++i) { - while (nums[i] != i) { - int j = nums[i]; - if (nums[j] == j) { - return j; - } - int t = nums[i]; - nums[i] = nums[j]; - nums[j] = t; - } - } - } -} \ No newline at end of file +public class Solution { + public int FindRepeatNumber(int[] nums) { + for (int i = 0; ; ++i) { + while (nums[i] != i) { + int j = nums[i]; + if (nums[j] == j) { + return j; + } + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } + } + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.go" "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.go" index 4f9d3e49c3369..910faabc94eeb 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.go" +++ "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.go" @@ -1,11 +1,8 @@ func findRepeatNumber(nums []int) int { + sort.Ints(nums) for i := 0; ; i++ { - for nums[i] != i { - j := nums[i] - if nums[j] == j { - return j - } - nums[i], nums[j] = nums[j], nums[i] + if nums[i] == nums[i+1] { + return nums[i] } } } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.java" "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.java" index f0ae7ecca3a94..5c40f8397772e 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.java" +++ "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.java" @@ -1,14 +1,9 @@ class Solution { public int findRepeatNumber(int[] nums) { + Arrays.sort(nums); for (int i = 0;; ++i) { - while (nums[i] != i) { - int j = nums[i]; - if (nums[j] == j) { - return j; - } - int t = nums[i]; - nums[i] = nums[j]; - nums[j] = t; + if (nums[i] == nums[i + 1]) { + return nums[i]; } } } diff --git "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.kt" "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.kt" index 07184776ddc46..e7c09c9e6c134 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.kt" +++ "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.kt" @@ -16,4 +16,4 @@ class Solution { nums[i] = nums[j]; nums[j] = t; } -} \ No newline at end of file +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.py" "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.py" index 360580bea1ef0..066134a44659d 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.py" +++ "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution.py" @@ -1,8 +1,5 @@ class Solution: def findRepeatNumber(self, nums: List[int]) -> int: - for i, v in enumerate(nums): - while v != i: - if nums[v] == v: - return v - nums[i], nums[v] = nums[v], nums[i] - v = nums[i] + for a, b in pairwise(sorted(nums)): + if a == b: + return a diff --git "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution2.cpp" new file mode 100644 index 0000000000000..bb0bcfe2935a5 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution2.cpp" @@ -0,0 +1,12 @@ +class Solution { +public: + int findRepeatNumber(vector& nums) { + unordered_set vis; + for (int i = 0;; ++i) { + if (vis.count(nums[i])) { + return nums[i]; + } + vis.insert(nums[i]); + } + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution2.go" new file mode 100644 index 0000000000000..7d11464630ffc --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution2.go" @@ -0,0 +1,9 @@ +func findRepeatNumber(nums []int) int { + vis := map[int]bool{} + for i := 0; ; i++ { + if vis[nums[i]] { + return nums[i] + } + vis[nums[i]] = true + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution2.java" new file mode 100644 index 0000000000000..2f849310e5c8f --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution2.java" @@ -0,0 +1,10 @@ +class Solution { + public int findRepeatNumber(int[] nums) { + Set vis = new HashSet<>(); + for (int i = 0;; ++i) { + if (!vis.add(nums[i])) { + return nums[i]; + } + } + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution2.py" new file mode 100644 index 0000000000000..5536f9643d09d --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution2.py" @@ -0,0 +1,7 @@ +class Solution: + def findRepeatNumber(self, nums: List[int]) -> int: + vis = set() + for v in nums: + if v in vis: + return v + vis.add(v) diff --git "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution3.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution3.cpp" new file mode 100644 index 0000000000000..af7eff7e5a15f --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution3.cpp" @@ -0,0 +1,14 @@ +class Solution { +public: + int findRepeatNumber(vector& nums) { + for (int i = 0;; ++i) { + while (nums[i] != i) { + int j = nums[i]; + if (nums[j] == j) { + return j; + } + swap(nums[i], nums[j]); + } + } + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution3.go" "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution3.go" new file mode 100644 index 0000000000000..4f9d3e49c3369 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution3.go" @@ -0,0 +1,11 @@ +func findRepeatNumber(nums []int) int { + for i := 0; ; i++ { + for nums[i] != i { + j := nums[i] + if nums[j] == j { + return j + } + nums[i], nums[j] = nums[j], nums[i] + } + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution3.java" "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution3.java" new file mode 100644 index 0000000000000..f0ae7ecca3a94 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution3.java" @@ -0,0 +1,15 @@ +class Solution { + public int findRepeatNumber(int[] nums) { + for (int i = 0;; ++i) { + while (nums[i] != i) { + int j = nums[i]; + if (nums[j] == j) { + return j; + } + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } + } + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution3.py" "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution3.py" new file mode 100644 index 0000000000000..360580bea1ef0 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/Solution3.py" @@ -0,0 +1,8 @@ +class Solution: + def findRepeatNumber(self, nums: List[int]) -> int: + for i, v in enumerate(nums): + while v != i: + if nums[v] == v: + return v + nums[i], nums[v] = nums[v], nums[i] + v = nums[i] diff --git "a/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.cpp" index a269e0e87b927..248d3c3bfee93 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.cpp" +++ "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.cpp" @@ -1,20 +1,12 @@ class Solution { public: bool findNumberIn2DArray(vector>& matrix, int target) { - if (matrix.empty()) { - return false; - } - int m = matrix.size(), n = matrix[0].size(); - int i = 0, j = n - 1; - while (i < m && j >= 0) { - if (matrix[i][j] == target) { + for (auto& row : matrix) { + int j = lower_bound(row.begin(), row.end(), target) - row.begin(); + if (j < matrix[0].size() && row[j] == target) { return true; - } else if (matrix[i][j] < target) { - ++i; - } else { - --j; } } return false; } -}; +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.cs" index 19df841ec616b..ff4200944b8e4 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.cs" @@ -1,18 +1,18 @@ -public class Solution { - public bool FindNumberIn2DArray(int[][] matrix, int target) { - if (matrix.Length == 0 || matrix[0].Length == 0) { - return false; - } - int i = 0, j = matrix[0].Length - 1; - while (i < matrix.Length && j >= 0) { - if (target == matrix[i][j]) { - return true; - } else if (target > matrix[i][j]) { - i += 1; - } else { - j -= 1; - } - } - return false; - } -} \ No newline at end of file +public class Solution { + public bool FindNumberIn2DArray(int[][] matrix, int target) { + if (matrix.Length == 0 || matrix[0].Length == 0) { + return false; + } + int i = 0, j = matrix[0].Length - 1; + while (i < matrix.Length && j >= 0) { + if (target == matrix[i][j]) { + return true; + } else if (target > matrix[i][j]) { + i += 1; + } else { + j -= 1; + } + } + return false; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.go" "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.go" index f8cace4229a3d..f360539da3efd 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.go" +++ "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.go" @@ -1,17 +1,9 @@ func findNumberIn2DArray(matrix [][]int, target int) bool { - if len(matrix) == 0 { - return false - } - m, n := len(matrix), len(matrix[0]) - for i, j := 0, n-1; i < m && j >= 0; { - if matrix[i][j] == target { + for _, row := range matrix { + j := sort.SearchInts(row, target) + if j < len(matrix[0]) && row[j] == target { return true } - if matrix[i][j] < target { - i++ - } else { - j-- - } } return false } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.java" "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.java" index 7ba22ae68ea94..4f651274f38ab 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.java" +++ "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.java" @@ -1,18 +1,10 @@ class Solution { public boolean findNumberIn2DArray(int[][] matrix, int target) { - if (matrix.length == 0 || matrix[0].length == 0) { - return false; - } - int m = matrix.length, n = matrix[0].length; - for (int i = m - 1, j = 0; i >= 0 && j < n;) { - if (matrix[i][j] == target) { + for (var row : matrix) { + int j = Arrays.binarySearch(row, target); + if (j >= 0) { return true; } - if (matrix[i][j] > target) { - --i; - } else { - ++j; - } } return false; } diff --git "a/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.py" "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.py" index 7860bfcb23a24..92bae58a4e8ba 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.py" +++ "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution.py" @@ -1,14 +1,7 @@ class Solution: def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool: - if not matrix or not matrix[0]: - return False - m, n = len(matrix), len(matrix[0]) - i, j = m - 1, 0 - while i >= 0 and j < n: - if matrix[i][j] == target: + for row in matrix: + j = bisect_left(row, target) + if j < len(matrix[0]) and row[j] == target: return True - if matrix[i][j] > target: - i -= 1 - else: - j += 1 return False diff --git "a/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution2.cpp" new file mode 100644 index 0000000000000..d08a39430191c --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution2.cpp" @@ -0,0 +1,20 @@ +class Solution { +public: + bool findNumberIn2DArray(vector>& matrix, int target) { + if (matrix.empty()) { + return false; + } + int m = matrix.size(), n = matrix[0].size(); + int i = 0, j = n - 1; + while (i < m && j >= 0) { + if (matrix[i][j] == target) { + return true; + } else if (matrix[i][j] < target) { + ++i; + } else { + --j; + } + } + return false; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution2.go" new file mode 100644 index 0000000000000..f8cace4229a3d --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution2.go" @@ -0,0 +1,17 @@ +func findNumberIn2DArray(matrix [][]int, target int) bool { + if len(matrix) == 0 { + return false + } + m, n := len(matrix), len(matrix[0]) + for i, j := 0, n-1; i < m && j >= 0; { + if matrix[i][j] == target { + return true + } + if matrix[i][j] < target { + i++ + } else { + j-- + } + } + return false +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution2.java" new file mode 100644 index 0000000000000..7ba22ae68ea94 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution2.java" @@ -0,0 +1,19 @@ +class Solution { + public boolean findNumberIn2DArray(int[][] matrix, int target) { + if (matrix.length == 0 || matrix[0].length == 0) { + return false; + } + int m = matrix.length, n = matrix[0].length; + for (int i = m - 1, j = 0; i >= 0 && j < n;) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution2.py" new file mode 100644 index 0000000000000..7860bfcb23a24 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/Solution2.py" @@ -0,0 +1,14 @@ +class Solution: + def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool: + if not matrix or not matrix[0]: + return False + m, n = len(matrix), len(matrix[0]) + i, j = m - 1, 0 + while i >= 0 and j < n: + if matrix[i][j] == target: + return True + if matrix[i][j] > target: + i -= 1 + else: + j += 1 + return False diff --git "a/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution.cpp" index fb2c7e606d350..34b37e1fb0b00 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution.cpp" +++ "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution.cpp" @@ -10,4 +10,4 @@ class Solution { } return ans; } -}; +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution.cs" index c1fa2b86b431f..8d2049bd8830e 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution.cs" @@ -1,5 +1,5 @@ -public class Solution { - public string ReplaceSpace(string s) { - return s.Replace(" ", "%20"); - } -} \ No newline at end of file +public class Solution { + public string ReplaceSpace(string s) { + return s.Replace(" ", "%20"); + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution.js" "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution.js" index 204b5855c134b..6a3b08cc6c4ab 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution.js" +++ "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution.js" @@ -3,5 +3,5 @@ * @return {string} */ var replaceSpace = function (s) { - return s.replace(/\s/g, '%20'); + return s.split(' ').join('%20'); }; diff --git "a/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution.php" "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution.php" index 659f952044056..254ed7f3254cb 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution.php" +++ "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution.php" @@ -14,4 +14,4 @@ function replaceSpace($s) { } return $rs; } -} \ No newline at end of file +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.cs" "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.cs" new file mode 100644 index 0000000000000..9e260432cd6e9 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.cs" @@ -0,0 +1,13 @@ +public class Solution { + public string ReplaceSpace(string s) { + StringBuilder res = new StringBuilder(); + foreach (var c in s) { + if (c == ' ') { + res.Append("%20"); + } else { + res.Append(c); + } + } + return res.ToString(); + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.go" new file mode 100644 index 0000000000000..50da097005b31 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.go" @@ -0,0 +1,11 @@ +func replaceSpace(s string) string { + ans := strings.Builder{} + for _, c := range s { + if c == ' ' { + ans.WriteString("%20") + } else { + ans.WriteRune(c) + } + } + return ans.String() +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.java" new file mode 100644 index 0000000000000..a026a8f79ab24 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.java" @@ -0,0 +1,9 @@ +class Solution { + public String replaceSpace(String s) { + StringBuilder ans = new StringBuilder(); + for (char c : s.toCharArray()) { + ans.append(c == ' ' ? "%20" : c); + } + return ans.toString(); + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.js" "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.js" new file mode 100644 index 0000000000000..204b5855c134b --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.js" @@ -0,0 +1,7 @@ +/** + * @param {string} s + * @return {string} + */ +var replaceSpace = function (s) { + return s.replace(/\s/g, '%20'); +}; diff --git "a/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.py" new file mode 100644 index 0000000000000..e0093e34829d5 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.py" @@ -0,0 +1,6 @@ +class Solution: + def replaceSpace(self, s: str) -> str: + ans = [] + for c in s: + ans.append('%20' if c == ' ' else c) + return ''.join(ans) diff --git "a/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.rs" "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.rs" new file mode 100644 index 0000000000000..bec7765c141e5 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.rs" @@ -0,0 +1,13 @@ +impl Solution { + pub fn replace_space(s: String) -> String { + let mut result = String::new(); + for c in s.chars() { + if c == ' ' { + result.push_str("%20"); + } else { + result.push(c); + } + } + result + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.ts" "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.ts" new file mode 100644 index 0000000000000..ca30b301c0d40 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution2.ts" @@ -0,0 +1,7 @@ +function replaceSpace(s: string): string { + const strArr = []; + for (const c of s) { + strArr.push(c === ' ' ? '%20' : c); + } + return strArr.join(''); +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution3.js" "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution3.js" new file mode 100644 index 0000000000000..78591349162b5 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/Solution3.js" @@ -0,0 +1,11 @@ +/** + * @param {string} s + * @return {string} + */ +var replaceSpace = function (s) { + const ans = []; + for (const c of s) { + ans.push(c === ' ' ? '%20' : c); + } + return ans.join(''); +}; diff --git "a/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution.cs" index b3ccf1e2d7fd2..84ebd3e236c03 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution.cs" @@ -1,19 +1,19 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int x) { val = x; } - * } - */ - public class Solution { - public int[] ReversePrint(ListNode head) { - List ans = new List(); - while (head != null) { - ans.Add(head.val); - head = head.next; - } - ans.Reverse(); - return ans.ToArray(); - } - } \ No newline at end of file +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int x) { val = x; } + * } + */ + public class Solution { + public int[] ReversePrint(ListNode head) { + List ans = new List(); + while (head != null) { + ans.Add(head.val); + head = head.next; + } + ans.Reverse(); + return ans.ToArray(); + } + } diff --git "a/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution2.cpp" new file mode 100644 index 0000000000000..aa0ba71ca67d1 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution2.cpp" @@ -0,0 +1,19 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + vector reversePrint(ListNode* head) { + vector ans; + for (; head; head = head->next) { + ans.push_back(head->val); + } + reverse(ans.begin(), ans.end()); + return ans; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution2.go" new file mode 100644 index 0000000000000..aca42eeb1bcf9 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution2.go" @@ -0,0 +1,15 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func reversePrint(head *ListNode) (ans []int) { + if head == nil { + return + } + ans = reversePrint(head.Next) + ans = append(ans, head.Val) + return +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution2.java" new file mode 100644 index 0000000000000..eaf8f7730e502 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution2.java" @@ -0,0 +1,23 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public int[] reversePrint(ListNode head) { + int n = 0; + ListNode cur = head; + for (; cur != null; cur = cur.next) { + ++n; + } + int[] ans = new int[n]; + cur = head; + for (; cur != null; cur = cur.next) { + ans[--n] = cur.val; + } + return ans; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution2.js" "b/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution2.js" new file mode 100644 index 0000000000000..3a3505ebff274 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution2.js" @@ -0,0 +1,19 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {number[]} + */ +var reversePrint = function (head) { + if (!head) { + return []; + } + const ans = reversePrint(head.next); + ans.push(head.val); + return ans; +}; diff --git "a/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution2.py" new file mode 100644 index 0000000000000..eb684198e04e0 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution2.py" @@ -0,0 +1,14 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + + +class Solution: + def reversePrint(self, head: ListNode) -> List[int]: + if head is None: + return [] + ans = self.reversePrint(head.next) + ans.append(head.val) + return ans diff --git "a/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution2.rs" "b/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution2.rs" new file mode 100644 index 0000000000000..b2eb334c68189 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/Solution2.rs" @@ -0,0 +1,35 @@ +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn reverse_print(head: Option>) -> Vec { + let mut cur = &head; + let mut n = 0; + while let Some(node) = cur { + cur = &node.next; + n += 1; + } + + let mut arr = vec![0; n]; + let mut cur = head; + while let Some(node) = cur { + n -= 1; + arr[n] = node.val; + cur = node.next; + } + arr + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23007. \351\207\215\345\273\272\344\272\214\345\217\211\346\240\221/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23007. \351\207\215\345\273\272\344\272\214\345\217\211\346\240\221/Solution.cs" index 55f24531b41fb..6eaba56ed0ade 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23007. \351\207\215\345\273\272\344\272\214\345\217\211\346\240\221/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23007. \351\207\215\345\273\272\344\272\214\345\217\211\346\240\221/Solution.cs" @@ -1,21 +1,21 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public TreeNode BuildTree(int[] preorder, int[] inorder) { - if (preorder.Length == 0) { - return null; - } - TreeNode root = new TreeNode(preorder[0]); - int idx = Array.IndexOf(inorder, root.val); - root.left = BuildTree(preorder[1..(index+1)], inorder[0..idx]); - root.right = BuildTree(preorder[(index+1)..], inorder[(idx+1)..]); - return root; - } -} \ No newline at end of file +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public TreeNode BuildTree(int[] preorder, int[] inorder) { + if (preorder.Length == 0) { + return null; + } + TreeNode root = new TreeNode(preorder[0]); + int idx = Array.IndexOf(inorder, root.val); + root.left = BuildTree(preorder[1..(index+1)], inorder[0..idx]); + root.right = BuildTree(preorder[(index+1)..], inorder[(idx+1)..]); + return root; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23007. \351\207\215\345\273\272\344\272\214\345\217\211\346\240\221/Solution2.ts" "b/lcof/\351\235\242\350\257\225\351\242\23007. \351\207\215\345\273\272\344\272\214\345\217\211\346\240\221/Solution2.ts" new file mode 100644 index 0000000000000..62b8d124bff01 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23007. \351\207\215\345\273\272\344\272\214\345\217\211\346\240\221/Solution2.ts" @@ -0,0 +1,26 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function buildTree(preorder: number[], inorder: number[]): TreeNode | null { + if (inorder.length === 0) { + return null; + } + const val = preorder[0]; + const i = inorder.indexOf(val); + return new TreeNode( + val, + buildTree(preorder.slice(1, i + 1), inorder.slice(0, i)), + buildTree(preorder.slice(i + 1), inorder.slice(i + 1)), + ); +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23009. \347\224\250\344\270\244\344\270\252\346\240\210\345\256\236\347\216\260\351\230\237\345\210\227/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23009. \347\224\250\344\270\244\344\270\252\346\240\210\345\256\236\347\216\260\351\230\237\345\210\227/Solution.cs" index dbaa91acbc4bc..df0612b7e012c 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23009. \347\224\250\344\270\244\344\270\252\346\240\210\345\256\236\347\216\260\351\230\237\345\210\227/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23009. \347\224\250\344\270\244\344\270\252\346\240\210\345\256\236\347\216\260\351\230\237\345\210\227/Solution.cs" @@ -1,28 +1,28 @@ -public class CQueue { - private Stack stk1 = new Stack(); - private Stack stk2 = new Stack(); - - public CQueue() { - - } - - public void AppendTail(int value) { - stk1.Push(value); - } - - public int DeleteHead() { - if (stk2.Count == 0) { - while (stk1.Count != 0) { - stk2.Push(stk1.Pop()); - } - } - return stk2.Count == 0 ? -1 : stk2.Pop(); - } -} - -/** - * Your CQueue object will be instantiated and called as such: - * CQueue obj = new CQueue(); - * obj.AppendTail(value); - * int param_2 = obj.DeleteHead(); - */ \ No newline at end of file +public class CQueue { + private Stack stk1 = new Stack(); + private Stack stk2 = new Stack(); + + public CQueue() { + + } + + public void AppendTail(int value) { + stk1.Push(value); + } + + public int DeleteHead() { + if (stk2.Count == 0) { + while (stk1.Count != 0) { + stk2.Push(stk1.Pop()); + } + } + return stk2.Count == 0 ? -1 : stk2.Pop(); + } +} + +/** + * Your CQueue object will be instantiated and called as such: + * CQueue obj = new CQueue(); + * obj.AppendTail(value); + * int param_2 = obj.DeleteHead(); + */ diff --git "a/lcof/\351\235\242\350\257\225\351\242\23010- I. \346\226\220\346\263\242\351\202\243\345\245\221\346\225\260\345\210\227/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23010- I. \346\226\220\346\263\242\351\202\243\345\245\221\346\225\260\345\210\227/Solution.cs" index 4a503049edf87..1f98730c1e1c4 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23010- I. \346\226\220\346\263\242\351\202\243\345\245\221\346\225\260\345\210\227/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23010- I. \346\226\220\346\263\242\351\202\243\345\245\221\346\225\260\345\210\227/Solution.cs" @@ -1,11 +1,11 @@ -public class Solution { - public int Fib(int n) { - int a = 0, b = 1, tmp; - for (int i = 0; i < n; i++) { - tmp = a; - a = b; - b = (tmp + b) % 1000000007; - } - return a % 1000000007; - } -} \ No newline at end of file +public class Solution { + public int Fib(int n) { + int a = 0, b = 1, tmp; + for (int i = 0; i < n; i++) { + tmp = a; + a = b; + b = (tmp + b) % 1000000007; + } + return a % 1000000007; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23010- II. \351\235\222\350\233\231\350\267\263\345\217\260\351\230\266\351\227\256\351\242\230/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23010- II. \351\235\222\350\233\231\350\267\263\345\217\260\351\230\266\351\227\256\351\242\230/Solution.cs" index 674d3fa2850b4..c781090d71503 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23010- II. \351\235\222\350\233\231\350\267\263\345\217\260\351\230\266\351\227\256\351\242\230/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23010- II. \351\235\222\350\233\231\350\267\263\345\217\260\351\230\266\351\227\256\351\242\230/Solution.cs" @@ -1,11 +1,11 @@ -public class Solution { - public int NumWays(int n) { - int a = 1, b = 1, tmp; - for (int i = 0; i < n; i++) { - tmp = a; - a = b; - b = (tmp + b) % 1000000007; - } - return a % 1000000007; - } -} \ No newline at end of file +public class Solution { + public int NumWays(int n) { + int a = 1, b = 1, tmp; + for (int i = 0; i < n; i++) { + tmp = a; + a = b; + b = (tmp + b) % 1000000007; + } + return a % 1000000007; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution.cs" index 6fc0d857df2ec..15596f0fa99b9 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution.cs" @@ -1,16 +1,16 @@ -public class Solution { - public int MinArray(int[] numbers) { - int l = 0, r = numbers.Length - 1; - while (l < r) { - int m = (l + r) >> 1; - if (numbers[m] > numbers[r]) { - l = m + 1; - } else if (numbers[m] < numbers[r]) { - r = m; - } else { - --r; - } - } - return numbers[l]; - } -} \ No newline at end of file +public class Solution { + public int MinArray(int[] numbers) { + int l = 0, r = numbers.Length - 1; + while (l < r) { + int m = (l + r) >> 1; + if (numbers[m] > numbers[r]) { + l = m + 1; + } else if (numbers[m] < numbers[r]) { + r = m; + } else { + --r; + } + } + return numbers[l]; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.cpp" new file mode 100644 index 0000000000000..313cff9b78b03 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.cpp" @@ -0,0 +1,20 @@ +class Solution { +public: + int minArray(vector& numbers) { + int l = 0, r = numbers.size() - 1; + while (l < r) { + if (numbers[l] < numbers[r]) { + break; + } + int mid = (l + r) >> 1; + if (numbers[mid] > numbers[l]) { + l = mid + 1; + } else if (numbers[mid] < numbers[l]) { + r = mid; + } else { + ++l; + } + } + return numbers[l]; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.cs" "b/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.cs" new file mode 100644 index 0000000000000..1e0944c95a2d7 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.cs" @@ -0,0 +1,19 @@ +public class Solution { + public int MinArray(int[] numbers) { + int l = 0, r = numbers.Length - 1; + while (l < r) { + if (numbers[l] < numbers[r]) { + break; + } + int m = (l + r) >> 1; + if (numbers[m] > numbers[l]) { + l = m + 1; + } else if (numbers[m] < numbers[l]) { + r = m; + } else { + ++l; + } + } + return numbers[l]; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.go" new file mode 100644 index 0000000000000..ad49eb1bda103 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.go" @@ -0,0 +1,17 @@ +func minArray(numbers []int) int { + l, r := 0, len(numbers)-1 + for l < r { + if numbers[l] < numbers[r] { + break + } + mid := (l + r) >> 1 + if numbers[mid] > numbers[l] { + l = mid + 1 + } else if numbers[mid] < numbers[l] { + r = mid + } else { + l++ + } + } + return numbers[l] +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.java" new file mode 100644 index 0000000000000..3d531fd601a16 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.java" @@ -0,0 +1,19 @@ +class Solution { + public int minArray(int[] numbers) { + int l = 0, r = numbers.length - 1; + while (l < r) { + if (numbers[l] < numbers[r]) { + break; + } + int m = (l + r) >>> 1; + if (numbers[m] > numbers[l]) { + l = m + 1; + } else if (numbers[m] < numbers[l]) { + r = m; + } else { + ++l; + } + } + return numbers[l]; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.js" "b/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.js" new file mode 100644 index 0000000000000..f82594055e53b --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.js" @@ -0,0 +1,22 @@ +/** + * @param {number[]} numbers + * @return {number} + */ +var minArray = function (numbers) { + let l = 0, + r = numbers.length - 1; + while (l < r) { + if (numbers[l] < numbers[r]) { + break; + } + let m = (l + r) >>> 1; + if (numbers[m] > numbers[l]) { + l = m + 1; + } else if (numbers[m] < numbers[l]) { + r = m; + } else { + ++l; + } + } + return numbers[l]; +}; diff --git "a/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.py" new file mode 100644 index 0000000000000..c961feba200d4 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.py" @@ -0,0 +1,14 @@ +class Solution: + def minArray(self, numbers: List[int]) -> int: + l, r = 0, len(numbers) - 1 + while l < r: + if numbers[l] < numbers[r]: + return numbers[l] + mid = (l + r) >> 1 + if numbers[mid] > numbers[l]: + l = mid + 1 + elif numbers[mid] < numbers[l]: + r = mid + else: + l += 1 + return numbers[l] diff --git "a/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.rs" "b/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.rs" new file mode 100644 index 0000000000000..94a29b5ced18d --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/Solution2.rs" @@ -0,0 +1,24 @@ +impl Solution { + pub fn min_array(numbers: Vec) -> i32 { + let mut l = 0; + let mut r = numbers.len() - 1; + while l < r { + if numbers[l] < numbers[r] { + break; + } + let mid = (l + r) >> 1; + match numbers[mid].cmp(&numbers[l]) { + std::cmp::Ordering::Less => { + r = mid; + } + std::cmp::Ordering::Equal => { + l += 1; + } + std::cmp::Ordering::Greater => { + l = mid + 1; + } + } + } + numbers[l] + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23012. \347\237\251\351\230\265\344\270\255\347\232\204\350\267\257\345\276\204/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23012. \347\237\251\351\230\265\344\270\255\347\232\204\350\267\257\345\276\204/Solution.cs" index 53584e9e4962e..c44c45d503721 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23012. \347\237\251\351\230\265\344\270\255\347\232\204\350\267\257\345\276\204/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23012. \347\237\251\351\230\265\344\270\255\347\232\204\350\267\257\345\276\204/Solution.cs" @@ -1,38 +1,38 @@ -public class Solution { - private char[][] board; - private string word; - private int m; - private int n; - - public bool Exist(char[][] board, string word) { - m = board.Length; - n = board[0].Length; - this.board = board; - this.word = word; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (dfs(i, j, 0)) { - return true; - } - } - } - return false; - } - - private bool dfs(int i, int j, int k) { - if (k == word.Length) { - return true; - } - if (i < 0 || i >= m || j < 0 || j >= n || word[k] != board[i][j]) { - return false; - } - board[i][j] = ' '; - int[] dirs = {-1, 0, 1, 0, -1}; - bool ans = false; - for (int l = 0; l < 4; ++l) { - ans = ans || dfs(i + dirs[l], j + dirs[l + 1], k + 1); - } - board[i][j] = word[k]; - return ans; - } -} \ No newline at end of file +public class Solution { + private char[][] board; + private string word; + private int m; + private int n; + + public bool Exist(char[][] board, string word) { + m = board.Length; + n = board[0].Length; + this.board = board; + this.word = word; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (dfs(i, j, 0)) { + return true; + } + } + } + return false; + } + + private bool dfs(int i, int j, int k) { + if (k == word.Length) { + return true; + } + if (i < 0 || i >= m || j < 0 || j >= n || word[k] != board[i][j]) { + return false; + } + board[i][j] = ' '; + int[] dirs = {-1, 0, 1, 0, -1}; + bool ans = false; + for (int l = 0; l < 4; ++l) { + ans = ans || dfs(i + dirs[l], j + dirs[l + 1], k + 1); + } + board[i][j] = word[k]; + return ans; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.cpp" index f3155eacd0eea..5493e23c6bf66 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.cpp" +++ "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.cpp" @@ -1,22 +1,28 @@ -class Solution { -public: - int movingCount(int m, int n, int k) { - bool vis[m][n]; - memset(vis, false, sizeof vis); - auto f = [](int x) { - int s = 0; - for (; x; x /= 10) { - s += x % 10; - } - return s; - }; - function dfs = [&](int i, int j) -> int { - if (i < 0 || i >= m || j < 0 || j >= n || vis[i][j] || f(i) + f(j) > k) { - return false; - } - vis[i][j] = true; - return 1 + dfs(i + 1, j) + dfs(i, j + 1); - }; - return dfs(0, 0); - } +class Solution { +public: + int movingCount(int m, int n, int k) { + bool vis[m][n]; + memset(vis, false, sizeof vis); + int ans = 0; + int dirs[3] = {1, 0, 1}; + auto f = [](int x) { + int s = 0; + for (; x; x /= 10) { + s += x % 10; + } + return s; + }; + function dfs = [&](int i, int j) { + vis[i][j] = true; + ++ans; + for (int l = 0; l < 2; ++l) { + int x = i + dirs[l], y = j + dirs[l + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && f(x) + f(y) <= k && !vis[x][y]) { + dfs(x, y); + } + } + }; + dfs(0, 0); + return ans; + } }; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.cs" index d444a4de7e807..ddebf46ee8351 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.cs" @@ -1,39 +1,14 @@ -// public class Solution { -// int res = 0; -// public int MovingCount(int m, int n, int k) [ -// bool[,] arr = new bool[m, n]; -// dfs(0, 0, m, n, k, arr); -// return res; -// ] - -// public void dfs(int i, int j, int m, int n, int k, bool[,] arr) { -// if (i >= m || i < 0 || j >= n || j < 0 || arr[i, j]) { -// return; -// } -// arr[i, j] = true; -// int sum = i % 10 + j % 10 + i / 10 + j / 10; -// if (sum > k) { -// return; -// } -// res += 1; -// dfs(i+1, j, m, n, k, arr); -// dfs(i-1, j, m, n, k, arr); -// dfs(i, j+1, m, n, k, arr); -// dfs(i, j-1, m, n, k, arr); -// } -// } - -public class Solution { - public int MovingCount(int m, int n, int k) { - bool[,] arr = new bool[m, n]; - return dfs(0, 0, m, n, k, arr); - } - - public int dfs(int i, int j, int m, int n, int k, bool[,] arr) { - if (i >= m || j >= n || arr[i,j] || (i % 10 + j % 10 + i / 10 + j / 10) > k) { - return 0; - } - arr[i,j] = true; - return 1 + dfs(i+1, j, m, n, k, arr) + dfs(i, j+1, m, n, k, arr); - } -} \ No newline at end of file +public class Solution { + public int MovingCount(int m, int n, int k) { + bool[,] arr = new bool[m, n]; + return dfs(0, 0, m, n, k, arr); + } + + public int dfs(int i, int j, int m, int n, int k, bool[,] arr) { + if (i >= m || j >= n || arr[i,j] || (i % 10 + j % 10 + i / 10 + j / 10) > k) { + return 0; + } + arr[i,j] = true; + return 1 + dfs(i+1, j, m, n, k, arr) + dfs(i, j+1, m, n, k, arr); + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.java" "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.java" index e06104fcec7fa..585ca76d088c6 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.java" +++ "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.java" @@ -3,20 +3,34 @@ class Solution { private int m; private int n; private int k; + private int ans; public int movingCount(int m, int n, int k) { this.m = m; this.n = n; this.k = k; vis = new boolean[m][n]; - return dfs(0, 0); + dfs(0, 0); + return ans; } - private int dfs(int i, int j) { - if (i >= m || j >= n || vis[i][j] || (i % 10 + i / 10 + j % 10 + j / 10) > k) { - return 0; - } + private void dfs(int i, int j) { vis[i][j] = true; - return 1 + dfs(i + 1, j) + dfs(i, j + 1); + ++ans; + int[] dirs = {1, 0, 1}; + for (int l = 0; l < 2; ++l) { + int x = i + dirs[l], y = j + dirs[l + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && f(x) + f(y) <= k && !vis[x][y]) { + dfs(x, y); + } + } + } + + private int f(int x) { + int s = 0; + for (; x > 0; x /= 10) { + s += x % 10; + } + return s; } } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.py" "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.py" index eb1001d1914c3..b36352407ab56 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.py" +++ "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.py" @@ -8,10 +8,16 @@ def f(x): return s def dfs(i, j): - if not (0 <= i < m) or not (0 <= j < n) or f(i) + f(j) > k or (i, j) in vis: - return 0 vis.add((i, j)) - return 1 + dfs(i + 1, j) + dfs(i, j + 1) + nonlocal ans + ans += 1 + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n and f(x) + f(y) <= k and (x, y) not in vis: + dfs(x, y) vis = set() - return dfs(0, 0) + ans = 0 + dirs = (0, 1, 0) + dfs(0, 0) + return ans diff --git "a/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.rs" "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.rs" index 161b9fc85b07b..af85dc1f3bb34 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.rs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution.rs" @@ -1,19 +1,27 @@ +use std::collections::{ HashSet, VecDeque }; impl Solution { - fn dfs(sign: &mut Vec>, k: usize, i: usize, j: usize) -> i32 { - if - i == sign.len() || - j == sign[0].len() || - sign[i][j] || - (j % 10) + ((j / 10) % 10) + (i % 10) + ((i / 10) % 10) > k - { - return 0; - } - sign[i][j] = true; - 1 + Self::dfs(sign, k, i + 1, j) + Self::dfs(sign, k, i, j + 1) - } - pub fn moving_count(m: i32, n: i32, k: i32) -> i32 { - let mut sign = vec![vec![false; n as usize]; m as usize]; - Self::dfs(&mut sign, k as usize, 0, 0) + let mut set = HashSet::new(); + let mut queue = VecDeque::new(); + queue.push_back([0, 0]); + while let Some([i, j]) = queue.pop_front() { + let key = format!("{},{}", i, j); + if + i == m || + j == n || + set.contains(&key) || + k < + format!("{}{}", i, j) + .chars() + .map(|c| c.to_string().parse::().unwrap()) + .sum::() + { + continue; + } + set.insert(key); + queue.push_back([i + 1, j]); + queue.push_back([i, j + 1]); + } + set.len() as i32 } } diff --git "a/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution2.cpp" new file mode 100644 index 0000000000000..97d71c5c316c7 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution2.cpp" @@ -0,0 +1,22 @@ +class Solution { +public: + int movingCount(int m, int n, int k) { + bool vis[m][n]; + memset(vis, false, sizeof vis); + auto f = [](int x) { + int s = 0; + for (; x; x /= 10) { + s += x % 10; + } + return s; + }; + function dfs = [&](int i, int j) -> int { + if (i < 0 || i >= m || j < 0 || j >= n || vis[i][j] || f(i) + f(j) > k) { + return false; + } + vis[i][j] = true; + return 1 + dfs(i + 1, j) + dfs(i, j + 1); + }; + return dfs(0, 0); + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution2.go" new file mode 100644 index 0000000000000..20fa0f3281ac7 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution2.go" @@ -0,0 +1,27 @@ +func movingCount(m int, n int, k int) (ans int) { + f := func(x int) (s int) { + for ; x > 0; x /= 10 { + s += x % 10 + } + return + } + vis := make([][]bool, m) + for i := range vis { + vis[i] = make([]bool, n) + } + + dirs := [3]int{1, 0, 1} + var dfs func(i, j int) + dfs = func(i, j int) { + vis[i][j] = true + ans++ + for l := 0; l < 2; l++ { + x, y := i+dirs[l], j+dirs[l+1] + if x >= 0 && x < m && y >= 0 && y < n && f(x)+f(y) <= k && !vis[x][y] { + dfs(x, y) + } + } + } + dfs(0, 0) + return +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution2.java" new file mode 100644 index 0000000000000..e06104fcec7fa --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution2.java" @@ -0,0 +1,22 @@ +class Solution { + private boolean[][] vis; + private int m; + private int n; + private int k; + + public int movingCount(int m, int n, int k) { + this.m = m; + this.n = n; + this.k = k; + vis = new boolean[m][n]; + return dfs(0, 0); + } + + private int dfs(int i, int j) { + if (i >= m || j >= n || vis[i][j] || (i % 10 + i / 10 + j % 10 + j / 10) > k) { + return 0; + } + vis[i][j] = true; + return 1 + dfs(i + 1, j) + dfs(i, j + 1); + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution2.py" new file mode 100644 index 0000000000000..eb1001d1914c3 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution2.py" @@ -0,0 +1,17 @@ +class Solution: + def movingCount(self, m: int, n: int, k: int) -> int: + def f(x): + s = 0 + while x: + s += x % 10 + x //= 10 + return s + + def dfs(i, j): + if not (0 <= i < m) or not (0 <= j < n) or f(i) + f(j) > k or (i, j) in vis: + return 0 + vis.add((i, j)) + return 1 + dfs(i + 1, j) + dfs(i, j + 1) + + vis = set() + return dfs(0, 0) diff --git "a/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution2.rs" "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution2.rs" new file mode 100644 index 0000000000000..161b9fc85b07b --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/Solution2.rs" @@ -0,0 +1,19 @@ +impl Solution { + fn dfs(sign: &mut Vec>, k: usize, i: usize, j: usize) -> i32 { + if + i == sign.len() || + j == sign[0].len() || + sign[i][j] || + (j % 10) + ((j / 10) % 10) + (i % 10) + ((i / 10) % 10) > k + { + return 0; + } + sign[i][j] = true; + 1 + Self::dfs(sign, k, i + 1, j) + Self::dfs(sign, k, i, j + 1) + } + + pub fn moving_count(m: i32, n: i32, k: i32) -> i32 { + let mut sign = vec![vec![false; n as usize]; m as usize]; + Self::dfs(&mut sign, k as usize, 0, 0) + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.cpp" index 8984743b1aed7..3f3c056001447 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.cpp" +++ "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.cpp" @@ -1,15 +1,13 @@ class Solution { public: int cuttingRope(int n) { - if (n < 4) { - return n - 1; + vector dp(n + 1); + dp[1] = 1; + for (int i = 2; i <= n; ++i) { + for (int j = 1; j < i; ++j) { + dp[i] = max(max(dp[i], dp[i - j] * j), (i - j) * j); + } } - if (n % 3 == 0) { - return pow(3, n / 3); - } - if (n % 3 == 1) { - return pow(3, n / 3 - 1) * 4; - } - return pow(3, n / 3) * 2; + return dp[n]; } }; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.cs" index 8564662d2e995..68c0698421d5b 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.cs" @@ -1,14 +1,14 @@ -public class Solution { - public int CuttingRope(int n) { - if (n < 4) { - return n - 1; - } - if (n % 3 == 0) { - return (int) Math.Pow(3, n / 3); - } - if (n % 3 == 1) { - return (int) Math.Pow(3, n / 3 - 1) * 4; - } - return (int) Math.Pow(3, n / 3) * 2; - } -} \ No newline at end of file +public class Solution { + public int CuttingRope(int n) { + if (n < 4) { + return n - 1; + } + if (n % 3 == 0) { + return (int) Math.Pow(3, n / 3); + } + if (n % 3 == 1) { + return (int) Math.Pow(3, n / 3 - 1) * 4; + } + return (int) Math.Pow(3, n / 3) * 2; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.go" "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.go" index f2c6fb6de81d2..931b6ef4c06fa 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.go" +++ "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.go" @@ -1,12 +1,10 @@ func cuttingRope(n int) int { - if n < 4 { - return n - 1 + dp := make([]int, n+1) + dp[1] = 1 + for i := 2; i <= n; i++ { + for j := 1; j < i; j++ { + dp[i] = max(max(dp[i], dp[i-j]*j), (i-j)*j) + } } - if n%3 == 0 { - return int(math.Pow(3, float64(n/3))) - } - if n%3 == 1 { - return int(math.Pow(3, float64(n/3-1))) * 4 - } - return int(math.Pow(3, float64(n/3))) * 2 + return dp[n] } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.java" "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.java" index 551d8e1a0a60c..11fd766a8d8ce 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.java" +++ "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.java" @@ -1,14 +1,12 @@ class Solution { public int cuttingRope(int n) { - if (n < 4) { - return n - 1; + int[] dp = new int[n + 1]; + dp[1] = 1; + for (int i = 2; i <= n; ++i) { + for (int j = 1; j < i; ++j) { + dp[i] = Math.max(Math.max(dp[i], dp[i - j] * j), (i - j) * j); + } } - if (n % 3 == 0) { - return (int) Math.pow(3, n / 3); - } - if (n % 3 == 1) { - return (int) Math.pow(3, n / 3 - 1) * 4; - } - return (int) Math.pow(3, n / 3) * 2; + return dp[n]; } } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.py" "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.py" index 2f7de5c72249e..7cc305956c371 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.py" +++ "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution.py" @@ -1,9 +1,7 @@ class Solution: def cuttingRope(self, n: int) -> int: - if n < 4: - return n - 1 - if n % 3 == 0: - return pow(3, n // 3) - if n % 3 == 1: - return pow(3, n // 3 - 1) * 4 - return pow(3, n // 3) * 2 + dp = [1] * (n + 1) + for i in range(2, n + 1): + for j in range(1, i): + dp[i] = max(dp[i], dp[i - j] * j, (i - j) * j) + return dp[n] diff --git "a/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution2.cpp" new file mode 100644 index 0000000000000..8984743b1aed7 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution2.cpp" @@ -0,0 +1,15 @@ +class Solution { +public: + int cuttingRope(int n) { + if (n < 4) { + return n - 1; + } + if (n % 3 == 0) { + return pow(3, n / 3); + } + if (n % 3 == 1) { + return pow(3, n / 3 - 1) * 4; + } + return pow(3, n / 3) * 2; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution2.go" new file mode 100644 index 0000000000000..f2c6fb6de81d2 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution2.go" @@ -0,0 +1,12 @@ +func cuttingRope(n int) int { + if n < 4 { + return n - 1 + } + if n%3 == 0 { + return int(math.Pow(3, float64(n/3))) + } + if n%3 == 1 { + return int(math.Pow(3, float64(n/3-1))) * 4 + } + return int(math.Pow(3, float64(n/3))) * 2 +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution2.java" new file mode 100644 index 0000000000000..551d8e1a0a60c --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution2.java" @@ -0,0 +1,14 @@ +class Solution { + public int cuttingRope(int n) { + if (n < 4) { + return n - 1; + } + if (n % 3 == 0) { + return (int) Math.pow(3, n / 3); + } + if (n % 3 == 1) { + return (int) Math.pow(3, n / 3 - 1) * 4; + } + return (int) Math.pow(3, n / 3) * 2; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution2.py" new file mode 100644 index 0000000000000..2f7de5c72249e --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/Solution2.py" @@ -0,0 +1,9 @@ +class Solution: + def cuttingRope(self, n: int) -> int: + if n < 4: + return n - 1 + if n % 3 == 0: + return pow(3, n // 3) + if n % 3 == 1: + return pow(3, n // 3 - 1) * 4 + return pow(3, n // 3) * 2 diff --git "a/lcof/\351\235\242\350\257\225\351\242\23014- II. \345\211\252\347\273\263\345\255\220 II/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23014- II. \345\211\252\347\273\263\345\255\220 II/Solution.cpp" index 530e2c14d7abc..6bb457804d1f9 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23014- II. \345\211\252\347\273\263\345\255\220 II/Solution.cpp" +++ "b/lcof/\351\235\242\350\257\225\351\242\23014- II. \345\211\252\347\273\263\345\255\220 II/Solution.cpp" @@ -1,26 +1,26 @@ -class Solution { -public: - int cuttingRope(int n) { - if (n < 4) { - return n - 1; - } - const int mod = 1e9 + 7; - auto qpow = [&](long long a, long long n) { - long long ans = 1; - for (; n; n >>= 1) { - if (n & 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return (int) ans; - }; - if (n % 3 == 0) { - return qpow(3, n / 3); - } - if (n % 3 == 1) { - return qpow(3, n / 3 - 1) * 4L % mod; - } - return qpow(3, n / 3) * 2 % mod; - } +class Solution { +public: + int cuttingRope(int n) { + if (n < 4) { + return n - 1; + } + const int mod = 1e9 + 7; + auto qpow = [&](long long a, long long n) { + long long ans = 1; + for (; n; n >>= 1) { + if (n & 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return (int) ans; + }; + if (n % 3 == 0) { + return qpow(3, n / 3); + } + if (n % 3 == 1) { + return qpow(3, n / 3 - 1) * 4L % mod; + } + return qpow(3, n / 3) * 2 % mod; + } }; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23014- II. \345\211\252\347\273\263\345\255\220 II/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23014- II. \345\211\252\347\273\263\345\255\220 II/Solution.cs" index f24a909ed0e97..14417b24b7361 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23014- II. \345\211\252\347\273\263\345\255\220 II/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23014- II. \345\211\252\347\273\263\345\255\220 II/Solution.cs" @@ -1,16 +1,16 @@ -public class Solution { - public int CuttingRope(int n) { - if (n < 4) { - return n - 1; - } - int res = 1; - while (n > 4) { - res *= 3; - n -= 3; - } - if (n == 4) { - return (res << 2) % 1000000007; - } - return (res * n) % 1000000007; - } -} \ No newline at end of file +public class Solution { + public int CuttingRope(int n) { + if (n < 4) { + return n - 1; + } + int res = 1; + while (n > 4) { + res *= 3; + n -= 3; + } + if (n == 4) { + return (res << 2) % 1000000007; + } + return (res * n) % 1000000007; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23014- II. \345\211\252\347\273\263\345\255\220 II/Solution.java" "b/lcof/\351\235\242\350\257\225\351\242\23014- II. \345\211\252\347\273\263\345\255\220 II/Solution.java" index 45a5ee4e6607d..45082436d2b68 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23014- II. \345\211\252\347\273\263\345\255\220 II/Solution.java" +++ "b/lcof/\351\235\242\350\257\225\351\242\23014- II. \345\211\252\347\273\263\345\255\220 II/Solution.java" @@ -1,27 +1,27 @@ -class Solution { - private final int mod = (int) 1e9 + 7; - - public int cuttingRope(int n) { - if (n < 4) { - return n - 1; - } - if (n % 3 == 0) { - return qpow(3, n / 3); - } - if (n % 3 == 1) { - return (int) (4L * qpow(3, n / 3 - 1) % mod); - } - return 2 * qpow(3, n / 3) % mod; - } - - private int qpow(long a, long n) { - long ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return (int) ans; - } +class Solution { + private final int mod = (int) 1e9 + 7; + + public int cuttingRope(int n) { + if (n < 4) { + return n - 1; + } + if (n % 3 == 0) { + return qpow(3, n / 3); + } + if (n % 3 == 1) { + return (int) (4L * qpow(3, n / 3 - 1) % mod); + } + return 2 * qpow(3, n / 3) % mod; + } + + private int qpow(long a, long n) { + long ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return (int) ans; + } } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution.cs" index 9f79d6fa56ffc..5299e0d399a3b 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution.cs" @@ -1,10 +1,10 @@ -public class Solution { - public int HammingWeight(uint n) { - int ans = 0; - while (n != 0) { - n &= (n - 1); - ++ans; - } - return ans; - } -} \ No newline at end of file +public class Solution { + public int HammingWeight(uint n) { + int ans = 0; + while (n != 0) { + n &= (n - 1); + ++ans; + } + return ans; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution.py" "b/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution.py" index 171f0364b43a6..e2bcead204feb 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution.py" +++ "b/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution.py" @@ -1,7 +1,3 @@ class Solution: def hammingWeight(self, n: int) -> int: - ans = 0 - while n: - n &= n - 1 - ans += 1 - return ans + return n.bit_count() diff --git "a/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution2.cpp" new file mode 100644 index 0000000000000..d30b7874a6733 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution2.cpp" @@ -0,0 +1,11 @@ +class Solution { +public: + int hammingWeight(uint32_t n) { + int ans = 0; + while (n != 0) { + n -= n & -n; + ++ans; + } + return ans; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution2.go" new file mode 100644 index 0000000000000..7a1451c406b07 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution2.go" @@ -0,0 +1,7 @@ +func hammingWeight(num uint32) (ans int) { + for num != 0 { + num -= num & -num + ans++ + } + return +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution2.java" new file mode 100644 index 0000000000000..a1aa3df2377dc --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution2.java" @@ -0,0 +1,11 @@ +public class Solution { + // you need to treat n as an unsigned value + public int hammingWeight(int n) { + int ans = 0; + while (n != 0) { + n -= n & -n; + ++ans; + } + return ans; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution2.py" new file mode 100644 index 0000000000000..171f0364b43a6 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution2.py" @@ -0,0 +1,7 @@ +class Solution: + def hammingWeight(self, n: int) -> int: + ans = 0 + while n: + n &= n - 1 + ans += 1 + return ans diff --git "a/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution3.py" "b/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution3.py" new file mode 100644 index 0000000000000..b3d2c526d9aaf --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/Solution3.py" @@ -0,0 +1,7 @@ +class Solution: + def hammingWeight(self, n: int) -> int: + ans = 0 + while n: + n -= n & (-n) + ans += 1 + return ans diff --git "a/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/Solution.cpp" index 352fcf7bea155..4315d748935cd 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/Solution.cpp" +++ "b/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/Solution.cpp" @@ -1,16 +1,16 @@ -class Solution { -public: - double myPow(double x, int n) { - auto qpow = [](double a, long long n) { - double ans = 1; - for (; n; n >>= 1) { - if (n & 1) { - ans *= a; - } - a *= a; - } - return ans; - }; - return n >= 0 ? qpow(x, n) : 1 / qpow(x, -(long long) n); - } +class Solution { +public: + double myPow(double x, int n) { + auto qpow = [](double a, long long n) { + double ans = 1; + for (; n; n >>= 1) { + if (n & 1) { + ans *= a; + } + a *= a; + } + return ans; + }; + return n >= 0 ? qpow(x, n) : 1 / qpow(x, -(long long) n); + } }; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/Solution.cs" index 93f0cd8681a88..7b4b6a29191dd 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/Solution.cs" @@ -1,16 +1,16 @@ -public class Solution { - public double MyPow(double x, int n) { - return n >= 0 ? qpow(x, n) : 1.0 / qpow(x, -(long)n); - } - - private double qpow(double a, long n) { - double ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans *= a; - } - a *= a; - } - return ans; - } -} \ No newline at end of file +public class Solution { + public double MyPow(double x, int n) { + return n >= 0 ? qpow(x, n) : 1.0 / qpow(x, -(long)n); + } + + private double qpow(double a, long n) { + double ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans *= a; + } + a *= a; + } + return ans; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/Solution.java" "b/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/Solution.java" index efa1dc56dd04d..df591fd553fdf 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/Solution.java" +++ "b/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/Solution.java" @@ -1,16 +1,16 @@ -class Solution { - public double myPow(double x, int n) { - return n >= 0 ? qpow(x, n) : 1 / qpow(x, -(long) n); - } - - private double qpow(double a, long n) { - double ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans = ans * a; - } - a = a * a; - } - return ans; - } +class Solution { + public double myPow(double x, int n) { + return n >= 0 ? qpow(x, n) : 1 / qpow(x, -(long) n); + } + + private double qpow(double a, long n) { + double ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans = ans * a; + } + a = a * a; + } + return ans; + } } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/Solution.py" "b/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/Solution.py" index 94981abc703d4..a0d019240926a 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/Solution.py" +++ "b/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/Solution.py" @@ -1,12 +1,12 @@ -class Solution: - def myPow(self, x: float, n: int) -> float: - def qpow(a: float, n: int) -> float: - ans = 1 - while n: - if n & 1: - ans *= a - a *= a - n >>= 1 - return ans - - return qpow(x, n) if n >= 0 else 1 / qpow(x, -n) +class Solution: + def myPow(self, x: float, n: int) -> float: + def qpow(a: float, n: int) -> float: + ans = 1 + while n: + if n & 1: + ans *= a + a *= a + n >>= 1 + return ans + + return qpow(x, n) if n >= 0 else 1 / qpow(x, -n) diff --git "a/lcof/\351\235\242\350\257\225\351\242\23017. \346\211\223\345\215\260\344\273\2161\345\210\260\346\234\200\345\244\247\347\232\204n\344\275\215\346\225\260/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23017. \346\211\223\345\215\260\344\273\2161\345\210\260\346\234\200\345\244\247\347\232\204n\344\275\215\346\225\260/Solution.cs" index 4b7dc899e0b92..33ea8a9fcc845 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23017. \346\211\223\345\215\260\344\273\2161\345\210\260\346\234\200\345\244\247\347\232\204n\344\275\215\346\225\260/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23017. \346\211\223\345\215\260\344\273\2161\345\210\260\346\234\200\345\244\247\347\232\204n\344\275\215\346\225\260/Solution.cs" @@ -1,10 +1,10 @@ -public class Solution { - public int[] PrintNumbers(int n) { - List ans = new List(); - for (int i = 0; i < Math.Pow(10, n); i++) - { - ans.Add(i); - } - return ans.ToArray(); - } -} \ No newline at end of file +public class Solution { + public int[] PrintNumbers(int n) { + List ans = new List(); + for (int i = 0; i < Math.Pow(10, n); i++) + { + ans.Add(i); + } + return ans.ToArray(); + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23018. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\350\212\202\347\202\271/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23018. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\350\212\202\347\202\271/Solution.cs" index 56d1b296e257f..291d4e4dc6678 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23018. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\350\212\202\347\202\271/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23018. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\350\212\202\347\202\271/Solution.cs" @@ -1,20 +1,20 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int x) { val = x; } - * } - */ -public class Solution { - public ListNode DeleteNode(ListNode head, int val) { - ListNode dummy = new ListNode(0, head); - for (ListNode cur = dummy; cur.next != null; cur = cur.next) { - if (cur.next.val == val) { - cur.next = cur.next.next; - break; - } - } - return dummy.next; - } -} \ No newline at end of file +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int x) { val = x; } + * } + */ +public class Solution { + public ListNode DeleteNode(ListNode head, int val) { + ListNode dummy = new ListNode(0, head); + for (ListNode cur = dummy; cur.next != null; cur = cur.next) { + if (cur.next.val == val) { + cur.next = cur.next.next; + break; + } + } + return dummy.next; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.cpp" index 5e172f02c21b6..17da3a5f8bfbd 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.cpp" +++ "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.cpp" @@ -2,21 +2,26 @@ class Solution { public: bool isMatch(string s, string p) { int m = s.size(), n = p.size(); - bool f[m + 1][n + 1]; - memset(f, false, sizeof f); - f[0][0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (p[j - 1] == '*') { - f[i][j] = f[i][j - 2]; - if (i && (p[j - 2] == '.' || p[j - 2] == s[i - 1])) { - f[i][j] |= f[i - 1][j]; - } - } else if (i && (p[j - 1] == '.' || p[j - 1] == s[i - 1])) { - f[i][j] = f[i - 1][j - 1]; + int f[m + 1][n + 1]; + memset(f, 0, sizeof f); + function dfs = [&](int i, int j) -> bool { + if (j >= n) { + return i == m; + } + if (f[i][j]) { + return f[i][j] == 1; + } + int res = -1; + if (j + 1 < n && p[j + 1] == '*') { + if (dfs(i, j + 2) or (i < m and (s[i] == p[j] or p[j] == '.') and dfs(i + 1, j))) { + res = 1; } + } else if (i < m and (s[i] == p[j] or p[j] == '.') and dfs(i + 1, j + 1)) { + res = 1; } - } - return f[m][n]; + f[i][j] = res; + return res == 1; + }; + return dfs(0, 0); } }; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.cs" index abcb071edbcbd..e481761ed9e0e 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.cs" @@ -1,20 +1,35 @@ -public class Solution { - public bool IsMatch(string s, string p) { - int m = s.Length, n = p.Length; - bool[,] f = new bool[m + 1, n + 1]; - f[0, 0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (p[j - 1] == '*') { - f[i, j] = f[i, j - 2]; - if (i > 0 && (p[j - 2] == '.' || p[j - 2] == s[i - 1])) { - f[i, j] |= f[i - 1, j]; - } - } else if (i > 0 && (p[j - 1] == '.' || p[j - 1] == s[i - 1])) { - f[i, j] = f[i - 1, j - 1]; - } - } - } - return f[m, n]; - } -} \ No newline at end of file +public class Solution { + private string s; + private string p; + private int m; + private int n; + private int[,] f; + + public bool IsMatch(string s, string p) { + m = s.Length; + n = p.Length; + f = new int[m + 1, n + 1]; + this.s = s; + this.p = p; + return dfs(0, 0); + } + + private bool dfs(int i, int j) { + if (j >= n) { + return i == m; + } + if (f[i, j] != 0) { + return f[i, j] == 1; + } + int res = -1; + if (j + 1 < n && p[j + 1] == '*') { + if (dfs(i, j + 2) || (i < m && (s[i] == p[j] || p[j] == '.') && dfs(i + 1, j))) { + res = 1; + } + } else if (i < m && (s[i] == p[j] || p[j] == '.') && dfs(i + 1, j + 1)) { + res = 1; + } + f[i, j] = res; + return res == 1; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.go" "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.go" index c162c1cc62a62..9154a39e738ec 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.go" +++ "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.go" @@ -1,21 +1,27 @@ func isMatch(s string, p string) bool { m, n := len(s), len(p) - f := make([][]bool, m+1) + f := make([][]int, m+1) for i := range f { - f[i] = make([]bool, n+1) + f[i] = make([]int, n+1) } - f[0][0] = true - for i := 0; i <= m; i++ { - for j := 1; j <= n; j++ { - if p[j-1] == '*' { - f[i][j] = f[i][j-2] - if i > 0 && (p[j-2] == '.' || p[j-2] == s[i-1]) { - f[i][j] = f[i][j] || f[i-1][j] - } - } else if i > 0 && (p[j-1] == '.' || p[j-1] == s[i-1]) { - f[i][j] = f[i-1][j-1] + var dfs func(i, j int) bool + dfs = func(i, j int) bool { + if j >= n { + return i == m + } + if f[i][j] != 0 { + return f[i][j] == 1 + } + res := -1 + if j+1 < n && p[j+1] == '*' { + if dfs(i, j+2) || (i < m && (s[i] == p[j] || p[j] == '.') && dfs(i+1, j)) { + res = 1 } + } else if i < m && (s[i] == p[j] || p[j] == '.') && dfs(i+1, j+1) { + res = 1 } + f[i][j] = res + return res == 1 } - return f[m][n] + return dfs(0, 0) } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.java" "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.java" index dfbc862318064..7b6048f5f1627 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.java" +++ "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.java" @@ -1,21 +1,33 @@ class Solution { + private Boolean[][] f; + private String s; + private String p; + private int m; + private int n; + public boolean isMatch(String s, String p) { - int m = s.length(), n = p.length(); - boolean[][] f = new boolean[m + 1][n + 1]; - f[0][0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (p.charAt(j - 1) == '*') { - f[i][j] = f[i][j - 2]; - if (i > 0 && (p.charAt(j - 2) == '.' || p.charAt(j - 2) == s.charAt(i - 1))) { - f[i][j] |= f[i - 1][j]; - } - } else if (i > 0 - && (p.charAt(j - 1) == '.' || p.charAt(j - 1) == s.charAt(i - 1))) { - f[i][j] = f[i - 1][j - 1]; - } - } + m = s.length(); + n = p.length(); + f = new Boolean[m + 1][n + 1]; + this.s = s; + this.p = p; + return dfs(0, 0); + } + + private boolean dfs(int i, int j) { + if (j >= n) { + return i == m; + } + if (f[i][j] != null) { + return f[i][j]; + } + boolean res = false; + if (j + 1 < n && p.charAt(j + 1) == '*') { + res = dfs(i, j + 2) + || (i < m && (s.charAt(i) == p.charAt(j) || p.charAt(j) == '.') && dfs(i + 1, j)); + } else { + res = i < m && (s.charAt(i) == p.charAt(j) || p.charAt(j) == '.') && dfs(i + 1, j + 1); } - return f[m][n]; + return f[i][j] = res; } } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.js" "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.js" index 9608f48ac1797..17d839b224a8c 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.js" +++ "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.js" @@ -6,19 +6,24 @@ var isMatch = function (s, p) { const m = s.length; const n = p.length; - const f = Array.from({ length: m + 1 }, () => Array(n + 1).fill(false)); - f[0][0] = true; - for (let i = 0; i <= m; ++i) { - for (let j = 1; j <= n; ++j) { - if (p[j - 1] === '*') { - f[i][j] = f[i][j - 2]; - if (i && (p[j - 2] === '.' || p[j - 2] == s[i - 1])) { - f[i][j] |= f[i - 1][j]; - } - } else if (i && (p[j - 1] === '.' || p[j - 1] == s[i - 1])) { - f[i][j] = f[i - 1][j - 1]; + const f = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); + const dfs = (i, j) => { + if (j >= n) { + return i == m; + } + if (f[i][j]) { + return f[i][j] == 1; + } + let res = -1; + if (j + 1 < n && p[j + 1] === '*') { + if (dfs(i, j + 2) || (i < m && (s[i] == p[j] || p[j] == '.') && dfs(i + 1, j))) { + res = 1; } + } else if (i < m && (s[i] == p[j] || p[j] == '.') && dfs(i + 1, j + 1)) { + res = 1; } - } - return f[m][n]; + f[i][j] = res; + return res == 1; + }; + return dfs(0, 0); }; diff --git "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.py" "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.py" index e2d563a26cc21..5b426ef2d958d 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.py" +++ "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.py" @@ -1,14 +1,14 @@ class Solution: def isMatch(self, s: str, p: str) -> bool: + @cache + def dfs(i, j): + if j >= n: + return i == m + if j + 1 < n and p[j + 1] == '*': + return dfs(i, j + 2) or ( + i < m and (s[i] == p[j] or p[j] == '.') and dfs(i + 1, j) + ) + return i < m and (s[i] == p[j] or p[j] == '.') and dfs(i + 1, j + 1) + m, n = len(s), len(p) - f = [[False] * (n + 1) for _ in range(m + 1)] - f[0][0] = True - for i in range(m + 1): - for j in range(1, n + 1): - if p[j - 1] == "*": - f[i][j] = f[i][j - 2] - if i > 0 and (p[j - 2] == "." or s[i - 1] == p[j - 2]): - f[i][j] |= f[i - 1][j] - elif i > 0 and (p[j - 1] == "." or s[i - 1] == p[j - 1]): - f[i][j] = f[i - 1][j - 1] - return f[m][n] + return dfs(0, 0) diff --git "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution2.cpp" new file mode 100644 index 0000000000000..5e172f02c21b6 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution2.cpp" @@ -0,0 +1,22 @@ +class Solution { +public: + bool isMatch(string s, string p) { + int m = s.size(), n = p.size(); + bool f[m + 1][n + 1]; + memset(f, false, sizeof f); + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (p[j - 1] == '*') { + f[i][j] = f[i][j - 2]; + if (i && (p[j - 2] == '.' || p[j - 2] == s[i - 1])) { + f[i][j] |= f[i - 1][j]; + } + } else if (i && (p[j - 1] == '.' || p[j - 1] == s[i - 1])) { + f[i][j] = f[i - 1][j - 1]; + } + } + } + return f[m][n]; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution2.cs" "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution2.cs" new file mode 100644 index 0000000000000..b2a7c8e40061f --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution2.cs" @@ -0,0 +1,20 @@ +public class Solution { + public bool IsMatch(string s, string p) { + int m = s.Length, n = p.Length; + bool[,] f = new bool[m + 1, n + 1]; + f[0, 0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (p[j - 1] == '*') { + f[i, j] = f[i, j - 2]; + if (i > 0 && (p[j - 2] == '.' || p[j - 2] == s[i - 1])) { + f[i, j] |= f[i - 1, j]; + } + } else if (i > 0 && (p[j - 1] == '.' || p[j - 1] == s[i - 1])) { + f[i, j] = f[i - 1, j - 1]; + } + } + } + return f[m, n]; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution2.go" new file mode 100644 index 0000000000000..c162c1cc62a62 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution2.go" @@ -0,0 +1,21 @@ +func isMatch(s string, p string) bool { + m, n := len(s), len(p) + f := make([][]bool, m+1) + for i := range f { + f[i] = make([]bool, n+1) + } + f[0][0] = true + for i := 0; i <= m; i++ { + for j := 1; j <= n; j++ { + if p[j-1] == '*' { + f[i][j] = f[i][j-2] + if i > 0 && (p[j-2] == '.' || p[j-2] == s[i-1]) { + f[i][j] = f[i][j] || f[i-1][j] + } + } else if i > 0 && (p[j-1] == '.' || p[j-1] == s[i-1]) { + f[i][j] = f[i-1][j-1] + } + } + } + return f[m][n] +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution2.java" new file mode 100644 index 0000000000000..dfbc862318064 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution2.java" @@ -0,0 +1,21 @@ +class Solution { + public boolean isMatch(String s, String p) { + int m = s.length(), n = p.length(); + boolean[][] f = new boolean[m + 1][n + 1]; + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (p.charAt(j - 1) == '*') { + f[i][j] = f[i][j - 2]; + if (i > 0 && (p.charAt(j - 2) == '.' || p.charAt(j - 2) == s.charAt(i - 1))) { + f[i][j] |= f[i - 1][j]; + } + } else if (i > 0 + && (p.charAt(j - 1) == '.' || p.charAt(j - 1) == s.charAt(i - 1))) { + f[i][j] = f[i - 1][j - 1]; + } + } + } + return f[m][n]; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution2.js" "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution2.js" new file mode 100644 index 0000000000000..9608f48ac1797 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution2.js" @@ -0,0 +1,24 @@ +/** + * @param {string} s + * @param {string} p + * @return {boolean} + */ +var isMatch = function (s, p) { + const m = s.length; + const n = p.length; + const f = Array.from({ length: m + 1 }, () => Array(n + 1).fill(false)); + f[0][0] = true; + for (let i = 0; i <= m; ++i) { + for (let j = 1; j <= n; ++j) { + if (p[j - 1] === '*') { + f[i][j] = f[i][j - 2]; + if (i && (p[j - 2] === '.' || p[j - 2] == s[i - 1])) { + f[i][j] |= f[i - 1][j]; + } + } else if (i && (p[j - 1] === '.' || p[j - 1] == s[i - 1])) { + f[i][j] = f[i - 1][j - 1]; + } + } + } + return f[m][n]; +}; diff --git "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution2.py" new file mode 100644 index 0000000000000..e2d563a26cc21 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution2.py" @@ -0,0 +1,14 @@ +class Solution: + def isMatch(self, s: str, p: str) -> bool: + m, n = len(s), len(p) + f = [[False] * (n + 1) for _ in range(m + 1)] + f[0][0] = True + for i in range(m + 1): + for j in range(1, n + 1): + if p[j - 1] == "*": + f[i][j] = f[i][j - 2] + if i > 0 and (p[j - 2] == "." or s[i - 1] == p[j - 2]): + f[i][j] |= f[i - 1][j] + elif i > 0 and (p[j - 1] == "." or s[i - 1] == p[j - 1]): + f[i][j] = f[i - 1][j - 1] + return f[m][n] diff --git "a/lcof/\351\235\242\350\257\225\351\242\23020. \350\241\250\347\244\272\346\225\260\345\200\274\347\232\204\345\255\227\347\254\246\344\270\262/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23020. \350\241\250\347\244\272\346\225\260\345\200\274\347\232\204\345\255\227\347\254\246\344\270\262/Solution.cs" index 377204e4584d3..3c3acbe3fdc3c 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23020. \350\241\250\347\244\272\346\225\260\345\200\274\347\232\204\345\255\227\347\254\246\344\270\262/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23020. \350\241\250\347\244\272\346\225\260\345\200\274\347\232\204\345\255\227\347\254\246\344\270\262/Solution.cs" @@ -1,38 +1,38 @@ -public class Solution { - public bool IsNumber(string s) { - int i = 0, j = s.Length - 1; - while (i < j && s[i] == ' ') { - ++i; - } - while (i <= j && s[j] == ' ') { - --j; - } - if (i > j) { - return false; - } - bool digit = false, dot = false, e = false; - for (; i <= j; ++i) { - if (s[i] == '+' || s[i] == '-') { - if (i > 0 && s[i - 1] != ' ' && s[i - 1] != 'e' && s[i - 1] != 'E') { - return false; - } - } else if (s[i] >= '0' && s[i] <= '9') { - digit = true; - } else if (s[i] == '.') { - if (dot || e) { - return false; - } - dot = true; - } else if (s[i] == 'e' || s[i] == 'E') { - if (!digit || e) { - return false; - } - e = true; - digit = false; - } else { - return false; - } - } - return digit; - } -} \ No newline at end of file +public class Solution { + public bool IsNumber(string s) { + int i = 0, j = s.Length - 1; + while (i < j && s[i] == ' ') { + ++i; + } + while (i <= j && s[j] == ' ') { + --j; + } + if (i > j) { + return false; + } + bool digit = false, dot = false, e = false; + for (; i <= j; ++i) { + if (s[i] == '+' || s[i] == '-') { + if (i > 0 && s[i - 1] != ' ' && s[i - 1] != 'e' && s[i - 1] != 'E') { + return false; + } + } else if (s[i] >= '0' && s[i] <= '9') { + digit = true; + } else if (s[i] == '.') { + if (dot || e) { + return false; + } + dot = true; + } else if (s[i] == 'e' || s[i] == 'E') { + if (!digit || e) { + return false; + } + e = true; + digit = false; + } else { + return false; + } + } + return digit; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23021. \350\260\203\346\225\264\346\225\260\347\273\204\351\241\272\345\272\217\344\275\277\345\245\207\346\225\260\344\275\215\344\272\216\345\201\266\346\225\260\345\211\215\351\235\242/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23021. \350\260\203\346\225\264\346\225\260\347\273\204\351\241\272\345\272\217\344\275\277\345\245\207\346\225\260\344\275\215\344\272\216\345\201\266\346\225\260\345\211\215\351\235\242/Solution.cs" index 9ec03fd66a776..680e34c61b093 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23021. \350\260\203\346\225\264\346\225\260\347\273\204\351\241\272\345\272\217\344\275\277\345\245\207\346\225\260\344\275\215\344\272\216\345\201\266\346\225\260\345\211\215\351\235\242/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23021. \350\260\203\346\225\264\346\225\260\347\273\204\351\241\272\345\272\217\344\275\277\345\245\207\346\225\260\344\275\215\344\272\216\345\201\266\346\225\260\345\211\215\351\235\242/Solution.cs" @@ -1,13 +1,13 @@ -public class Solution { - public int[] Exchange(int[] nums) { - int j = 0; - for (int i = 0; i < nums.Length; ++i) { - if (nums[i] % 2 == 1) { - int t = nums[i]; - nums[i] = nums[j]; - nums[j++] = t; - } - } - return nums; - } -} \ No newline at end of file +public class Solution { + public int[] Exchange(int[] nums) { + int j = 0; + for (int i = 0; i < nums.Length; ++i) { + if (nums[i] % 2 == 1) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j++] = t; + } + } + return nums; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23022. \351\223\276\350\241\250\344\270\255\345\200\222\346\225\260\347\254\254k\344\270\252\350\212\202\347\202\271/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23022. \351\223\276\350\241\250\344\270\255\345\200\222\346\225\260\347\254\254k\344\270\252\350\212\202\347\202\271/Solution.cs" index 65c42117d85e4..47ff189727726 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23022. \351\223\276\350\241\250\344\270\255\345\200\222\346\225\260\347\254\254k\344\270\252\350\212\202\347\202\271/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23022. \351\223\276\350\241\250\344\270\255\345\200\222\346\225\260\347\254\254k\344\270\252\350\212\202\347\202\271/Solution.cs" @@ -1,21 +1,21 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int x) { val = x; } - * } - */ -public class Solution { - public ListNode GetKthFromEnd(ListNode head, int k) { - ListNode fast = head, slow = head; - while (k-- > 0) { - fast = fast.next; - } - while (fast != null) { - slow = slow.next; - fast = fast.next; - } - return slow; - } -} \ No newline at end of file +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int x) { val = x; } + * } + */ +public class Solution { + public ListNode GetKthFromEnd(ListNode head, int k) { + ListNode fast = head, slow = head; + while (k-- > 0) { + fast = fast.next; + } + while (fast != null) { + slow = slow.next; + fast = fast.next; + } + return slow; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution.cs" index b5fe28e1699b0..870c37f85ddb4 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution.cs" @@ -1,21 +1,21 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int x) { val = x; } - * } - */ -public class Solution { - public ListNode ReverseList(ListNode head) { - ListNode dummy = new ListNode(0); - ListNode curr = head; - while (curr != null) { - ListNode next = curr.next; - curr.next = dummy.next; - dummy.next = curr; - curr = next; - } - return dummy.next; - } -} \ No newline at end of file +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int x) { val = x; } + * } + */ +public class Solution { + public ListNode ReverseList(ListNode head) { + ListNode dummy = new ListNode(0); + ListNode curr = head; + while (curr != null) { + ListNode next = curr.next; + curr.next = dummy.next; + dummy.next = curr; + curr = next; + } + return dummy.next; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.cpp" new file mode 100644 index 0000000000000..cef56a3ae368f --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.cpp" @@ -0,0 +1,20 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + if (!head || !head->next) { + return head; + } + ListNode* ans = reverseList(head->next); + head->next->next = head; + head->next = nullptr; + return ans; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.cs" "b/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.cs" new file mode 100644 index 0000000000000..12e1c5355a9d8 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.cs" @@ -0,0 +1,19 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int x) { val = x; } + * } + */ +public class Solution { + public ListNode ReverseList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode ans = ReverseList(head.next); + head.next.next = head; + head.next = null; + return ans; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.go" new file mode 100644 index 0000000000000..4c55cdf095e0d --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.go" @@ -0,0 +1,16 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func reverseList(head *ListNode) *ListNode { + if head == nil || head.Next == nil { + return head + } + ans := reverseList(head.Next) + head.Next.Next = head + head.Next = nil + return ans +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.java" new file mode 100644 index 0000000000000..c82dbe0bc4e42 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.java" @@ -0,0 +1,19 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode reverseList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode ans = reverseList(head.next); + head.next.next = head; + head.next = null; + return ans; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.js" "b/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.js" new file mode 100644 index 0000000000000..db8861911827b --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.js" @@ -0,0 +1,20 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var reverseList = function (head) { + if (!head || !head.next) { + return head; + } + const ans = reverseList(head.next); + head.next.next = head; + head.next = null; + return ans; +}; diff --git "a/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.py" new file mode 100644 index 0000000000000..756051c7b75bb --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.py" @@ -0,0 +1,15 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + + +class Solution: + def reverseList(self, head: ListNode) -> ListNode: + if head is None or head.next is None: + return head + ans = self.reverseList(head.next) + head.next.next = head + head.next = None + return ans diff --git "a/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.ts" "b/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.ts" new file mode 100644 index 0000000000000..338e97075166c --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.ts" @@ -0,0 +1,21 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function reverseList(head: ListNode | null): ListNode | null { + if (!head || !head.next) { + return head; + } + const ans = reverseList(head.next); + head.next.next = head; + head.next = null; + return ans; +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution.cs" index 49589ede0a681..869b2ccf8c2eb 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution.cs" @@ -1,26 +1,26 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int x) { val = x; } - * } - */ -public class Solution { - public ListNode MergeTwoLists(ListNode l1, ListNode l2) { - ListNode dummy = new ListNode(0); - ListNode cur = dummy; - while (l1 != null && l2 != null) { - if (l1.val <= l2.val) { - cur.next = l1; - l1 = l1.next; - } else { - cur.next = l2; - l2 = l2.next; - } - cur = cur.next; - } - cur.next = l1 == null ? l2 : l1; - return dummy.next; - } -} \ No newline at end of file +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int x) { val = x; } + * } + */ +public class Solution { + public ListNode MergeTwoLists(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(0); + ListNode cur = dummy; + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution.rs" "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution.rs" index 6b39d8c9626d7..94199fc748cb2 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution.rs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution.rs" @@ -16,22 +16,31 @@ // } impl Solution { pub fn merge_two_lists( - l1: Option>, - l2: Option> + mut l1: Option>, + mut l2: Option> ) -> Option> { - match (l1, l2) { - (Some(mut n1), Some(mut n2)) => { - if n1.val < n2.val { - n1.next = Self::merge_two_lists(n1.next, Some(n2)); - Some(n1) - } else { - n2.next = Self::merge_two_lists(Some(n1), n2.next); - Some(n2) + match (l1.is_some(), l2.is_some()) { + (false, false) => None, + (true, false) => l1, + (false, true) => l2, + (true, true) => { + let mut dummy = Box::new(ListNode::new(0)); + let mut cur = &mut dummy; + while l1.is_some() && l2.is_some() { + cur.next = if l1.as_ref().unwrap().val < l2.as_ref().unwrap().val { + let mut res = l1.take(); + l1 = res.as_mut().unwrap().next.take(); + res + } else { + let mut res = l2.take(); + l2 = res.as_mut().unwrap().next.take(); + res + }; + cur = cur.next.as_mut().unwrap(); } + cur.next = if l1.is_some() { l1.take() } else { l2.take() }; + dummy.next.take() } - (Some(node), None) => Some(node), - (None, Some(node)) => Some(node), - (None, None) => None, } } } diff --git "a/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.cpp" new file mode 100644 index 0000000000000..93610dd3bd739 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.cpp" @@ -0,0 +1,26 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + if (!l1) { + return l2; + } + if (!l2) { + return l1; + } + if (l1->val <= l2->val) { + l1->next = mergeTwoLists(l1->next, l2); + return l1; + } else { + l2->next = mergeTwoLists(l1, l2->next); + return l2; + } + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.cs" "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.cs" new file mode 100644 index 0000000000000..31747611467d3 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.cs" @@ -0,0 +1,25 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int x) { val = x; } + * } + */ +public class Solution { + public ListNode MergeTwoLists(ListNode l1, ListNode l2) { + if (l1 == null) { + return l2; + } + if (l2 == null) { + return l1; + } + if (l1.val <= l2.val) { + l1.next = MergeTwoLists(l1.next, l2); + return l1; + } else { + l2.next = MergeTwoLists(l1, l2.next); + return l2; + } + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.go" new file mode 100644 index 0000000000000..6178e09b0b6b1 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.go" @@ -0,0 +1,22 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { + if l1 == nil { + return l2 + } + if l2 == nil { + return l1 + } + if l1.Val <= l2.Val { + l1.Next = mergeTwoLists(l1.Next, l2) + return l1 + } else { + l2.Next = mergeTwoLists(l1, l2.Next) + return l2 + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.java" new file mode 100644 index 0000000000000..f0dc0985cf0f0 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.java" @@ -0,0 +1,25 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + if (l1 == null) { + return l2; + } + if (l2 == null) { + return l1; + } + if (l1.val <= l2.val) { + l1.next = mergeTwoLists(l1.next, l2); + return l1; + } else { + l2.next = mergeTwoLists(l1, l2.next); + return l2; + } + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.js" "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.js" new file mode 100644 index 0000000000000..c0252f29d3340 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.js" @@ -0,0 +1,24 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var mergeTwoLists = function (l1, l2) { + if (!(l1 && l2)) { + return l1 || l2; + } + if (l1.val < l2.val) { + l1.next = mergeTwoLists(l1.next, l2); + return l1; + } else { + l2.next = mergeTwoLists(l2.next, l1); + return l2; + } +}; diff --git "a/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.py" new file mode 100644 index 0000000000000..04639c2fff99d --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.py" @@ -0,0 +1,17 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + + +class Solution: + def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: + if l1 is None or l2 is None: + return l1 or l2 + if l1.val <= l2.val: + l1.next = self.mergeTwoLists(l1.next, l2) + return l1 + else: + l2.next = self.mergeTwoLists(l1, l2.next) + return l2 diff --git "a/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.rs" "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.rs" new file mode 100644 index 0000000000000..6b39d8c9626d7 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.rs" @@ -0,0 +1,37 @@ +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn merge_two_lists( + l1: Option>, + l2: Option> + ) -> Option> { + match (l1, l2) { + (Some(mut n1), Some(mut n2)) => { + if n1.val < n2.val { + n1.next = Self::merge_two_lists(n1.next, Some(n2)); + Some(n1) + } else { + n2.next = Self::merge_two_lists(Some(n1), n2.next); + Some(n2) + } + } + (Some(node), None) => Some(node), + (None, Some(node)) => Some(node), + (None, None) => None, + } + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.ts" "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.ts" new file mode 100644 index 0000000000000..8cbf3ffacbb00 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/Solution2.ts" @@ -0,0 +1,23 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function mergeTwoLists(l1: ListNode | null, l2: ListNode | null): ListNode | null { + if (l1 == null || l2 == null) { + return l1 || l2; + } + if (l1.val < l2.val) { + l1.next = mergeTwoLists(l1.next, l2); + return l1; + } + l2.next = mergeTwoLists(l1, l2.next); + return l2; +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23026. \346\240\221\347\232\204\345\255\220\347\273\223\346\236\204/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23026. \346\240\221\347\232\204\345\255\220\347\273\223\346\236\204/Solution.cs" index 1a2c32128f8ac..0ef22717367f9 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23026. \346\240\221\347\232\204\345\255\220\347\273\223\346\236\204/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23026. \346\240\221\347\232\204\345\255\220\347\273\223\346\236\204/Solution.cs" @@ -1,27 +1,27 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public bool IsSubStructure(TreeNode A, TreeNode B) { - if (A == null || B == null) { - return false; - } - return dfs(A, B) || IsSubStructure(A.left, B) || IsSubStructure(A.right, B); - } - - public bool dfs(TreeNode A, TreeNode B) { - if (B == null) { - return true; - } - if (A == null || A.val != B.val) { - return false; - } - return dfs(A.left, B.left) && dfs(A.right, B.right); - } -} \ No newline at end of file +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public bool IsSubStructure(TreeNode A, TreeNode B) { + if (A == null || B == null) { + return false; + } + return dfs(A, B) || IsSubStructure(A.left, B) || IsSubStructure(A.right, B); + } + + public bool dfs(TreeNode A, TreeNode B) { + if (B == null) { + return true; + } + if (A == null || A.val != B.val) { + return false; + } + return dfs(A.left, B.left) && dfs(A.right, B.right); + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23027. \344\272\214\345\217\211\346\240\221\347\232\204\351\225\234\345\203\217/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23027. \344\272\214\345\217\211\346\240\221\347\232\204\351\225\234\345\203\217/Solution.cs" index 2eccd84daa4da..a3ee2d2df1649 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23027. \344\272\214\345\217\211\346\240\221\347\232\204\351\225\234\345\203\217/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23027. \344\272\214\345\217\211\346\240\221\347\232\204\351\225\234\345\203\217/Solution.cs" @@ -1,22 +1,22 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public TreeNode MirrorTree(TreeNode root) { - if (root == null) { - return root; - } - TreeNode t = root.left; - root.left = root.right; - root.right = t; - MirrorTree(root.left); - MirrorTree(root.right); - return root; - } -} \ No newline at end of file +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public TreeNode MirrorTree(TreeNode root) { + if (root == null) { + return root; + } + TreeNode t = root.left; + root.left = root.right; + root.right = t; + MirrorTree(root.left); + MirrorTree(root.right); + return root; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23027. \344\272\214\345\217\211\346\240\221\347\232\204\351\225\234\345\203\217/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23027. \344\272\214\345\217\211\346\240\221\347\232\204\351\225\234\345\203\217/Solution2.py" new file mode 100644 index 0000000000000..9876e281340a4 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23027. \344\272\214\345\217\211\346\240\221\347\232\204\351\225\234\345\203\217/Solution2.py" @@ -0,0 +1,17 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution: + def mirrorTree(self, root: TreeNode) -> TreeNode: + if root is None: + return root + left = self.mirrorTree(root.left) + right = self.mirrorTree(root.right) + root.left = right + root.right = left + return root diff --git "a/lcof/\351\235\242\350\257\225\351\242\23028. \345\257\271\347\247\260\347\232\204\344\272\214\345\217\211\346\240\221/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23028. \345\257\271\347\247\260\347\232\204\344\272\214\345\217\211\346\240\221/Solution.cs" index 312c7fe369227..d879870d2880f 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23028. \345\257\271\347\247\260\347\232\204\344\272\214\345\217\211\346\240\221/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23028. \345\257\271\347\247\260\347\232\204\344\272\214\345\217\211\346\240\221/Solution.cs" @@ -1,24 +1,24 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public bool IsSymmetric(TreeNode root) { - return dfs(root, root); - } - - private bool dfs(TreeNode a, TreeNode b) { - if (a == null && b == null) { - return true; - } - if (a == null || b == null || a.val != b.val) { - return false; - } - return dfs(a.left, b.right) && dfs(a.right, b.left); - } -} \ No newline at end of file +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public bool IsSymmetric(TreeNode root) { + return dfs(root, root); + } + + private bool dfs(TreeNode a, TreeNode b) { + if (a == null && b == null) { + return true; + } + if (a == null || b == null || a.val != b.val) { + return false; + } + return dfs(a.left, b.right) && dfs(a.right, b.left); + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.cpp" index 74e87e9dfc4d9..2e0fdbfe60db7 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.cpp" +++ "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.cpp" @@ -5,19 +5,22 @@ class Solution { return {}; } int m = matrix.size(), n = matrix[0].size(); - int top = 0, bottom = m - 1, left = 0, right = n - 1; - vector ans; - while (top <= bottom && left <= right) { - for (int j = left; j <= right; ++j) ans.push_back(matrix[top][j]); - for (int i = top + 1; i <= bottom; ++i) ans.push_back(matrix[i][right]); - if (left < right && top < bottom) { - for (int j = right - 1; j >= left; --j) ans.push_back(matrix[bottom][j]); - for (int i = bottom - 1; i > top; --i) ans.push_back(matrix[i][left]); + bool vis[m][n]; + memset(vis, false, sizeof vis); + int i = 0, j = 0, k = 0; + int dirs[5] = {0, 1, 0, -1, 0}; + vector ans(m * n); + for (int h = 0; h < m * n; ++h) { + ans[h] = matrix[i][j]; + vis[i][j] = true; + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x < 0 || y < 0 || x >= m || y >= n || vis[x][y]) { + k = (k + 1) % 4; + x = i + dirs[k]; + y = j + dirs[k + 1]; } - ++top; - --bottom; - ++left; - --right; + i = x; + j = y; } return ans; } diff --git "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.cs" index 367a4baa4753c..c2ba6a81bd971 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.cs" @@ -1,40 +1,40 @@ -public class Solution { - public int[] SpiralOrder(int[][] matrix) { - List ans = new List(); - if (matrix.Length == 0) { - return ans.ToArray(); - } - int left = 0, top = 0, bottom = matrix.Length - 1, right = matrix[0].Length - 1; - while (true) { - for (int i = left; i <= right; i++) { - ans.Add(matrix[top][i]); - } - top += 1; - if (top > bottom) { - break; - } - for (int i = top; i <= bottom; i++) { - ans.Add(matrix[i][right]); - } - right -= 1; - if (right < left) { - break; - } - for (int i = right; i >= left; i--) { - ans.Add(matrix[bottom][i]); - } - bottom -= 1; - if (bottom < top) { - break; - } - for (int i = bottom; i >= top; i--) { - ans.Add(matrix[i][left]); - } - left += 1; - if (left > right) { - break; - } - } - return ans.ToArray(); - } -} \ No newline at end of file +public class Solution { + public int[] SpiralOrder(int[][] matrix) { + List ans = new List(); + if (matrix.Length == 0) { + return ans.ToArray(); + } + int left = 0, top = 0, bottom = matrix.Length - 1, right = matrix[0].Length - 1; + while (true) { + for (int i = left; i <= right; i++) { + ans.Add(matrix[top][i]); + } + top += 1; + if (top > bottom) { + break; + } + for (int i = top; i <= bottom; i++) { + ans.Add(matrix[i][right]); + } + right -= 1; + if (right < left) { + break; + } + for (int i = right; i >= left; i--) { + ans.Add(matrix[bottom][i]); + } + bottom -= 1; + if (bottom < top) { + break; + } + for (int i = bottom; i >= top; i--) { + ans.Add(matrix[i][left]); + } + left += 1; + if (left > right) { + break; + } + } + return ans.ToArray(); + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.go" "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.go" index bee7753f45b60..726b5694e3bd6 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.go" +++ "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.go" @@ -3,29 +3,22 @@ func spiralOrder(matrix [][]int) []int { return []int{} } m, n := len(matrix), len(matrix[0]) - ans := make([]int, 0, m*n) - - top, bottom, left, right := 0, m-1, 0, n-1 - for left <= right && top <= bottom { - for i := left; i <= right; i++ { - ans = append(ans, matrix[top][i]) - } - for i := top + 1; i <= bottom; i++ { - ans = append(ans, matrix[i][right]) - } - if left < right && top < bottom { - for i := right - 1; i >= left; i-- { - ans = append(ans, matrix[bottom][i]) - } - for i := bottom - 1; i > top; i-- { - ans = append(ans, matrix[i][left]) - } + vis := make([][]bool, m) + for i := range vis { + vis[i] = make([]bool, n) + } + i, j, k := 0, 0, 0 + dirs := [5]int{0, 1, 0, -1, 0} + ans := make([]int, m*n) + for h := 0; h < m*n; h++ { + ans[h] = matrix[i][j] + vis[i][j] = true + x, y := i+dirs[k], j+dirs[k+1] + if x < 0 || y < 0 || x >= m || y >= n || vis[x][y] { + k = (k + 1) % 4 + x, y = i+dirs[k], j+dirs[k+1] } - top++ - bottom-- - left++ - right-- + i, j = x, y } - return ans } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.java" "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.java" index e28b52c7ec5e3..8377217004ecb 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.java" +++ "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.java" @@ -4,28 +4,21 @@ public int[] spiralOrder(int[][] matrix) { return new int[] {}; } int m = matrix.length, n = matrix[0].length; - int top = 0, bottom = m - 1, left = 0, right = n - 1; + boolean[][] vis = new boolean[m][n]; int[] ans = new int[m * n]; - int k = 0; - while (left <= right && top <= bottom) { - for (int j = left; j <= right; ++j) { - ans[k++] = matrix[top][j]; + int i = 0, j = 0, k = 0; + int[] dirs = {0, 1, 0, -1, 0}; + for (int h = 0; h < m * n; ++h) { + ans[h] = matrix[i][j]; + vis[i][j] = true; + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x < 0 || y < 0 || x >= m || y >= n || vis[x][y]) { + k = (k + 1) % 4; + x = i + dirs[k]; + y = j + dirs[k + 1]; } - for (int i = top + 1; i <= bottom; ++i) { - ans[k++] = matrix[i][right]; - } - if (left < right && top < bottom) { - for (int j = right - 1; j >= left; --j) { - ans[k++] = matrix[bottom][j]; - } - for (int i = bottom - 1; i > top; --i) { - ans[k++] = matrix[i][left]; - } - } - ++top; - --bottom; - ++left; - --right; + i = x; + j = y; } return ans; } diff --git "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.py" "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.py" index b440252e597a9..5a7d80c28c211 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.py" +++ "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.py" @@ -2,14 +2,17 @@ class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: if not matrix or not matrix[0]: return [] + dirs = (0, 1, 0, -1, 0) m, n = len(matrix), len(matrix[0]) + vis = [[False] * n for _ in range(m)] ans = [] - top, bottom, left, right = 0, m - 1, 0, n - 1 - while left <= right and top <= bottom: - ans.extend([matrix[top][j] for j in range(left, right + 1)]) - ans.extend([matrix[i][right] for i in range(top + 1, bottom + 1)]) - if left < right and top < bottom: - ans.extend([matrix[bottom][j] for j in range(right - 1, left - 1, -1)]) - ans.extend([matrix[i][left] for i in range(bottom - 1, top, -1)]) - top, bottom, left, right = top + 1, bottom - 1, left + 1, right - 1 + i = j = k = 0 + for _ in range(m * n): + ans.append(matrix[i][j]) + vis[i][j] = True + x, y = i + dirs[k], j + dirs[k + 1] + if x < 0 or y < 0 or x >= m or y >= n or vis[x][y]: + k = (k + 1) % 4 + x, y = i + dirs[k], j + dirs[k + 1] + i, j = x, y return ans diff --git "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution2.cpp" new file mode 100644 index 0000000000000..74e87e9dfc4d9 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution2.cpp" @@ -0,0 +1,24 @@ +class Solution { +public: + vector spiralOrder(vector>& matrix) { + if (matrix.size() == 0 || matrix[0].size() == 0) { + return {}; + } + int m = matrix.size(), n = matrix[0].size(); + int top = 0, bottom = m - 1, left = 0, right = n - 1; + vector ans; + while (top <= bottom && left <= right) { + for (int j = left; j <= right; ++j) ans.push_back(matrix[top][j]); + for (int i = top + 1; i <= bottom; ++i) ans.push_back(matrix[i][right]); + if (left < right && top < bottom) { + for (int j = right - 1; j >= left; --j) ans.push_back(matrix[bottom][j]); + for (int i = bottom - 1; i > top; --i) ans.push_back(matrix[i][left]); + } + ++top; + --bottom; + ++left; + --right; + } + return ans; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution2.go" new file mode 100644 index 0000000000000..bee7753f45b60 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution2.go" @@ -0,0 +1,31 @@ +func spiralOrder(matrix [][]int) []int { + if len(matrix) == 0 || len(matrix[0]) == 0 { + return []int{} + } + m, n := len(matrix), len(matrix[0]) + ans := make([]int, 0, m*n) + + top, bottom, left, right := 0, m-1, 0, n-1 + for left <= right && top <= bottom { + for i := left; i <= right; i++ { + ans = append(ans, matrix[top][i]) + } + for i := top + 1; i <= bottom; i++ { + ans = append(ans, matrix[i][right]) + } + if left < right && top < bottom { + for i := right - 1; i >= left; i-- { + ans = append(ans, matrix[bottom][i]) + } + for i := bottom - 1; i > top; i-- { + ans = append(ans, matrix[i][left]) + } + } + top++ + bottom-- + left++ + right-- + } + + return ans +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution2.java" new file mode 100644 index 0000000000000..e28b52c7ec5e3 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution2.java" @@ -0,0 +1,32 @@ +class Solution { + public int[] spiralOrder(int[][] matrix) { + if (matrix.length == 0 || matrix[0].length == 0) { + return new int[] {}; + } + int m = matrix.length, n = matrix[0].length; + int top = 0, bottom = m - 1, left = 0, right = n - 1; + int[] ans = new int[m * n]; + int k = 0; + while (left <= right && top <= bottom) { + for (int j = left; j <= right; ++j) { + ans[k++] = matrix[top][j]; + } + for (int i = top + 1; i <= bottom; ++i) { + ans[k++] = matrix[i][right]; + } + if (left < right && top < bottom) { + for (int j = right - 1; j >= left; --j) { + ans[k++] = matrix[bottom][j]; + } + for (int i = bottom - 1; i > top; --i) { + ans[k++] = matrix[i][left]; + } + } + ++top; + --bottom; + ++left; + --right; + } + return ans; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution2.py" new file mode 100644 index 0000000000000..b440252e597a9 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution2.py" @@ -0,0 +1,15 @@ +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + if not matrix or not matrix[0]: + return [] + m, n = len(matrix), len(matrix[0]) + ans = [] + top, bottom, left, right = 0, m - 1, 0, n - 1 + while left <= right and top <= bottom: + ans.extend([matrix[top][j] for j in range(left, right + 1)]) + ans.extend([matrix[i][right] for i in range(top + 1, bottom + 1)]) + if left < right and top < bottom: + ans.extend([matrix[bottom][j] for j in range(right - 1, left - 1, -1)]) + ans.extend([matrix[i][left] for i in range(bottom - 1, top, -1)]) + top, bottom, left, right = top + 1, bottom - 1, left + 1, right - 1 + return ans diff --git "a/lcof/\351\235\242\350\257\225\351\242\23030. \345\214\205\345\220\253min\345\207\275\346\225\260\347\232\204\346\240\210/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23030. \345\214\205\345\220\253min\345\207\275\346\225\260\347\232\204\346\240\210/Solution.cs" index aa4c705fd390e..23c1cf7a8d41c 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23030. \345\214\205\345\220\253min\345\207\275\346\225\260\347\232\204\346\240\210/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23030. \345\214\205\345\220\253min\345\207\275\346\225\260\347\232\204\346\240\210/Solution.cs" @@ -1,36 +1,36 @@ -public class MinStack { - private Stack stk1 = new Stack(); - private Stack stk2 = new Stack(); - - /** initialize your data structure here. */ - public MinStack() { - stk2.Push(int.MaxValue); - } - - public void Push(int x) { - stk1.Push(x); - stk2.Push(Math.Min(x, GetMin())); - } - - public void Pop() { - stk1.Pop(); - stk2.Pop(); - } - - public int Top() { - return stk1.Peek(); - } - - public int GetMin() { - return stk2.Peek(); - } -} - -/** - * Your MinStack object will be instantiated and called as such: - * MinStack obj = new MinStack(); - * obj.Push(x); - * obj.Pop(); - * int param_3 = obj.Top(); - * int param_4 = obj.GetMin(); - */ \ No newline at end of file +public class MinStack { + private Stack stk1 = new Stack(); + private Stack stk2 = new Stack(); + + /** initialize your data structure here. */ + public MinStack() { + stk2.Push(int.MaxValue); + } + + public void Push(int x) { + stk1.Push(x); + stk2.Push(Math.Min(x, GetMin())); + } + + public void Pop() { + stk1.Pop(); + stk2.Pop(); + } + + public int Top() { + return stk1.Peek(); + } + + public int GetMin() { + return stk2.Peek(); + } +} + +/** + * Your MinStack object will be instantiated and called as such: + * MinStack obj = new MinStack(); + * obj.Push(x); + * obj.Pop(); + * int param_3 = obj.Top(); + * int param_4 = obj.GetMin(); + */ diff --git "a/lcof/\351\235\242\350\257\225\351\242\23030. \345\214\205\345\220\253min\345\207\275\346\225\260\347\232\204\346\240\210/Solution.ts" "b/lcof/\351\235\242\350\257\225\351\242\23030. \345\214\205\345\220\253min\345\207\275\346\225\260\347\232\204\346\240\210/Solution.ts" index 091a296221328..aa6dafc3fba70 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23030. \345\214\205\345\220\253min\345\207\275\346\225\260\347\232\204\346\240\210/Solution.ts" +++ "b/lcof/\351\235\242\350\257\225\351\242\23030. \345\214\205\345\220\253min\345\207\275\346\225\260\347\232\204\346\240\210/Solution.ts" @@ -1,28 +1,27 @@ class MinStack { - stk1: number[]; - stk2: number[]; - + stack: number[]; + mins: number[]; constructor() { - this.stk1 = []; - this.stk2 = [Infinity]; + this.stack = []; + this.mins = []; } push(x: number): void { - this.stk1.push(x); - this.stk2.push(Math.min(x, this.stk2[this.stk2.length - 1])); + this.stack.push(x); + this.mins.push(Math.min(this.getMin(), x)); } pop(): void { - this.stk1.pop(); - this.stk2.pop(); + this.stack.pop(); + this.mins.pop(); } top(): number { - return this.stk1[this.stk1.length - 1]; + return this.stack[this.stack.length - 1]; } getMin(): number { - return this.stk2[this.stk2.length - 1]; + return this.mins.length == 0 ? Infinity : this.mins[this.mins.length - 1]; } } diff --git "a/lcof/\351\235\242\350\257\225\351\242\23031. \346\240\210\347\232\204\345\216\213\345\205\245\343\200\201\345\274\271\345\207\272\345\272\217\345\210\227/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23031. \346\240\210\347\232\204\345\216\213\345\205\245\343\200\201\345\274\271\345\207\272\345\272\217\345\210\227/Solution.cs" index 7f524be461b83..eb939e6252c72 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23031. \346\240\210\347\232\204\345\216\213\345\205\245\343\200\201\345\274\271\345\207\272\345\272\217\345\210\227/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23031. \346\240\210\347\232\204\345\216\213\345\205\245\343\200\201\345\274\271\345\207\272\345\272\217\345\210\227/Solution.cs" @@ -1,15 +1,15 @@ -public class Solution { - public bool ValidateStackSequences(int[] pushed, int[] popped) { - Stack stk = new Stack(); - int j = 0; - foreach (int x in pushed) - { - stk.Push(x); - while (stk.Count != 0 && stk.Peek() == popped[j]) { - stk.Pop(); - ++j; - } - } - return stk.Count == 0; - } -} \ No newline at end of file +public class Solution { + public bool ValidateStackSequences(int[] pushed, int[] popped) { + Stack stk = new Stack(); + int j = 0; + foreach (int x in pushed) + { + stk.Push(x); + while (stk.Count != 0 && stk.Peek() == popped[j]) { + stk.Pop(); + ++j; + } + } + return stk.Count == 0; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23032 - I. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23032 - I. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221/Solution.cs" index 09f62fae0f266..9af0ef22e97db 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23032 - I. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23032 - I. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221/Solution.cs" @@ -1,33 +1,33 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public int[] LevelOrder(TreeNode root) { - if (root == null) { - return new int[]{}; - } - Queue q = new Queue(); - q.Enqueue(root); - List ans = new List(); - while (q.Count != 0) { - int x = q.Count; - for (int i = 0; i < x; i++) { - TreeNode node = q.Dequeue(); - ans.Add(node.val); - if (node.left != null) { - q.Enqueue(node.left); - } - if (node.right != null) { - q.Enqueue(node.right); - } - } - } - return ans.ToArray(); - } -} \ No newline at end of file +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public int[] LevelOrder(TreeNode root) { + if (root == null) { + return new int[]{}; + } + Queue q = new Queue(); + q.Enqueue(root); + List ans = new List(); + while (q.Count != 0) { + int x = q.Count; + for (int i = 0; i < x; i++) { + TreeNode node = q.Dequeue(); + ans.Add(node.val); + if (node.left != null) { + q.Enqueue(node.left); + } + if (node.right != null) { + q.Enqueue(node.right); + } + } + } + return ans.ToArray(); + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23032 - II. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221 II/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23032 - II. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221 II/Solution.cs" index 83a33dd9772e3..dabb7d32c4457 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23032 - II. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221 II/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23032 - II. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221 II/Solution.cs" @@ -1,35 +1,35 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public IList> LevelOrder(TreeNode root) { - if (root == null) { - return new List>(); - } - Queue q = new Queue(); - q.Enqueue(root); - List> ans = new List>(); - while (q.Count != 0) { - List tmp = new List(); - int x = q.Count; - for (int i = 0; i < x; i++) { - TreeNode node = q.Dequeue(); - tmp.Add(node.val); - if (node.left != null) { - q.Enqueue(node.left); - } - if (node.right != null) { - q.Enqueue(node.right); - } - } - ans.Add(tmp); - } - return ans; - } -} \ No newline at end of file +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public IList> LevelOrder(TreeNode root) { + if (root == null) { + return new List>(); + } + Queue q = new Queue(); + q.Enqueue(root); + List> ans = new List>(); + while (q.Count != 0) { + List tmp = new List(); + int x = q.Count; + for (int i = 0; i < x; i++) { + TreeNode node = q.Dequeue(); + tmp.Add(node.val); + if (node.left != null) { + q.Enqueue(node.left); + } + if (node.right != null) { + q.Enqueue(node.right); + } + } + ans.Add(tmp); + } + return ans; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23032 - III. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221 III/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23032 - III. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221 III/Solution.cs" index fcfd8f9d62a1c..62c812c737952 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23032 - III. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221 III/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23032 - III. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221 III/Solution.cs" @@ -1,37 +1,37 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public IList> LevelOrder(TreeNode root) { - var ans = new List>(); - if (root == null) { - return ans; - } - var q = new Queue(); - q.Enqueue(root); - while (q.Count > 0) { - var t = new List(); - for (int n = q.Count; n > 0; --n) { - var node = q.Dequeue(); - t.Add(node.val); - if (node.left != null) { - q.Enqueue(node.left); - } - if (node.right != null) { - q.Enqueue(node.right); - } - } - if (ans.Count % 2 == 1) { - t.Reverse(); - } - ans.Add(t); - } - return ans; - } -} \ No newline at end of file +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public IList> LevelOrder(TreeNode root) { + var ans = new List>(); + if (root == null) { + return ans; + } + var q = new Queue(); + q.Enqueue(root); + while (q.Count > 0) { + var t = new List(); + for (int n = q.Count; n > 0; --n) { + var node = q.Dequeue(); + t.Add(node.val); + if (node.left != null) { + q.Enqueue(node.left); + } + if (node.right != null) { + q.Enqueue(node.right); + } + } + if (ans.Count % 2 == 1) { + t.Reverse(); + } + ans.Add(t); + } + return ans; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution.cs" index ff19a112ef29d..d5af2f0c17011 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution.cs" @@ -1,25 +1,25 @@ -public class Solution { - private int[] postorder; - - public bool VerifyPostorder(int[] postorder) { - this.postorder = postorder; - return dfs(0, postorder.Length - 1); - } - - private bool dfs(int l, int r) { - if (l >= r) { - return true; - } - int v = postorder[r]; - int i = l; - while (i < r && postorder[i] < v) { - ++i; - } - for (int j = i; j < r; ++j) { - if (postorder[j] < v) { - return false; - } - } - return dfs(l, i - 1) && dfs(i, r - 1); - } -} \ No newline at end of file +public class Solution { + private int[] postorder; + + public bool VerifyPostorder(int[] postorder) { + this.postorder = postorder; + return dfs(0, postorder.Length - 1); + } + + private bool dfs(int l, int r) { + if (l >= r) { + return true; + } + int v = postorder[r]; + int i = l; + while (i < r && postorder[i] < v) { + ++i; + } + for (int j = i; j < r; ++j) { + if (postorder[j] < v) { + return false; + } + } + return dfs(l, i - 1) && dfs(i, r - 1); + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution2.cpp" new file mode 100644 index 0000000000000..2d140bd8c8e3d --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution2.cpp" @@ -0,0 +1,19 @@ +class Solution { +public: + bool verifyPostorder(vector& postorder) { + stack stk; + int mx = 1 << 30; + reverse(postorder.begin(), postorder.end()); + for (int& x : postorder) { + if (x > mx) { + return false; + } + while (!stk.empty() && stk.top() > x) { + mx = stk.top(); + stk.pop(); + } + stk.push(x); + } + return true; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution2.go" new file mode 100644 index 0000000000000..6e641711797c4 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution2.go" @@ -0,0 +1,16 @@ +func verifyPostorder(postorder []int) bool { + mx := 1 << 30 + stk := []int{} + for i := len(postorder) - 1; i >= 0; i-- { + x := postorder[i] + if x > mx { + return false + } + for len(stk) > 0 && stk[len(stk)-1] > x { + mx = stk[len(stk)-1] + stk = stk[:len(stk)-1] + } + stk = append(stk, x) + } + return true +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution2.java" new file mode 100644 index 0000000000000..8db2ab9060f3f --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution2.java" @@ -0,0 +1,17 @@ +class Solution { + public boolean verifyPostorder(int[] postorder) { + int mx = 1 << 30; + Deque stk = new ArrayDeque<>(); + for (int i = postorder.length - 1; i >= 0; --i) { + int x = postorder[i]; + if (x > mx) { + return false; + } + while (!stk.isEmpty() && stk.peek() > x) { + mx = stk.pop(); + } + stk.push(x); + } + return true; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution2.js" "b/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution2.js" new file mode 100644 index 0000000000000..8d3007088d591 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution2.js" @@ -0,0 +1,19 @@ +/** + * @param {number[]} postorder + * @return {boolean} + */ +var verifyPostorder = function (postorder) { + let mx = 1 << 30; + const stk = []; + for (let i = postorder.length - 1; i >= 0; --i) { + const x = postorder[i]; + if (x > mx) { + return false; + } + while (stk.length && stk[stk.length - 1] > x) { + mx = stk.pop(); + } + stk.push(x); + } + return true; +}; diff --git "a/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution2.py" new file mode 100644 index 0000000000000..e186415500d7d --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution2.py" @@ -0,0 +1,11 @@ +class Solution: + def verifyPostorder(self, postorder: List[int]) -> bool: + mx = inf + stk = [] + for x in postorder[::-1]: + if x > mx: + return False + while stk and stk[-1] > x: + mx = stk.pop() + stk.append(x) + return True diff --git "a/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution2.ts" "b/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution2.ts" new file mode 100644 index 0000000000000..01e092caa9d6a --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/Solution2.ts" @@ -0,0 +1,15 @@ +function verifyPostorder(postorder: number[]): boolean { + let mx = 1 << 30; + const stk: number[] = []; + for (let i = postorder.length - 1; i >= 0; --i) { + const x = postorder[i]; + if (x > mx) { + return false; + } + while (stk.length && stk[stk.length - 1] > x) { + mx = stk.pop(); + } + stk.push(x); + } + return true; +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23034. \344\272\214\345\217\211\346\240\221\344\270\255\345\222\214\344\270\272\346\237\220\344\270\200\345\200\274\347\232\204\350\267\257\345\276\204/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23034. \344\272\214\345\217\211\346\240\221\344\270\255\345\222\214\344\270\272\346\237\220\344\270\200\345\200\274\347\232\204\350\267\257\345\276\204/Solution.cs" index 732920aec6753..9675fe524ae68 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23034. \344\272\214\345\217\211\346\240\221\344\270\255\345\222\214\344\270\272\346\237\220\344\270\200\345\200\274\347\232\204\350\267\257\345\276\204/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23034. \344\272\214\345\217\211\346\240\221\344\270\255\345\222\214\344\270\272\346\237\220\344\270\200\345\200\274\347\232\204\350\267\257\345\276\204/Solution.cs" @@ -1,36 +1,36 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -public class Solution { - private List> ans = new List>(); - private List t = new List(); - - public IList> PathSum(TreeNode root, int target) { - dfs(root, target); - return ans; - } - - private void dfs(TreeNode root, int s) { - if (root == null) { - return; - } - t.Add(root.val); - s -= root.val; - if (root.left == null && root.right == null && s == 0) { - ans.Add(new List(t)); - } - dfs(root.left, s); - dfs(root.right, s); - t.RemoveAt(t.Count - 1); - } -} \ No newline at end of file +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + private List> ans = new List>(); + private List t = new List(); + + public IList> PathSum(TreeNode root, int target) { + dfs(root, target); + return ans; + } + + private void dfs(TreeNode root, int s) { + if (root == null) { + return; + } + t.Add(root.val); + s -= root.val; + if (root.left == null && root.right == null && s == 0) { + ans.Add(new List(t)); + } + dfs(root.left, s); + dfs(root.right, s); + t.RemoveAt(t.Count - 1); + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23034. \344\272\214\345\217\211\346\240\221\344\270\255\345\222\214\344\270\272\346\237\220\344\270\200\345\200\274\347\232\204\350\267\257\345\276\204/Solution2.rs" "b/lcof/\351\235\242\350\257\225\351\242\23034. \344\272\214\345\217\211\346\240\221\344\270\255\345\222\214\344\270\272\346\237\220\344\270\200\345\200\274\347\232\204\350\267\257\345\276\204/Solution2.rs" new file mode 100644 index 0000000000000..29c0c3efd1b5b --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23034. \344\272\214\345\217\211\346\240\221\344\270\255\345\222\214\344\270\272\346\237\220\344\270\200\345\200\274\347\232\204\350\267\257\345\276\204/Solution2.rs" @@ -0,0 +1,59 @@ +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn dfs( + root: &Option>>, + mut target: i32, + paths: &mut Vec + ) -> Vec> { + let node = root.as_ref().unwrap().borrow(); + paths.push(node.val); + target -= node.val; + let mut res = vec![]; + // 确定叶结点身份 + if node.left.is_none() && node.right.is_none() { + if target == 0 { + res.push(paths.clone()); + } + } else { + if node.left.is_some() { + let res_l = Self::dfs(&node.left, target, paths); + if !res_l.is_empty() { + res = [res, res_l].concat(); + } + } + if node.right.is_some() { + let res_r = Self::dfs(&node.right, target, paths); + if !res_r.is_empty() { + res = [res, res_r].concat(); + } + } + } + paths.pop(); + res + } + pub fn path_sum(root: Option>>, target: i32) -> Vec> { + if root.is_none() { + return vec![]; + } + Self::dfs(&root, target, &mut vec![]) + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.cpp" index a98a121581a14..48858e8ac32bd 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.cpp" +++ "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.cpp" @@ -16,28 +16,19 @@ class Node { class Solution { public: Node* copyRandomList(Node* head) { - if (!head) { - return nullptr; + unordered_map d; + Node* dummy = new Node(0); + Node* tail = dummy; + for (auto cur = head; cur; cur = cur->next) { + tail->next = new Node(cur->val); + tail = tail->next; + d[cur] = tail; } - for (Node* cur = head; cur;) { - Node* node = new Node(cur->val); - node->next = cur->next; - cur->next = node; - cur = node->next; + tail = dummy->next; + for (auto cur = head; cur; cur = cur->next) { + tail->random = d[cur->random]; + tail = tail->next; } - for (Node* cur = head; cur; cur = cur->next->next) { - if (cur->random) { - cur->next->random = cur->random->next; - } - } - Node* ans = head->next; - for (Node* cur = head; cur;) { - Node* nxt = cur->next; - if (nxt) { - cur->next = nxt->next; - } - cur = nxt; - } - return ans; + return dummy->next; } }; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.cs" index 901c7ecc99bcb..97a43f56c2934 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.cs" @@ -15,27 +15,19 @@ public Node(int _val) { public class Solution { public Node CopyRandomList(Node head) { - if (head == null) { - return null; + Dictionary d = new Dictionary(); + Node dummy = new Node(0); + Node tail = dummy; + for (Node cur = head; cur != null; cur = cur.next) { + tail.next = new Node(cur.val); + tail = tail.next; + d[cur] = tail; } - for (Node cur = head; cur != null; ) { - Node node = new Node(cur.val, cur.next); - cur.next = node; - cur = node.next; + tail = dummy.next; + for (Node cur = head; cur != null; cur = cur.next) { + tail.random = cur.random == null ? null : d[cur.random]; + tail = tail.next; } - for (Node cur = head; cur != null; cur = cur.next.next) { - if (cur.random != null) { - cur.next.random = cur.random.next; - } - } - Node ans = head.next; - for (Node cur = head; cur != null; ) { - Node nxt = cur.next; - if (nxt != null) { - cur.next = nxt.next; - } - cur = nxt; - } - return ans; + return dummy.next; } -} \ No newline at end of file +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.go" "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.go" index 8039efadcbe65..08ed594b862b9 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.go" +++ "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.go" @@ -8,26 +8,18 @@ */ func copyRandomList(head *Node) *Node { - if head == nil { - return nil + d := map[*Node]*Node{} + dummy := &Node{} + tail := dummy + for cur := head; cur != nil; cur = cur.Next { + tail.Next = &Node{Val: cur.Val} + tail = tail.Next + d[cur] = tail } - for cur := head; cur != nil; { - node := &Node{cur.Val, cur.Next, nil} - cur.Next = node - cur = node.Next + tail = dummy.Next + for cur := head; cur != nil; cur = cur.Next { + tail.Random = d[cur.Random] + tail = tail.Next } - for cur := head; cur != nil; cur = cur.Next.Next { - if cur.Random != nil { - cur.Next.Random = cur.Random.Next - } - } - ans := head.Next - for cur := head; cur != nil; { - nxt := cur.Next - if nxt != nil { - cur.Next = nxt.Next - } - cur = nxt - } - return ans + return dummy.Next } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.java" "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.java" index 9ed0bdedf01f1..2bce78d217257 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.java" +++ "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.java" @@ -14,27 +14,19 @@ public Node(int val) { */ class Solution { public Node copyRandomList(Node head) { - if (head == null) { - return null; + Map d = new HashMap<>(); + Node dummy = new Node(0); + Node tail = dummy; + for (Node cur = head; cur != null; cur = cur.next) { + tail.next = new Node(cur.val); + tail = tail.next; + d.put(cur, tail); } - for (Node cur = head; cur != null;) { - Node node = new Node(cur.val, cur.next); - cur.next = node; - cur = node.next; + tail = dummy.next; + for (Node cur = head; cur != null; cur = cur.next) { + tail.random = d.get(cur.random); + tail = tail.next; } - for (Node cur = head; cur != null; cur = cur.next.next) { - if (cur.random != null) { - cur.next.random = cur.random.next; - } - } - Node ans = head.next; - for (Node cur = head; cur != null;) { - Node nxt = cur.next; - if (nxt != null) { - cur.next = nxt.next; - } - cur = nxt; - } - return ans; + return dummy.next; } } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.js" "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.js" index 93fd2cf31a78b..b7cd78df5c464 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.js" +++ "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.js" @@ -12,26 +12,18 @@ * @return {Node} */ var copyRandomList = function (head) { - if (!head) { - return null; + const d = new Map(); + const dummy = new Node(0); + let tail = dummy; + for (let cur = head; cur; cur = cur.next) { + tail.next = new Node(cur.val); + tail = tail.next; + d.set(cur, tail); } - for (let cur = head; cur; ) { - const node = new Node(cur.val, cur.next, null); - cur.next = node; - cur = node.next; + tail = dummy.next; + for (let cur = head; cur; cur = cur.next) { + tail.random = d.get(cur.random); + tail = tail.next; } - for (let cur = head; cur; cur = cur.next.next) { - if (cur.random) { - cur.next.random = cur.random.next; - } - } - const ans = head.next; - for (let cur = head; cur; ) { - const nxt = cur.next; - if (nxt) { - cur.next = nxt.next; - } - cur = nxt; - } - return ans; + return dummy.next; }; diff --git "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.py" "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.py" index e70ccac9789b0..57797589c37c6 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.py" +++ "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution.py" @@ -10,25 +10,18 @@ def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): class Solution: def copyRandomList(self, head: "Node") -> "Node": - if head is None: - return None + d = {} + dummy = tail = Node(0) cur = head while cur: - node = Node(cur.val, cur.next) - cur.next = node - cur = node.next - - cur = head - while cur: - if cur.random: - cur.next.random = cur.random.next - cur = cur.next.next - - ans = head.next + tail.next = Node(cur.val) + tail = tail.next + d[cur] = tail + cur = cur.next + tail = dummy.next cur = head while cur: - nxt = cur.next - if nxt: - cur.next = nxt.next - cur = nxt - return ans + tail.random = d.get(cur.random) + tail = tail.next + cur = cur.next + return dummy.next diff --git "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution2.cpp" new file mode 100644 index 0000000000000..a98a121581a14 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution2.cpp" @@ -0,0 +1,43 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + Node* next; + Node* random; + + Node(int _val) { + val = _val; + next = NULL; + random = NULL; + } +}; +*/ +class Solution { +public: + Node* copyRandomList(Node* head) { + if (!head) { + return nullptr; + } + for (Node* cur = head; cur;) { + Node* node = new Node(cur->val); + node->next = cur->next; + cur->next = node; + cur = node->next; + } + for (Node* cur = head; cur; cur = cur->next->next) { + if (cur->random) { + cur->next->random = cur->random->next; + } + } + Node* ans = head->next; + for (Node* cur = head; cur;) { + Node* nxt = cur->next; + if (nxt) { + cur->next = nxt->next; + } + cur = nxt; + } + return ans; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution2.cs" "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution2.cs" new file mode 100644 index 0000000000000..c05d1da4a1065 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution2.cs" @@ -0,0 +1,41 @@ +/* +// Definition for a Node. +public class Node { + public int val; + public Node next; + public Node random; + + public Node(int _val) { + val = _val; + next = null; + random = null; + } +} +*/ + +public class Solution { + public Node CopyRandomList(Node head) { + if (head == null) { + return null; + } + for (Node cur = head; cur != null; ) { + Node node = new Node(cur.val, cur.next); + cur.next = node; + cur = node.next; + } + for (Node cur = head; cur != null; cur = cur.next.next) { + if (cur.random != null) { + cur.next.random = cur.random.next; + } + } + Node ans = head.next; + for (Node cur = head; cur != null; ) { + Node nxt = cur.next; + if (nxt != null) { + cur.next = nxt.next; + } + cur = nxt; + } + return ans; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution2.go" new file mode 100644 index 0000000000000..8039efadcbe65 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution2.go" @@ -0,0 +1,33 @@ +/** + * Definition for a Node. + * type Node struct { + * Val int + * Next *Node + * Random *Node + * } + */ + +func copyRandomList(head *Node) *Node { + if head == nil { + return nil + } + for cur := head; cur != nil; { + node := &Node{cur.Val, cur.Next, nil} + cur.Next = node + cur = node.Next + } + for cur := head; cur != nil; cur = cur.Next.Next { + if cur.Random != nil { + cur.Next.Random = cur.Random.Next + } + } + ans := head.Next + for cur := head; cur != nil; { + nxt := cur.Next + if nxt != nil { + cur.Next = nxt.Next + } + cur = nxt + } + return ans +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution2.java" new file mode 100644 index 0000000000000..9ed0bdedf01f1 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution2.java" @@ -0,0 +1,40 @@ +/* +// Definition for a Node. +class Node { + int val; + Node next; + Node random; + + public Node(int val) { + this.val = val; + this.next = null; + this.random = null; + } +} +*/ +class Solution { + public Node copyRandomList(Node head) { + if (head == null) { + return null; + } + for (Node cur = head; cur != null;) { + Node node = new Node(cur.val, cur.next); + cur.next = node; + cur = node.next; + } + for (Node cur = head; cur != null; cur = cur.next.next) { + if (cur.random != null) { + cur.next.random = cur.random.next; + } + } + Node ans = head.next; + for (Node cur = head; cur != null;) { + Node nxt = cur.next; + if (nxt != null) { + cur.next = nxt.next; + } + cur = nxt; + } + return ans; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution2.js" "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution2.js" new file mode 100644 index 0000000000000..93fd2cf31a78b --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution2.js" @@ -0,0 +1,37 @@ +/** + * // Definition for a Node. + * function Node(val, next, random) { + * this.val = val; + * this.next = next; + * this.random = random; + * }; + */ + +/** + * @param {Node} head + * @return {Node} + */ +var copyRandomList = function (head) { + if (!head) { + return null; + } + for (let cur = head; cur; ) { + const node = new Node(cur.val, cur.next, null); + cur.next = node; + cur = node.next; + } + for (let cur = head; cur; cur = cur.next.next) { + if (cur.random) { + cur.next.random = cur.random.next; + } + } + const ans = head.next; + for (let cur = head; cur; ) { + const nxt = cur.next; + if (nxt) { + cur.next = nxt.next; + } + cur = nxt; + } + return ans; +}; diff --git "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution2.py" new file mode 100644 index 0000000000000..e70ccac9789b0 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/Solution2.py" @@ -0,0 +1,34 @@ +""" +# Definition for a Node. +class Node: + def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): + self.val = int(x) + self.next = next + self.random = random +""" + + +class Solution: + def copyRandomList(self, head: "Node") -> "Node": + if head is None: + return None + cur = head + while cur: + node = Node(cur.val, cur.next) + cur.next = node + cur = node.next + + cur = head + while cur: + if cur.random: + cur.next.random = cur.random.next + cur = cur.next.next + + ans = head.next + cur = head + while cur: + nxt = cur.next + if nxt: + cur.next = nxt.next + cur = nxt + return ans diff --git "a/lcof/\351\235\242\350\257\225\351\242\23036. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\216\345\217\214\345\220\221\351\223\276\350\241\250/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23036. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\216\345\217\214\345\220\221\351\223\276\350\241\250/Solution.cs" index 9194b397734c1..9d3329636ff57 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23036. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\216\345\217\214\345\220\221\351\223\276\350\241\250/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23036. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\216\345\217\214\345\220\221\351\223\276\350\241\250/Solution.cs" @@ -1,52 +1,52 @@ -/* -// Definition for a Node. -public class Node { - public int val; - public Node left; - public Node right; - - public Node() {} - - public Node(int _val) { - val = _val; - left = null; - right = null; - } - - public Node(int _val,Node _left,Node _right) { - val = _val; - left = _left; - right = _right; - } -} -*/ - -public class Solution { - private Node head; - private Node pre; - - public Node TreeToDoublyList(Node root) { - if (root == null) { - return null; - } - dfs(root); - head.left = pre; - pre.right = head; - return head; - } - - private void dfs(Node root) { - if (root == null) { - return; - } - dfs(root.left); - if (pre != null) { - pre.right = root; - } else { - head = root; - } - root.left = pre; - pre = root; - dfs(root.right); - } -} \ No newline at end of file +/* +// Definition for a Node. +public class Node { + public int val; + public Node left; + public Node right; + + public Node() {} + + public Node(int _val) { + val = _val; + left = null; + right = null; + } + + public Node(int _val,Node _left,Node _right) { + val = _val; + left = _left; + right = _right; + } +} +*/ + +public class Solution { + private Node head; + private Node pre; + + public Node TreeToDoublyList(Node root) { + if (root == null) { + return null; + } + dfs(root); + head.left = pre; + pre.right = head; + return head; + } + + private void dfs(Node root) { + if (root == null) { + return; + } + dfs(root.left); + if (pre != null) { + pre.right = root; + } else { + head = root; + } + root.left = pre; + pre = root; + dfs(root.right); + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23037. \345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23037. \345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/Solution.cs" index 1febc5b6fb681..96f6e7fb52f00 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23037. \345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23037. \345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/Solution.cs" @@ -1,49 +1,49 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int x) { val = x; } - * } - */ -public class Codec { - public string serialize(TreeNode root) { - return rserialize(root, ""); - } - - public TreeNode deserialize(string data) { - string[] dataArray = data.Split(","); - LinkedList dataList = new LinkedList(dataArray.ToList()); - return rdeserialize(dataList); - } - - public string rserialize(TreeNode root, string str) { - if (root == null) { - str += "None,"; - } else { - str += root.val.ToString() + ","; - str = rserialize(root.left, str); - str = rserialize(root.right, str); - } - return str; - } - - public TreeNode rdeserialize(LinkedList dataList) { - if (dataList.First.Value.Equals("None")) { - dataList.RemoveFirst(); - return null; - } - - TreeNode root = new TreeNode(int.Parse(dataList.First.Value)); - dataList.RemoveFirst(); - root.left = rdeserialize(dataList); - root.right = rdeserialize(dataList); - - return root; - } -} - -// Your Codec object will be instantiated and called as such: -// Codec codec = new Codec(); -// codec.deserialize(codec.serialize(root)); \ No newline at end of file +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int x) { val = x; } + * } + */ +public class Codec { + public string serialize(TreeNode root) { + return rserialize(root, ""); + } + + public TreeNode deserialize(string data) { + string[] dataArray = data.Split(","); + LinkedList dataList = new LinkedList(dataArray.ToList()); + return rdeserialize(dataList); + } + + public string rserialize(TreeNode root, string str) { + if (root == null) { + str += "None,"; + } else { + str += root.val.ToString() + ","; + str = rserialize(root.left, str); + str = rserialize(root.right, str); + } + return str; + } + + public TreeNode rdeserialize(LinkedList dataList) { + if (dataList.First.Value.Equals("None")) { + dataList.RemoveFirst(); + return null; + } + + TreeNode root = new TreeNode(int.Parse(dataList.First.Value)); + dataList.RemoveFirst(); + root.left = rdeserialize(dataList); + root.right = rdeserialize(dataList); + + return root; + } +} + +// Your Codec object will be instantiated and called as such: +// Codec codec = new Codec(); +// codec.deserialize(codec.serialize(root)); diff --git "a/lcof/\351\235\242\350\257\225\351\242\23037. \345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23037. \345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/Solution2.cpp" new file mode 100644 index 0000000000000..2d8fff93b8a29 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23037. \345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/Solution2.cpp" @@ -0,0 +1,50 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Codec { +public: + string empty = "#"; + string sep = ","; + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + if (!root) return empty + sep; + string res = to_string(root->val) + sep; + res += serialize(root->left); + res += serialize(root->right); + return res; + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + list nodes; + size_t pos = 0; + string node; + while ((pos = data.find(sep)) != string::npos) { + node = data.substr(0, pos); + nodes.push_back(node); + data.erase(0, pos + sep.length()); + } + return deserialize(nodes); + } + + TreeNode* deserialize(list& data) { + if (data.empty()) return nullptr; + string first = data.front(); + data.pop_front(); + if (first == empty) return nullptr; + TreeNode* root = new TreeNode(stoi(first)); + root->left = deserialize(data); + root->right = deserialize(data); + return root; + } +}; + +// Your Codec object will be instantiated and called as such: +// Codec codec; +// codec.deserialize(codec.serialize(root)); \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23037. \345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/Solution2.js" "b/lcof/\351\235\242\350\257\225\351\242\23037. \345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/Solution2.js" new file mode 100644 index 0000000000000..dcb4b708b97ee --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23037. \345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/Solution2.js" @@ -0,0 +1,48 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ + +/** + * Encodes a tree to a single string. + * + * @param {TreeNode} root + * @return {string} + */ +var serialize = function (root) { + if (root == null) { + return '#'; + } + const { val, left, right } = root; + return `${val},${serialize(left)},${serialize(right)}`; +}; + +/** + * Decodes your encoded data to tree. + * + * @param {string} data + * @return {TreeNode} + */ +var deserialize = function (data) { + const vals = data.split(','); + let index = 0; + const dfs = () => { + if (vals[index] == '#') { + index++; + return null; + } + const res = new TreeNode(vals[index++]); + res.left = dfs(); + res.right = dfs(); + return res; + }; + return dfs(); +}; + +/** + * Your functions will be called as such: + * deserialize(serialize(root)); + */ diff --git "a/lcof/\351\235\242\350\257\225\351\242\23037. \345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/Solution3.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23037. \345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/Solution3.cpp" new file mode 100644 index 0000000000000..ad1b80f821b46 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23037. \345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/Solution3.cpp" @@ -0,0 +1,52 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Codec { +public: + string empty = "#"; + string sep = ","; + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + if (!root) return empty + sep; + string res = ""; + res += serialize(root->left); + res += serialize(root->right); + res += to_string(root->val) + sep; + return res; + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + vector nodes; + size_t pos = 0; + string node; + while ((pos = data.find(sep)) != string::npos) { + node = data.substr(0, pos); + nodes.push_back(node); + data.erase(0, pos + sep.length()); + } + return deserialize(nodes); + } + + TreeNode* deserialize(vector& nodes) { + if (nodes.empty()) return nullptr; + string front = nodes.back(); + nodes.pop_back(); + if (front == empty) return nullptr; + TreeNode* root = new TreeNode(stoi(front)); + // 先构造右子树,后构造左子树 + root->right = deserialize(nodes); + root->left = deserialize(nodes); + return root; + } +}; + +// Your Codec object will be instantiated and called as such: +// Codec codec; +// codec.deserialize(codec.serialize(root)); \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23038. \345\255\227\347\254\246\344\270\262\347\232\204\346\216\222\345\210\227/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23038. \345\255\227\347\254\246\344\270\262\347\232\204\346\216\222\345\210\227/Solution.cs" index 642789333608e..c92628d8725f3 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23038. \345\255\227\347\254\246\344\270\262\347\232\204\346\216\222\345\210\227/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23038. \345\255\227\347\254\246\344\270\262\347\232\204\346\216\222\345\210\227/Solution.cs" @@ -1,25 +1,25 @@ -public class Solution { - private char[] cs; - private List ans = new List(); - - public string[] Permutation(string s) { - cs = s.ToCharArray(); - dfs(0); - return ans.ToArray(); - } - - private void dfs(int i) { - if (i == cs.Length - 1) { - ans.Add(new string(cs)); - return; - } - var vis = new HashSet(); - for (int j = i; j < cs.Length; ++j) { - if (vis.Add(cs[j])) { - (cs[i], cs[j]) = (cs[j], cs[i]); - dfs(i + 1); - (cs[i], cs[j]) = (cs[j], cs[i]); - } - } - } -} \ No newline at end of file +public class Solution { + private char[] cs; + private List ans = new List(); + + public string[] Permutation(string s) { + cs = s.ToCharArray(); + dfs(0); + return ans.ToArray(); + } + + private void dfs(int i) { + if (i == cs.Length - 1) { + ans.Add(new string(cs)); + return; + } + var vis = new HashSet(); + for (int j = i; j < cs.Length; ++j) { + if (vis.Add(cs[j])) { + (cs[i], cs[j]) = (cs[j], cs[i]); + dfs(i + 1); + (cs[i], cs[j]) = (cs[j], cs[i]); + } + } + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23039. \346\225\260\347\273\204\344\270\255\345\207\272\347\216\260\346\254\241\346\225\260\350\266\205\350\277\207\344\270\200\345\215\212\347\232\204\346\225\260\345\255\227/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23039. \346\225\260\347\273\204\344\270\255\345\207\272\347\216\260\346\254\241\346\225\260\350\266\205\350\277\207\344\270\200\345\215\212\347\232\204\346\225\260\345\255\227/Solution.cs" index 7a5ed76de0bc5..5cdbb1af6f963 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23039. \346\225\260\347\273\204\344\270\255\345\207\272\347\216\260\346\254\241\346\225\260\350\266\205\350\277\207\344\270\200\345\215\212\347\232\204\346\225\260\345\255\227/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23039. \346\225\260\347\273\204\344\270\255\345\207\272\347\216\260\346\254\241\346\225\260\350\266\205\350\277\207\344\270\200\345\215\212\347\232\204\346\225\260\345\255\227/Solution.cs" @@ -15,4 +15,4 @@ public int MajorityElement(int[] nums) { } return m; } -} \ No newline at end of file +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.cpp" index 672f4f9b58ca9..0802153bce420 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.cpp" +++ "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.cpp" @@ -1,27 +1,7 @@ class Solution { public: vector getLeastNumbers(vector& arr, int k) { - int n = arr.size(); - function(int, int)> quickSort = [&](int l, int r) -> vector { - int i = l, j = r; - while (i < j) { - while (i < j && arr[j] >= arr[l]) { - --j; - } - while (i < j && arr[i] <= arr[l]) { - ++i; - } - swap(arr[i], arr[j]); - } - swap(arr[i], arr[l]); - if (k < i) { - return quickSort(l, i - 1); - } - if (k > i) { - return quickSort(i + 1, r); - } - return vector(arr.begin(), arr.begin() + k); - }; - return k == n ? arr : quickSort(0, n - 1); + sort(arr.begin(), arr.end()); + return vector(arr.begin(), arr.begin() + k); } }; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.cs" index de39cb8123844..697966212293e 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.cs" @@ -1,6 +1,6 @@ -public class Solution { - public int[] GetLeastNumbers(int[] arr, int k) { - Array.Sort(arr); - return arr[..k]; - } -} \ No newline at end of file +public class Solution { + public int[] GetLeastNumbers(int[] arr, int k) { + Array.Sort(arr); + return arr[..k]; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.go" "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.go" index 3d19d6a88f645..02c83654c517d 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.go" +++ "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.go" @@ -1,28 +1,4 @@ func getLeastNumbers(arr []int, k int) []int { - n := len(arr) - if k == n { - return arr - } - var quickSort func(l, r int) []int - quickSort = func(l, r int) []int { - i, j := l, r - for i < j { - for i < j && arr[j] >= arr[l] { - j-- - } - for i < j && arr[i] <= arr[l] { - i++ - } - arr[i], arr[j] = arr[j], arr[i] - } - arr[i], arr[l] = arr[l], arr[i] - if k < i { - return quickSort(l, i-1) - } - if k > i { - return quickSort(i+1, r) - } - return arr[:k] - } - return quickSort(0, n-1) + sort.Ints(arr) + return arr[:k] } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.java" "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.java" index da7e24187fef5..db2e06f6f887f 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.java" +++ "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.java" @@ -1,38 +1,10 @@ class Solution { - private int[] arr; - private int k; - public int[] getLeastNumbers(int[] arr, int k) { - int n = arr.length; - this.arr = arr; - this.k = k; - return k == n ? arr : quickSort(0, n - 1); - } - - private int[] quickSort(int l, int r) { - int i = l, j = r; - while (i < j) { - while (i < j && arr[j] >= arr[l]) { - --j; - } - while (i < j && arr[i] <= arr[l]) { - ++i; - } - swap(i, j); - } - swap(i, l); - if (k < i) { - return quickSort(l, i - 1); + Arrays.sort(arr); + int[] ans = new int[k]; + for (int i = 0; i < k; ++i) { + ans[i] = arr[i]; } - if (k > i) { - return quickSort(i + 1, r); - } - return Arrays.copyOf(arr, k); - } - - private void swap(int i, int j) { - int t = arr[i]; - arr[i] = arr[j]; - arr[j] = t; + return ans; } } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.py" "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.py" index 4277f3a38ed1f..ad48df3966efe 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.py" +++ "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution.py" @@ -1,19 +1,4 @@ class Solution: def getLeastNumbers(self, arr: List[int], k: int) -> List[int]: - def quick_sort(l, r): - i, j = l, r - while i < j: - while i < j and arr[j] >= arr[l]: - j -= 1 - while i < j and arr[i] <= arr[l]: - i += 1 - arr[i], arr[j] = arr[j], arr[i] - arr[i], arr[l] = arr[l], arr[i] - if k < i: - return quick_sort(l, i - 1) - if k > i: - return quick_sort(i + 1, r) - return arr[:k] - - n = len(arr) - return arr if k == n else quick_sort(0, n - 1) + arr.sort() + return arr[:k] diff --git "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution2.cpp" new file mode 100644 index 0000000000000..a71eff9308f2c --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution2.cpp" @@ -0,0 +1,18 @@ +class Solution { +public: + vector getLeastNumbers(vector& arr, int k) { + priority_queue q; + for (int& x : arr) { + q.push(x); + if (q.size() > k) { + q.pop(); + } + } + vector ans(k); + for (int i = 0; i < k; ++i) { + ans[i] = q.top(); + q.pop(); + } + return ans; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution2.go" new file mode 100644 index 0000000000000..ed128ddd63e4f --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution2.go" @@ -0,0 +1,26 @@ +func getLeastNumbers(arr []int, k int) (ans []int) { + q := hp{} + for _, x := range arr { + heap.Push(&q, x) + if q.Len() > k { + heap.Pop(&q) + } + } + for i := 0; i < k; i++ { + ans = append(ans, heap.Pop(&q).(int)) + } + return +} + +type hp struct{ sort.IntSlice } + +func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } +func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) } +func (h *hp) Pop() any { + a := h.IntSlice + v := a[len(a)-1] + h.IntSlice = a[:len(a)-1] + return v +} +func (h *hp) push(v int) { heap.Push(h, v) } +func (h *hp) pop() int { return heap.Pop(h).(int) } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution2.java" new file mode 100644 index 0000000000000..3584ad60d21e6 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution2.java" @@ -0,0 +1,16 @@ +class Solution { + public int[] getLeastNumbers(int[] arr, int k) { + PriorityQueue q = new PriorityQueue<>((a, b) -> b - a); + for (int x : arr) { + q.offer(x); + if (q.size() > k) { + q.poll(); + } + } + int[] ans = new int[k]; + for (int i = 0; i < k; ++i) { + ans[i] = q.poll(); + } + return ans; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution2.py" new file mode 100644 index 0000000000000..157b7fb74b684 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution2.py" @@ -0,0 +1,8 @@ +class Solution: + def getLeastNumbers(self, arr: List[int], k: int) -> List[int]: + h = [] + for x in arr: + heappush(h, -x) + if len(h) > k: + heappop(h) + return [-x for x in h] diff --git "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution3.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution3.cpp" new file mode 100644 index 0000000000000..672f4f9b58ca9 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution3.cpp" @@ -0,0 +1,27 @@ +class Solution { +public: + vector getLeastNumbers(vector& arr, int k) { + int n = arr.size(); + function(int, int)> quickSort = [&](int l, int r) -> vector { + int i = l, j = r; + while (i < j) { + while (i < j && arr[j] >= arr[l]) { + --j; + } + while (i < j && arr[i] <= arr[l]) { + ++i; + } + swap(arr[i], arr[j]); + } + swap(arr[i], arr[l]); + if (k < i) { + return quickSort(l, i - 1); + } + if (k > i) { + return quickSort(i + 1, r); + } + return vector(arr.begin(), arr.begin() + k); + }; + return k == n ? arr : quickSort(0, n - 1); + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution3.go" "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution3.go" new file mode 100644 index 0000000000000..3d19d6a88f645 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution3.go" @@ -0,0 +1,28 @@ +func getLeastNumbers(arr []int, k int) []int { + n := len(arr) + if k == n { + return arr + } + var quickSort func(l, r int) []int + quickSort = func(l, r int) []int { + i, j := l, r + for i < j { + for i < j && arr[j] >= arr[l] { + j-- + } + for i < j && arr[i] <= arr[l] { + i++ + } + arr[i], arr[j] = arr[j], arr[i] + } + arr[i], arr[l] = arr[l], arr[i] + if k < i { + return quickSort(l, i-1) + } + if k > i { + return quickSort(i+1, r) + } + return arr[:k] + } + return quickSort(0, n-1) +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution3.java" "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution3.java" new file mode 100644 index 0000000000000..da7e24187fef5 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution3.java" @@ -0,0 +1,38 @@ +class Solution { + private int[] arr; + private int k; + + public int[] getLeastNumbers(int[] arr, int k) { + int n = arr.length; + this.arr = arr; + this.k = k; + return k == n ? arr : quickSort(0, n - 1); + } + + private int[] quickSort(int l, int r) { + int i = l, j = r; + while (i < j) { + while (i < j && arr[j] >= arr[l]) { + --j; + } + while (i < j && arr[i] <= arr[l]) { + ++i; + } + swap(i, j); + } + swap(i, l); + if (k < i) { + return quickSort(l, i - 1); + } + if (k > i) { + return quickSort(i + 1, r); + } + return Arrays.copyOf(arr, k); + } + + private void swap(int i, int j) { + int t = arr[i]; + arr[i] = arr[j]; + arr[j] = t; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution3.py" "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution3.py" new file mode 100644 index 0000000000000..4277f3a38ed1f --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/Solution3.py" @@ -0,0 +1,19 @@ +class Solution: + def getLeastNumbers(self, arr: List[int], k: int) -> List[int]: + def quick_sort(l, r): + i, j = l, r + while i < j: + while i < j and arr[j] >= arr[l]: + j -= 1 + while i < j and arr[i] <= arr[l]: + i += 1 + arr[i], arr[j] = arr[j], arr[i] + arr[i], arr[l] = arr[l], arr[i] + if k < i: + return quick_sort(l, i - 1) + if k > i: + return quick_sort(i + 1, r) + return arr[:k] + + n = len(arr) + return arr if k == n else quick_sort(0, n - 1) diff --git "a/lcof/\351\235\242\350\257\225\351\242\23041. \346\225\260\346\215\256\346\265\201\344\270\255\347\232\204\344\270\255\344\275\215\346\225\260/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23041. \346\225\260\346\215\256\346\265\201\344\270\255\347\232\204\344\270\255\344\275\215\346\225\260/Solution.cs" index 6830ebed30865..9ec974fe07e5f 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23041. \346\225\260\346\215\256\346\265\201\344\270\255\347\232\204\344\270\255\344\275\215\346\225\260/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23041. \346\225\260\346\215\256\346\265\201\344\270\255\347\232\204\344\270\255\344\275\215\346\225\260/Solution.cs" @@ -1,56 +1,56 @@ -public class MedianFinder { - private List nums; - private int curIndex; - - /** initialize your data structure here. */ - public MedianFinder() { - nums = new List(); - } - - private int FindIndex(int val) { - int left = 0; - int right = nums.Count - 1; - while (left <= right) { - int mid = left + (right - left) / 2; - if (val > nums[mid]) { - left = mid + 1; - } else { - right = mid - 1; - } - } - return left; - } - - public void AddNum(int num) { - if (nums.Count == 0) { - nums.Add(num); - curIndex = 0; - } else { - curIndex = FindIndex(num); - if (curIndex == nums.Count) { - nums.Add(num); - } else { - nums.Insert(curIndex, num); - } - } - } - - public double FindMedian() { - if (nums.Count % 2 == 1) { - return (double)nums[nums.Count / 2]; - } else { - if (nums.Count == 0) { - return 0; - } else { - return (double) (nums[nums.Count / 2 - 1] + nums[nums.Count / 2]) / 2; - } - } - } -} - -/** - * Your MedianFinder object will be instantiated and called as such: - * MedianFinder obj = new MedianFinder(); - * obj.AddNum(num); - * double param_2 = obj.FindMedian(); - */ \ No newline at end of file +public class MedianFinder { + private List nums; + private int curIndex; + + /** initialize your data structure here. */ + public MedianFinder() { + nums = new List(); + } + + private int FindIndex(int val) { + int left = 0; + int right = nums.Count - 1; + while (left <= right) { + int mid = left + (right - left) / 2; + if (val > nums[mid]) { + left = mid + 1; + } else { + right = mid - 1; + } + } + return left; + } + + public void AddNum(int num) { + if (nums.Count == 0) { + nums.Add(num); + curIndex = 0; + } else { + curIndex = FindIndex(num); + if (curIndex == nums.Count) { + nums.Add(num); + } else { + nums.Insert(curIndex, num); + } + } + } + + public double FindMedian() { + if (nums.Count % 2 == 1) { + return (double)nums[nums.Count / 2]; + } else { + if (nums.Count == 0) { + return 0; + } else { + return (double) (nums[nums.Count / 2 - 1] + nums[nums.Count / 2]) / 2; + } + } + } +} + +/** + * Your MedianFinder object will be instantiated and called as such: + * MedianFinder obj = new MedianFinder(); + * obj.AddNum(num); + * double param_2 = obj.FindMedian(); + */ diff --git "a/lcof/\351\235\242\350\257\225\351\242\23041. \346\225\260\346\215\256\346\265\201\344\270\255\347\232\204\344\270\255\344\275\215\346\225\260/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23041. \346\225\260\346\215\256\346\265\201\344\270\255\347\232\204\344\270\255\344\275\215\346\225\260/Solution2.py" new file mode 100644 index 0000000000000..ba0aa0cd2532e --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23041. \346\225\260\346\215\256\346\265\201\344\270\255\347\232\204\344\270\255\344\275\215\346\225\260/Solution2.py" @@ -0,0 +1,24 @@ +from sortedcontainers import SortedList + + +class MedianFinder: + def __init__(self): + """ + initialize your data structure here. + """ + self.sl = SortedList() + + def addNum(self, num: int) -> None: + self.sl.add(num) + + def findMedian(self) -> float: + n = len(self.sl) + if n & 1: + return self.sl[n // 2] + return (self.sl[(n - 1) // 2] + self.sl[n // 2]) / 2 + + +# Your MedianFinder object will be instantiated and called as such: +# obj = MedianFinder() +# obj.addNum(num) +# param_2 = obj.findMedian() diff --git "a/lcof/\351\235\242\350\257\225\351\242\23042. \350\277\236\347\273\255\345\255\220\346\225\260\347\273\204\347\232\204\346\234\200\345\244\247\345\222\214/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23042. \350\277\236\347\273\255\345\255\220\346\225\260\347\273\204\347\232\204\346\234\200\345\244\247\345\222\214/Solution.cs" index a77ff0d1a9b02..1f802d8dfc904 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23042. \350\277\236\347\273\255\345\255\220\346\225\260\347\273\204\347\232\204\346\234\200\345\244\247\345\222\214/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23042. \350\277\236\347\273\255\345\255\220\346\225\260\347\273\204\347\232\204\346\234\200\345\244\247\345\222\214/Solution.cs" @@ -1,11 +1,11 @@ -public class Solution { - public int MaxSubArray(int[] nums) { - int ans = -1000000000; - int f = 0; - foreach (int x in nums) { - f = Math.Max(f, 0) + x; - ans = Math.Max(ans, f); - } - return ans; - } -} \ No newline at end of file +public class Solution { + public int MaxSubArray(int[] nums) { + int ans = -1000000000; + int f = 0; + foreach (int x in nums) { + f = Math.Max(f, 0) + x; + ans = Math.Max(ans, f); + } + return ans; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23043. 1\357\275\236n\346\225\264\346\225\260\344\270\2551\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23043. 1\357\275\236n\346\225\264\346\225\260\344\270\2551\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/Solution.cs" index 4fd8e2ffdee0e..67267adcb6524 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23043. 1\357\275\236n\346\225\264\346\225\260\344\270\2551\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23043. 1\357\275\236n\346\225\264\346\225\260\344\270\2551\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/Solution.cs" @@ -1,11 +1,11 @@ -public class Solution { - public int CountDigitOne(int n) { - long mulk = 1; - int ans = 0; - for (int k = 0; n >= mulk; ++k) { - ans += (int) (n / (mulk * 10) * mulk) + (int) Math.Min(Math.Max(n % (mulk * 10) - mulk + 1, 0), mulk); - mulk *= 10; - } - return ans; - } -} \ No newline at end of file +public class Solution { + public int CountDigitOne(int n) { + long mulk = 1; + int ans = 0; + for (int k = 0; n >= mulk; ++k) { + ans += (int) (n / (mulk * 10) * mulk) + (int) Math.Min(Math.Max(n % (mulk * 10) - mulk + 1, 0), mulk); + mulk *= 10; + } + return ans; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/Solution.cs" index 4b391421a19d8..483966882445d 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/Solution.cs" @@ -1,13 +1,13 @@ -public class Solution { - public int FindNthDigit(int n) { - int k = 1, cnt = 9; - while ((long) k * cnt < n) { - n -= k * cnt; - ++k; - cnt *= 10; - } - int num = (int) Math.Pow(10, k - 1) + (n - 1) / k; - int idx = (n - 1) % k; - return num.ToString()[idx] - '0'; - } -} \ No newline at end of file +public class Solution { + public int FindNthDigit(int n) { + int k = 1, cnt = 9; + while ((long) k * cnt < n) { + n -= k * cnt; + ++k; + cnt *= 10; + } + int num = (int) Math.Pow(10, k - 1) + (n - 1) / k; + int idx = (n - 1) % k; + return num.ToString()[idx] - '0'; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/Solution2.cpp" new file mode 100644 index 0000000000000..7fa9ff8bb188a --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/Solution2.cpp" @@ -0,0 +1,17 @@ +class Solution { +public: + int findNthDigit(int n) { + if (n < 10) { + return n; + } + n -= 10; + int k = 2, p = 10; + while (n >= 9ll * k * p) { + n -= 9 * k * p; + ++k; + p *= 10; + } + int x = p + n / k; + return to_string(x)[n % k] - '0'; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/Solution2.go" new file mode 100644 index 0000000000000..28e4d913217ac --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/Solution2.go" @@ -0,0 +1,14 @@ +func findNthDigit(n int) int { + if n < 10 { + return n + } + n -= 10 + k, p := 2, 10 + for n >= 9*k*p { + n -= 9 * k * p + k++ + p *= 10 + } + x := p + n/k + return int(strconv.Itoa(x)[n%k] - '0') +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/Solution2.java" new file mode 100644 index 0000000000000..4dcbebf230792 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/Solution2.java" @@ -0,0 +1,16 @@ +class Solution { + public int findNthDigit(int n) { + if (n < 10) { + return n; + } + n -= 10; + int k = 2, p = 10; + while (n >= (long) 9 * k * p) { + n -= 9 * k * p; + ++k; + p *= 10; + } + int x = p + n / k; + return String.valueOf(x).charAt(n % k) - '0'; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/Solution2.py" new file mode 100644 index 0000000000000..05bc175b512b9 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/Solution2.py" @@ -0,0 +1,12 @@ +class Solution: + def findNthDigit(self, n: int) -> int: + if n < 10: + return n + n -= 10 + k, p = 2, 10 + while n >= 9 * k * p: + n -= 9 * k * p + k += 1 + p *= 10 + x = p + n // k + return int(str(x)[n % k]) diff --git "a/lcof/\351\235\242\350\257\225\351\242\23045. \346\212\212\346\225\260\347\273\204\346\216\222\346\210\220\346\234\200\345\260\217\347\232\204\346\225\260/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23045. \346\212\212\346\225\260\347\273\204\346\216\222\346\210\220\346\234\200\345\260\217\347\232\204\346\225\260/Solution.cs" index 38bccdf2d25ca..459dbd446f4bd 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23045. \346\212\212\346\225\260\347\273\204\346\216\222\346\210\220\346\234\200\345\260\217\347\232\204\346\225\260/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23045. \346\212\212\346\225\260\347\273\204\346\216\222\346\210\220\346\234\200\345\260\217\347\232\204\346\225\260/Solution.cs" @@ -1,10 +1,10 @@ -public class Solution { - public string MinNumber(int[] nums) { - List ans = new List(); - foreach (int x in nums) { - ans.Add(x.ToString()); - } - ans.Sort((a, b) => (a + b).CompareTo(b + a)); - return string.Join("", ans); - } -} \ No newline at end of file +public class Solution { + public string MinNumber(int[] nums) { + List ans = new List(); + foreach (int x in nums) { + ans.Add(x.ToString()); + } + ans.Sort((a, b) => (a + b).CompareTo(b + a)); + return string.Join("", ans); + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.cpp" index 15179eacc3aef..d0c550b4d2048 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.cpp" +++ "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.cpp" @@ -3,15 +3,20 @@ class Solution { int translateNum(int num) { string s = to_string(num); int n = s.size(); - int a = 1, b = 1; - for (int i = 1; i < n; ++i) { - int c = b; - if (s[i - 1] == '1' || (s[i - 1] == '2' && s[i] < '6')) { - c += a; + int f[12]{}; + function dfs = [&](int i) -> int { + if (i >= n - 1) { + return 1; } - a = b; - b = c; - } - return b; + if (f[i]) { + return f[i]; + } + int ans = dfs(i + 1); + if (s[i] == '1' || (s[i] == '2' && s[i + 1] < '6')) { + ans += dfs(i + 2); + } + return f[i] = ans; + }; + return dfs(0); } }; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.cs" index fcd772ecb3d60..c887930edbca5 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.cs" @@ -1,16 +1,16 @@ -public class Solution { - public int TranslateNum(int num) { - var s = num.ToString(); - int n = s.Length; - int a = 1, b = 1; - for (int i = 1; i < n; ++i) { - int c = b; - if (s[i - 1] == '1' || (s[i - 1] == '2' && s[i] < '6')) { - c += a; - } - a = b; - b = c; - } - return b; - } -} \ No newline at end of file +public class Solution { + public int TranslateNum(int num) { + var s = num.ToString(); + int n = s.Length; + int a = 1, b = 1; + for (int i = 1; i < n; ++i) { + int c = b; + if (s[i - 1] == '1' || (s[i - 1] == '2' && s[i] < '6')) { + c += a; + } + a = b; + b = c; + } + return b; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.go" "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.go" index eec272141e0d1..d247fddc9f3a3 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.go" +++ "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.go" @@ -1,13 +1,21 @@ func translateNum(num int) int { s := strconv.Itoa(num) n := len(s) - a, b := 1, 1 - for i := 1; i < n; i++ { - c := b - if s[i-1] == '1' || (s[i-1] == '2' && s[i] < '6') { - c += a + f := [12]int{} + var dfs func(int) int + dfs = func(i int) int { + if i >= n-1 { + return 1 } - a, b = b, c + if f[i] != 0 { + return f[i] + } + ans := dfs(i + 1) + if s[i] == '1' || (s[i] == '2' && s[i+1] < '6') { + ans += dfs(i + 2) + } + f[i] = ans + return ans } - return b + return dfs(0) } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.java" "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.java" index b3cad40a23fca..8eb62b03c58b6 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.java" +++ "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.java" @@ -1,16 +1,26 @@ class Solution { + private int n; + private char[] s; + private Integer[] f; + public int translateNum(int num) { - char[] s = String.valueOf(num).toCharArray(); - int n = s.length; - int a = 1, b = 1; - for (int i = 1; i < n; ++i) { - int c = b; - if (s[i - 1] == '1' || (s[i - 1] == '2' && s[i] < '6')) { - c += a; - } - a = b; - b = c; + s = String.valueOf(num).toCharArray(); + n = s.length; + f = new Integer[n]; + return dfs(0); + } + + private int dfs(int i) { + if (i >= n - 1) { + return 1; + } + if (f[i] != null) { + return f[i]; + } + int ans = dfs(i + 1); + if (s[i] == '1' || (s[i] == '2' && s[i + 1] < '6')) { + ans += dfs(i + 2); } - return b; + return f[i] = ans; } } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.js" "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.js" index 4fb135940418e..d20b95f809d97 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.js" +++ "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.js" @@ -5,15 +5,20 @@ var translateNum = function (num) { const s = num.toString(); const n = s.length; - let a = 1; - let b = 1; - for (let i = 1; i < n; ++i) { - let c = b; - if (s[i - 1] === '1' || (s[i - 1] === '2' && s[i] < '6')) { - c += a; + const f = new Array(n).fill(0); + const dfs = i => { + if (i >= n - 1) { + return 1; } - a = b; - b = c; - } - return b; + if (f[i]) { + return f[i]; + } + let ans = dfs(i + 1); + if (s[i] === '1' || (s[i] === '2' && s[i + 1] < '6')) { + ans += dfs(i + 2); + } + f[i] = ans; + return ans; + }; + return dfs(0); }; diff --git "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.py" "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.py" index 09cd33e087a77..fd08323a2008f 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.py" +++ "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.py" @@ -1,11 +1,14 @@ class Solution: def translateNum(self, num: int) -> int: + @cache + def dfs(i): + if i >= n - 1: + return 1 + ans = dfs(i + 1) + if s[i] == "1" or (s[i] == "2" and s[i + 1] < "6"): + ans += dfs(i + 2) + return ans + s = str(num) n = len(s) - a = b = 1 - for i in range(1, n): - c = b - if s[i - 1] == "1" or (s[i - 1] == "2" and s[i] < "6"): - c += a - a, b = b, c - return b + return dfs(0) diff --git "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.ts" "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.ts" index df7d66546c804..b8edce0af1c86 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.ts" +++ "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.ts" @@ -1,15 +1,20 @@ function translateNum(num: number): number { const s = num.toString(); const n = s.length; - let a = 1; - let b = 1; - for (let i = 1; i < n; ++i) { - let c = b; - if (s[i - 1] === '1' || (s[i - 1] === '2' && s[i] < '6')) { - c += a; + const f = new Array(n).fill(0); + const dfs = (i: number): number => { + if (i >= n - 1) { + return 1; } - a = b; - b = c; - } - return b; + if (f[i]) { + return f[i]; + } + let ans = dfs(i + 1); + if (s[i] === '1' || (s[i] === '2' && s[i + 1] < '6')) { + ans += dfs(i + 2); + } + f[i] = ans; + return ans; + }; + return dfs(0); } diff --git "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.cpp" new file mode 100644 index 0000000000000..15179eacc3aef --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.cpp" @@ -0,0 +1,17 @@ +class Solution { +public: + int translateNum(int num) { + string s = to_string(num); + int n = s.size(); + int a = 1, b = 1; + for (int i = 1; i < n; ++i) { + int c = b; + if (s[i - 1] == '1' || (s[i - 1] == '2' && s[i] < '6')) { + c += a; + } + a = b; + b = c; + } + return b; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.go" new file mode 100644 index 0000000000000..eec272141e0d1 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.go" @@ -0,0 +1,13 @@ +func translateNum(num int) int { + s := strconv.Itoa(num) + n := len(s) + a, b := 1, 1 + for i := 1; i < n; i++ { + c := b + if s[i-1] == '1' || (s[i-1] == '2' && s[i] < '6') { + c += a + } + a, b = b, c + } + return b +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.java" new file mode 100644 index 0000000000000..b3cad40a23fca --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.java" @@ -0,0 +1,16 @@ +class Solution { + public int translateNum(int num) { + char[] s = String.valueOf(num).toCharArray(); + int n = s.length; + int a = 1, b = 1; + for (int i = 1; i < n; ++i) { + int c = b; + if (s[i - 1] == '1' || (s[i - 1] == '2' && s[i] < '6')) { + c += a; + } + a = b; + b = c; + } + return b; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.js" "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.js" new file mode 100644 index 0000000000000..4fb135940418e --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.js" @@ -0,0 +1,19 @@ +/** + * @param {number} num + * @return {number} + */ +var translateNum = function (num) { + const s = num.toString(); + const n = s.length; + let a = 1; + let b = 1; + for (let i = 1; i < n; ++i) { + let c = b; + if (s[i - 1] === '1' || (s[i - 1] === '2' && s[i] < '6')) { + c += a; + } + a = b; + b = c; + } + return b; +}; diff --git "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.py" new file mode 100644 index 0000000000000..00c29735313b3 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.py" @@ -0,0 +1,11 @@ +class Solution: + def translateNum(self, num: int) -> int: + s = str(num) + n = len(s) + a = b = 1 + for i in range(1, n): + c = b + if s[i - 1] == '1' or (s[i - 1] == '2' and s[i] < '6'): + c += a + a, b = b, c + return b diff --git "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.rs" "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.rs" new file mode 100644 index 0000000000000..465d8d1cb03ad --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.rs" @@ -0,0 +1,20 @@ +impl Solution { + fn dfs(s: &String, i: usize, res: &mut i32) { + if i >= s.len() { + return; + } + let val = s[i - 1..=i].parse::().unwrap(); + if val >= 10 && val <= 25 { + *res += 1; + Self::dfs(s, i + 2, res); + } + Self::dfs(s, i + 1, res); + } + + pub fn translate_num(num: i32) -> i32 { + let s = num.to_string(); + let mut res = 1; + Self::dfs(&s, 1, &mut res); + res + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.ts" "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.ts" new file mode 100644 index 0000000000000..df7d66546c804 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution2.ts" @@ -0,0 +1,15 @@ +function translateNum(num: number): number { + const s = num.toString(); + const n = s.length; + let a = 1; + let b = 1; + for (let i = 1; i < n; ++i) { + let c = b; + if (s[i - 1] === '1' || (s[i - 1] === '2' && s[i] < '6')) { + c += a; + } + a = b; + b = c; + } + return b; +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.cpp" index 3da038ff05078..aeb6a04d4cb2a 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.cpp" +++ "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.cpp" @@ -2,12 +2,12 @@ class Solution { public: int maxValue(vector>& grid) { int m = grid.size(), n = grid[0].size(); - vector> f(2, vector(n + 1, 0)); + vector> f(m + 1, vector(n + 1, 0)); for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { - f[i & 1][j] = max(f[i & 1 ^ 1][j], f[i & 1][j - 1]) + grid[i - 1][j - 1]; + f[i][j] = max(f[i - 1][j], f[i][j - 1]) + grid[i - 1][j - 1]; } } - return f[m & 1][n]; + return f[m][n]; } }; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.cs" index 9a764b3fee407..efad6d7ef1e96 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.cs" @@ -1,12 +1,12 @@ -public class Solution { - public int MaxValue(int[][] grid) { - int m = grid.Length, n = grid[0].Length; - int[, ] f = new int[m + 1, n + 1]; - for (int i = 1; i < m + 1; i++) { - for (int j = 1; j < n + 1; j++) { - f[i, j] = Math.Max(f[i - 1, j], f[i, j - 1]) + grid[i - 1][j - 1]; - } - } - return f[m, n]; - } -} \ No newline at end of file +public class Solution { + public int MaxValue(int[][] grid) { + int m = grid.Length, n = grid[0].Length; + int[, ] f = new int[m + 1, n + 1]; + for (int i = 1; i < m + 1; i++) { + for (int j = 1; j < n + 1; j++) { + f[i, j] = Math.Max(f[i - 1, j], f[i, j - 1]) + grid[i - 1][j - 1]; + } + } + return f[m, n]; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.go" "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.go" index fbf618d8fa36a..9773d64e1e149 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.go" +++ "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.go" @@ -1,13 +1,13 @@ func maxValue(grid [][]int) int { m, n := len(grid), len(grid[0]) - f := make([][]int, 2) + f := make([][]int, m+1) for i := range f { f[i] = make([]int, n+1) } for i := 1; i <= m; i++ { for j := 1; j <= n; j++ { - f[i&1][j] = max(f[i&1^1][j], f[i&1][j-1]) + grid[i-1][j-1] + f[i][j] = max(f[i-1][j], f[i][j-1]) + grid[i-1][j-1] } } - return f[m&1][n] + return f[m][n] } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.java" "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.java" index 1aa5127239907..714e796891c38 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.java" +++ "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.java" @@ -1,12 +1,12 @@ class Solution { public int maxValue(int[][] grid) { int m = grid.length, n = grid[0].length; - int[][] f = new int[2][n + 1]; + int[][] f = new int[m + 1][n + 1]; for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { - f[i & 1][j] = Math.max(f[i & 1 ^ 1][j], f[i & 1][j - 1]) + grid[i - 1][j - 1]; + f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]) + grid[i - 1][j - 1]; } } - return f[m & 1][n]; + return f[m][n]; } } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.js" "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.js" index 2a068ed97a29b..5b0e746705964 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.js" +++ "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.js" @@ -5,11 +5,11 @@ var maxValue = function (grid) { const m = grid.length; const n = grid[0].length; - const f = new Array(2).fill(0).map(() => new Array(n + 1).fill(0)); + const f = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); for (let i = 1; i <= m; ++i) { for (let j = 1; j <= n; ++j) { - f[i & 1][j] = Math.max(f[(i & 1) ^ 1][j], f[i & 1][j - 1]) + grid[i - 1][j - 1]; + f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]) + grid[i - 1][j - 1]; } } - return f[m & 1][n]; + return f[m][n]; }; diff --git "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.py" "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.py" index a1dd3b4c4bffb..98e8272191ec2 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.py" +++ "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.py" @@ -1,8 +1,8 @@ class Solution: def maxValue(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) - f = [[0] * (n + 1) for _ in range(2)] + f = [[0] * (n + 1) for _ in range(m + 1)] for i, row in enumerate(grid, 1): for j, v in enumerate(row, 1): - f[i & 1][j] = max(f[i & 1 ^ 1][j], f[i & 1][j - 1]) + v - return f[m & 1][n] + f[i][j] = max(f[i - 1][j], f[i][j - 1]) + v + return f[m][n] diff --git "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.ts" "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.ts" index 5b9d58e4ff7fc..30f874d6833fc 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.ts" +++ "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution.ts" @@ -1,11 +1,11 @@ function maxValue(grid: number[][]): number { const m = grid.length; const n = grid[0].length; - const f = Array.from({ length: 2 }, _ => new Array(n + 1).fill(0)); + const f = Array.from({ length: m + 1 }, _ => new Array(n + 1).fill(0)); for (let i = 1; i <= m; ++i) { for (let j = 1; j <= n; ++j) { - f[i & 1][j] = Math.max(f[(i & 1) ^ 1][j], f[i & 1][j - 1]) + grid[i - 1][j - 1]; + f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]) + grid[i - 1][j - 1]; } } - return f[m & 1][n]; + return f[m][n]; } diff --git "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution2.cpp" new file mode 100644 index 0000000000000..3da038ff05078 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution2.cpp" @@ -0,0 +1,13 @@ +class Solution { +public: + int maxValue(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + vector> f(2, vector(n + 1, 0)); + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + f[i & 1][j] = max(f[i & 1 ^ 1][j], f[i & 1][j - 1]) + grid[i - 1][j - 1]; + } + } + return f[m & 1][n]; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution2.go" new file mode 100644 index 0000000000000..fbf618d8fa36a --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution2.go" @@ -0,0 +1,13 @@ +func maxValue(grid [][]int) int { + m, n := len(grid), len(grid[0]) + f := make([][]int, 2) + for i := range f { + f[i] = make([]int, n+1) + } + for i := 1; i <= m; i++ { + for j := 1; j <= n; j++ { + f[i&1][j] = max(f[i&1^1][j], f[i&1][j-1]) + grid[i-1][j-1] + } + } + return f[m&1][n] +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution2.java" new file mode 100644 index 0000000000000..1aa5127239907 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution2.java" @@ -0,0 +1,12 @@ +class Solution { + public int maxValue(int[][] grid) { + int m = grid.length, n = grid[0].length; + int[][] f = new int[2][n + 1]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + f[i & 1][j] = Math.max(f[i & 1 ^ 1][j], f[i & 1][j - 1]) + grid[i - 1][j - 1]; + } + } + return f[m & 1][n]; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution2.js" "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution2.js" new file mode 100644 index 0000000000000..2a068ed97a29b --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution2.js" @@ -0,0 +1,15 @@ +/** + * @param {number[][]} grid + * @return {number} + */ +var maxValue = function (grid) { + const m = grid.length; + const n = grid[0].length; + const f = new Array(2).fill(0).map(() => new Array(n + 1).fill(0)); + for (let i = 1; i <= m; ++i) { + for (let j = 1; j <= n; ++j) { + f[i & 1][j] = Math.max(f[(i & 1) ^ 1][j], f[i & 1][j - 1]) + grid[i - 1][j - 1]; + } + } + return f[m & 1][n]; +}; diff --git "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution2.py" new file mode 100644 index 0000000000000..a1dd3b4c4bffb --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution2.py" @@ -0,0 +1,8 @@ +class Solution: + def maxValue(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + f = [[0] * (n + 1) for _ in range(2)] + for i, row in enumerate(grid, 1): + for j, v in enumerate(row, 1): + f[i & 1][j] = max(f[i & 1 ^ 1][j], f[i & 1][j - 1]) + v + return f[m & 1][n] diff --git "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution2.ts" "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution2.ts" new file mode 100644 index 0000000000000..5b9d58e4ff7fc --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/Solution2.ts" @@ -0,0 +1,11 @@ +function maxValue(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const f = Array.from({ length: 2 }, _ => new Array(n + 1).fill(0)); + for (let i = 1; i <= m; ++i) { + for (let j = 1; j <= n; ++j) { + f[i & 1][j] = Math.max(f[(i & 1) ^ 1][j], f[i & 1][j - 1]) + grid[i - 1][j - 1]; + } + } + return f[m & 1][n]; +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution.cs" index 5e8d69e5e663a..284e54a9eafd5 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution.cs" @@ -1,14 +1,14 @@ -public class Solution { - public int LengthOfLongestSubstring(string s) { - var vis = new HashSet(); - int ans = 0; - for (int i = 0, j = 0; i < s.Length; ++i) { - while (vis.Contains(s[i])) { - vis.Remove(s[j++]); - } - vis.Add(s[i]); - ans = Math.Max(ans, i - j + 1); - } - return ans; - } -} \ No newline at end of file +public class Solution { + public int LengthOfLongestSubstring(string s) { + var vis = new HashSet(); + int ans = 0; + for (int i = 0, j = 0; i < s.Length; ++i) { + while (vis.Contains(s[i])) { + vis.Remove(s[j++]); + } + vis.Add(s[i]); + ans = Math.Max(ans, i - j + 1); + } + return ans; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution.py" "b/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution.py" index fa46518f0b4cc..ec1c72e4a5b9f 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution.py" +++ "b/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution.py" @@ -1,11 +1,11 @@ class Solution: def lengthOfLongestSubstring(self, s: str) -> int: - vis = set() + cnt = Counter() ans = j = 0 for i, c in enumerate(s): - while c in vis: - vis.remove(s[j]) + cnt[c] += 1 + while cnt[c] > 1: + cnt[s[j]] -= 1 j += 1 - vis.add(c) ans = max(ans, i - j + 1) return ans diff --git "a/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.cpp" new file mode 100644 index 0000000000000..880290ebf8141 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.cpp" @@ -0,0 +1,16 @@ +class Solution { +public: + int lengthOfLongestSubstring(string s) { + bool ss[128] = {false}; + int n = s.size(); + int ans = 0; + for (int i = 0, j = 0; i < n; ++i) { + while (ss[s[i]]) { + ss[s[j++]] = false; + } + ss[s[i]] = true; + ans = max(ans, i - j + 1); + } + return ans; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.go" new file mode 100644 index 0000000000000..aa5d5c36eced9 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.go" @@ -0,0 +1,13 @@ +func lengthOfLongestSubstring(s string) (ans int) { + ss := make([]bool, 128) + j := 0 + for i, c := range s { + for ss[c] { + ss[s[j]] = false + j++ + } + ss[c] = true + ans = max(ans, i-j+1) + } + return +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.java" new file mode 100644 index 0000000000000..4ecaf7468b942 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.java" @@ -0,0 +1,16 @@ +class Solution { + public int lengthOfLongestSubstring(String s) { + boolean[] ss = new boolean[128]; + int ans = 0, j = 0; + int n = s.length(); + for (int i = 0; i < n; ++i) { + char c = s.charAt(i); + while (ss[c]) { + ss[s.charAt(j++)] = false; + } + ans = Math.max(ans, i - j + 1); + ss[c] = true; + } + return ans; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.py" new file mode 100644 index 0000000000000..fa46518f0b4cc --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.py" @@ -0,0 +1,11 @@ +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + vis = set() + ans = j = 0 + for i, c in enumerate(s): + while c in vis: + vis.remove(s[j]) + j += 1 + vis.add(c) + ans = max(ans, i - j + 1) + return ans diff --git "a/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.rs" "b/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.rs" new file mode 100644 index 0000000000000..3a2b13ee0b9d2 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.rs" @@ -0,0 +1,20 @@ +use std::collections::HashMap; +impl Solution { + pub fn length_of_longest_substring(s: String) -> i32 { + let s = s.as_bytes(); + let n = s.len(); + let mut map = HashMap::new(); + let mut res = 0; + let mut i = -1; + for j in 0..n { + let c = s[j]; + let j = j as i32; + if map.contains_key(&c) { + i = i.max(*map.get(&c).unwrap()); + } + map.insert(c, j); + res = res.max(j - i); + } + res + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.ts" "b/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.ts" new file mode 100644 index 0000000000000..ec55dc4dab91a --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.ts" @@ -0,0 +1,13 @@ +function lengthOfLongestSubstring(s: string): number { + let ans = 0; + const n = s.length; + const ss: boolean[] = new Array(128).fill(false); + for (let i = 0, j = 0; i < n; ++i) { + while (ss[s[i]]) { + ss[s[j++]] = false; + } + ss[s[i]] = true; + ans = Math.max(ans, i - j + 1); + } + return ans; +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.cpp" index 9bd1a3e0a14af..a5334855ddb7b 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.cpp" +++ "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.cpp" @@ -1,16 +1,22 @@ class Solution { public: int nthUglyNumber(int n) { - vector dp(n); - dp[0] = 1; - int p2 = 0, p3 = 0, p5 = 0; - for (int i = 1; i < n; ++i) { - int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; - dp[i] = min(next2, min(next3, next5)); - if (dp[i] == next2) ++p2; - if (dp[i] == next3) ++p3; - if (dp[i] == next5) ++p5; + priority_queue, greater> q; + q.push(1l); + unordered_set vis{{1l}}; + long ans = 1; + vector f = {2, 3, 5}; + while (n--) { + ans = q.top(); + q.pop(); + for (int& v : f) { + long nxt = ans * v; + if (!vis.count(nxt)) { + vis.insert(nxt); + q.push(nxt); + } + } } - return dp[n - 1]; + return (int) ans; } }; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.cs" index c7701ca4992be..9179cb2c6fca6 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.cs" @@ -1,21 +1,21 @@ -public class Solution { - public int NthUglyNumber(int n) { - int[] dp = new int[n]; - dp[0] = 1; - int p2 = 0, p3 = 0, p5 = 0; - for (int i = 1; i < n; ++i) { - int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; - dp[i] = Math.Min(next2, Math.Min(next3, next5)); - if (dp[i] == next2) { - ++p2; - } - if (dp[i] == next3) { - ++p3; - } - if (dp[i] == next5) { - ++p5; - } - } - return dp[n - 1]; - } -} \ No newline at end of file +public class Solution { + public int NthUglyNumber(int n) { + int[] dp = new int[n]; + dp[0] = 1; + int p2 = 0, p3 = 0, p5 = 0; + for (int i = 1; i < n; ++i) { + int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; + dp[i] = Math.Min(next2, Math.Min(next3, next5)); + if (dp[i] == next2) { + ++p2; + } + if (dp[i] == next3) { + ++p3; + } + if (dp[i] == next5) { + ++p5; + } + } + return dp[n - 1]; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.go" "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.go" index b6204b937c703..1232c4e6c911d 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.go" +++ "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.go" @@ -1,19 +1,34 @@ func nthUglyNumber(n int) int { - dp := make([]int, n) - dp[0] = 1 - p2, p3, p5 := 0, 0, 0 - for i := 1; i < n; i++ { - next2, next3, next5 := dp[p2]*2, dp[p3]*3, dp[p5]*5 - dp[i] = min(next2, min(next3, next5)) - if dp[i] == next2 { - p2++ - } - if dp[i] == next3 { - p3++ - } - if dp[i] == next5 { - p5++ + h := IntHeap([]int{1}) + heap.Init(&h) + ans := 1 + vis := map[int]bool{1: true} + for n > 0 { + ans = heap.Pop(&h).(int) + for _, v := range []int{2, 3, 5} { + nxt := ans * v + if !vis[nxt] { + vis[nxt] = true + heap.Push(&h, nxt) + } } + n-- } - return dp[n-1] + return ans +} + +type IntHeap []int + +func (h IntHeap) Len() int { return len(h) } +func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } +func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *IntHeap) Push(x any) { + *h = append(*h, x.(int)) +} +func (h *IntHeap) Pop() any { + old := *h + n := len(old) + x := old[n-1] + *h = old[0 : n-1] + return x } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.java" "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.java" index 8689e9dce620d..f7eeea2be6349 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.java" +++ "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.java" @@ -1,15 +1,20 @@ class Solution { public int nthUglyNumber(int n) { - int[] dp = new int[n]; - dp[0] = 1; - int p2 = 0, p3 = 0, p5 = 0; - for (int i = 1; i < n; ++i) { - int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; - dp[i] = Math.min(next2, Math.min(next3, next5)); - if (dp[i] == next2) ++p2; - if (dp[i] == next3) ++p3; - if (dp[i] == next5) ++p5; + Set vis = new HashSet<>(); + PriorityQueue q = new PriorityQueue<>(); + int[] f = new int[] {2, 3, 5}; + q.offer(1L); + vis.add(1L); + long ans = 0; + while (n-- > 0) { + ans = q.poll(); + for (int v : f) { + long next = ans * v; + if (vis.add(next)) { + q.offer(next); + } + } } - return dp[n - 1]; + return (int) ans; } } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.py" "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.py" index a2427e7cfaea6..38ddc3b458a6b 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.py" +++ "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution.py" @@ -1,14 +1,13 @@ class Solution: def nthUglyNumber(self, n: int) -> int: - dp = [1] * n - p2 = p3 = p5 = 0 - for i in range(1, n): - next2, next3, next5 = dp[p2] * 2, dp[p3] * 3, dp[p5] * 5 - dp[i] = min(next2, next3, next5) - if dp[i] == next2: - p2 += 1 - if dp[i] == next3: - p3 += 1 - if dp[i] == next5: - p5 += 1 - return dp[n - 1] + h = [1] + vis = {1} + ans = 1 + for _ in range(n): + ans = heappop(h) + for v in [2, 3, 5]: + nxt = ans * v + if nxt not in vis: + vis.add(nxt) + heappush(h, nxt) + return ans diff --git "a/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution2.cpp" new file mode 100644 index 0000000000000..9bd1a3e0a14af --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution2.cpp" @@ -0,0 +1,16 @@ +class Solution { +public: + int nthUglyNumber(int n) { + vector dp(n); + dp[0] = 1; + int p2 = 0, p3 = 0, p5 = 0; + for (int i = 1; i < n; ++i) { + int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; + dp[i] = min(next2, min(next3, next5)); + if (dp[i] == next2) ++p2; + if (dp[i] == next3) ++p3; + if (dp[i] == next5) ++p5; + } + return dp[n - 1]; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution2.go" new file mode 100644 index 0000000000000..b6204b937c703 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution2.go" @@ -0,0 +1,19 @@ +func nthUglyNumber(n int) int { + dp := make([]int, n) + dp[0] = 1 + p2, p3, p5 := 0, 0, 0 + for i := 1; i < n; i++ { + next2, next3, next5 := dp[p2]*2, dp[p3]*3, dp[p5]*5 + dp[i] = min(next2, min(next3, next5)) + if dp[i] == next2 { + p2++ + } + if dp[i] == next3 { + p3++ + } + if dp[i] == next5 { + p5++ + } + } + return dp[n-1] +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution2.java" new file mode 100644 index 0000000000000..8689e9dce620d --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution2.java" @@ -0,0 +1,15 @@ +class Solution { + public int nthUglyNumber(int n) { + int[] dp = new int[n]; + dp[0] = 1; + int p2 = 0, p3 = 0, p5 = 0; + for (int i = 1; i < n; ++i) { + int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; + dp[i] = Math.min(next2, Math.min(next3, next5)); + if (dp[i] == next2) ++p2; + if (dp[i] == next3) ++p3; + if (dp[i] == next5) ++p5; + } + return dp[n - 1]; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution2.py" new file mode 100644 index 0000000000000..ebe1e4414fa47 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/Solution2.py" @@ -0,0 +1,14 @@ +class Solution: + def nthUglyNumber(self, n: int) -> int: + dp = [1] * n + p2 = p3 = p5 = 0 + for i in range(1, n): + next2, next3, next5 = dp[p2] * 2, dp[p3] * 3, dp[p5] * 5 + dp[i] = min(next2, next3, next5) + if dp[i] == next2: + p2 += 1 + if dp[i] == next3: + p3 += 1 + if dp[i] == next5: + p5 += 1 + return dp[-1] diff --git "a/lcof/\351\235\242\350\257\225\351\242\23050. \347\254\254\344\270\200\344\270\252\345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\345\255\227\347\254\246/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23050. \347\254\254\344\270\200\344\270\252\345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\345\255\227\347\254\246/Solution.cs" index a7dccd9311d88..74d06d029b5ff 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23050. \347\254\254\344\270\200\344\270\252\345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\345\255\227\347\254\246/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23050. \347\254\254\344\270\200\344\270\252\345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\345\255\227\347\254\246/Solution.cs" @@ -1,14 +1,14 @@ -public class Solution { - public char FirstUniqChar(string s) { - var cnt = new int[26]; - foreach(var c in s) { - cnt[c - 'a'] ++; - } - foreach(var c in s) { - if (cnt[c - 'a'] == 1) { - return c; - } - } - return ' '; - } -} \ No newline at end of file +public class Solution { + public char FirstUniqChar(string s) { + var cnt = new int[26]; + foreach(var c in s) { + cnt[c - 'a'] ++; + } + foreach(var c in s) { + if (cnt[c - 'a'] == 1) { + return c; + } + } + return ' '; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/Solution.cs" index e2581868a571a..dd0341448dcae 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/Solution.cs" @@ -1,38 +1,38 @@ -public class Solution { - private int[] nums; - private int[] t; - - public int ReversePairs(int[] nums) { - this.nums = nums; - int n = nums.Length; - this.t = new int[n]; - return mergeSort(0, n - 1); - } - - private int mergeSort(int l, int r) { - if (l >= r) { - return 0; - } - int mid = (l + r) >> 1; - int ans = mergeSort(l, mid) + mergeSort(mid + 1, r); - int i = l, j = mid + 1, k = 0; - while (i <= mid && j <= r) { - if (nums[i] <= nums[j]) { - t[k++] = nums[i++]; - } else { - ans += mid - i + 1; - t[k++] = nums[j++]; - } - } - while (i <= mid) { - t[k++] = nums[i++]; - } - while (j <= r) { - t[k++] = nums[j++]; - } - for (i = l; i <= r; ++i) { - nums[i] = t[i - l]; - } - return ans; - } -} \ No newline at end of file +public class Solution { + private int[] nums; + private int[] t; + + public int ReversePairs(int[] nums) { + this.nums = nums; + int n = nums.Length; + this.t = new int[n]; + return mergeSort(0, n - 1); + } + + private int mergeSort(int l, int r) { + if (l >= r) { + return 0; + } + int mid = (l + r) >> 1; + int ans = mergeSort(l, mid) + mergeSort(mid + 1, r); + int i = l, j = mid + 1, k = 0; + while (i <= mid && j <= r) { + if (nums[i] <= nums[j]) { + t[k++] = nums[i++]; + } else { + ans += mid - i + 1; + t[k++] = nums[j++]; + } + } + while (i <= mid) { + t[k++] = nums[i++]; + } + while (j <= r) { + t[k++] = nums[j++]; + } + for (i = l; i <= r; ++i) { + nums[i] = t[i - l]; + } + return ans; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/Solution2.cpp" new file mode 100644 index 0000000000000..bda167bd84275 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/Solution2.cpp" @@ -0,0 +1,42 @@ +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +}; + +class Solution { +public: + int reversePairs(vector& nums) { + vector alls = nums; + sort(alls.begin(), alls.end()); + alls.erase(unique(alls.begin(), alls.end()), alls.end()); + BinaryIndexedTree tree(alls.size()); + int ans = 0; + for (int i = nums.size() - 1; ~i; --i) { + int x = lower_bound(alls.begin(), alls.end(), nums[i]) - alls.begin() + 1; + ans += tree.query(x - 1); + tree.update(x, 1); + } + return ans; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/Solution2.go" new file mode 100644 index 0000000000000..b0490baa4bb3a --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/Solution2.go" @@ -0,0 +1,44 @@ +func reversePairs(nums []int) (ans int) { + s := map[int]bool{} + for _, v := range nums { + s[v] = true + } + alls := []int{} + for v := range s { + alls = append(alls, v) + } + sort.Ints(alls) + tree := newBinaryIndexedTree(len(alls)) + for i := len(nums) - 1; i >= 0; i-- { + x := sort.SearchInts(alls, nums[i]) + 1 + ans += tree.query(x - 1) + tree.update(x, 1) + } + return +} + +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) update(x, delta int) { + for x <= this.n { + this.c[x] += delta + x += x & -x + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= x & -x + } + return s +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/Solution2.java" new file mode 100644 index 0000000000000..2f5338fbc89a4 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/Solution2.java" @@ -0,0 +1,47 @@ +class Solution { + public int reversePairs(int[] nums) { + Set s = new TreeSet<>(); + for (int v : nums) { + s.add(v); + } + Map alls = new HashMap<>(); + int i = 1; + for (int v : s) { + alls.put(v, i++); + } + BinaryIndexedTree tree = new BinaryIndexedTree(s.size()); + int ans = 0; + for (i = nums.length - 1; i >= 0; --i) { + int x = alls.get(nums[i]); + ans += tree.query(x - 1); + tree.update(x, 1); + } + return ans; + } +} + +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/Solution2.py" new file mode 100644 index 0000000000000..9e51fcbe6a809 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/Solution2.py" @@ -0,0 +1,29 @@ +class BinaryIndexedTree: + def __init__(self, n): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x, delta): + while x <= self.n: + self.c[x] += delta + x += x & -x + + def query(self, x): + s = 0 + while x: + s += self.c[x] + x -= x & -x + return s + + +class Solution: + def reversePairs(self, nums: List[int]) -> int: + alls = sorted(set(nums)) + m = len(alls) + tree = BinaryIndexedTree(m) + ans = 0 + for v in nums[::-1]: + x = bisect_left(alls, v) + 1 + ans += tree.query(x - 1) + tree.update(x, 1) + return ans diff --git "a/lcof/\351\235\242\350\257\225\351\242\23052. \344\270\244\344\270\252\351\223\276\350\241\250\347\232\204\347\254\254\344\270\200\344\270\252\345\205\254\345\205\261\350\212\202\347\202\271/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23052. \344\270\244\344\270\252\351\223\276\350\241\250\347\232\204\347\254\254\344\270\200\344\270\252\345\205\254\345\205\261\350\212\202\347\202\271/Solution.cs" index 3c0b9f9f9ea69..9057d2647a678 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23052. \344\270\244\344\270\252\351\223\276\350\241\250\347\232\204\347\254\254\344\270\200\344\270\252\345\205\254\345\205\261\350\212\202\347\202\271/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23052. \344\270\244\344\270\252\351\223\276\350\241\250\347\232\204\347\254\254\344\270\200\344\270\252\345\205\254\345\205\261\350\212\202\347\202\271/Solution.cs" @@ -15,4 +15,4 @@ public ListNode GetIntersectionNode(ListNode headA, ListNode headB) { } return a; } -} \ No newline at end of file +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/Solution.cs" index 7e6d624faa069..96d9c2a71fd75 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/Solution.cs" @@ -1,20 +1,20 @@ -public class Solution { - public int Search(int[] nums, int target) { - int l = search(nums, target); - int r = search(nums, target + 1); - return r - l; - } - - private int search(int[] nums, int x) { - int l = 0, r = nums.Length; - while (l < r) { - int mid = (l + r) >> 1; - if (nums[mid] >= x) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } -} \ No newline at end of file +public class Solution { + public int Search(int[] nums, int target) { + int l = search(nums, target); + int r = search(nums, target + 1); + return r - l; + } + + private int search(int[] nums, int x) { + int l = 0, r = nums.Length; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/Solution.cs" index 545cae48cb9d7..248c28c3bd66a 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/Solution.cs" @@ -1,14 +1,14 @@ -public class Solution { - public int MissingNumber(int[] nums) { - int l = 0, r = nums.Length; - while (l < r) { - int mid = (l + r) >> 1; - if (nums[mid] > mid) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } -} \ No newline at end of file +public class Solution { + public int MissingNumber(int[] nums) { + int l = 0, r = nums.Length; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid] > mid) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/Solution2.rs" "b/lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/Solution2.rs" new file mode 100644 index 0000000000000..d798edb978118 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/Solution2.rs" @@ -0,0 +1,10 @@ +impl Solution { + pub fn missing_number(nums: Vec) -> i32 { + let n = nums.len() as i32; + let mut sum = ((1 + n) * n) / 2; + for num in nums.iter() { + sum -= num; + } + sum + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/Solution.cs" index 1c8dc177019aa..9d63c0d7217aa 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/Solution.cs" @@ -1,30 +1,30 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int x) { val = x; } - * } - */ -public class Solution { - private int ans; - private int k; - - public int KthLargest(TreeNode root, int k) { - this.k = k; - dfs(root); - return ans; - } - - private void dfs(TreeNode root) { - if (root == null || k == 0) { - return; - } - dfs(root.right); - if (--k == 0) { - ans = root.val; - } - dfs(root.left); - } -} \ No newline at end of file +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int x) { val = x; } + * } + */ +public class Solution { + private int ans; + private int k; + + public int KthLargest(TreeNode root, int k) { + this.k = k; + dfs(root); + return ans; + } + + private void dfs(TreeNode root) { + if (root == null || k == 0) { + return; + } + dfs(root.right); + if (--k == 0) { + ans = root.val; + } + dfs(root.left); + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/Solution2.go" new file mode 100644 index 0000000000000..acc10096996db --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/Solution2.go" @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func kthLargest(root *TreeNode, k int) int { + ch := make(chan int) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go inorder(ctx, root, ch) + for ; k > 1; k-- { + <-ch + } + return <-ch +} + +func inorder(ctx context.Context, cur *TreeNode, ch chan<- int) { + if cur != nil { + inorder(ctx, cur.Right, ch) + select { + case ch <- cur.Val: + case <-ctx.Done(): + return + } + inorder(ctx, cur.Left, ch) + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/Solution.cs" index 6ccb44e3733a5..ce0f4200aa7b6 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/Solution.cs" @@ -1,17 +1,17 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public int MaxDepth(TreeNode root) { - if (root == null) { - return 0; - } - return 1 + Math.Max(MaxDepth(root.left), MaxDepth(root.right)); - } -} \ No newline at end of file +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public int MaxDepth(TreeNode root) { + if (root == null) { + return 0; + } + return 1 + Math.Max(MaxDepth(root.left), MaxDepth(root.right)); + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/Solution2.py" new file mode 100644 index 0000000000000..ca29da983b6cc --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/Solution2.py" @@ -0,0 +1,17 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution: + def maxDepth(self, root: TreeNode) -> int: + def dfs(root): + if root is None: + return 0 + l, r = dfs(root.left), dfs(root.right) + return 1 + max(l, r) + + return dfs(root) diff --git "a/lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/Solution.cs" index 39f1615af0813..57fc5c7679061 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/Solution.cs" @@ -1,26 +1,26 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public bool IsBalanced(TreeNode root) { - return dfs(root) != -1; - } - - private int dfs(TreeNode root) { - if (root == null) { - return 0; - } - int l = dfs(root.left); - int r = dfs(root.right); - if (l == -1 || r == -1 || Math.Abs(l - r) > 1) { - return -1; - } - return 1 + Math.Max(l, r); - } -} \ No newline at end of file +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public bool IsBalanced(TreeNode root) { + return dfs(root) != -1; + } + + private int dfs(TreeNode root) { + if (root == null) { + return 0; + } + int l = dfs(root.left); + int r = dfs(root.right); + if (l == -1 || r == -1 || Math.Abs(l - r) > 1) { + return -1; + } + return 1 + Math.Max(l, r); + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/Solution2.py" new file mode 100644 index 0000000000000..adbbaa03346c5 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/Solution2.py" @@ -0,0 +1,21 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution: + def isBalanced(self, root: TreeNode) -> bool: + def dfs(root): + if root is None: + return (True, 0) + l, ld = dfs(root.left) + r, rd = dfs(root.right) + d = max(ld, rd) + 1 + if l and r and abs(ld - rd) <= 1: + return (True, d) + return (False, d) + + return dfs(root)[0] diff --git "a/lcof/\351\235\242\350\257\225\351\242\23056 - I. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23056 - I. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/Solution.cs" index 45f777d683930..77a62d568fece 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23056 - I. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23056 - I. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/Solution.cs" @@ -1,17 +1,17 @@ -public class Solution { - public int[] SingleNumbers(int[] nums) { - int xs = 0; - foreach(int x in nums) { - xs ^= x; - } - int lb = xs & - xs; - int a = 0; - foreach(int x in nums) { - if ((x & lb) != 0) { - a ^= x; - } - } - int b = xs ^ a; - return new int[] {a, b}; - } -} \ No newline at end of file +public class Solution { + public int[] SingleNumbers(int[] nums) { + int xs = 0; + foreach(int x in nums) { + xs ^= x; + } + int lb = xs & - xs; + int a = 0; + foreach(int x in nums) { + if ((x & lb) != 0) { + a ^= x; + } + } + int b = xs ^ a; + return new int[] {a, b}; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23056 - II. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260 II/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23056 - II. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260 II/Solution.cs" index 8a5c2bba64451..2bf65b6fcba4a 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23056 - II. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260 II/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23056 - II. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260 II/Solution.cs" @@ -1,19 +1,19 @@ -public class Solution { - public int SingleNumber(int[] nums) { - int[] cnt = new int[32]; - foreach(int x in nums) { - int v = x; - for (int i = 0; i < 32; ++i) { - cnt[i] += v & 1; - v >>= 1; - } - } - int ans = 0; - for (int i = 0; i < 32; ++i) { - if (cnt[i] % 3 == 1) { - ans |= 1 << i; - } - } - return ans; - } -} \ No newline at end of file +public class Solution { + public int SingleNumber(int[] nums) { + int[] cnt = new int[32]; + foreach(int x in nums) { + int v = x; + for (int i = 0; i < 32; ++i) { + cnt[i] += v & 1; + v >>= 1; + } + } + int ans = 0; + for (int i = 0; i < 32; ++i) { + if (cnt[i] % 3 == 1) { + ans |= 1 << i; + } + } + return ans; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23057 - II. \345\222\214\344\270\272s\347\232\204\350\277\236\347\273\255\346\255\243\346\225\260\345\272\217\345\210\227/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23057 - II. \345\222\214\344\270\272s\347\232\204\350\277\236\347\273\255\346\255\243\346\225\260\345\272\217\345\210\227/Solution.cs" index 656ca20ab5c4e..305f73b1fb4c4 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23057 - II. \345\222\214\344\270\272s\347\232\204\350\277\236\347\273\255\346\255\243\346\225\260\345\272\217\345\210\227/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23057 - II. \345\222\214\344\270\272s\347\232\204\350\277\236\347\273\255\346\255\243\346\225\260\345\272\217\345\210\227/Solution.cs" @@ -1,22 +1,22 @@ -public class Solution { - public int[][] FindContinuousSequence(int target) { - List ans = new List(); - int l = 1, r = 2; - while (l < r) { - int s = (l + r) * (r - l + 1) >> 1; - if (s == target) { - List t = new List(); - for (int i = l; i <= r; i++) { - t.Add(i); - } - l += 1; - ans.Add(t.ToArray()); - } else if (s < target) { - r += 1; - } else { - l += 1; - } - } - return ans.ToArray(); - } -} \ No newline at end of file +public class Solution { + public int[][] FindContinuousSequence(int target) { + List ans = new List(); + int l = 1, r = 2; + while (l < r) { + int s = (l + r) * (r - l + 1) >> 1; + if (s == target) { + List t = new List(); + for (int i = l; i <= r; i++) { + t.Add(i); + } + l += 1; + ans.Add(t.ToArray()); + } else if (s < target) { + r += 1; + } else { + l += 1; + } + } + return ans.ToArray(); + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23057. \345\222\214\344\270\272s\347\232\204\344\270\244\344\270\252\346\225\260\345\255\227/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23057. \345\222\214\344\270\272s\347\232\204\344\270\244\344\270\252\346\225\260\345\255\227/Solution.cs" index de504c8f9bb53..6e09a21d9b4fe 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23057. \345\222\214\344\270\272s\347\232\204\344\270\244\344\270\252\346\225\260\345\255\227/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23057. \345\222\214\344\270\272s\347\232\204\344\270\244\344\270\252\346\225\260\345\255\227/Solution.cs" @@ -1,15 +1,15 @@ -public class Solution { - public int[] TwoSum(int[] nums, int target) { - int l = 0, r = nums.Length - 1; - while (true) { - if (nums[l] + nums[r] == target) { - return new int[] {nums[l], nums[r]}; - } - if (nums[l] + nums[r] > target) { - --r; - } else { - ++l; - } - } - } -} \ No newline at end of file +public class Solution { + public int[] TwoSum(int[] nums, int target) { + int l = 0, r = nums.Length - 1; + while (true) { + if (nums[l] + nums[r] == target) { + return new int[] {nums[l], nums[r]}; + } + if (nums[l] + nums[r] > target) { + --r; + } else { + ++l; + } + } + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.cs" index 2d315ab9f39d0..4c90180b3fc7b 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.cs" @@ -1,19 +1,19 @@ -public class Solution { - public string ReverseWords(string s) { - string[] tmp = s.Split(' ', StringSplitOptions.RemoveEmptyEntries); - Stack ss = new Stack(); - string res = ""; - - foreach (var i in tmp) { - ss.Push(i); - } - - while (ss.Count > 0) { - res += ss.Pop(); - if (ss.Count > 0) { - res += " "; - } - } - return res; - } -} \ No newline at end of file +public class Solution { + public string ReverseWords(string s) { + string[] tmp = s.Split(' ', StringSplitOptions.RemoveEmptyEntries); + Stack ss = new Stack(); + string res = ""; + + foreach (var i in tmp) { + ss.Push(i); + } + + while (ss.Count > 0) { + res += ss.Pop(); + if (ss.Count > 0) { + res += " "; + } + } + return res; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.rs" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.rs" index c7d89d0e6d2b4..c0df6a4e36143 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.rs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.rs" @@ -1,5 +1,11 @@ impl Solution { pub fn reverse_words(mut s: String) -> String { - s.split_whitespace().rev().collect::>().join(" ") + let mut res = s.trim().split(' ').rev().collect::>(); + for i in (0..res.len()).rev() { + if res[i] == "" { + res.remove(i); + } + } + res.join(" ") } } diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.rs" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.rs" new file mode 100644 index 0000000000000..2cbefc51d68a2 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.rs" @@ -0,0 +1,9 @@ +impl Solution { + pub fn reverse_words(s: String) -> String { + s.split(' ') + .filter(|str| str != &"") + .rev() + .collect::>() + .join("") + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.ts" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.ts" new file mode 100644 index 0000000000000..5645865765f1f --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.ts" @@ -0,0 +1,17 @@ +function reverseWords(s: string): string { + s = s.trim(); + const res = []; + let l = s.length - 1; + let r = s.length - 1; + while (l >= 0) { + while (s[l] !== ' ' && l >= 0) { + l--; + } + res.push(s.substring(l + 1, r + 1)); + while (s[l] === ' ' && l >= 0) { + l--; + } + r = l; + } + return res.join(' '); +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution3.rs" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution3.rs" new file mode 100644 index 0000000000000..8e244b2222f04 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution3.rs" @@ -0,0 +1,5 @@ +impl Solution { + pub fn reverse_words(s: String) -> String { + s.split_whitespace().rev().collect::>().join(" ") + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution4.rs" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution4.rs" new file mode 100644 index 0000000000000..a8dac78a3dac7 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution4.rs" @@ -0,0 +1,32 @@ +impl Solution { + pub fn reverse_words(mut s: String) -> String { + s = s.trim().to_string(); + // 添加辅助空格,防止 usize 破界 + s.insert_str(0, " "); + let chars = s.chars().collect::>(); + let mut res = vec![]; + let mut l = chars.len() - 1; + let mut r = chars.len() - 1; + while l > 0 { + while chars[l] == ' ' { + if l == 0 { + break; + } + l -= 1; + } + r = l; + while chars[l] != ' ' { + if l == 0 { + break; + } + l -= 1; + } + let mut str = String::new(); + for i in l + 1..r + 1 { + str.push(chars[i]); + } + res.push(str); + } + res.join(" ") + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/Solution.cpp" index 95d0e5fbba237..9862969e33a09 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/Solution.cpp" +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/Solution.cpp" @@ -3,4 +3,4 @@ class Solution { string reverseLeftWords(string s, int n) { return s.substr(n) + s.substr(0, n); } -}; +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/Solution.cs" index 6df1ee00b958d..bad1300318e57 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/Solution.cs" @@ -1,5 +1,5 @@ -public class Solution { - public string ReverseLeftWords(string s, int n) { - return s.Substring(n) + s.Substring(0, n); - } -} \ No newline at end of file +public class Solution { + public string ReverseLeftWords(string s, int n) { + return s.Substring(n) + s.Substring(0, n); + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/Solution2.cpp" new file mode 100644 index 0000000000000..cc632130155b1 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/Solution2.cpp" @@ -0,0 +1,9 @@ +class Solution { +public: + string reverseLeftWords(string s, int n) { + reverse(s.begin(), s.begin() + n); + reverse(s.begin() + n, s.end()); + reverse(s.begin(), s.end()); + return s; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23059 - I. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\346\234\200\345\244\247\345\200\274/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23059 - I. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\346\234\200\345\244\247\345\200\274/Solution.cs" index f47085fe9797b..6a605702a9b38 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23059 - I. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\346\234\200\345\244\247\345\200\274/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23059 - I. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\346\234\200\345\244\247\345\200\274/Solution.cs" @@ -1,19 +1,19 @@ -public class Solution { - public int[] MaxSlidingWindow(int[] nums, int k) { - if (nums.Length == 0) { - return new int[]{}; - } - int[] array = new int[nums.Length - (k - 1)]; - Queue queue = new Queue(); - int index = 0; - for (int i = 0; i < nums.Length; i++) { - queue.Enqueue(nums[i]); - if (queue.Count == k) { - array[index] = queue.Max(); - queue.Dequeue(); - index++; - } - } - return array; - } -} \ No newline at end of file +public class Solution { + public int[] MaxSlidingWindow(int[] nums, int k) { + if (nums.Length == 0) { + return new int[]{}; + } + int[] array = new int[nums.Length - (k - 1)]; + Queue queue = new Queue(); + int index = 0; + for (int i = 0; i < nums.Length; i++) { + queue.Enqueue(nums[i]); + if (queue.Count == k) { + array[index] = queue.Max(); + queue.Dequeue(); + index++; + } + } + return array; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23059 - II. \351\230\237\345\210\227\347\232\204\346\234\200\345\244\247\345\200\274/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23059 - II. \351\230\237\345\210\227\347\232\204\346\234\200\345\244\247\345\200\274/Solution.cs" index c3f3c0a1ccaa3..5d68d46c33b9d 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23059 - II. \351\230\237\345\210\227\347\232\204\346\234\200\345\244\247\345\200\274/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23059 - II. \351\230\237\345\210\227\347\232\204\346\234\200\345\244\247\345\200\274/Solution.cs" @@ -1,43 +1,43 @@ -public class MaxQueue { - LinkedList mvq; - Queue q; - - public MaxQueue() { - mvq = new LinkedList(); - q = new Queue(); - } - - public int Max_value() { - if (mvq.Count == 0) { - return -1; - } - return mvq.First.Value; - } - - public void Push_back(int value) { - q.Enqueue(value); - while (mvq.Count > 0 && mvq.Last.Value < value) { - mvq.RemoveLast(); - } - mvq.AddLast(value); - } - - public int Pop_front() { - if (q.Count == 0) { - return -1; - } - int v = q.Dequeue(); - if (mvq.First.Value == v) { - mvq.RemoveFirst(); - } - return v; - } -} - -/** - * Your MaxQueue object will be instantiated and called as such: - * MaxQueue obj = new MaxQueue(); - * int param_1 = obj.Max_value(); - * obj.Push_back(value); - * int param_3 = obj.Pop_front(); - */ \ No newline at end of file +public class MaxQueue { + LinkedList mvq; + Queue q; + + public MaxQueue() { + mvq = new LinkedList(); + q = new Queue(); + } + + public int Max_value() { + if (mvq.Count == 0) { + return -1; + } + return mvq.First.Value; + } + + public void Push_back(int value) { + q.Enqueue(value); + while (mvq.Count > 0 && mvq.Last.Value < value) { + mvq.RemoveLast(); + } + mvq.AddLast(value); + } + + public int Pop_front() { + if (q.Count == 0) { + return -1; + } + int v = q.Dequeue(); + if (mvq.First.Value == v) { + mvq.RemoveFirst(); + } + return v; + } +} + +/** + * Your MaxQueue object will be instantiated and called as such: + * MaxQueue obj = new MaxQueue(); + * int param_1 = obj.Max_value(); + * obj.Push_back(value); + * int param_3 = obj.Pop_front(); + */ diff --git "a/lcof/\351\235\242\350\257\225\351\242\23060. n\344\270\252\351\252\260\345\255\220\347\232\204\347\202\271\346\225\260/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23060. n\344\270\252\351\252\260\345\255\220\347\232\204\347\202\271\346\225\260/Solution.cs" index a36e6ed009175..e5d1d6b7bf730 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23060. n\344\270\252\351\252\260\345\255\220\347\232\204\347\202\271\346\225\260/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23060. n\344\270\252\351\252\260\345\255\220\347\232\204\347\202\271\346\225\260/Solution.cs" @@ -1,19 +1,19 @@ -public class Solution { - public double[] DicesProbability(int n) { - var bp = new double[6]; - for (int i = 0; i < 6; i++) { - bp[i] = 1 / 6.0; - } - double[] ans = new double[]{1}; - for (int i = 1; i <= n; i++) { - var tmp = ans; - ans = new double[tmp.Length + 5]; - for (int i1 = 0; i1 < tmp.Length; i1++) { - for (int i2 = 0; i2 < bp.Length; i2++) { - ans[i1+i2] += tmp[i1] * bp[i2]; - } - } - } - return ans; - } -} \ No newline at end of file +public class Solution { + public double[] DicesProbability(int n) { + var bp = new double[6]; + for (int i = 0; i < 6; i++) { + bp[i] = 1 / 6.0; + } + double[] ans = new double[]{1}; + for (int i = 1; i <= n; i++) { + var tmp = ans; + ans = new double[tmp.Length + 5]; + for (int i1 = 0; i1 < tmp.Length; i1++) { + for (int i2 = 0; i2 < bp.Length; i2++) { + ans[i1+i2] += tmp[i1] * bp[i2]; + } + } + } + return ans; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23060. n\344\270\252\351\252\260\345\255\220\347\232\204\347\202\271\346\225\260/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23060. n\344\270\252\351\252\260\345\255\220\347\232\204\347\202\271\346\225\260/Solution2.go" new file mode 100644 index 0000000000000..40ddec8b2720e --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23060. n\344\270\252\351\252\260\345\255\220\347\232\204\347\202\271\346\225\260/Solution2.go" @@ -0,0 +1,17 @@ +func dicesProbability(n int) []float64 { + dp := make([]float64, 7) + for i := 1; i <= 6; i++ { + dp[i] = 1.0 / 6.0 + } + for i := 2; i <= n; i++ { + n := len(dp) + tmp := make([]float64, 6*i+1) + for j := 0; j < n; j++ { + for k := 1; k <= 6; k++ { + tmp[j+k] += dp[j] / 6.0 + } + } + dp = tmp + } + return dp[n:] +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23060. n\344\270\252\351\252\260\345\255\220\347\232\204\347\202\271\346\225\260/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23060. n\344\270\252\351\252\260\345\255\220\347\232\204\347\202\271\346\225\260/Solution2.py" new file mode 100644 index 0000000000000..464f5d40cac6b --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23060. n\344\270\252\351\252\260\345\255\220\347\232\204\347\202\271\346\225\260/Solution2.py" @@ -0,0 +1,12 @@ +class Solution: + def dicesProbability(self, n: int) -> List[float]: + f = [0] + [1] * 6 + for i in range(2, n + 1): + g = [0] * (6 * i + 1) + for j in range(i, 6 * i + 1): + for k in range(1, 7): + if 0 <= j - k < len(f): + g[j] += f[j - k] + f = g + m = pow(6, n) + return [f[j] / m for j in range(n, 6 * n + 1)] diff --git "a/lcof/\351\235\242\350\257\225\351\242\23061. \346\211\221\345\205\213\347\211\214\344\270\255\347\232\204\351\241\272\345\255\220/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23061. \346\211\221\345\205\213\347\211\214\344\270\255\347\232\204\351\241\272\345\255\220/Solution.cs" index 21ca3217e4607..8700cc280d45c 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23061. \346\211\221\345\205\213\347\211\214\344\270\255\347\232\204\351\241\272\345\255\220/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23061. \346\211\221\345\205\213\347\211\214\344\270\255\347\232\204\351\241\272\345\255\220/Solution.cs" @@ -1,18 +1,18 @@ -public class Solution { - public bool IsStraight(int[] nums) { - bool[] vis = new bool[14]; - int mi = 20, mx = -1; - foreach(int x in nums) { - if (x == 0) { - continue; - } - if (vis[x]) { - return false; - } - vis[x] = true; - mi = Math.Min(mi, x); - mx = Math.Max(mx, x); - } - return mx - mi <= 4; - } -} \ No newline at end of file +public class Solution { + public bool IsStraight(int[] nums) { + bool[] vis = new bool[14]; + int mi = 20, mx = -1; + foreach(int x in nums) { + if (x == 0) { + continue; + } + if (vis[x]) { + return false; + } + vis[x] = true; + mi = Math.Min(mi, x); + mx = Math.Max(mx, x); + } + return mx - mi <= 4; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution.cs" index 9db9a1daba7b2..8df2bce856dc9 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution.cs" @@ -1,9 +1,9 @@ -public class Solution { - public int LastRemaining(int n, int m) { - int f = 0; - for (int i = 2; i < n + 1; i++) { - f = (f + m) % i; - } - return f; - } -} \ No newline at end of file +public class Solution { + public int LastRemaining(int n, int m) { + int f = 0; + for (int i = 2; i < n + 1; i++) { + f = (f + m) % i; + } + return f; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution.go" "b/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution.go" index 67464d7293789..10eca5a5cdd06 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution.go" +++ "b/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution.go" @@ -1,7 +1,11 @@ func lastRemaining(n int, m int) int { - f := 0 - for i := 2; i <= n; i++ { - f = (f + m) % i + var f func(n, m int) int + f = func(n, m int) int { + if n == 1 { + return 0 + } + x := f(n-1, m) + return (m + x) % n } - return f + return f(n, m) } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution.java" "b/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution.java" index a95747683c489..7458011647b20 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution.java" +++ "b/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution.java" @@ -1,9 +1,13 @@ class Solution { public int lastRemaining(int n, int m) { - int f = 0; - for (int i = 2; i <= n; ++i) { - f = (f + m) % i; + return f(n, m); + } + + private int f(int n, int m) { + if (n == 1) { + return 0; } - return f; + int x = f(n - 1, m); + return (m + x) % n; } } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution.py" "b/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution.py" index 56ead9a81808f..4983303393583 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution.py" +++ "b/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution.py" @@ -1,6 +1,9 @@ class Solution: def lastRemaining(self, n: int, m: int) -> int: - f = 0 - for i in range(2, n + 1): - f = (f + m) % i - return f + def f(n, m): + if n == 1: + return 0 + x = f(n - 1, m) + return (m + x) % n + + return f(n, m) diff --git "a/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution2.cpp" new file mode 100644 index 0000000000000..a082613874ff7 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution2.cpp" @@ -0,0 +1,10 @@ +class Solution { +public: + int lastRemaining(int n, int m) { + int f = 0; + for (int i = 2; i <= n; ++i) { + f = (f + m) % i; + } + return f; + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution2.go" new file mode 100644 index 0000000000000..67464d7293789 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution2.go" @@ -0,0 +1,7 @@ +func lastRemaining(n int, m int) int { + f := 0 + for i := 2; i <= n; i++ { + f = (f + m) % i + } + return f +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution2.java" new file mode 100644 index 0000000000000..a95747683c489 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution2.java" @@ -0,0 +1,9 @@ +class Solution { + public int lastRemaining(int n, int m) { + int f = 0; + for (int i = 2; i <= n; ++i) { + f = (f + m) % i; + } + return f; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution2.py" new file mode 100644 index 0000000000000..56ead9a81808f --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/Solution2.py" @@ -0,0 +1,6 @@ +class Solution: + def lastRemaining(self, n: int, m: int) -> int: + f = 0 + for i in range(2, n + 1): + f = (f + m) % i + return f diff --git "a/lcof/\351\235\242\350\257\225\351\242\23063. \350\202\241\347\245\250\347\232\204\346\234\200\345\244\247\345\210\251\346\266\246/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23063. \350\202\241\347\245\250\347\232\204\346\234\200\345\244\247\345\210\251\346\266\246/Solution.cs" index 2eec1ab492fc1..90a3c752e6982 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23063. \350\202\241\347\245\250\347\232\204\346\234\200\345\244\247\345\210\251\346\266\246/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23063. \350\202\241\347\245\250\347\232\204\346\234\200\345\244\247\345\210\251\346\266\246/Solution.cs" @@ -1,11 +1,11 @@ -public class Solution { - public int MaxProfit(int[] prices) { - int mi = 1 << 30; - int ans = 0; - foreach(int x in prices) { - ans = Math.Max(ans, x - mi); - mi = Math.Min(mi, x); - } - return ans; - } -} \ No newline at end of file +public class Solution { + public int MaxProfit(int[] prices) { + int mi = 1 << 30; + int ans = 0; + foreach(int x in prices) { + ans = Math.Max(ans, x - mi); + mi = Math.Min(mi, x); + } + return ans; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23064. \346\261\2021+2+\342\200\246+n/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23064. \346\261\2021+2+\342\200\246+n/Solution.cpp" index 54c9c11c93ea4..3469230575cd1 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23064. \346\261\2021+2+\342\200\246+n/Solution.cpp" +++ "b/lcof/\351\235\242\350\257\225\351\242\23064. \346\261\2021+2+\342\200\246+n/Solution.cpp" @@ -1,7 +1,7 @@ -class Solution { -public: - int sumNums(int n) { - n && (n += sumNums(n - 1)); - return n; - } +class Solution { +public: + int sumNums(int n) { + n && (n += sumNums(n - 1)); + return n; + } }; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23064. \346\261\2021+2+\342\200\246+n/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23064. \346\261\2021+2+\342\200\246+n/Solution.cs" index c1bb82b8d5536..fbbdadc57463a 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23064. \346\261\2021+2+\342\200\246+n/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23064. \346\261\2021+2+\342\200\246+n/Solution.cs" @@ -1,12 +1,13 @@ -public class Solution { - public int result; - public int SumNums(int n) { - helper(n); - return result; - } - - public bool helper(int n) { - result += n; - return n == 0 || helper(n - 1); - } -} \ No newline at end of file +public class Solution { + public int result; + public int SumNums(int n) { + helper(n); + return result; + } + + public bool helper(int n) { + result += n; + return n == 0 || helper(n - 1); + } +} + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23065. \344\270\215\347\224\250\345\212\240\345\207\217\344\271\230\351\231\244\345\201\232\345\212\240\346\263\225/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23065. \344\270\215\347\224\250\345\212\240\345\207\217\344\271\230\351\231\244\345\201\232\345\212\240\346\263\225/Solution.cs" index e79ba4686659f..ce8147a3ff792 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23065. \344\270\215\347\224\250\345\212\240\345\207\217\344\271\230\351\231\244\345\201\232\345\212\240\346\263\225/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23065. \344\270\215\347\224\250\345\212\240\345\207\217\344\271\230\351\231\244\345\201\232\345\212\240\346\263\225/Solution.cs" @@ -1,11 +1,11 @@ -public class Solution { - public int Add(int a, int b) { - while (b != 0) { - int c = (a & b) << 1; - a = a ^ b; - b = c; - } - - return a; - } -} \ No newline at end of file +public class Solution { + public int Add(int a, int b) { + while (b != 0) { + int c = (a & b) << 1; + a = a ^ b; + b = c; + } + + return a; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23065. \344\270\215\347\224\250\345\212\240\345\207\217\344\271\230\351\231\244\345\201\232\345\212\240\346\263\225/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23065. \344\270\215\347\224\250\345\212\240\345\207\217\344\271\230\351\231\244\345\201\232\345\212\240\346\263\225/Solution2.java" new file mode 100644 index 0000000000000..78a33f44c19e5 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23065. \344\270\215\347\224\250\345\212\240\345\207\217\344\271\230\351\231\244\345\201\232\345\212\240\346\263\225/Solution2.java" @@ -0,0 +1,8 @@ +class Solution { + public int add(int a, int b) { + if (b == 0) { + return a; + } + return add(a ^ b, (a & b) << 1); + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23066. \346\236\204\345\273\272\344\271\230\347\247\257\346\225\260\347\273\204/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23066. \346\236\204\345\273\272\344\271\230\347\247\257\346\225\260\347\273\204/Solution.cs" index 6f8f58c3eb03b..4b7cbbf90eca1 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23066. \346\236\204\345\273\272\344\271\230\347\247\257\346\225\260\347\273\204/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23066. \346\236\204\345\273\272\344\271\230\347\247\257\346\225\260\347\273\204/Solution.cs" @@ -1,16 +1,16 @@ -public class Solution { - public int[] ConstructArr(int[] a) { - int n = a.Length; - int[] ans = new int[n]; - int left = 1, right = 1; - for (int i = 0; i < n; i++) { - ans[i] = left; - left *= a[i]; - } - for (int i = n - 1; i > -1; i--) { - ans[i] *= right; - right *= a[i]; - } - return ans; - } -} \ No newline at end of file +public class Solution { + public int[] ConstructArr(int[] a) { + int n = a.Length; + int[] ans = new int[n]; + int left = 1, right = 1; + for (int i = 0; i < n; i++) { + ans[i] = left; + left *= a[i]; + } + for (int i = n - 1; i > -1; i--) { + ans[i] *= right; + right *= a[i]; + } + return ans; + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/Solution.cs" index 2ace7b326c9d1..bfe5e256b9616 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/Solution.cs" @@ -1,56 +1,56 @@ -public class Solution { - public int StrToInt(string str) { - if (string.IsNullOrWhiteSpace(str)) - { - return 0; - } - - str = str.Trim(); - int currentIndex = 0; - bool minus = false; - if (str[currentIndex] == '+') - { - minus = false; - currentIndex++; - } - else if (str[currentIndex] == '-') - { - minus = true; - currentIndex++; - } - - long result = 0; - for (; currentIndex < str.Length; currentIndex++) - { - if (!char.IsDigit(str[currentIndex])) - { - break; - } - - if (minus && result - 1 > int.MaxValue) - { - return int.MinValue; - } - else if (!minus && result > int.MaxValue) - { - return int.MaxValue; - } - - result = result * 10 + (str[currentIndex] - '0'); - } - - if (minus && result - 1 > int.MaxValue) - { - return int.MinValue; - } - else if (!minus && result > int.MaxValue) - { - return int.MaxValue; - } - else - { - return (minus ? -1 : 1) * (int)result; - } - - } -} \ No newline at end of file +public class Solution { + public int StrToInt(string str) { + if (string.IsNullOrWhiteSpace(str)) + { + return 0; + } + + str = str.Trim(); + int currentIndex = 0; + bool minus = false; + if (str[currentIndex] == '+') + { + minus = false; + currentIndex++; + } + else if (str[currentIndex] == '-') + { + minus = true; + currentIndex++; + } + + long result = 0; + for (; currentIndex < str.Length; currentIndex++) + { + if (!char.IsDigit(str[currentIndex])) + { + break; + } + + if (minus && result - 1 > int.MaxValue) + { + return int.MinValue; + } + else if (!minus && result > int.MaxValue) + { + return int.MaxValue; + } + + result = result * 10 + (str[currentIndex] - '0'); + } + + if (minus && result - 1 > int.MaxValue) + { + return int.MinValue; + } + else if (!minus && result > int.MaxValue) + { + return int.MaxValue; + } + else + { + return (minus ? -1 : 1) * (int)result; + } + + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/Solution.java" "b/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/Solution.java" index 480db6de6ae3b..ca6ea72fe3dfc 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/Solution.java" +++ "b/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/Solution.java" @@ -5,6 +5,7 @@ public int strToInt(String str) { if (n == 0) return 0; int i = 0; while (str.charAt(i) == ' ') { + // 仅包含空格 if (++i == n) return 0; } int sign = 1; @@ -12,7 +13,9 @@ public int strToInt(String str) { if (str.charAt(i) == '-' || str.charAt(i) == '+') ++i; int res = 0, flag = Integer.MAX_VALUE / 10; for (; i < n; ++i) { + // 非数字,跳出循环体 if (str.charAt(i) < '0' || str.charAt(i) > '9') break; + // 溢出判断 if (res > flag || (res == flag) && str.charAt(i) > '7') return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE; res = res * 10 + (str.charAt(i) - '0'); diff --git "a/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/Solution.py" "b/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/Solution.py" index 0dd75dc814d3d..997d11ee793da 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/Solution.py" +++ "b/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/Solution.py" @@ -16,7 +16,7 @@ def strToInt(self, str: str) -> int: i += 1 res, flag = 0, (2**31 - 1) // 10 while i < n: - # 非数字,跳出循环 + # 非数字,跳出循环体 if not str[i].isdigit(): break c = int(str[i]) diff --git "a/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution.java" "b/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution.java" index 30e58ff6ca8cd..1427f7652850b 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution.java" +++ "b/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution.java" @@ -9,10 +9,7 @@ */ class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { - if (p == q) { - return p; - } - while (root != null) { + while (true) { if (root.val < p.val && root.val < q.val) { root = root.right; } else if (root.val > p.val && root.val > q.val) { @@ -21,6 +18,5 @@ public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { return root; } } - return null; } } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution.ts" "b/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution.ts" index 314993ddf9752..838d4098ed9ec 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution.ts" +++ "b/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution.ts" @@ -19,13 +19,11 @@ function lowestCommonAncestor( if (root == null) { return root; } - while (true) { - if (root.val > p.val && root.val > q.val) { - root = root.left; - } else if (root.val < p.val && root.val < q.val) { - root = root.right; - } else { - return root; - } + if (root.val > p.val && root.val > q.val) { + return lowestCommonAncestor(root.left, p, q); } + if (root.val < p.val && root.val < q.val) { + return lowestCommonAncestor(root.right, p, q); + } + return root; } diff --git "a/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution2.cpp" new file mode 100644 index 0000000000000..dd32bad7cebf1 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution2.cpp" @@ -0,0 +1,23 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + while (1) { + if (root->val < p->val && root->val < q->val) { + root = root->right; + } else if (root->val > p->val && root->val > q->val) { + root = root->left; + } else { + return root; + } + } + } +}; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution2.go" new file mode 100644 index 0000000000000..46ac599a9e887 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution2.go" @@ -0,0 +1,20 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { + for { + if root.Val < p.Val && root.Val < q.Val { + root = root.Right + } else if root.Val > p.Val && root.Val > q.Val { + root = root.Left + } else { + return root + } + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution2.java" new file mode 100644 index 0000000000000..c3a92e6519497 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution2.java" @@ -0,0 +1,20 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root.val < p.val && root.val < q.val) { + return lowestCommonAncestor(root.right, p, q); + } + if (root.val > p.val && root.val > q.val) { + return lowestCommonAncestor(root.left, p, q); + } + return root; + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution2.py" new file mode 100644 index 0000000000000..be6d2fae40187 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution2.py" @@ -0,0 +1,17 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution: + def lowestCommonAncestor( + self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode' + ) -> 'TreeNode': + if root.val < p.val and root.val < q.val: + return self.lowestCommonAncestor(root.right, p, q) + if root.val > p.val and root.val > q.val: + return self.lowestCommonAncestor(root.left, p, q) + return root diff --git "a/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution2.ts" "b/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution2.ts" new file mode 100644 index 0000000000000..314993ddf9752 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution2.ts" @@ -0,0 +1,31 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ +function lowestCommonAncestor( + root: TreeNode | null, + p: TreeNode | null, + q: TreeNode | null, +): TreeNode | null { + if (root == null) { + return root; + } + while (true) { + if (root.val > p.val && root.val > q.val) { + root = root.left; + } else if (root.val < p.val && root.val < q.val) { + root = root.right; + } else { + return root; + } + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23068 - II. \344\272\214\345\217\211\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23068 - II. \344\272\214\345\217\211\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution.cpp" index 46defdcc82a5c..80073f4c78bb7 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23068 - II. \344\272\214\345\217\211\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution.cpp" +++ "b/lcof/\351\235\242\350\257\225\351\242\23068 - II. \344\272\214\345\217\211\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/Solution.cpp" @@ -29,4 +29,4 @@ class Solution { return left; } } -}; +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.cpp" index e6e59f4a50f44..26d265a0ebb5f 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.cpp" @@ -1,26 +1,26 @@ -class Solution { -public: - int divide(int a, int b) { - if (b == 1) { - return a; - } - if (a == INT_MIN && b == -1) { - return INT_MAX; - } - bool sign = (a > 0 && b > 0) || (a < 0 && b < 0); - a = a > 0 ? -a : a; - b = b > 0 ? -b : b; - int ans = 0; - while (a <= b) { - int x = b; - int cnt = 1; - while (x >= (INT_MIN >> 1) && a <= (x << 1)) { - x <<= 1; - cnt <<= 1; - } - ans += cnt; - a -= x; - } - return sign ? ans : -ans; - } +class Solution { +public: + int divide(int a, int b) { + if (b == 1) { + return a; + } + if (a == INT_MIN && b == -1) { + return INT_MAX; + } + bool sign = (a > 0 && b > 0) || (a < 0 && b < 0); + a = a > 0 ? -a : a; + b = b > 0 ? -b : b; + int ans = 0; + while (a <= b) { + int x = b; + int cnt = 1; + while (x >= (INT_MIN >> 1) && a <= (x << 1)) { + x <<= 1; + cnt <<= 1; + } + ans += cnt; + a -= x; + } + return sign ? ans : -ans; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.cs" index 0eda8847194d9..40369d3d61aa8 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.cs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.cs" @@ -1,25 +1,25 @@ -public class Solution { - public int Divide(int a, int b) { - if (b == 1) { - return a; - } - if (a == int.MinValue && b == -1) { - return int.MaxValue; - } - bool sign = (a > 0 && b > 0) || (a < 0 && b < 0); - a = a > 0 ? -a : a; - b = b > 0 ? -b : b; - int ans = 0; - while (a <= b) { - int x = b; - int cnt = 1; - while (x >= (int.MinValue >> 1) && a <= (x << 1)) { - x <<= 1; - cnt <<= 1; - } - ans += cnt; - a -= x; - } - return sign ? ans : -ans; - } -} \ No newline at end of file +public class Solution { + public int Divide(int a, int b) { + if (b == 1) { + return a; + } + if (a == int.MinValue && b == -1) { + return int.MaxValue; + } + bool sign = (a > 0 && b > 0) || (a < 0 && b < 0); + a = a > 0 ? -a : a; + b = b > 0 ? -b : b; + int ans = 0; + while (a <= b) { + int x = b; + int cnt = 1; + while (x >= (int.MinValue >> 1) && a <= (x << 1)) { + x <<= 1; + cnt <<= 1; + } + ans += cnt; + a -= x; + } + return sign ? ans : -ans; + } +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.java" index 39a3fa4229851..fcdf55eedb442 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.java" @@ -1,25 +1,25 @@ -class Solution { - public int divide(int a, int b) { - if (b == 1) { - return a; - } - if (a == Integer.MIN_VALUE && b == -1) { - return Integer.MAX_VALUE; - } - boolean sign = (a > 0 && b > 0) || (a < 0 && b < 0); - a = a > 0 ? -a : a; - b = b > 0 ? -b : b; - int ans = 0; - while (a <= b) { - int x = b; - int cnt = 1; - while (x >= (Integer.MIN_VALUE >> 1) && a <= (x << 1)) { - x <<= 1; - cnt <<= 1; - } - ans += cnt; - a -= x; - } - return sign ? ans : -ans; - } +class Solution { + public int divide(int a, int b) { + if (b == 1) { + return a; + } + if (a == Integer.MIN_VALUE && b == -1) { + return Integer.MAX_VALUE; + } + boolean sign = (a > 0 && b > 0) || (a < 0 && b < 0); + a = a > 0 ? -a : a; + b = b > 0 ? -b : b; + int ans = 0; + while (a <= b) { + int x = b; + int cnt = 1; + while (x >= (Integer.MIN_VALUE >> 1) && a <= (x << 1)) { + x <<= 1; + cnt <<= 1; + } + ans += cnt; + a -= x; + } + return sign ? ans : -ans; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.py" index 8ae7276462454..8870ed193fe42 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.py" @@ -1,19 +1,19 @@ -class Solution: - def divide(self, a: int, b: int) -> int: - if b == 1: - return a - if a == -(2**31) and b == -1: - return 2**31 - 1 - sign = (a > 0 and b > 0) or (a < 0 and b < 0) - a = -a if a > 0 else a - b = -b if b > 0 else b - ans = 0 - while a <= b: - x = b - cnt = 1 - while x >= (-(2**30)) and a <= (x << 1): - x <<= 1 - cnt <<= 1 - a -= x - ans += cnt - return ans if sign else -ans +class Solution: + def divide(self, a: int, b: int) -> int: + if b == 1: + return a + if a == -(2**31) and b == -1: + return 2**31 - 1 + sign = (a > 0 and b > 0) or (a < 0 and b < 0) + a = -a if a > 0 else a + b = -b if b > 0 else b + ans = 0 + while a <= b: + x = b + cnt = 1 + while x >= (-(2**30)) and a <= (x << 1): + x <<= 1 + cnt <<= 1 + a -= x + ans += cnt + return ans if sign else -ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution.cpp" index 486f0a13a8af2..74686204d3f17 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution.cpp" @@ -1,14 +1,14 @@ -class Solution { -public: - string addBinary(string a, string b) { - string ans; - int i = a.size() - 1, j = b.size() - 1; - for (int carry = 0; i >= 0 || j >= 0 || carry; --i, --j) { - carry += (i >= 0 ? a[i] - '0' : 0) + (j >= 0 ? b[j] - '0' : 0); - ans.push_back((carry % 2) + '0'); - carry /= 2; - } - reverse(ans.begin(), ans.end()); - return ans; - } +class Solution { +public: + string addBinary(string a, string b) { + string ans; + int i = a.size() - 1, j = b.size() - 1; + for (int carry = 0; i >= 0 || j >= 0 || carry; --i, --j) { + carry += (i >= 0 ? a[i] - '0' : 0) + (j >= 0 ? b[j] - '0' : 0); + ans.push_back((carry % 2) + '0'); + carry /= 2; + } + reverse(ans.begin(), ans.end()); + return ans; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution.java" index 66ae1c5ee2f93..74dba05511318 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution.java" @@ -1,12 +1,12 @@ -class Solution { - public String addBinary(String a, String b) { - var sb = new StringBuilder(); - int i = a.length() - 1, j = b.length() - 1; - for (int carry = 0; i >= 0 || j >= 0 || carry > 0; --i, --j) { - carry += (i >= 0 ? a.charAt(i) - '0' : 0) + (j >= 0 ? b.charAt(j) - '0' : 0); - sb.append(carry % 2); - carry /= 2; - } - return sb.reverse().toString(); - } +class Solution { + public String addBinary(String a, String b) { + var sb = new StringBuilder(); + int i = a.length() - 1, j = b.length() - 1; + for (int carry = 0; i >= 0 || j >= 0 || carry > 0; --i, --j) { + carry += (i >= 0 ? a.charAt(i) - '0' : 0) + (j >= 0 ? b.charAt(j) - '0' : 0); + sb.append(carry % 2); + carry /= 2; + } + return sb.reverse().toString(); + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution.py" index 324ddf82389b5..d451827d22b99 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution.py" @@ -1,10 +1,3 @@ -class Solution: - def addBinary(self, a: str, b: str) -> str: - ans = [] - i, j, carry = len(a) - 1, len(b) - 1, 0 - while i >= 0 or j >= 0 or carry: - carry += (0 if i < 0 else int(a[i])) + (0 if j < 0 else int(b[j])) - carry, v = divmod(carry, 2) - ans.append(str(v)) - i, j = i - 1, j - 1 - return "".join(ans[::-1]) +class Solution: + def addBinary(self, a: str, b: str) -> str: + return bin(int(a, 2) + int(b, 2))[2:] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution.ts" index 41271cda5b144..9287735eb29eb 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution.ts" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution.ts" @@ -1,12 +1,3 @@ function addBinary(a: string, b: string): string { - let i = a.length - 1; - let j = b.length - 1; - let ans: number[] = []; - for (let carry = 0; i >= 0 || j >= 0 || carry; --i, --j) { - carry += (i >= 0 ? a[i] : '0').charCodeAt(0) - '0'.charCodeAt(0); - carry += (j >= 0 ? b[j] : '0').charCodeAt(0) - '0'.charCodeAt(0); - ans.push(carry % 2); - carry >>= 1; - } - return ans.reverse().join(''); + return (BigInt('0b' + a) + BigInt('0b' + b)).toString(2); } diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution2.py" new file mode 100644 index 0000000000000..8f15c0c8d670d --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution2.py" @@ -0,0 +1,10 @@ +class Solution: + def addBinary(self, a: str, b: str) -> str: + ans = [] + i, j, carry = len(a) - 1, len(b) - 1, 0 + while i >= 0 or j >= 0 or carry: + carry += (0 if i < 0 else int(a[i])) + (0 if j < 0 else int(b[j])) + carry, v = divmod(carry, 2) + ans.append(str(v)) + i, j = i - 1, j - 1 + return ''.join(ans[::-1]) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution2.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution2.ts" new file mode 100644 index 0000000000000..41271cda5b144 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/Solution2.ts" @@ -0,0 +1,12 @@ +function addBinary(a: string, b: string): string { + let i = a.length - 1; + let j = b.length - 1; + let ans: number[] = []; + for (let carry = 0; i >= 0 || j >= 0 || carry; --i, --j) { + carry += (i >= 0 ? a[i] : '0').charCodeAt(0) - '0'.charCodeAt(0); + carry += (j >= 0 ? b[j] : '0').charCodeAt(0) - '0'.charCodeAt(0); + ans.push(carry % 2); + carry >>= 1; + } + return ans.reverse().join(''); +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 003. \345\211\215 n \344\270\252\346\225\260\345\255\227\344\272\214\350\277\233\345\210\266\344\270\255 1 \347\232\204\344\270\252\346\225\260/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 003. \345\211\215 n \344\270\252\346\225\260\345\255\227\344\272\214\350\277\233\345\210\266\344\270\255 1 \347\232\204\344\270\252\346\225\260/Solution.cpp" index b457994cc3930..08a2967493f4e 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 003. \345\211\215 n \344\270\252\346\225\260\345\255\227\344\272\214\350\277\233\345\210\266\344\270\255 1 \347\232\204\344\270\252\346\225\260/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 003. \345\211\215 n \344\270\252\346\225\260\345\255\227\344\272\214\350\277\233\345\210\266\344\270\255 1 \347\232\204\344\270\252\346\225\260/Solution.cpp" @@ -1,10 +1,10 @@ -class Solution { -public: - vector countBits(int n) { - vector f(n + 1); - for (int i = 1; i <= n; ++i) { - f[i] = f[i & (i - 1)] + 1; - } - return f; - } +class Solution { +public: + vector countBits(int n) { + vector f(n + 1); + for (int i = 1; i <= n; ++i) { + f[i] = f[i & (i - 1)] + 1; + } + return f; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 003. \345\211\215 n \344\270\252\346\225\260\345\255\227\344\272\214\350\277\233\345\210\266\344\270\255 1 \347\232\204\344\270\252\346\225\260/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 003. \345\211\215 n \344\270\252\346\225\260\345\255\227\344\272\214\350\277\233\345\210\266\344\270\255 1 \347\232\204\344\270\252\346\225\260/Solution.java" index 966e07ff5da43..ebbfabaa2223c 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 003. \345\211\215 n \344\270\252\346\225\260\345\255\227\344\272\214\350\277\233\345\210\266\344\270\255 1 \347\232\204\344\270\252\346\225\260/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 003. \345\211\215 n \344\270\252\346\225\260\345\255\227\344\272\214\350\277\233\345\210\266\344\270\255 1 \347\232\204\344\270\252\346\225\260/Solution.java" @@ -1,9 +1,9 @@ -class Solution { - public int[] countBits(int n) { - int[] f = new int[n + 1]; - for (int i = 1; i <= n; ++i) { - f[i] = f[i & (i - 1)] + 1; - } - return f; - } +class Solution { + public int[] countBits(int n) { + int[] f = new int[n + 1]; + for (int i = 1; i <= n; ++i) { + f[i] = f[i & (i - 1)] + 1; + } + return f; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 003. \345\211\215 n \344\270\252\346\225\260\345\255\227\344\272\214\350\277\233\345\210\266\344\270\255 1 \347\232\204\344\270\252\346\225\260/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 003. \345\211\215 n \344\270\252\346\225\260\345\255\227\344\272\214\350\277\233\345\210\266\344\270\255 1 \347\232\204\344\270\252\346\225\260/Solution.py" index 8d1efffa43507..491b6d71b4009 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 003. \345\211\215 n \344\270\252\346\225\260\345\255\227\344\272\214\350\277\233\345\210\266\344\270\255 1 \347\232\204\344\270\252\346\225\260/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 003. \345\211\215 n \344\270\252\346\225\260\345\255\227\344\272\214\350\277\233\345\210\266\344\270\255 1 \347\232\204\344\270\252\346\225\260/Solution.py" @@ -1,6 +1,6 @@ -class Solution: - def countBits(self, n: int) -> List[int]: - f = [0] * (n + 1) - for i in range(1, n + 1): - f[i] = f[i & (i - 1)] + 1 - return f +class Solution: + def countBits(self, n: int) -> List[int]: + f = [0] * (n + 1) + for i in range(1, n + 1): + f[i] = f[i & (i - 1)] + 1 + return f diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 004. \345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 004. \345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/Solution.cpp" index 568d73743504d..78a8a43838d3e 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 004. \345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 004. \345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/Solution.cpp" @@ -1,15 +1,15 @@ -class Solution { -public: - int singleNumber(vector& nums) { - int ans = 0; - for (int i = 0; i < 32; ++i) { - int cnt = 0; - for (int x : nums) { - cnt += (x >> i) & 1; - } - cnt %= 3; - ans |= cnt << i; - } - return ans; - } +class Solution { +public: + int singleNumber(vector& nums) { + int ans = 0; + for (int i = 0; i < 32; ++i) { + int cnt = 0; + for (int x : nums) { + cnt += (x >> i) & 1; + } + cnt %= 3; + ans |= cnt << i; + } + return ans; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 004. \345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 004. \345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/Solution.java" index 27870248b7f72..5b7c8c5bad977 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 004. \345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 004. \345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/Solution.java" @@ -1,14 +1,14 @@ -class Solution { - public int singleNumber(int[] nums) { - int ans = 0; - for (int i = 0; i < 32; ++i) { - int cnt = 0; - for (int x : nums) { - cnt += x >> i & 1; - } - cnt %= 3; - ans |= cnt << i; - } - return ans; - } +class Solution { + public int singleNumber(int[] nums) { + int ans = 0; + for (int i = 0; i < 32; ++i) { + int cnt = 0; + for (int x : nums) { + cnt += x >> i & 1; + } + cnt %= 3; + ans |= cnt << i; + } + return ans; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 004. \345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 004. \345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/Solution.py" index 62b1fdce099ec..0b8d769026755 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 004. \345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 004. \345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/Solution.py" @@ -1,11 +1,11 @@ -class Solution: - def singleNumber(self, nums: List[int]) -> int: - ans = 0 - for i in range(32): - cnt = sum(x >> i & 1 for x in nums) - if cnt % 3: - if i == 31: - ans -= 1 << i - else: - ans |= 1 << i - return ans +class Solution: + def singleNumber(self, nums: List[int]) -> int: + ans = 0 + for i in range(32): + cnt = sum(x >> i & 1 for x in nums) + if cnt % 3: + if i == 31: + ans -= 1 << i + else: + ans |= 1 << i + return ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 005. \345\215\225\350\257\215\351\225\277\345\272\246\347\232\204\346\234\200\345\244\247\344\271\230\347\247\257/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 005. \345\215\225\350\257\215\351\225\277\345\272\246\347\232\204\346\234\200\345\244\247\344\271\230\347\247\257/Solution.cpp" index 98e126945025b..97c22b152443f 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 005. \345\215\225\350\257\215\351\225\277\345\272\246\347\232\204\346\234\200\345\244\247\344\271\230\347\247\257/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 005. \345\215\225\350\257\215\351\225\277\345\272\246\347\232\204\346\234\200\345\244\247\344\271\230\347\247\257/Solution.cpp" @@ -1,22 +1,22 @@ -class Solution { -public: - int maxProduct(vector& words) { - int n = words.size(); - int mask[n]; - memset(mask, 0, sizeof(mask)); - for (int i = 0; i < n; i++) { - for (char c : words[i]) { - mask[i] |= 1 << (c - 'a'); - } - } - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = i + 1; j < n; ++j) { - if ((mask[i] & mask[j]) == 0) { - ans = max(ans, int(words[i].size() * words[j].size())); - } - } - } - return ans; - } +class Solution { +public: + int maxProduct(vector& words) { + int n = words.size(); + int mask[n]; + memset(mask, 0, sizeof(mask)); + for (int i = 0; i < n; i++) { + for (char c : words[i]) { + mask[i] |= 1 << (c - 'a'); + } + } + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + if ((mask[i] & mask[j]) == 0) { + ans = max(ans, int(words[i].size() * words[j].size())); + } + } + } + return ans; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 005. \345\215\225\350\257\215\351\225\277\345\272\246\347\232\204\346\234\200\345\244\247\344\271\230\347\247\257/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 005. \345\215\225\350\257\215\351\225\277\345\272\246\347\232\204\346\234\200\345\244\247\344\271\230\347\247\257/Solution.java" index fca2e5f1aae96..43d3b4213988d 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 005. \345\215\225\350\257\215\351\225\277\345\272\246\347\232\204\346\234\200\345\244\247\344\271\230\347\247\257/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 005. \345\215\225\350\257\215\351\225\277\345\272\246\347\232\204\346\234\200\345\244\247\344\271\230\347\247\257/Solution.java" @@ -1,20 +1,20 @@ -class Solution { - public int maxProduct(String[] words) { - int n = words.length; - int[] mask = new int[n]; - for (int i = 0; i < n; ++i) { - for (char c : words[i].toCharArray()) { - mask[i] |= 1 << (c - 'a'); - } - } - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = i + 1; j < n; ++j) { - if ((mask[i] & mask[j]) == 0) { - ans = Math.max(ans, words[i].length() * words[j].length()); - } - } - } - return ans; - } +class Solution { + public int maxProduct(String[] words) { + int n = words.length; + int[] mask = new int[n]; + for (int i = 0; i < n; ++i) { + for (char c : words[i].toCharArray()) { + mask[i] |= 1 << (c - 'a'); + } + } + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + if ((mask[i] & mask[j]) == 0) { + ans = Math.max(ans, words[i].length() * words[j].length()); + } + } + } + return ans; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 005. \345\215\225\350\257\215\351\225\277\345\272\246\347\232\204\346\234\200\345\244\247\344\271\230\347\247\257/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 005. \345\215\225\350\257\215\351\225\277\345\272\246\347\232\204\346\234\200\345\244\247\344\271\230\347\247\257/Solution.py" index 7e47ac2e99aef..015ecf07ebcfa 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 005. \345\215\225\350\257\215\351\225\277\345\272\246\347\232\204\346\234\200\345\244\247\344\271\230\347\247\257/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 005. \345\215\225\350\257\215\351\225\277\345\272\246\347\232\204\346\234\200\345\244\247\344\271\230\347\247\257/Solution.py" @@ -1,12 +1,12 @@ -class Solution: - def maxProduct(self, words: List[str]) -> int: - mask = [0] * len(words) - for i, w in enumerate(words): - for c in w: - mask[i] |= 1 << (ord(c) - ord("a")) - ans = 0 - for i, a in enumerate(words): - for j, b in enumerate(words[i + 1 :], i + 1): - if (mask[i] & mask[j]) == 0: - ans = max(ans, len(a) * len(b)) - return ans +class Solution: + def maxProduct(self, words: List[str]) -> int: + mask = [0] * len(words) + for i, w in enumerate(words): + for c in w: + mask[i] |= 1 << (ord(c) - ord("a")) + ans = 0 + for i, a in enumerate(words): + for j, b in enumerate(words[i + 1 :], i + 1): + if (mask[i] & mask[j]) == 0: + ans = max(ans, len(a) * len(b)) + return ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.cpp" index 0e922a493cd53..3fe9cd9ed2120 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.cpp" @@ -1,16 +1,12 @@ -class Solution { -public: - vector twoSum(vector& numbers, int target) { - for (int i = 0, j = numbers.size() - 1;;) { - int x = numbers[i] + numbers[j]; - if (x == target) { - return {i, j}; - } - if (x < target) { - ++i; - } else { - --j; - } - } - } +class Solution { +public: + vector twoSum(vector& numbers, int target) { + for (int i = 0, n = numbers.size();; ++i) { + int x = target - numbers[i]; + int j = lower_bound(numbers.begin() + i + 1, numbers.end(), x) - numbers.begin(); + if (j < n && numbers[j] == x) { + return {i, j}; + } + } + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.go" "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.go" index 3c7ce78504468..b7bd2e9fd65da 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.go" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.go" @@ -1,13 +1,9 @@ func twoSum(numbers []int, target int) []int { - for i, j := 0, len(numbers)-1; ; { - x := numbers[i] + numbers[j] - if x == target { + for i, n := 0, len(numbers); ; i++ { + x := target - numbers[i] + j := sort.SearchInts(numbers[i+1:], x) + i + 1 + if j < n && numbers[j] == x { return []int{i, j} } - if x < target { - i++ - } else { - j-- - } } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.java" index d727bd151e893..9b9b5eab1cd8a 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.java" @@ -1,15 +1,19 @@ -class Solution { - public int[] twoSum(int[] numbers, int target) { - for (int i = 0, j = numbers.length - 1;;) { - int x = numbers[i] + numbers[j]; - if (x == target) { - return new int[] {i, j}; - } - if (x < target) { - ++i; - } else { - --j; - } - } - } +class Solution { + public int[] twoSum(int[] numbers, int target) { + for (int i = 0, n = numbers.length;; ++i) { + int x = target - numbers[i]; + int l = i + 1, r = n - 1; + while (l < r) { + int mid = (l + r) >> 1; + if (numbers[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + if (numbers[l] == x) { + return new int[] {i, l}; + } + } + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.py" index 970b3b771e5a9..7971af175de02 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.py" @@ -1,11 +1,8 @@ -class Solution: - def twoSum(self, numbers: List[int], target: int) -> List[int]: - i, j = 0, len(numbers) - 1 - while i < j: - x = numbers[i] + numbers[j] - if x == target: - return [i, j] - if x < target: - i += 1 - else: - j -= 1 +class Solution: + def twoSum(self, numbers: List[int], target: int) -> List[int]: + n = len(numbers) + for i in range(n - 1): + x = target - numbers[i] + j = bisect_left(numbers, x, lo=i + 1) + if j < n and numbers[j] == x: + return [i, j] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.ts" index 25498551a83c4..770fe2740ff73 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.ts" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution.ts" @@ -1,13 +1,19 @@ function twoSum(numbers: number[], target: number): number[] { - for (let i = 0, j = numbers.length - 1; ; ) { - const x = numbers[i] + numbers[j]; - if (x === target) { - return [i, j]; + const n = numbers.length; + for (let i = 0; ; ++i) { + const x = target - numbers[i]; + let l = i + 1; + let r = n - 1; + while (l < r) { + const mid = (l + r) >> 1; + if (numbers[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } } - if (x < target) { - ++i; - } else { - --j; + if (numbers[l] === x) { + return [i, l]; } } } diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution2.cpp" new file mode 100644 index 0000000000000..c41540a46ecba --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution2.cpp" @@ -0,0 +1,16 @@ +class Solution { +public: + vector twoSum(vector& numbers, int target) { + for (int i = 0, j = numbers.size() - 1;;) { + int x = numbers[i] + numbers[j]; + if (x == target) { + return {i, j}; + } + if (x < target) { + ++i; + } else { + --j; + } + } + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution2.go" new file mode 100644 index 0000000000000..3c7ce78504468 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution2.go" @@ -0,0 +1,13 @@ +func twoSum(numbers []int, target int) []int { + for i, j := 0, len(numbers)-1; ; { + x := numbers[i] + numbers[j] + if x == target { + return []int{i, j} + } + if x < target { + i++ + } else { + j-- + } + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution2.java" new file mode 100644 index 0000000000000..74605584f62ee --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution2.java" @@ -0,0 +1,15 @@ +class Solution { + public int[] twoSum(int[] numbers, int target) { + for (int i = 0, j = numbers.length - 1;;) { + int x = numbers[i] + numbers[j]; + if (x == target) { + return new int[] {i, j}; + } + if (x < target) { + ++i; + } else { + --j; + } + } + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution2.py" new file mode 100644 index 0000000000000..0e133591c5fc1 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution2.py" @@ -0,0 +1,11 @@ +class Solution: + def twoSum(self, numbers: List[int], target: int) -> List[int]: + i, j = 0, len(numbers) - 1 + while i < j: + x = numbers[i] + numbers[j] + if x == target: + return [i, j] + if x < target: + i += 1 + else: + j -= 1 diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution2.rs" "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution2.rs" new file mode 100644 index 0000000000000..8c77af0f1898a --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution2.rs" @@ -0,0 +1,27 @@ +use std::cmp::Ordering; + +impl Solution { + pub fn two_sum(numbers: Vec, target: i32) -> Vec { + let n = numbers.len(); + for i in 0..n - 1 { + let num = target - numbers[i]; + let mut l = i + 1; + let mut r = n - 1; + while l <= r { + let mid = l + (r - l) / 2; + match num.cmp(&numbers[mid]) { + Ordering::Less => { + r = mid - 1; + } + Ordering::Greater => { + l = mid + 1; + } + Ordering::Equal => { + return vec![i as i32, mid as i32]; + } + } + } + } + vec![-1, -1] + } +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution2.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution2.ts" new file mode 100644 index 0000000000000..25498551a83c4 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/Solution2.ts" @@ -0,0 +1,13 @@ +function twoSum(numbers: number[], target: number): number[] { + for (let i = 0, j = numbers.length - 1; ; ) { + const x = numbers[i] + numbers[j]; + if (x === target) { + return [i, j]; + } + if (x < target) { + ++i; + } else { + --j; + } + } +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 007. \346\225\260\347\273\204\344\270\255\345\222\214\344\270\272 0 \347\232\204\344\270\211\344\270\252\346\225\260/Solution.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 007. \346\225\260\347\273\204\344\270\255\345\222\214\344\270\272 0 \347\232\204\344\270\211\344\270\252\346\225\260/Solution.cs" index 8748130bea0e6..e79a80f700603 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 007. \346\225\260\347\273\204\344\270\255\345\222\214\344\270\272 0 \347\232\204\344\270\211\344\270\252\346\225\260/Solution.cs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 007. \346\225\260\347\273\204\344\270\255\345\222\214\344\270\272 0 \347\232\204\344\270\211\344\270\252\346\225\260/Solution.cs" @@ -1,30 +1,30 @@ -public class Solution { - public IList> ThreeSum(int[] nums) { - Array.Sort(nums); - int n = nums.Length; - IList> ans = new List>(); - for (int i = 0; i < n - 2 && nums[i] <= 0; ++i) { - if (i > 0 && nums[i] == nums[i - 1]) { - continue; - } - int j = i + 1, k = n - 1; - while (j < k) { - int x = nums[i] + nums[j] + nums[k]; - if (x < 0) { - ++j; - } else if (x > 0) { - --k; - } else { - ans.Add(new List { nums[i], nums[j--], nums[k--] }); - while (j < k && nums[j] == nums[j + 1]) { - ++j; - } - while (j < k && nums[k] == nums[k + 1]) { - --k; - } - } - } - } - return ans; - } -} \ No newline at end of file +public class Solution { + public IList> ThreeSum(int[] nums) { + Array.Sort(nums); + int n = nums.Length; + IList> ans = new List>(); + for (int i = 0; i < n - 2 && nums[i] <= 0; ++i) { + if (i > 0 && nums[i] == nums[i - 1]) { + continue; + } + int j = i + 1, k = n - 1; + while (j < k) { + int x = nums[i] + nums[j] + nums[k]; + if (x < 0) { + ++j; + } else if (x > 0) { + --k; + } else { + ans.Add(new List { nums[i], nums[j--], nums[k--] }); + while (j < k && nums[j] == nums[j + 1]) { + ++j; + } + while (j < k && nums[k] == nums[k + 1]) { + --k; + } + } + } + } + return ans; + } +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 007. \346\225\260\347\273\204\344\270\255\345\222\214\344\270\272 0 \347\232\204\344\270\211\344\270\252\346\225\260/Solution.rb" "b/lcof2/\345\211\221\346\214\207 Offer II 007. \346\225\260\347\273\204\344\270\255\345\222\214\344\270\272 0 \347\232\204\344\270\211\344\270\252\346\225\260/Solution.rb" index 5dd48ad6284bd..6714ce328e4e7 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 007. \346\225\260\347\273\204\344\270\255\345\222\214\344\270\272 0 \347\232\204\344\270\211\344\270\252\346\225\260/Solution.rb" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 007. \346\225\260\347\273\204\344\270\255\345\222\214\344\270\272 0 \347\232\204\344\270\211\344\270\252\346\225\260/Solution.rb" @@ -1,28 +1,28 @@ -# @param {Integer[]} nums -# @return {Integer[][]} -def three_sum(nums) - res = [] - nums.sort! - - for i in 0..(nums.length - 3) - next if i > 0 && nums[i - 1] == nums[i] - j = i + 1 - k = nums.length - 1 - while j < k do - sum = nums[i] + nums[j] + nums[k] - if sum < 0 - j += 1 - elsif sum > 0 - k -= 1 - else - res += [[nums[i], nums[j], nums[k]]] - j += 1 - k -= 1 - j += 1 while nums[j] == nums[j - 1] - k -= 1 while nums[k] == nums[k + 1] - end - end - end - - res -end +# @param {Integer[]} nums +# @return {Integer[][]} +def three_sum(nums) + res = [] + nums.sort! + + for i in 0..(nums.length - 3) + next if i > 0 && nums[i - 1] == nums[i] + j = i + 1 + k = nums.length - 1 + while j < k do + sum = nums[i] + nums[j] + nums[k] + if sum < 0 + j += 1 + elsif sum > 0 + k -= 1 + else + res += [[nums[i], nums[j], nums[k]]] + j += 1 + k -= 1 + j += 1 while nums[j] == nums[j - 1] + k -= 1 while nums[k] == nums[k + 1] + end + end + end + + res +end diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 008. \345\222\214\345\244\247\344\272\216\347\255\211\344\272\216 target \347\232\204\346\234\200\347\237\255\345\255\220\346\225\260\347\273\204/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 008. \345\222\214\345\244\247\344\272\216\347\255\211\344\272\216 target \347\232\204\346\234\200\347\237\255\345\255\220\346\225\260\347\273\204/Solution.cpp" index 098b56bd2cc0b..0c48e4d94a576 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 008. \345\222\214\345\244\247\344\272\216\347\255\211\344\272\216 target \347\232\204\346\234\200\347\237\255\345\255\220\346\225\260\347\273\204/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 008. \345\222\214\345\244\247\344\272\216\347\255\211\344\272\216 target \347\232\204\346\234\200\347\237\255\345\255\220\346\225\260\347\273\204/Solution.cpp" @@ -1,17 +1,17 @@ -class Solution { -public: - int minSubArrayLen(int target, vector& nums) { - const int inf = 1 << 30; - int ans = inf; - int n = nums.size(); - int s = 0; - for (int i = 0, j = 0; j < n; ++j) { - s += nums[j]; - while (s >= target) { - ans = min(ans, j - i + 1); - s -= nums[i++]; - } - } - return ans == inf ? 0 : ans; - } +class Solution { +public: + int minSubArrayLen(int target, vector& nums) { + const int inf = 1 << 30; + int ans = inf; + int n = nums.size(); + int s = 0; + for (int i = 0, j = 0; j < n; ++j) { + s += nums[j]; + while (s >= target) { + ans = min(ans, j - i + 1); + s -= nums[i++]; + } + } + return ans == inf ? 0 : ans; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 008. \345\222\214\345\244\247\344\272\216\347\255\211\344\272\216 target \347\232\204\346\234\200\347\237\255\345\255\220\346\225\260\347\273\204/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 008. \345\222\214\345\244\247\344\272\216\347\255\211\344\272\216 target \347\232\204\346\234\200\347\237\255\345\255\220\346\225\260\347\273\204/Solution.java" index 25ade37ef352a..662627be12298 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 008. \345\222\214\345\244\247\344\272\216\347\255\211\344\272\216 target \347\232\204\346\234\200\347\237\255\345\255\220\346\225\260\347\273\204/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 008. \345\222\214\345\244\247\344\272\216\347\255\211\344\272\216 target \347\232\204\346\234\200\347\237\255\345\255\220\346\225\260\347\273\204/Solution.java" @@ -1,15 +1,15 @@ -class Solution { - public int minSubArrayLen(int target, int[] nums) { - final int inf = 1 << 30; - int ans = inf; - int s = 0; - for (int i = 0, j = 0; j < nums.length; ++j) { - s += nums[j]; - while (s >= target) { - ans = Math.min(ans, j - i + 1); - s -= nums[i++]; - } - } - return ans == inf ? 0 : ans; - } +class Solution { + public int minSubArrayLen(int target, int[] nums) { + final int inf = 1 << 30; + int ans = inf; + int s = 0; + for (int i = 0, j = 0; j < nums.length; ++j) { + s += nums[j]; + while (s >= target) { + ans = Math.min(ans, j - i + 1); + s -= nums[i++]; + } + } + return ans == inf ? 0 : ans; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 008. \345\222\214\345\244\247\344\272\216\347\255\211\344\272\216 target \347\232\204\346\234\200\347\237\255\345\255\220\346\225\260\347\273\204/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 008. \345\222\214\345\244\247\344\272\216\347\255\211\344\272\216 target \347\232\204\346\234\200\347\237\255\345\255\220\346\225\260\347\273\204/Solution.py" index c5322c9381039..b83c722560df6 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 008. \345\222\214\345\244\247\344\272\216\347\255\211\344\272\216 target \347\232\204\346\234\200\347\237\255\345\255\220\346\225\260\347\273\204/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 008. \345\222\214\345\244\247\344\272\216\347\255\211\344\272\216 target \347\232\204\346\234\200\347\237\255\345\255\220\346\225\260\347\273\204/Solution.py" @@ -1,11 +1,11 @@ -class Solution: - def minSubArrayLen(self, target: int, nums: List[int]) -> int: - ans = inf - s = i = 0 - for j, x in enumerate(nums): - s += x - while s >= target: - ans = min(ans, j - i + 1) - s -= nums[i] - i += 1 - return 0 if ans == inf else ans +class Solution: + def minSubArrayLen(self, target: int, nums: List[int]) -> int: + ans = inf + s = i = 0 + for j, x in enumerate(nums): + s += x + while s >= target: + ans = min(ans, j - i + 1) + s -= nums[i] + i += 1 + return 0 if ans == inf else ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/Solution.cpp" index 1ac989a86e63e..16382d02921a7 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/Solution.cpp" @@ -1,15 +1,15 @@ -class Solution { -public: - int numSubarrayProductLessThanK(vector& nums, int k) { - long long s = 1; - int ans = 0, n = nums.size(); - for (int i = 0, j = 0; j < n; ++j) { - s *= nums[j]; - while (i <= j && s >= k) { - s /= nums[i++]; - } - ans += j - i + 1; - } - return ans; - } +class Solution { +public: + int numSubarrayProductLessThanK(vector& nums, int k) { + long long s = 1; + int ans = 0, n = nums.size(); + for (int i = 0, j = 0; j < n; ++j) { + s *= nums[j]; + while (i <= j && s >= k) { + s /= nums[i++]; + } + ans += j - i + 1; + } + return ans; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/Solution.java" index 8bcac34651804..95f4959678ea3 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/Solution.java" @@ -1,14 +1,14 @@ -class Solution { - public int numSubarrayProductLessThanK(int[] nums, int k) { - long s = 1; - int ans = 0; - for (int i = 0, j = 0; j < nums.length; ++j) { - s *= nums[j]; - while (i <= j && s >= k) { - s /= nums[i++]; - } - ans += j - i + 1; - } - return ans; - } +class Solution { + public int numSubarrayProductLessThanK(int[] nums, int k) { + long s = 1; + int ans = 0; + for (int i = 0, j = 0; j < nums.length; ++j) { + s *= nums[j]; + while (i <= j && s >= k) { + s /= nums[i++]; + } + ans += j - i + 1; + } + return ans; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/Solution.py" index 807b6000cf738..3dbbd46c8c3fa 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/Solution.py" @@ -1,11 +1,11 @@ -class Solution: - def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: - s = 1 - ans = i = 0 - for j, x in enumerate(nums): - s *= x - while i <= j and s >= k: - s //= nums[i] - i += 1 - ans += j - i + 1 - return ans +class Solution: + def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: + s = 1 + ans = i = 0 + for j, x in enumerate(nums): + s *= x + while i <= j and s >= k: + s //= nums[i] + i += 1 + ans += j - i + 1 + return ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 010. \345\222\214\344\270\272 k \347\232\204\345\255\220\346\225\260\347\273\204/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 010. \345\222\214\344\270\272 k \347\232\204\345\255\220\346\225\260\347\273\204/Solution.cpp" index a0172233ed1bf..ca63132f28a2a 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 010. \345\222\214\344\270\272 k \347\232\204\345\255\220\346\225\260\347\273\204/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 010. \345\222\214\344\270\272 k \347\232\204\345\255\220\346\225\260\347\273\204/Solution.cpp" @@ -1,14 +1,14 @@ -class Solution { -public: - int subarraySum(vector& nums, int k) { - unordered_map cnt; - cnt[0] = 1; - int ans = 0, s = 0; - for (int x : nums) { - s += x; - ans += cnt[s - k]; - cnt[s]++; - } - return ans; - } +class Solution { +public: + int subarraySum(vector& nums, int k) { + unordered_map cnt; + cnt[0] = 1; + int ans = 0, s = 0; + for (int x : nums) { + s += x; + ans += cnt[s - k]; + cnt[s]++; + } + return ans; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 010. \345\222\214\344\270\272 k \347\232\204\345\255\220\346\225\260\347\273\204/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 010. \345\222\214\344\270\272 k \347\232\204\345\255\220\346\225\260\347\273\204/Solution.java" index 314390902bd2a..cfb0264824894 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 010. \345\222\214\344\270\272 k \347\232\204\345\255\220\346\225\260\347\273\204/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 010. \345\222\214\344\270\272 k \347\232\204\345\255\220\346\225\260\347\273\204/Solution.java" @@ -1,13 +1,13 @@ -class Solution { - public int subarraySum(int[] nums, int k) { - Map cnt = new HashMap<>(); - cnt.put(0, 1); - int ans = 0, s = 0; - for (int x : nums) { - s += x; - ans += cnt.getOrDefault(s - k, 0); - cnt.merge(s, 1, Integer::sum); - } - return ans; - } +class Solution { + public int subarraySum(int[] nums, int k) { + Map cnt = new HashMap<>(); + cnt.put(0, 1); + int ans = 0, s = 0; + for (int x : nums) { + s += x; + ans += cnt.getOrDefault(s - k, 0); + cnt.merge(s, 1, Integer::sum); + } + return ans; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 010. \345\222\214\344\270\272 k \347\232\204\345\255\220\346\225\260\347\273\204/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 010. \345\222\214\344\270\272 k \347\232\204\345\255\220\346\225\260\347\273\204/Solution.py" index 7538dd2af2e00..3b73d683bea41 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 010. \345\222\214\344\270\272 k \347\232\204\345\255\220\346\225\260\347\273\204/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 010. \345\222\214\344\270\272 k \347\232\204\345\255\220\346\225\260\347\273\204/Solution.py" @@ -1,9 +1,9 @@ -class Solution: - def subarraySum(self, nums: List[int], k: int) -> int: - cnt = Counter({0: 1}) - ans = s = 0 - for x in nums: - s += x - ans += cnt[s - k] - cnt[s] += 1 - return ans +class Solution: + def subarraySum(self, nums: List[int], k: int) -> int: + cnt = Counter({0: 1}) + ans = s = 0 + for x in nums: + s += x + ans += cnt[s - k] + cnt[s] += 1 + return ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 011. 0 \345\222\214 1 \344\270\252\346\225\260\347\233\270\345\220\214\347\232\204\345\255\220\346\225\260\347\273\204/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 011. 0 \345\222\214 1 \344\270\252\346\225\260\347\233\270\345\220\214\347\232\204\345\255\220\346\225\260\347\273\204/Solution.cpp" index 0dc06ce5a1818..55167b6d92387 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 011. 0 \345\222\214 1 \344\270\252\346\225\260\347\233\270\345\220\214\347\232\204\345\255\220\346\225\260\347\273\204/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 011. 0 \345\222\214 1 \344\270\252\346\225\260\347\233\270\345\220\214\347\232\204\345\255\220\346\225\260\347\273\204/Solution.cpp" @@ -1,18 +1,18 @@ -class Solution { -public: - int findMaxLength(vector& nums) { - unordered_map d; - d[0] = -1; - int ans = 0, s = 0; - int n = nums.size(); - for (int i = 0; i < n; ++i) { - s += nums[i] ? 1 : -1; - if (d.count(s)) { - ans = max(ans, i - d[s]); - } else { - d[s] = i; - } - } - return ans; - } +class Solution { +public: + int findMaxLength(vector& nums) { + unordered_map d; + d[0] = -1; + int ans = 0, s = 0; + int n = nums.size(); + for (int i = 0; i < n; ++i) { + s += nums[i] ? 1 : -1; + if (d.count(s)) { + ans = max(ans, i - d[s]); + } else { + d[s] = i; + } + } + return ans; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 011. 0 \345\222\214 1 \344\270\252\346\225\260\347\233\270\345\220\214\347\232\204\345\255\220\346\225\260\347\273\204/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 011. 0 \345\222\214 1 \344\270\252\346\225\260\347\233\270\345\220\214\347\232\204\345\255\220\346\225\260\347\273\204/Solution.java" index e5215988fdaf5..54566919b6662 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 011. 0 \345\222\214 1 \344\270\252\346\225\260\347\233\270\345\220\214\347\232\204\345\255\220\346\225\260\347\273\204/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 011. 0 \345\222\214 1 \344\270\252\346\225\260\347\233\270\345\220\214\347\232\204\345\255\220\346\225\260\347\273\204/Solution.java" @@ -1,16 +1,16 @@ -class Solution { - public int findMaxLength(int[] nums) { - Map d = new HashMap<>(); - d.put(0, -1); - int ans = 0, s = 0; - for (int i = 0; i < nums.length; ++i) { - s += nums[i] == 0 ? -1 : 1; - if (d.containsKey(s)) { - ans = Math.max(ans, i - d.get(s)); - } else { - d.put(s, i); - } - } - return ans; - } +class Solution { + public int findMaxLength(int[] nums) { + Map d = new HashMap<>(); + d.put(0, -1); + int ans = 0, s = 0; + for (int i = 0; i < nums.length; ++i) { + s += nums[i] == 0 ? -1 : 1; + if (d.containsKey(s)) { + ans = Math.max(ans, i - d.get(s)); + } else { + d.put(s, i); + } + } + return ans; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 011. 0 \345\222\214 1 \344\270\252\346\225\260\347\233\270\345\220\214\347\232\204\345\255\220\346\225\260\347\273\204/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 011. 0 \345\222\214 1 \344\270\252\346\225\260\347\233\270\345\220\214\347\232\204\345\255\220\346\225\260\347\273\204/Solution.py" index 216fb2ef5ba9e..0c5c9dda41e48 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 011. 0 \345\222\214 1 \344\270\252\346\225\260\347\233\270\345\220\214\347\232\204\345\255\220\346\225\260\347\273\204/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 011. 0 \345\222\214 1 \344\270\252\346\225\260\347\233\270\345\220\214\347\232\204\345\255\220\346\225\260\347\273\204/Solution.py" @@ -1,11 +1,11 @@ -class Solution: - def findMaxLength(self, nums: List[int]) -> int: - d = {0: -1} - ans = s = 0 - for i, x in enumerate(nums): - s += 1 if x else -1 - if s in d: - ans = max(ans, i - d[s]) - else: - d[s] = i - return ans +class Solution: + def findMaxLength(self, nums: List[int]) -> int: + d = {0: -1} + ans = s = 0 + for i, x in enumerate(nums): + s += 1 if x else -1 + if s in d: + ans = max(ans, i - d[s]) + else: + d[s] = i + return ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/Solution.cpp" index 308e4e291eaeb..70bfe373d6c2e 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/Solution.cpp" @@ -1,16 +1,16 @@ -class Solution { -public: - int pivotIndex(vector& nums) { - int left = 0; - int right = accumulate(nums.begin(), nums.end(), 0); - int n = nums.size(); - for (int i = 0; i < n; ++i) { - right -= nums[i]; - if (left == right) { - return i; - } - left += nums[i]; - } - return -1; - } +class Solution { +public: + int pivotIndex(vector& nums) { + int left = 0; + int right = accumulate(nums.begin(), nums.end(), 0); + int n = nums.size(); + for (int i = 0; i < n; ++i) { + right -= nums[i]; + if (left == right) { + return i; + } + left += nums[i]; + } + return -1; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/Solution.java" index 2354e6e002db1..99603e931640f 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/Solution.java" @@ -1,17 +1,17 @@ -class Solution { - public int pivotIndex(int[] nums) { - int left = 0, right = 0; - for (int x : nums) { - right += x; - } - int n = nums.length; - for (int i = 0; i < n; ++i) { - right -= nums[i]; - if (left == right) { - return i; - } - left += nums[i]; - } - return -1; - } +class Solution { + public int pivotIndex(int[] nums) { + int left = 0, right = 0; + for (int x : nums) { + right += x; + } + int n = nums.length; + for (int i = 0; i < n; ++i) { + right -= nums[i]; + if (left == right) { + return i; + } + left += nums[i]; + } + return -1; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/Solution.php" "b/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/Solution.php" index 56cc02bd2cafd..19ef175e5d586 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/Solution.php" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/Solution.php" @@ -15,4 +15,4 @@ function pivotIndex($nums) { } return -1; } -} \ No newline at end of file +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/Solution.py" index 1edb93f459e19..8af90cad14a14 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/Solution.py" @@ -1,9 +1,9 @@ -class Solution: - def pivotIndex(self, nums: List[int]) -> int: - left, right = 0, sum(nums) - for i, x in enumerate(nums): - right -= x - if left == right: - return i - left += x - return -1 +class Solution: + def pivotIndex(self, nums: List[int]) -> int: + left, right = 0, sum(nums) + for i, x in enumerate(nums): + right -= x + if left == right: + return i + left += x + return -1 diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/Solution.cpp" index b85d408946081..9ce09a8c3edd1 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/Solution.cpp" @@ -1,26 +1,26 @@ -class NumMatrix { -public: - NumMatrix(vector>& matrix) { - int m = matrix.size(); - int n = matrix[0].size(); - s.resize(m + 1, vector(n + 1, 0)); - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + matrix[i - 1][j - 1]; - } - } - } - - int sumRegion(int row1, int col1, int row2, int col2) { - return s[row2 + 1][col2 + 1] - s[row2 + 1][col1] - s[row1][col2 + 1] + s[row1][col1]; - } - -private: - vector> s; -}; - -/** - * Your NumMatrix object will be instantiated and called as such: - * NumMatrix* obj = new NumMatrix(matrix); - * int param_1 = obj->sumRegion(row1,col1,row2,col2); +class NumMatrix { +public: + NumMatrix(vector>& matrix) { + int m = matrix.size(); + int n = matrix[0].size(); + s.resize(m + 1, vector(n + 1, 0)); + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + matrix[i - 1][j - 1]; + } + } + } + + int sumRegion(int row1, int col1, int row2, int col2) { + return s[row2 + 1][col2 + 1] - s[row2 + 1][col1] - s[row1][col2 + 1] + s[row1][col1]; + } + +private: + vector> s; +}; + +/** + * Your NumMatrix object will be instantiated and called as such: + * NumMatrix* obj = new NumMatrix(matrix); + * int param_1 = obj->sumRegion(row1,col1,row2,col2); */ \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/Solution.java" index 4b614d3dbe5bb..7bff61098c51d 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/Solution.java" @@ -1,24 +1,24 @@ -class NumMatrix { - private int[][] s; - - public NumMatrix(int[][] matrix) { - int m = matrix.length; - int n = matrix[0].length; - s = new int[m + 1][n + 1]; - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + matrix[i - 1][j - 1]; - } - } - } - - public int sumRegion(int row1, int col1, int row2, int col2) { - return s[row2 + 1][col2 + 1] - s[row2 + 1][col1] - s[row1][col2 + 1] + s[row1][col1]; - } -} - -/** - * Your NumMatrix object will be instantiated and called as such: - * NumMatrix obj = new NumMatrix(matrix); - * int param_1 = obj.sumRegion(row1,col1,row2,col2); +class NumMatrix { + private int[][] s; + + public NumMatrix(int[][] matrix) { + int m = matrix.length; + int n = matrix[0].length; + s = new int[m + 1][n + 1]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + matrix[i - 1][j - 1]; + } + } + } + + public int sumRegion(int row1, int col1, int row2, int col2) { + return s[row2 + 1][col2 + 1] - s[row2 + 1][col1] - s[row1][col2 + 1] + s[row1][col1]; + } +} + +/** + * Your NumMatrix object will be instantiated and called as such: + * NumMatrix obj = new NumMatrix(matrix); + * int param_1 = obj.sumRegion(row1,col1,row2,col2); */ \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/Solution.py" index 71897d74d0c01..1c467fb229293 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/Solution.py" @@ -1,21 +1,21 @@ -class NumMatrix: - def __init__(self, matrix: List[List[int]]): - self.s = [[0] * (len(matrix[0]) + 1) for _ in range(len(matrix) + 1)] - for i, row in enumerate(matrix, 1): - for j, x in enumerate(row, 1): - self.s[i][j] = ( - self.s[i - 1][j] + self.s[i][j - 1] - self.s[i - 1][j - 1] + x - ) - - def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int: - return ( - self.s[row2 + 1][col2 + 1] - - self.s[row2 + 1][col1] - - self.s[row1][col2 + 1] - + self.s[row1][col1] - ) - - -# Your NumMatrix object will be instantiated and called as such: -# obj = NumMatrix(matrix) -# param_1 = obj.sumRegion(row1,col1,row2,col2) +class NumMatrix: + def __init__(self, matrix: List[List[int]]): + self.s = [[0] * (len(matrix[0]) + 1) for _ in range(len(matrix) + 1)] + for i, row in enumerate(matrix, 1): + for j, x in enumerate(row, 1): + self.s[i][j] = ( + self.s[i - 1][j] + self.s[i][j - 1] - self.s[i - 1][j - 1] + x + ) + + def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int: + return ( + self.s[row2 + 1][col2 + 1] + - self.s[row2 + 1][col1] + - self.s[row1][col2 + 1] + + self.s[row1][col1] + ) + + +# Your NumMatrix object will be instantiated and called as such: +# obj = NumMatrix(matrix) +# param_1 = obj.sumRegion(row1,col1,row2,col2) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.cpp" index 90a623c18a0fe..113f59a8238d9 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.cpp" @@ -1,45 +1,25 @@ -class Solution { -public: - bool checkInclusion(string s1, string s2) { - int m = s1.size(), n = s2.size(); - if (m > n) { - return false; - } - vector cnt(26); - for (int i = 0; i < m; ++i) { - --cnt[s1[i] - 'a']; - ++cnt[s2[i] - 'a']; - } - int diff = 0; - for (int x : cnt) { - if (x != 0) { - ++diff; - } - } - if (diff == 0) { - return true; - } - for (int i = m; i < n; ++i) { - int a = s2[i - m] - 'a'; - int b = s2[i] - 'a'; - if (cnt[a] == 0) { - ++diff; - } - --cnt[a]; - if (cnt[a] == 0) { - --diff; - } - if (cnt[b] == 0) { - ++diff; - } - ++cnt[b]; - if (cnt[b] == 0) { - --diff; - } - if (diff == 0) { - return true; - } - } - return false; - } +class Solution { +public: + bool checkInclusion(string s1, string s2) { + int m = s1.size(), n = s2.size(); + if (m > n) { + return false; + } + vector cnt1(26), cnt2(26); + for (int i = 0; i < m; ++i) { + ++cnt1[s1[i] - 'a']; + ++cnt2[s2[i] - 'a']; + } + if (cnt1 == cnt2) { + return true; + } + for (int i = m; i < n; ++i) { + ++cnt2[s2[i] - 'a']; + --cnt2[s2[i - m] - 'a']; + if (cnt1 == cnt2) { + return true; + } + } + return false; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.go" "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.go" index 3bec082f27123..656509286d850 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.go" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.go" @@ -3,37 +3,18 @@ func checkInclusion(s1 string, s2 string) bool { if m > n { return false } - cnt := [26]int{} + var cnt1, cnt2 [26]int for i := 0; i < m; i++ { - cnt[s1[i]-'a']-- - cnt[s2[i]-'a']++ + cnt1[s1[i]-'a']++ + cnt2[s2[i]-'a']++ } - diff := 0 - for _, x := range cnt { - if x != 0 { - diff++ - } - } - if diff == 0 { + if cnt1 == cnt2 { return true } for i := m; i < n; i++ { - a, b := s2[i-m]-'a', s2[i]-'a' - if cnt[a] == 0 { - diff++ - } - cnt[a]-- - if cnt[a] == 0 { - diff-- - } - if cnt[b] == 0 { - diff++ - } - cnt[b]++ - if cnt[b] == 0 { - diff-- - } - if diff == 0 { + cnt2[s2[i]-'a']++ + cnt2[s2[i-m]-'a']-- + if cnt1 == cnt2 { return true } } diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.java" index a6832f343f97a..58ab42e2235c7 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.java" @@ -1,45 +1,26 @@ -class Solution { - public boolean checkInclusion(String s1, String s2) { - int m = s1.length(); - int n = s2.length(); - if (m > n) { - return false; - } - int[] cnt = new int[26]; - for (int i = 0; i < m; ++i) { - --cnt[s1.charAt(i) - 'a']; - ++cnt[s2.charAt(i) - 'a']; - } - int diff = 0; - for (int x : cnt) { - if (x != 0) { - ++diff; - } - } - if (diff == 0) { - return true; - } - for (int i = m; i < n; ++i) { - int a = s2.charAt(i - m) - 'a'; - int b = s2.charAt(i) - 'a'; - if (cnt[a] == 0) { - ++diff; - } - --cnt[a]; - if (cnt[a] == 0) { - --diff; - } - if (cnt[b] == 0) { - ++diff; - } - ++cnt[b]; - if (cnt[b] == 0) { - --diff; - } - if (diff == 0) { - return true; - } - } - return false; - } +class Solution { + public boolean checkInclusion(String s1, String s2) { + int m = s1.length(); + int n = s2.length(); + if (m > n) { + return false; + } + int[] cnt1 = new int[26]; + int[] cnt2 = new int[26]; + for (int i = 0; i < m; ++i) { + ++cnt1[s1.charAt(i) - 'a']; + ++cnt2[s2.charAt(i) - 'a']; + } + if (Arrays.equals(cnt1, cnt2)) { + return true; + } + for (int i = m; i < n; ++i) { + ++cnt2[s2.charAt(i) - 'a']; + --cnt2[s2.charAt(i - m) - 'a']; + if (Arrays.equals(cnt1, cnt2)) { + return true; + } + } + return false; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.py" index 272d508752baf..8165ecbd5336a 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.py" @@ -1,27 +1,15 @@ -class Solution: - def checkInclusion(self, s1: str, s2: str) -> bool: - m, n = len(s1), len(s2) - if m > n: - return False - cnt = Counter() - for a, b in zip(s1, s2): - cnt[a] -= 1 - cnt[b] += 1 - diff = sum(x != 0 for x in cnt.values()) - if diff == 0: - return True - for i in range(m, n): - a, b = s2[i - m], s2[i] - if cnt[a] == 0: - diff += 1 - cnt[a] -= 1 - if cnt[a] == 0: - diff -= 1 - if cnt[b] == 0: - diff += 1 - cnt[b] += 1 - if cnt[b] == 0: - diff -= 1 - if diff == 0: - return True - return False +class Solution: + def checkInclusion(self, s1: str, s2: str) -> bool: + m, n = len(s1), len(s2) + if m > n: + return False + cnt1 = Counter(s1) + cnt2 = Counter(s2[:m]) + if cnt1 == cnt2: + return True + for i in range(m, n): + cnt2[s2[i]] += 1 + cnt2[s2[i - m]] -= 1 + if cnt1 == cnt2: + return True + return False diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.ts" index 498a9c9755a0e..3cdb3579a96e2 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.ts" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution.ts" @@ -4,36 +4,19 @@ function checkInclusion(s1: string, s2: string): boolean { if (m > n) { return false; } - const cnt: number[] = new Array(26).fill(0); + const cnt1 = new Array(26).fill(0); + const cnt2 = new Array(26).fill(0); for (let i = 0; i < m; ++i) { - --cnt[s1[i].charCodeAt(0) - 'a'.charCodeAt(0)]; - ++cnt[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)]; + ++cnt1[s1[i].charCodeAt(0) - 'a'.charCodeAt(0)]; + ++cnt2[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)]; } - let diff = 0; - for (const x of cnt) { - if (x !== 0) { - ++diff; - } - } - if (diff === 0) { + if (cnt1.toString() === cnt2.toString()) { return true; } for (let i = m; i < n; ++i) { - const a = s2[i - m].charCodeAt(0) - 'a'.charCodeAt(0); - const b = s2[i].charCodeAt(0) - 'a'.charCodeAt(0); - if (cnt[a] === 0) { - ++diff; - } - if (--cnt[a] === 0) { - --diff; - } - if (cnt[b] === 0) { - ++diff; - } - if (++cnt[b] === 0) { - --diff; - } - if (diff === 0) { + ++cnt2[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)]; + --cnt2[s2[i - m].charCodeAt(0) - 'a'.charCodeAt(0)]; + if (cnt1.toString() === cnt2.toString()) { return true; } } diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution2.cpp" new file mode 100644 index 0000000000000..9b546abfeea5c --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution2.cpp" @@ -0,0 +1,45 @@ +class Solution { +public: + bool checkInclusion(string s1, string s2) { + int m = s1.size(), n = s2.size(); + if (m > n) { + return false; + } + vector cnt(26); + for (int i = 0; i < m; ++i) { + --cnt[s1[i] - 'a']; + ++cnt[s2[i] - 'a']; + } + int diff = 0; + for (int x : cnt) { + if (x != 0) { + ++diff; + } + } + if (diff == 0) { + return true; + } + for (int i = m; i < n; ++i) { + int a = s2[i - m] - 'a'; + int b = s2[i] - 'a'; + if (cnt[a] == 0) { + ++diff; + } + --cnt[a]; + if (cnt[a] == 0) { + --diff; + } + if (cnt[b] == 0) { + ++diff; + } + ++cnt[b]; + if (cnt[b] == 0) { + --diff; + } + if (diff == 0) { + return true; + } + } + return false; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution2.go" new file mode 100644 index 0000000000000..3bec082f27123 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution2.go" @@ -0,0 +1,41 @@ +func checkInclusion(s1 string, s2 string) bool { + m, n := len(s1), len(s2) + if m > n { + return false + } + cnt := [26]int{} + for i := 0; i < m; i++ { + cnt[s1[i]-'a']-- + cnt[s2[i]-'a']++ + } + diff := 0 + for _, x := range cnt { + if x != 0 { + diff++ + } + } + if diff == 0 { + return true + } + for i := m; i < n; i++ { + a, b := s2[i-m]-'a', s2[i]-'a' + if cnt[a] == 0 { + diff++ + } + cnt[a]-- + if cnt[a] == 0 { + diff-- + } + if cnt[b] == 0 { + diff++ + } + cnt[b]++ + if cnt[b] == 0 { + diff-- + } + if diff == 0 { + return true + } + } + return false +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution2.java" new file mode 100644 index 0000000000000..e94310b038fdd --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution2.java" @@ -0,0 +1,45 @@ +class Solution { + public boolean checkInclusion(String s1, String s2) { + int m = s1.length(); + int n = s2.length(); + if (m > n) { + return false; + } + int[] cnt = new int[26]; + for (int i = 0; i < m; ++i) { + --cnt[s1.charAt(i) - 'a']; + ++cnt[s2.charAt(i) - 'a']; + } + int diff = 0; + for (int x : cnt) { + if (x != 0) { + ++diff; + } + } + if (diff == 0) { + return true; + } + for (int i = m; i < n; ++i) { + int a = s2.charAt(i - m) - 'a'; + int b = s2.charAt(i) - 'a'; + if (cnt[a] == 0) { + ++diff; + } + --cnt[a]; + if (cnt[a] == 0) { + --diff; + } + if (cnt[b] == 0) { + ++diff; + } + ++cnt[b]; + if (cnt[b] == 0) { + --diff; + } + if (diff == 0) { + return true; + } + } + return false; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution2.py" new file mode 100644 index 0000000000000..402cdad3c9789 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution2.py" @@ -0,0 +1,27 @@ +class Solution: + def checkInclusion(self, s1: str, s2: str) -> bool: + m, n = len(s1), len(s2) + if m > n: + return False + cnt = Counter() + for a, b in zip(s1, s2): + cnt[a] -= 1 + cnt[b] += 1 + diff = sum(x != 0 for x in cnt.values()) + if diff == 0: + return True + for i in range(m, n): + a, b = s2[i - m], s2[i] + if cnt[a] == 0: + diff += 1 + cnt[a] -= 1 + if cnt[a] == 0: + diff -= 1 + if cnt[b] == 0: + diff += 1 + cnt[b] += 1 + if cnt[b] == 0: + diff -= 1 + if diff == 0: + return True + return False diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution2.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution2.ts" new file mode 100644 index 0000000000000..498a9c9755a0e --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/Solution2.ts" @@ -0,0 +1,41 @@ +function checkInclusion(s1: string, s2: string): boolean { + const m = s1.length; + const n = s2.length; + if (m > n) { + return false; + } + const cnt: number[] = new Array(26).fill(0); + for (let i = 0; i < m; ++i) { + --cnt[s1[i].charCodeAt(0) - 'a'.charCodeAt(0)]; + ++cnt[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)]; + } + let diff = 0; + for (const x of cnt) { + if (x !== 0) { + ++diff; + } + } + if (diff === 0) { + return true; + } + for (let i = m; i < n; ++i) { + const a = s2[i - m].charCodeAt(0) - 'a'.charCodeAt(0); + const b = s2[i].charCodeAt(0) - 'a'.charCodeAt(0); + if (cnt[a] === 0) { + ++diff; + } + if (--cnt[a] === 0) { + --diff; + } + if (cnt[b] === 0) { + ++diff; + } + if (++cnt[b] === 0) { + --diff; + } + if (diff === 0) { + return true; + } + } + return false; +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.cpp" index b935da9d1e77a..7743f21174ea9 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.cpp" @@ -1,46 +1,27 @@ -class Solution { -public: - vector findAnagrams(string s, string p) { - int m = s.size(), n = p.size(); - vector ans; - if (m < n) { - return ans; - } - vector cnt(26); - for (int i = 0; i < n; ++i) { - ++cnt[s[i] - 'a']; - --cnt[p[i] - 'a']; - } - int diff = 0; - for (int x : cnt) { - if (x != 0) { - ++diff; - } - } - if (diff == 0) { - ans.push_back(0); - } - for (int i = n; i < m; ++i) { - int a = s[i - n] - 'a'; - int b = s[i] - 'a'; - if (cnt[a] == 0) { - ++diff; - } - --cnt[a]; - if (cnt[a] == 0) { - --diff; - } - if (cnt[b] == 0) { - ++diff; - } - ++cnt[b]; - if (cnt[b] == 0) { - --diff; - } - if (diff == 0) { - ans.push_back(i - n + 1); - } - } - return ans; - } +class Solution { +public: + vector findAnagrams(string s, string p) { + int m = s.size(); + int n = p.size(); + vector ans; + if (m < n) { + return ans; + } + vector cnt1(26), cnt2(26); + for (int i = 0; i < n; ++i) { + ++cnt1[s[i] - 'a']; + ++cnt2[p[i] - 'a']; + } + if (cnt1 == cnt2) { + ans.push_back(0); + } + for (int i = n; i < m; ++i) { + ++cnt1[s[i] - 'a']; + --cnt1[s[i - n] - 'a']; + if (cnt1 == cnt2) { + ans.push_back(i - n + 1); + } + } + return ans; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.go" "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.go" index dca8010ff646c..08ac31f1a78b2 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.go" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.go" @@ -3,37 +3,18 @@ func findAnagrams(s string, p string) (ans []int) { if m < n { return } - cnt := [26]int{} - for i := 0; i < n; i++ { - cnt[s[i]-'a']++ - cnt[p[i]-'a']-- + var cnt1, cnt2 [26]int + for i, ch := range p { + cnt1[s[i]-'a']++ + cnt2[ch-'a']++ } - diff := 0 - for _, x := range cnt { - if x != 0 { - diff++ - } - } - if diff == 0 { + if cnt1 == cnt2 { ans = append(ans, 0) } for i := n; i < m; i++ { - a, b := s[i-n]-'a', s[i]-'a' - if cnt[a] == 0 { - diff++ - } - cnt[a]-- - if cnt[a] == 0 { - diff-- - } - if cnt[b] == 0 { - diff++ - } - cnt[b]++ - if cnt[b] == 0 { - diff-- - } - if diff == 0 { + cnt1[s[i]-'a']++ + cnt1[s[i-n]-'a']-- + if cnt1 == cnt2 { ans = append(ans, i-n+1) } } diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.java" index d708a248a59a1..9d970dcac7d81 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.java" @@ -1,46 +1,27 @@ -class Solution { - public List findAnagrams(String s, String p) { - int m = s.length(); - int n = p.length(); - List ans = new ArrayList<>(); - if (m < n) { - return ans; - } - int[] cnt = new int[26]; - for (int i = 0; i < n; ++i) { - ++cnt[s.charAt(i) - 'a']; - --cnt[p.charAt(i) - 'a']; - } - int diff = 0; - for (int x : cnt) { - if (x != 0) { - ++diff; - } - } - if (diff == 0) { - ans.add(0); - } - for (int i = n; i < m; ++i) { - int a = s.charAt(i - n) - 'a'; - int b = s.charAt(i) - 'a'; - if (cnt[a] == 0) { - ++diff; - } - --cnt[a]; - if (cnt[a] == 0) { - --diff; - } - if (cnt[b] == 0) { - ++diff; - } - ++cnt[b]; - if (cnt[b] == 0) { - --diff; - } - if (diff == 0) { - ans.add(i - n + 1); - } - } - return ans; - } +class Solution { + public List findAnagrams(String s, String p) { + int m = s.length(); + int n = p.length(); + List ans = new ArrayList<>(); + if (m < n) { + return ans; + } + int[] cnt1 = new int[26]; + int[] cnt2 = new int[26]; + for (int i = 0; i < n; ++i) { + ++cnt1[s.charAt(i) - 'a']; + ++cnt2[p.charAt(i) - 'a']; + } + if (Arrays.equals(cnt1, cnt2)) { + ans.add(0); + } + for (int i = n; i < m; ++i) { + ++cnt1[s.charAt(i) - 'a']; + --cnt1[s.charAt(i - n) - 'a']; + if (Arrays.equals(cnt1, cnt2)) { + ans.add(i - n + 1); + } + } + return ans; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.py" index c1c4b269ce771..9a9ad97e182dc 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.py" @@ -1,28 +1,16 @@ -class Solution: - def findAnagrams(self, s: str, p: str) -> List[int]: - m, n = len(s), len(p) - if m < n: - return [] - cnt = Counter() - for a, b in zip(s, p): - cnt[a] += 1 - cnt[b] -= 1 - diff = sum(x != 0 for x in cnt.values()) - ans = [] - if diff == 0: - ans.append(0) - for i in range(n, m): - a, b = s[i - n], s[i] - if cnt[a] == 0: - diff += 1 - cnt[a] -= 1 - if cnt[a] == 0: - diff -= 1 - if cnt[b] == 0: - diff += 1 - cnt[b] += 1 - if cnt[b] == 0: - diff -= 1 - if diff == 0: - ans.append(i - n + 1) - return ans +class Solution: + def findAnagrams(self, s: str, p: str) -> List[int]: + m, n = len(s), len(p) + if m < n: + return [] + cnt1 = Counter(s[:n]) + cnt2 = Counter(p) + ans = [] + if cnt1 == cnt2: + ans.append(0) + for i in range(n, m): + cnt1[s[i]] += 1 + cnt1[s[i - n]] -= 1 + if cnt1 == cnt2: + ans.append(i - n + 1) + return ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.ts" index 43b5ae388af90..13afc3fba61bb 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.ts" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution.ts" @@ -5,36 +5,19 @@ function findAnagrams(s: string, p: string): number[] { if (m < n) { return ans; } - const cnt: number[] = new Array(26).fill(0); + const cnt1: number[] = new Array(26).fill(0); + const cnt2: number[] = new Array(26).fill(0); for (let i = 0; i < n; ++i) { - --cnt[p[i].charCodeAt(0) - 'a'.charCodeAt(0)]; - ++cnt[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]; + ++cnt1[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]; + ++cnt2[p[i].charCodeAt(0) - 'a'.charCodeAt(0)]; } - let diff = 0; - for (const x of cnt) { - if (x !== 0) { - ++diff; - } - } - if (diff === 0) { + if (cnt1.toString() === cnt2.toString()) { ans.push(0); } for (let i = n; i < m; ++i) { - const a = s[i - n].charCodeAt(0) - 'a'.charCodeAt(0); - const b = s[i].charCodeAt(0) - 'a'.charCodeAt(0); - if (cnt[a] === 0) { - ++diff; - } - if (--cnt[a] === 0) { - --diff; - } - if (cnt[b] === 0) { - ++diff; - } - if (++cnt[b] === 0) { - --diff; - } - if (diff === 0) { + ++cnt1[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]; + --cnt1[s[i - n].charCodeAt(0) - 'a'.charCodeAt(0)]; + if (cnt1.toString() === cnt2.toString()) { ans.push(i - n + 1); } } diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution2.cpp" new file mode 100644 index 0000000000000..18c10295d8066 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution2.cpp" @@ -0,0 +1,46 @@ +class Solution { +public: + vector findAnagrams(string s, string p) { + int m = s.size(), n = p.size(); + vector ans; + if (m < n) { + return ans; + } + vector cnt(26); + for (int i = 0; i < n; ++i) { + ++cnt[s[i] - 'a']; + --cnt[p[i] - 'a']; + } + int diff = 0; + for (int x : cnt) { + if (x != 0) { + ++diff; + } + } + if (diff == 0) { + ans.push_back(0); + } + for (int i = n; i < m; ++i) { + int a = s[i - n] - 'a'; + int b = s[i] - 'a'; + if (cnt[a] == 0) { + ++diff; + } + --cnt[a]; + if (cnt[a] == 0) { + --diff; + } + if (cnt[b] == 0) { + ++diff; + } + ++cnt[b]; + if (cnt[b] == 0) { + --diff; + } + if (diff == 0) { + ans.push_back(i - n + 1); + } + } + return ans; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution2.go" new file mode 100644 index 0000000000000..dca8010ff646c --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution2.go" @@ -0,0 +1,41 @@ +func findAnagrams(s string, p string) (ans []int) { + m, n := len(s), len(p) + if m < n { + return + } + cnt := [26]int{} + for i := 0; i < n; i++ { + cnt[s[i]-'a']++ + cnt[p[i]-'a']-- + } + diff := 0 + for _, x := range cnt { + if x != 0 { + diff++ + } + } + if diff == 0 { + ans = append(ans, 0) + } + for i := n; i < m; i++ { + a, b := s[i-n]-'a', s[i]-'a' + if cnt[a] == 0 { + diff++ + } + cnt[a]-- + if cnt[a] == 0 { + diff-- + } + if cnt[b] == 0 { + diff++ + } + cnt[b]++ + if cnt[b] == 0 { + diff-- + } + if diff == 0 { + ans = append(ans, i-n+1) + } + } + return +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution2.java" new file mode 100644 index 0000000000000..611adfdd8cbda --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution2.java" @@ -0,0 +1,46 @@ +class Solution { + public List findAnagrams(String s, String p) { + int m = s.length(); + int n = p.length(); + List ans = new ArrayList<>(); + if (m < n) { + return ans; + } + int[] cnt = new int[26]; + for (int i = 0; i < n; ++i) { + ++cnt[s.charAt(i) - 'a']; + --cnt[p.charAt(i) - 'a']; + } + int diff = 0; + for (int x : cnt) { + if (x != 0) { + ++diff; + } + } + if (diff == 0) { + ans.add(0); + } + for (int i = n; i < m; ++i) { + int a = s.charAt(i - n) - 'a'; + int b = s.charAt(i) - 'a'; + if (cnt[a] == 0) { + ++diff; + } + --cnt[a]; + if (cnt[a] == 0) { + --diff; + } + if (cnt[b] == 0) { + ++diff; + } + ++cnt[b]; + if (cnt[b] == 0) { + --diff; + } + if (diff == 0) { + ans.add(i - n + 1); + } + } + return ans; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution2.py" new file mode 100644 index 0000000000000..87326238fdb92 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution2.py" @@ -0,0 +1,28 @@ +class Solution: + def findAnagrams(self, s: str, p: str) -> List[int]: + m, n = len(s), len(p) + if m < n: + return [] + cnt = Counter() + for a, b in zip(s, p): + cnt[a] += 1 + cnt[b] -= 1 + diff = sum(x != 0 for x in cnt.values()) + ans = [] + if diff == 0: + ans.append(0) + for i in range(n, m): + a, b = s[i - n], s[i] + if cnt[a] == 0: + diff += 1 + cnt[a] -= 1 + if cnt[a] == 0: + diff -= 1 + if cnt[b] == 0: + diff += 1 + cnt[b] += 1 + if cnt[b] == 0: + diff -= 1 + if diff == 0: + ans.append(i - n + 1) + return ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution2.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution2.ts" new file mode 100644 index 0000000000000..43b5ae388af90 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/Solution2.ts" @@ -0,0 +1,42 @@ +function findAnagrams(s: string, p: string): number[] { + const m = s.length; + const n = p.length; + const ans: number[] = []; + if (m < n) { + return ans; + } + const cnt: number[] = new Array(26).fill(0); + for (let i = 0; i < n; ++i) { + --cnt[p[i].charCodeAt(0) - 'a'.charCodeAt(0)]; + ++cnt[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]; + } + let diff = 0; + for (const x of cnt) { + if (x !== 0) { + ++diff; + } + } + if (diff === 0) { + ans.push(0); + } + for (let i = n; i < m; ++i) { + const a = s[i - n].charCodeAt(0) - 'a'.charCodeAt(0); + const b = s[i].charCodeAt(0) - 'a'.charCodeAt(0); + if (cnt[a] === 0) { + ++diff; + } + if (--cnt[a] === 0) { + --diff; + } + if (cnt[b] === 0) { + ++diff; + } + if (++cnt[b] === 0) { + --diff; + } + if (diff === 0) { + ans.push(i - n + 1); + } + } + return ans; +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution.cpp" index 909c2c0b5a5e2..880290ebf8141 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution.cpp" @@ -1,16 +1,16 @@ -class Solution { -public: - int lengthOfLongestSubstring(string s) { - bool ss[128] = {false}; - int n = s.size(); - int ans = 0; - for (int i = 0, j = 0; i < n; ++i) { - while (ss[s[i]]) { - ss[s[j++]] = false; - } - ss[s[i]] = true; - ans = max(ans, i - j + 1); - } - return ans; - } +class Solution { +public: + int lengthOfLongestSubstring(string s) { + bool ss[128] = {false}; + int n = s.size(); + int ans = 0; + for (int i = 0, j = 0; i < n; ++i) { + while (ss[s[i]]) { + ss[s[j++]] = false; + } + ss[s[i]] = true; + ans = max(ans, i - j + 1); + } + return ans; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution.java" index 0c0c32e13db7a..4ecaf7468b942 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution.java" @@ -1,16 +1,16 @@ -class Solution { - public int lengthOfLongestSubstring(String s) { - boolean[] ss = new boolean[128]; - int ans = 0, j = 0; - int n = s.length(); - for (int i = 0; i < n; ++i) { - char c = s.charAt(i); - while (ss[c]) { - ss[s.charAt(j++)] = false; - } - ans = Math.max(ans, i - j + 1); - ss[c] = true; - } - return ans; - } +class Solution { + public int lengthOfLongestSubstring(String s) { + boolean[] ss = new boolean[128]; + int ans = 0, j = 0; + int n = s.length(); + for (int i = 0; i < n; ++i) { + char c = s.charAt(i); + while (ss[c]) { + ss[s.charAt(j++)] = false; + } + ans = Math.max(ans, i - j + 1); + ss[c] = true; + } + return ans; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution.py" index 8e5c11bf26bda..e5d0aae335bdb 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution.py" @@ -1,11 +1,11 @@ -class Solution: - def lengthOfLongestSubstring(self, s: str) -> int: - ss = set() - ans = j = 0 - for i, c in enumerate(s): - while c in ss: - ss.remove(s[j]) - j += 1 - ans = max(ans, i - j + 1) - ss.add(c) - return ans +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + ss = set() + ans = j = 0 + for i, c in enumerate(s): + while c in ss: + ss.remove(s[j]) + j += 1 + ans = max(ans, i - j + 1) + ss.add(c) + return ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution.ts" index ec55dc4dab91a..9ecfb9cbd55d6 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution.ts" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution.ts" @@ -1,12 +1,11 @@ function lengthOfLongestSubstring(s: string): number { let ans = 0; - const n = s.length; - const ss: boolean[] = new Array(128).fill(false); - for (let i = 0, j = 0; i < n; ++i) { - while (ss[s[i]]) { - ss[s[j++]] = false; + const vis = new Set(); + for (let i = 0, j = 0; i < s.length; ++i) { + while (vis.has(s[i])) { + vis.delete(s[j++]); } - ss[s[i]] = true; + vis.add(s[i]); ans = Math.max(ans, i - j + 1); } return ans; diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.ts" new file mode 100644 index 0000000000000..ec55dc4dab91a --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/Solution2.ts" @@ -0,0 +1,13 @@ +function lengthOfLongestSubstring(s: string): number { + let ans = 0; + const n = s.length; + const ss: boolean[] = new Array(128).fill(false); + for (let i = 0, j = 0; i < n; ++i) { + while (ss[s[i]]) { + ss[s[j++]] = false; + } + ss[s[i]] = true; + ans = Math.max(ans, i - j + 1); + } + return ans; +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution.go" "b/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution.go" index 8b7b8ddf0ced4..8a934a4e4a362 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution.go" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution.go" @@ -1,82 +1,37 @@ -// func minWindow(s string, t string) string { -// m, n := len(s), len(t) -// if n > m { -// return "" -// } -// need, window := make(map[byte]int), make(map[byte]int) -// for _, r := range t { -// need[byte(r)]++ -// } -// start, minLen := 0, math.MaxInt32 -// left, right := 0, 0 -// for right < m { -// window[s[right]]++ -// right++ -// for check(need, window) { -// if right-left < minLen { -// minLen = right - left -// start = left -// } -// window[s[left]]-- -// left++ -// } -// } -// if minLen == math.MaxInt32 { -// return "" -// } -// return s[start : start+minLen] -// } - -// func check(need, window map[byte]int) bool { -// for k, v := range need { -// if window[k] < v { -// return false -// } -// } -// return true -// } - func minWindow(s string, t string) string { m, n := len(s), len(t) if n > m { return "" } need, window := make(map[byte]int), make(map[byte]int) - needCount, windowCount := 0, 0 for _, r := range t { - if need[byte(r)] == 0 { - needCount++ - } need[byte(r)]++ } start, minLen := 0, math.MaxInt32 left, right := 0, 0 for right < m { - ch := s[right] + window[s[right]]++ right++ - if v, ok := need[ch]; ok { - window[ch]++ - if window[ch] == v { - windowCount++ - } - } - for windowCount == needCount { + for check(need, window) { if right-left < minLen { minLen = right - left start = left } - ch = s[left] + window[s[left]]-- left++ - if v, ok := need[ch]; ok { - if window[ch] == v { - windowCount-- - } - window[ch]-- - } } } if minLen == math.MaxInt32 { return "" } return s[start : start+minLen] +} + +func check(need, window map[byte]int) bool { + for k, v := range need { + if window[k] < v { + return false + } + } + return true } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution.java" index ca3885e3851c7..5a9234e956fdc 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution.java" @@ -1,39 +1,3 @@ -// class Solution { -// public String minWindow(String s, String t) { -// int m = s.length(), n = t.length(); -// if (n > m) { -// return ""; -// } -// Map need = new HashMap<>(); -// Map window = new HashMap<>(); -// for (char ch : t.toCharArray()) { -// need.merge(ch, 1, Integer::sum); -// } -// int start = 0, minLen = Integer.MAX_VALUE; -// int left = 0, right = 0; -// while (right < m) { -// window.merge(s.charAt(right++), 1, Integer::sum); -// while (check(need, window)) { -// if (right - left < minLen) { -// minLen = right - left; -// start = left; -// } -// window.merge(s.charAt(left++), -1, Integer::sum); -// } -// } -// return minLen == Integer.MAX_VALUE ? "" : s.substring(start, start + minLen); -// } - -// private boolean check(Map need, Map window) { -// for (Map.Entry entry : need.entrySet()) { -// if (window.getOrDefault(entry.getKey(), 0) < entry.getValue()) { -// return false; -// } -// } -// return true; -// } -// } - class Solution { public String minWindow(String s, String t) { int m = s.length(), n = t.length(); @@ -42,39 +6,30 @@ public String minWindow(String s, String t) { } Map need = new HashMap<>(); Map window = new HashMap<>(); - int needCount = 0, windowCount = 0; for (char ch : t.toCharArray()) { - if (!need.containsKey(ch)) { - needCount++; - } need.merge(ch, 1, Integer::sum); } int start = 0, minLen = Integer.MAX_VALUE; int left = 0, right = 0; while (right < m) { - char ch = s.charAt(right++); - if (need.containsKey(ch)) { - int val = window.getOrDefault(ch, 0) + 1; - if (val == need.get(ch)) { - windowCount++; - } - window.put(ch, val); - } - while (windowCount == needCount) { + window.merge(s.charAt(right++), 1, Integer::sum); + while (check(need, window)) { if (right - left < minLen) { minLen = right - left; start = left; } - ch = s.charAt(left++); - if (need.containsKey(ch)) { - int val = window.get(ch); - if (val == need.get(ch)) { - windowCount--; - } - window.put(ch, val - 1); - } + window.merge(s.charAt(left++), -1, Integer::sum); } } return minLen == Integer.MAX_VALUE ? "" : s.substring(start, start + minLen); } -} + + private boolean check(Map need, Map window) { + for (Map.Entry entry : need.entrySet()) { + if (window.getOrDefault(entry.getKey(), 0) < entry.getValue()) { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution.py" index 8733bdd4c4db0..362f324881925 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution.py" @@ -1,59 +1,26 @@ -# class Solution: -# def minWindow(self, s: str, t: str) -> str: -# m, n = len(s), len(t) -# if n > m: -# return "" -# need, window = defaultdict(int), defaultdict(int) -# for c in t: -# need[c] += 1 -# start, minLen = 0, inf -# left, right = 0, 0 -# while right < m: -# window[s[right]] += 1 -# right += 1 -# while self.check(need, window): -# if right - left < minLen: -# minLen = right - left -# start = left -# window[s[left]] -= 1 -# left += 1 -# return "" if minLen == inf else s[start:start + minLen] - -# def check(self, need, window): -# for k, v in need.items(): -# if window[k] < v: -# return False -# return True - - class Solution: def minWindow(self, s: str, t: str) -> str: m, n = len(s), len(t) if n > m: return "" need, window = defaultdict(int), defaultdict(int) - needCount, windowCount = 0, 0 for c in t: - if need[c] == 0: - needCount += 1 need[c] += 1 start, minLen = 0, inf left, right = 0, 0 while right < m: - ch = s[right] + window[s[right]] += 1 right += 1 - if ch in need: - window[ch] += 1 - if window[ch] == need[ch]: - windowCount += 1 - while windowCount == needCount: + while self.check(need, window): if right - left < minLen: minLen = right - left start = left - ch = s[left] + window[s[left]] -= 1 left += 1 - if ch in need: - if window[ch] == need[ch]: - windowCount -= 1 - window[ch] -= 1 return "" if minLen == inf else s[start : start + minLen] + + def check(self, need, window): + for k, v in need.items(): + if window[k] < v: + return False + return True diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution2.go" new file mode 100644 index 0000000000000..6c8f97176fba5 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution2.go" @@ -0,0 +1,44 @@ +func minWindow(s string, t string) string { + m, n := len(s), len(t) + if n > m { + return "" + } + need, window := make(map[byte]int), make(map[byte]int) + needCount, windowCount := 0, 0 + for _, r := range t { + if need[byte(r)] == 0 { + needCount++ + } + need[byte(r)]++ + } + start, minLen := 0, math.MaxInt32 + left, right := 0, 0 + for right < m { + ch := s[right] + right++ + if v, ok := need[ch]; ok { + window[ch]++ + if window[ch] == v { + windowCount++ + } + } + for windowCount == needCount { + if right-left < minLen { + minLen = right - left + start = left + } + ch = s[left] + left++ + if v, ok := need[ch]; ok { + if window[ch] == v { + windowCount-- + } + window[ch]-- + } + } + } + if minLen == math.MaxInt32 { + return "" + } + return s[start : start+minLen] +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution2.java" new file mode 100644 index 0000000000000..1f1da220521c4 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution2.java" @@ -0,0 +1,44 @@ +class Solution { + public String minWindow(String s, String t) { + int m = s.length(), n = t.length(); + if (n > m) { + return ""; + } + Map need = new HashMap<>(); + Map window = new HashMap<>(); + int needCount = 0, windowCount = 0; + for (char ch : t.toCharArray()) { + if (!need.containsKey(ch)) { + needCount++; + } + need.merge(ch, 1, Integer::sum); + } + int start = 0, minLen = Integer.MAX_VALUE; + int left = 0, right = 0; + while (right < m) { + char ch = s.charAt(right++); + if (need.containsKey(ch)) { + int val = window.getOrDefault(ch, 0) + 1; + if (val == need.get(ch)) { + windowCount++; + } + window.put(ch, val); + } + while (windowCount == needCount) { + if (right - left < minLen) { + minLen = right - left; + start = left; + } + ch = s.charAt(left++); + if (need.containsKey(ch)) { + int val = window.get(ch); + if (val == need.get(ch)) { + windowCount--; + } + window.put(ch, val - 1); + } + } + } + return minLen == Integer.MAX_VALUE ? "" : s.substring(start, start + minLen); + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution2.py" new file mode 100644 index 0000000000000..37bcbab7a9d19 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/Solution2.py" @@ -0,0 +1,31 @@ +class Solution: + def minWindow(self, s: str, t: str) -> str: + m, n = len(s), len(t) + if n > m: + return "" + need, window = defaultdict(int), defaultdict(int) + needCount, windowCount = 0, 0 + for c in t: + if need[c] == 0: + needCount += 1 + need[c] += 1 + start, minLen = 0, inf + left, right = 0, 0 + while right < m: + ch = s[right] + right += 1 + if ch in need: + window[ch] += 1 + if window[ch] == need[ch]: + windowCount += 1 + while windowCount == needCount: + if right - left < minLen: + minLen = right - left + start = left + ch = s[left] + left += 1 + if ch in need: + if window[ch] == need[ch]: + windowCount -= 1 + window[ch] -= 1 + return "" if minLen == inf else s[start : start + minLen] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 018. \346\234\211\346\225\210\347\232\204\345\233\236\346\226\207/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 018. \346\234\211\346\225\210\347\232\204\345\233\236\346\226\207/Solution.cpp" index 5bd0441865b63..805719409995c 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 018. \346\234\211\346\225\210\347\232\204\345\233\236\346\226\207/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 018. \346\234\211\346\225\210\347\232\204\345\233\236\346\226\207/Solution.cpp" @@ -1,20 +1,20 @@ -class Solution { -public: - bool isPalindrome(string s) { - int i = 0, j = s.size() - 1; - while (i < j) { - while (i < j && !isalnum(s[i])) { - ++i; - } - while (i < j && !isalnum(s[j])) { - --j; - } - if (tolower(s[i]) != tolower(s[j])) { - return false; - } - ++i; - --j; - } - return true; - } +class Solution { +public: + bool isPalindrome(string s) { + int i = 0, j = s.size() - 1; + while (i < j) { + while (i < j && !isalnum(s[i])) { + ++i; + } + while (i < j && !isalnum(s[j])) { + --j; + } + if (tolower(s[i]) != tolower(s[j])) { + return false; + } + ++i; + --j; + } + return true; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 018. \346\234\211\346\225\210\347\232\204\345\233\236\346\226\207/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 018. \346\234\211\346\225\210\347\232\204\345\233\236\346\226\207/Solution.java" index 24246142e53e9..b4e9fc7d1d5fb 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 018. \346\234\211\346\225\210\347\232\204\345\233\236\346\226\207/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 018. \346\234\211\346\225\210\347\232\204\345\233\236\346\226\207/Solution.java" @@ -1,19 +1,19 @@ -class Solution { - public boolean isPalindrome(String s) { - int i = 0, j = s.length() - 1; - while (i < j) { - while (i < j && !Character.isLetterOrDigit(s.charAt(i))) { - ++i; - } - while (i < j && !Character.isLetterOrDigit(s.charAt(j))) { - --j; - } - if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) { - return false; - } - ++i; - --j; - } - return true; - } +class Solution { + public boolean isPalindrome(String s) { + int i = 0, j = s.length() - 1; + while (i < j) { + while (i < j && !Character.isLetterOrDigit(s.charAt(i))) { + ++i; + } + while (i < j && !Character.isLetterOrDigit(s.charAt(j))) { + --j; + } + if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) { + return false; + } + ++i; + --j; + } + return true; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 018. \346\234\211\346\225\210\347\232\204\345\233\236\346\226\207/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 018. \346\234\211\346\225\210\347\232\204\345\233\236\346\226\207/Solution.py" index 0eea9cf942917..c39f43dc3091d 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 018. \346\234\211\346\225\210\347\232\204\345\233\236\346\226\207/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 018. \346\234\211\346\225\210\347\232\204\345\233\236\346\226\207/Solution.py" @@ -1,12 +1,12 @@ -class Solution: - def isPalindrome(self, s: str) -> bool: - i, j = 0, len(s) - 1 - while i < j: - while i < j and not s[i].isalnum(): - i += 1 - while i < j and not s[j].isalnum(): - j -= 1 - if s[i].lower() != s[j].lower(): - return False - i, j = i + 1, j - 1 - return True +class Solution: + def isPalindrome(self, s: str) -> bool: + i, j = 0, len(s) - 1 + while i < j: + while i < j and not s[i].isalnum(): + i += 1 + while i < j and not s[j].isalnum(): + j -= 1 + if s[i].lower() != s[j].lower(): + return False + i, j = i + 1, j - 1 + return True diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/Solution.cpp" index 0677010d0dcb2..5700c65b378ec 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/Solution.cpp" @@ -1,19 +1,19 @@ -class Solution { -public: - bool validPalindrome(string s) { - auto check = [&](int i, int j) { - for (; i < j; ++i, --j) { - if (s[i] != s[j]) { - return false; - } - } - return true; - }; - for (int i = 0, j = s.size() - 1; i < j; ++i, --j) { - if (s[i] != s[j]) { - return check(i + 1, j) || check(i, j - 1); - } - } - return true; - } +class Solution { +public: + bool validPalindrome(string s) { + auto check = [&](int i, int j) { + for (; i < j; ++i, --j) { + if (s[i] != s[j]) { + return false; + } + } + return true; + }; + for (int i = 0, j = s.size() - 1; i < j; ++i, --j) { + if (s[i] != s[j]) { + return check(i + 1, j) || check(i, j - 1); + } + } + return true; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/Solution.java" index a8379a8fafac2..4fd282ceb7f67 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/Solution.java" @@ -1,22 +1,22 @@ -class Solution { - private String s; - - public boolean validPalindrome(String s) { - this.s = s; - for (int i = 0, j = s.length() - 1; i < j; ++i, --j) { - if (s.charAt(i) != s.charAt(j)) { - return check(i + 1, j) || check(i, j - 1); - } - } - return true; - } - - private boolean check(int i, int j) { - for (; i < j; ++i, --j) { - if (s.charAt(i) != s.charAt(j)) { - return false; - } - } - return true; - } +class Solution { + private String s; + + public boolean validPalindrome(String s) { + this.s = s; + for (int i = 0, j = s.length() - 1; i < j; ++i, --j) { + if (s.charAt(i) != s.charAt(j)) { + return check(i + 1, j) || check(i, j - 1); + } + } + return true; + } + + private boolean check(int i, int j) { + for (; i < j; ++i, --j) { + if (s.charAt(i) != s.charAt(j)) { + return false; + } + } + return true; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/Solution.py" index 5525f3f1908ad..b1e7ba11a099b 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/Solution.py" @@ -1,15 +1,15 @@ -class Solution: - def validPalindrome(self, s: str) -> bool: - def check(i: int, j: int) -> bool: - while i < j: - if s[i] != s[j]: - return False - i, j = i + 1, j - 1 - return True - - i, j = 0, len(s) - 1 - while i < j: - if s[i] != s[j]: - return check(i + 1, j) or check(i, j - 1) - i, j = i + 1, j - 1 - return True +class Solution: + def validPalindrome(self, s: str) -> bool: + def check(i: int, j: int) -> bool: + while i < j: + if s[i] != s[j]: + return False + i, j = i + 1, j - 1 + return True + + i, j = 0, len(s) - 1 + while i < j: + if s[i] != s[j]: + return check(i + 1, j) or check(i, j - 1) + i, j = i + 1, j - 1 + return True diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 020. \345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262\347\232\204\344\270\252\346\225\260/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 020. \345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262\347\232\204\344\270\252\346\225\260/Solution.java" index 62987940055cc..314151b3ae55b 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 020. \345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262\347\232\204\344\270\252\346\225\260/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 020. \345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262\347\232\204\344\270\252\346\225\260/Solution.java" @@ -1,25 +1,21 @@ class Solution { + private String s; + public int countSubstrings(String s) { - StringBuilder sb = new StringBuilder("^#"); - for (char ch : s.toCharArray()) { - sb.append(ch).append('#'); - } - String t = sb.append('$').toString(); - int n = t.length(); - int[] p = new int[n]; - int pos = 0, maxRight = 0; int ans = 0; - for (int i = 1; i < n - 1; i++) { - p[i] = maxRight > i ? Math.min(maxRight - i, p[2 * pos - i]) : 1; - while (t.charAt(i - p[i]) == t.charAt(i + p[i])) { - p[i]++; - } - if (i + p[i] > maxRight) { - maxRight = i + p[i]; - pos = i; - } - ans += p[i] / 2; + this.s = s; + for (int i = 0; i < s.length(); ++i) { + ans += f(i, i); + ans += f(i, i + 1); } return ans; } -} + + private int f(int i, int j) { + int cnt = 0; + for (; i >= 0 && j < s.length() && s.charAt(i) == s.charAt(j); --i, ++j) { + ++cnt; + } + return cnt; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 020. \345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262\347\232\204\344\270\252\346\225\260/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 020. \345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262\347\232\204\344\270\252\346\225\260/Solution.py" index 9e0bdd8c6eeb9..a27692da636b7 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 020. \345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262\347\232\204\344\270\252\346\225\260/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 020. \345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262\347\232\204\344\270\252\346\225\260/Solution.py" @@ -1,16 +1,13 @@ class Solution: def countSubstrings(self, s: str) -> int: - t = '^#' + '#'.join(s) + '#$' - n = len(t) - p = [0 for _ in range(n)] - pos, maxRight = 0, 0 - ans = 0 - for i in range(1, n - 1): - p[i] = min(maxRight - i, p[2 * pos - i]) if maxRight > i else 1 - while t[i - p[i]] == t[i + p[i]]: - p[i] += 1 - if i + p[i] > maxRight: - maxRight = i + p[i] - pos = i - ans += p[i] // 2 - return ans + def f(i, j): + cnt = 0 + while i >= 0 and j < n: + if s[i] != s[j]: + break + cnt += 1 + i, j = i - 1, j + 1 + return cnt + + n = len(s) + return sum(f(i, i) + f(i, i + 1) for i in range(n)) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 020. \345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262\347\232\204\344\270\252\346\225\260/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 020. \345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262\347\232\204\344\270\252\346\225\260/Solution2.java" new file mode 100644 index 0000000000000..ad44cfc61d180 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 020. \345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262\347\232\204\344\270\252\346\225\260/Solution2.java" @@ -0,0 +1,25 @@ +class Solution { + public int countSubstrings(String s) { + StringBuilder sb = new StringBuilder("^#"); + for (char ch : s.toCharArray()) { + sb.append(ch).append('#'); + } + String t = sb.append('$').toString(); + int n = t.length(); + int[] p = new int[n]; + int pos = 0, maxRight = 0; + int ans = 0; + for (int i = 1; i < n - 1; i++) { + p[i] = maxRight > i ? Math.min(maxRight - i, p[2 * pos - i]) : 1; + while (t.charAt(i - p[i]) == t.charAt(i + p[i])) { + p[i]++; + } + if (i + p[i] > maxRight) { + maxRight = i + p[i]; + pos = i; + } + ans += p[i] / 2; + } + return ans; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 020. \345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262\347\232\204\344\270\252\346\225\260/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 020. \345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262\347\232\204\344\270\252\346\225\260/Solution2.py" new file mode 100644 index 0000000000000..9e0bdd8c6eeb9 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 020. \345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262\347\232\204\344\270\252\346\225\260/Solution2.py" @@ -0,0 +1,16 @@ +class Solution: + def countSubstrings(self, s: str) -> int: + t = '^#' + '#'.join(s) + '#$' + n = len(t) + p = [0 for _ in range(n)] + pos, maxRight = 0, 0 + ans = 0 + for i in range(1, n - 1): + p[i] = min(maxRight - i, p[2 * pos - i]) if maxRight > i else 1 + while t[i - p[i]] == t[i + p[i]]: + p[i] += 1 + if i + p[i] > maxRight: + maxRight = i + p[i] + pos = i + ans += p[i] // 2 + return ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 021. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254 n \344\270\252\347\273\223\347\202\271/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 021. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254 n \344\270\252\347\273\223\347\202\271/Solution.java" index 3052440a23872..21c965cd6aebb 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 021. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254 n \344\270\252\347\273\223\347\202\271/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 021. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254 n \344\270\252\347\273\223\347\202\271/Solution.java" @@ -22,4 +22,4 @@ public ListNode removeNthFromEnd(ListNode head, int n) { slow.next = slow.next.next; return dummy.next; } -} +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 021. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254 n \344\270\252\347\273\223\347\202\271/Solution.rb" "b/lcof2/\345\211\221\346\214\207 Offer II 021. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254 n \344\270\252\347\273\223\347\202\271/Solution.rb" index c372468c5e140..71dd3e89b8930 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 021. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254 n \344\270\252\347\273\223\347\202\271/Solution.rb" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 021. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254 n \344\270\252\347\273\223\347\202\271/Solution.rb" @@ -10,16 +10,16 @@ # @param {Integer} n # @return {ListNode} def remove_nth_from_end(head, n) - dummy = ListNode.new(0, head) - fast = slow = dummy - while n > 0 - fast = fast.next - n -= 1 - end - while fast.next - slow = slow.next - fast = fast.next - end - slow.next = slow.next.next - return dummy.next -end \ No newline at end of file + dummy = ListNode.new(0, head) + fast = slow = dummy + while n > 0 + fast = fast.next + n -= 1 + end + while fast.next + slow = slow.next + fast = fast.next + end + slow.next = slow.next.next + return dummy.next +end diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution.cs" index 0cf8d6bd470ff..fd70b47359d14 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution.cs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution.cs" @@ -21,4 +21,4 @@ public ListNode ReverseList(ListNode head) { } return pre; } -} \ No newline at end of file +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.java" new file mode 100644 index 0000000000000..b5452241e2842 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 024. \345\217\215\350\275\254\351\223\276\350\241\250/Solution2.java" @@ -0,0 +1,19 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode reverseList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode res = reverseList(head.next); + head.next.next = head; + head.next = null; + return res; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 025. \351\223\276\350\241\250\344\270\255\347\232\204\344\270\244\346\225\260\347\233\270\345\212\240/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 025. \351\223\276\350\241\250\344\270\255\347\232\204\344\270\244\346\225\260\347\233\270\345\212\240/Solution.py" index 5ad34d99ace62..664dc0353dd71 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 025. \351\223\276\350\241\250\344\270\255\347\232\204\344\270\244\346\225\260\347\233\270\345\212\240/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 025. \351\223\276\350\241\250\344\270\255\347\232\204\344\270\244\346\225\260\347\233\270\345\212\240/Solution.py" @@ -15,6 +15,7 @@ def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: carry, dummy = 0, ListNode() while s1 or s2 or carry: carry += (0 if not s1 else s1.pop()) + (0 if not s2 else s2.pop()) + # 创建结点,利用头插法将结点插入链表 node = ListNode(carry % 10, dummy.next) dummy.next = node carry //= 10 diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 026. \351\207\215\346\216\222\351\223\276\350\241\250/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 026. \351\207\215\346\216\222\351\223\276\350\241\250/Solution.java" index 88a404fbf1e81..a521c927de9c2 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 026. \351\207\215\346\216\222\351\223\276\350\241\250/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 026. \351\207\215\346\216\222\351\223\276\350\241\250/Solution.java" @@ -51,4 +51,4 @@ private ListNode mergeTwoLists(ListNode l1, ListNode l2) { cur.next = l1 != null ? l1 : l2; return dummy.next; } -} +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 027. \345\233\236\346\226\207\351\223\276\350\241\250/Solution.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 027. \345\233\236\346\226\207\351\223\276\350\241\250/Solution.cs" index 235bc2036f168..47f9d260e262f 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 027. \345\233\236\346\226\207\351\223\276\350\241\250/Solution.cs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 027. \345\233\236\346\226\207\351\223\276\350\241\250/Solution.cs" @@ -43,4 +43,4 @@ public bool IsPalindrome(ListNode head) { } return true; } -} \ No newline at end of file +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 028. \345\261\225\345\271\263\345\244\232\347\272\247\345\217\214\345\220\221\351\223\276\350\241\250/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 028. \345\261\225\345\271\263\345\244\232\347\272\247\345\217\214\345\220\221\351\223\276\350\241\250/Solution.cpp" index 7bc299f974c6c..67018df648616 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 028. \345\261\225\345\271\263\345\244\232\347\272\247\345\217\214\345\220\221\351\223\276\350\241\250/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 028. \345\261\225\345\271\263\345\244\232\347\272\247\345\217\214\345\220\221\351\223\276\350\241\250/Solution.cpp" @@ -1,47 +1,47 @@ -/* -// Definition for a Node. -class Node { -public: - int val; - Node* prev; - Node* next; - Node* child; -}; -*/ - -class Solution { -public: - Node* flatten(Node* head) { - flattenGetTail(head); - return head; - } - - Node* flattenGetTail(Node* head) { - Node* cur = head; - Node* tail = nullptr; - - while (cur) { - Node* next = cur->next; - if (cur->child) { - Node* child = cur->child; - Node* childTail = flattenGetTail(cur->child); - - cur->child = nullptr; - cur->next = child; - child->prev = cur; - childTail->next = next; - - if (next) - next->prev = childTail; - - tail = childTail; - } else { - tail = cur; - } - - cur = next; - } - - return tail; - } +/* +// Definition for a Node. +class Node { +public: + int val; + Node* prev; + Node* next; + Node* child; +}; +*/ + +class Solution { +public: + Node* flatten(Node* head) { + flattenGetTail(head); + return head; + } + + Node* flattenGetTail(Node* head) { + Node* cur = head; + Node* tail = nullptr; + + while (cur) { + Node* next = cur->next; + if (cur->child) { + Node* child = cur->child; + Node* childTail = flattenGetTail(cur->child); + + cur->child = nullptr; + cur->next = child; + child->prev = cur; + childTail->next = next; + + if (next) + next->prev = childTail; + + tail = childTail; + } else { + tail = cur; + } + + cur = next; + } + + return tail; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 028. \345\261\225\345\271\263\345\244\232\347\272\247\345\217\214\345\220\221\351\223\276\350\241\250/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 028. \345\261\225\345\271\263\345\244\232\347\272\247\345\217\214\345\220\221\351\223\276\350\241\250/Solution.java" index 01f3d5e6a656b..ce763b7e4a0b7 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 028. \345\261\225\345\271\263\345\244\232\347\272\247\345\217\214\345\220\221\351\223\276\350\241\250/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 028. \345\261\225\345\271\263\345\244\232\347\272\247\345\217\214\345\220\221\351\223\276\350\241\250/Solution.java" @@ -34,4 +34,4 @@ private void preOrder(Node node) { preOrder(child); preOrder(next); } -} +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 029. \346\216\222\345\272\217\347\232\204\345\276\252\347\216\257\351\223\276\350\241\250/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 029. \346\216\222\345\272\217\347\232\204\345\276\252\347\216\257\351\223\276\350\241\250/Solution.cpp" index 84580318378eb..727ca056efbe2 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 029. \346\216\222\345\272\217\347\232\204\345\276\252\347\216\257\351\223\276\350\241\250/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 029. \346\216\222\345\272\217\347\232\204\345\276\252\347\216\257\351\223\276\350\241\250/Solution.cpp" @@ -1,40 +1,40 @@ -/* -// Definition for a Node. -class Node { -public: - int val; - Node* next; - - Node() {} - - Node(int _val) { - val = _val; - next = NULL; - } - - Node(int _val, Node* _next) { - val = _val; - next = _next; - } -}; -*/ - -class Solution { -public: - Node* insert(Node* head, int insertVal) { - Node* node = new Node(insertVal); - if (!head) { - node->next = node; - return node; - } - Node *prev = head, *curr = head->next; - while (curr != head) { - if ((prev->val <= insertVal && insertVal <= curr->val) || (prev->val > curr->val && (insertVal >= prev->val || insertVal <= curr->val))) break; - prev = curr; - curr = curr->next; - } - prev->next = node; - node->next = curr; - return head; - } +/* +// Definition for a Node. +class Node { +public: + int val; + Node* next; + + Node() {} + + Node(int _val) { + val = _val; + next = NULL; + } + + Node(int _val, Node* _next) { + val = _val; + next = _next; + } +}; +*/ + +class Solution { +public: + Node* insert(Node* head, int insertVal) { + Node* node = new Node(insertVal); + if (!head) { + node->next = node; + return node; + } + Node *prev = head, *curr = head->next; + while (curr != head) { + if ((prev->val <= insertVal && insertVal <= curr->val) || (prev->val > curr->val && (insertVal >= prev->val || insertVal <= curr->val))) break; + prev = curr; + curr = curr->next; + } + prev->next = node; + node->next = curr; + return head; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 029. \346\216\222\345\272\217\347\232\204\345\276\252\347\216\257\351\223\276\350\241\250/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 029. \346\216\222\345\272\217\347\232\204\345\276\252\347\216\257\351\223\276\350\241\250/Solution.java" index 0840233bd62b6..8bf10dab720d1 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 029. \346\216\222\345\272\217\347\232\204\345\276\252\347\216\257\351\223\276\350\241\250/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 029. \346\216\222\345\272\217\347\232\204\345\276\252\347\216\257\351\223\276\350\241\250/Solution.java" @@ -37,4 +37,4 @@ public Node insert(Node head, int insertVal) { } return head; } -} +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 030. \346\217\222\345\205\245\343\200\201\345\210\240\351\231\244\345\222\214\351\232\217\346\234\272\350\256\277\351\227\256\351\203\275\346\230\257 O(1) \347\232\204\345\256\271\345\231\250/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 030. \346\217\222\345\205\245\343\200\201\345\210\240\351\231\244\345\222\214\351\232\217\346\234\272\350\256\277\351\227\256\351\203\275\346\230\257 O(1) \347\232\204\345\256\271\345\231\250/Solution.cpp" index e73dd7245a28b..298fd8f6457c1 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 030. \346\217\222\345\205\245\343\200\201\345\210\240\351\231\244\345\222\214\351\232\217\346\234\272\350\256\277\351\227\256\351\203\275\346\230\257 O(1) \347\232\204\345\256\271\345\231\250/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 030. \346\217\222\345\205\245\343\200\201\345\210\240\351\231\244\345\222\214\351\232\217\346\234\272\350\256\277\351\227\256\351\203\275\346\230\257 O(1) \347\232\204\345\256\271\345\231\250/Solution.cpp" @@ -1,42 +1,42 @@ -class RandomizedSet { - unordered_map mp; - vector nums; - -public: - RandomizedSet() { - } - - bool insert(int val) { - if (mp.count(val)) - return false; - - mp[val] = nums.size(); - nums.push_back(val); - return true; - } - - bool remove(int val) { - if (!mp.count(val)) - return false; - - int removeIndex = mp[val]; - nums[removeIndex] = nums.back(); - mp[nums.back()] = removeIndex; - - mp.erase(val); - nums.pop_back(); - return true; - } - - int getRandom() { - return nums[rand() % nums.size()]; - } -}; - -/** - * Your RandomizedSet object will be instantiated and called as such: - * RandomizedSet* obj = new RandomizedSet(); - * bool param_1 = obj->insert(val); - * bool param_2 = obj->remove(val); - * int param_3 = obj->getRandom(); +class RandomizedSet { + unordered_map mp; + vector nums; + +public: + RandomizedSet() { + } + + bool insert(int val) { + if (mp.count(val)) + return false; + + mp[val] = nums.size(); + nums.push_back(val); + return true; + } + + bool remove(int val) { + if (!mp.count(val)) + return false; + + int removeIndex = mp[val]; + nums[removeIndex] = nums.back(); + mp[nums.back()] = removeIndex; + + mp.erase(val); + nums.pop_back(); + return true; + } + + int getRandom() { + return nums[rand() % nums.size()]; + } +}; + +/** + * Your RandomizedSet object will be instantiated and called as such: + * RandomizedSet* obj = new RandomizedSet(); + * bool param_1 = obj->insert(val); + * bool param_2 = obj->remove(val); + * int param_3 = obj->getRandom(); */ \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 030. \346\217\222\345\205\245\343\200\201\345\210\240\351\231\244\345\222\214\351\232\217\346\234\272\350\256\277\351\227\256\351\203\275\346\230\257 O(1) \347\232\204\345\256\271\345\231\250/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 030. \346\217\222\345\205\245\343\200\201\345\210\240\351\231\244\345\222\214\351\232\217\346\234\272\350\256\277\351\227\256\351\203\275\346\230\257 O(1) \347\232\204\345\256\271\345\231\250/Solution.java" index 041a7df278756..d284e2e2c9b12 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 030. \346\217\222\345\205\245\343\200\201\345\210\240\351\231\244\345\222\214\351\232\217\346\234\272\350\256\277\351\227\256\351\203\275\346\230\257 O(1) \347\232\204\345\256\271\345\231\250/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 030. \346\217\222\345\205\245\343\200\201\345\210\240\351\231\244\345\222\214\351\232\217\346\234\272\350\256\277\351\227\256\351\203\275\346\230\257 O(1) \347\232\204\345\256\271\345\231\250/Solution.java" @@ -46,4 +46,4 @@ public int getRandom() { * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); - */ + */ \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/Solution.cpp" index dbbdf6b4847ae..2c467d2c13297 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/Solution.cpp" @@ -1,91 +1,91 @@ -struct Node { - int k; - int v; - Node* prev; - Node* next; - - Node() - : k(0) - , v(0) - , prev(nullptr) - , next(nullptr) {} - Node(int key, int val) - : k(key) - , v(val) - , prev(nullptr) - , next(nullptr) {} -}; - -class LRUCache { -public: - LRUCache(int capacity) - : cap(capacity) - , size(0) { - head = new Node(); - tail = new Node(); - head->next = tail; - tail->prev = head; - } - - int get(int key) { - if (!cache.count(key)) return -1; - Node* node = cache[key]; - moveToHead(node); - return node->v; - } - - void put(int key, int value) { - if (cache.count(key)) { - Node* node = cache[key]; - node->v = value; - moveToHead(node); - } else { - Node* node = new Node(key, value); - cache[key] = node; - addToHead(node); - ++size; - if (size > cap) { - node = removeTail(); - cache.erase(node->k); - --size; - } - } - } - -private: - unordered_map cache; - Node* head; - Node* tail; - int cap; - int size; - - void moveToHead(Node* node) { - removeNode(node); - addToHead(node); - } - - void removeNode(Node* node) { - node->prev->next = node->next; - node->next->prev = node->prev; - } - - void addToHead(Node* node) { - node->next = head->next; - node->prev = head; - head->next = node; - node->next->prev = node; - } - - Node* removeTail() { - Node* node = tail->prev; - removeNode(node); - return node; - } -}; - -/** - * Your LRUCache object will be instantiated and called as such: - * LRUCache* obj = new LRUCache(capacity); - * int param_1 = obj->get(key); - * obj->put(key,value); +struct Node { + int k; + int v; + Node* prev; + Node* next; + + Node() + : k(0) + , v(0) + , prev(nullptr) + , next(nullptr) {} + Node(int key, int val) + : k(key) + , v(val) + , prev(nullptr) + , next(nullptr) {} +}; + +class LRUCache { +public: + LRUCache(int capacity) + : cap(capacity) + , size(0) { + head = new Node(); + tail = new Node(); + head->next = tail; + tail->prev = head; + } + + int get(int key) { + if (!cache.count(key)) return -1; + Node* node = cache[key]; + moveToHead(node); + return node->v; + } + + void put(int key, int value) { + if (cache.count(key)) { + Node* node = cache[key]; + node->v = value; + moveToHead(node); + } else { + Node* node = new Node(key, value); + cache[key] = node; + addToHead(node); + ++size; + if (size > cap) { + node = removeTail(); + cache.erase(node->k); + --size; + } + } + } + +private: + unordered_map cache; + Node* head; + Node* tail; + int cap; + int size; + + void moveToHead(Node* node) { + removeNode(node); + addToHead(node); + } + + void removeNode(Node* node) { + node->prev->next = node->next; + node->next->prev = node->prev; + } + + void addToHead(Node* node) { + node->next = head->next; + node->prev = head; + head->next = node; + node->next->prev = node; + } + + Node* removeTail() { + Node* node = tail->prev; + removeNode(node); + return node; + } +}; + +/** + * Your LRUCache object will be instantiated and called as such: + * LRUCache* obj = new LRUCache(capacity); + * int param_1 = obj->get(key); + * obj->put(key,value); */ \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/Solution.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/Solution.cs" index d3f375860f849..a43d2901155ce 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/Solution.cs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/Solution.cs" @@ -1,76 +1,76 @@ -public class LRUCache { - class Node { - public Node Prev; - public Node Next; - public int Key; - public int Val; - } - - private Node head = new Node(); - private Node tail = new Node(); - private Dictionary cache = new Dictionary(); - private readonly int capacity; - private int size; - - public LRUCache(int capacity) { - this.capacity = capacity; - head.Next = tail; - tail.Prev = head; - } - - public int Get(int key) { - Node node; - if (cache.TryGetValue(key, out node)) { - moveToHead(node); - return node.Val; - } - return -1; - } - - public void Put(int key, int Val) { - Node node; - if (cache.TryGetValue(key, out node)) { - moveToHead(node); - node.Val = Val; - } else { - node = new Node() { Key = key, Val = Val }; - cache.Add(key, node); - addToHead(node); - if (++size > capacity) { - node = removeTail(); - cache.Remove(node.Key); - --size; - } - } - } - - private void moveToHead(Node node) { - removeNode(node); - addToHead(node); - } - - private void removeNode(Node node) { - node.Prev.Next = node.Next; - node.Next.Prev = node.Prev; - } - - private void addToHead(Node node) { - node.Next = head.Next; - node.Prev = head; - head.Next = node; - node.Next.Prev = node; - } - - private Node removeTail() { - Node node = tail.Prev; - removeNode(node); - return node; - } -} - -/** - * Your LRUCache object will be instantiated and called as such: - * LRUCache obj = new LRUCache(capacity); - * int param_1 = obj.Get(key); - * obj.Put(key,Val); - */ \ No newline at end of file +public class LRUCache { + class Node { + public Node Prev; + public Node Next; + public int Key; + public int Val; + } + + private Node head = new Node(); + private Node tail = new Node(); + private Dictionary cache = new Dictionary(); + private readonly int capacity; + private int size; + + public LRUCache(int capacity) { + this.capacity = capacity; + head.Next = tail; + tail.Prev = head; + } + + public int Get(int key) { + Node node; + if (cache.TryGetValue(key, out node)) { + moveToHead(node); + return node.Val; + } + return -1; + } + + public void Put(int key, int Val) { + Node node; + if (cache.TryGetValue(key, out node)) { + moveToHead(node); + node.Val = Val; + } else { + node = new Node() { Key = key, Val = Val }; + cache.Add(key, node); + addToHead(node); + if (++size > capacity) { + node = removeTail(); + cache.Remove(node.Key); + --size; + } + } + } + + private void moveToHead(Node node) { + removeNode(node); + addToHead(node); + } + + private void removeNode(Node node) { + node.Prev.Next = node.Next; + node.Next.Prev = node.Prev; + } + + private void addToHead(Node node) { + node.Next = head.Next; + node.Prev = head; + head.Next = node; + node.Next.Prev = node; + } + + private Node removeTail() { + Node node = tail.Prev; + removeNode(node); + return node; + } +} + +/** + * Your LRUCache object will be instantiated and called as such: + * LRUCache obj = new LRUCache(capacity); + * int param_1 = obj.Get(key); + * obj.Put(key,Val); + */ diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/Solution.java" index bd088d5f20fcb..3cbf7a5105dd3 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/Solution.java" @@ -1,85 +1,85 @@ -class Node { - int key; - int val; - Node prev; - Node next; - - Node() { - } - - Node(int key, int val) { - this.key = key; - this.val = val; - } -} - -class LRUCache { - private Map cache = new HashMap<>(); - private Node head = new Node(); - private Node tail = new Node(); - private int capacity; - private int size; - - public LRUCache(int capacity) { - this.capacity = capacity; - head.next = tail; - tail.prev = head; - } - - public int get(int key) { - if (!cache.containsKey(key)) { - return -1; - } - Node node = cache.get(key); - moveToHead(node); - return node.val; - } - - public void put(int key, int value) { - if (cache.containsKey(key)) { - Node node = cache.get(key); - node.val = value; - moveToHead(node); - } else { - Node node = new Node(key, value); - cache.put(key, node); - addToHead(node); - ++size; - if (size > capacity) { - node = removeTail(); - cache.remove(node.key); - --size; - } - } - } - - private void moveToHead(Node node) { - removeNode(node); - addToHead(node); - } - - private void removeNode(Node node) { - node.prev.next = node.next; - node.next.prev = node.prev; - } - - private void addToHead(Node node) { - node.next = head.next; - node.prev = head; - head.next = node; - node.next.prev = node; - } - - private Node removeTail() { - Node node = tail.prev; - removeNode(node); - return node; - } -} - -/** - * Your LRUCache object will be instantiated and called as such: - * LRUCache obj = new LRUCache(capacity); - * int param_1 = obj.get(key); - * obj.put(key,value); +class Node { + int key; + int val; + Node prev; + Node next; + + Node() { + } + + Node(int key, int val) { + this.key = key; + this.val = val; + } +} + +class LRUCache { + private Map cache = new HashMap<>(); + private Node head = new Node(); + private Node tail = new Node(); + private int capacity; + private int size; + + public LRUCache(int capacity) { + this.capacity = capacity; + head.next = tail; + tail.prev = head; + } + + public int get(int key) { + if (!cache.containsKey(key)) { + return -1; + } + Node node = cache.get(key); + moveToHead(node); + return node.val; + } + + public void put(int key, int value) { + if (cache.containsKey(key)) { + Node node = cache.get(key); + node.val = value; + moveToHead(node); + } else { + Node node = new Node(key, value); + cache.put(key, node); + addToHead(node); + ++size; + if (size > capacity) { + node = removeTail(); + cache.remove(node.key); + --size; + } + } + } + + private void moveToHead(Node node) { + removeNode(node); + addToHead(node); + } + + private void removeNode(Node node) { + node.prev.next = node.next; + node.next.prev = node.prev; + } + + private void addToHead(Node node) { + node.next = head.next; + node.prev = head; + head.next = node; + node.next.prev = node; + } + + private Node removeTail() { + Node node = tail.prev; + removeNode(node); + return node; + } +} + +/** + * Your LRUCache object will be instantiated and called as such: + * LRUCache obj = new LRUCache(capacity); + * int param_1 = obj.get(key); + * obj.put(key,value); */ \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/Solution.py" index d76142234ee0d..76457b08d8cfd 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/Solution.py" @@ -1,64 +1,64 @@ -class Node: - def __init__(self, key=0, val=0): - self.key = key - self.val = val - self.prev = None - self.next = None - - -class LRUCache: - def __init__(self, capacity: int): - self.cache = {} - self.head = Node() - self.tail = Node() - self.capacity = capacity - self.size = 0 - self.head.next = self.tail - self.tail.prev = self.head - - def get(self, key: int) -> int: - if key not in self.cache: - return -1 - node = self.cache[key] - self.move_to_head(node) - return node.val - - def put(self, key: int, value: int) -> None: - if key in self.cache: - node = self.cache[key] - node.val = value - self.move_to_head(node) - else: - node = Node(key, value) - self.cache[key] = node - self.add_to_head(node) - self.size += 1 - if self.size > self.capacity: - node = self.remove_tail() - self.cache.pop(node.key) - self.size -= 1 - - def move_to_head(self, node): - self.remove_node(node) - self.add_to_head(node) - - def remove_node(self, node): - node.prev.next = node.next - node.next.prev = node.prev - - def add_to_head(self, node): - node.next = self.head.next - node.prev = self.head - self.head.next = node - node.next.prev = node - - def remove_tail(self): - node = self.tail.prev - self.remove_node(node) - return node - - -# Your LRUCache object will be instantiated and called as such: -# obj = LRUCache(capacity) -# param_1 = obj.get(key) -# obj.put(key,value) +class Node: + def __init__(self, key=0, val=0): + self.key = key + self.val = val + self.prev = None + self.next = None + + +class LRUCache: + def __init__(self, capacity: int): + self.cache = {} + self.head = Node() + self.tail = Node() + self.capacity = capacity + self.size = 0 + self.head.next = self.tail + self.tail.prev = self.head + + def get(self, key: int) -> int: + if key not in self.cache: + return -1 + node = self.cache[key] + self.move_to_head(node) + return node.val + + def put(self, key: int, value: int) -> None: + if key in self.cache: + node = self.cache[key] + node.val = value + self.move_to_head(node) + else: + node = Node(key, value) + self.cache[key] = node + self.add_to_head(node) + self.size += 1 + if self.size > self.capacity: + node = self.remove_tail() + self.cache.pop(node.key) + self.size -= 1 + + def move_to_head(self, node): + self.remove_node(node) + self.add_to_head(node) + + def remove_node(self, node): + node.prev.next = node.next + node.next.prev = node.prev + + def add_to_head(self, node): + node.next = self.head.next + node.prev = self.head + self.head.next = node + node.next.prev = node + + def remove_tail(self): + node = self.tail.prev + self.remove_node(node) + return node + + +# Your LRUCache object will be instantiated and called as such: +# obj = LRUCache(capacity) +# param_1 = obj.get(key) +# obj.put(key,value) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 032. \346\234\211\346\225\210\347\232\204\345\217\230\344\275\215\350\257\215/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 032. \346\234\211\346\225\210\347\232\204\345\217\230\344\275\215\350\257\215/Solution.cpp" index d8904faf7471e..5f6e5a48e6442 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 032. \346\234\211\346\225\210\347\232\204\345\217\230\344\275\215\350\257\215/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 032. \346\234\211\346\225\210\347\232\204\345\217\230\344\275\215\350\257\215/Solution.cpp" @@ -1,21 +1,21 @@ -class Solution { -public: - bool isAnagram(string s, string t) { - int m = s.size(); - int n = t.size(); - if (m != n || s == t) { - return false; - } - vector cnt(26); - for (int i = 0; i < m; ++i) { - ++cnt[s[i] - 'a']; - --cnt[t[i] - 'a']; - } - for (int x : cnt) { - if (x) { - return false; - } - } - return true; - } +class Solution { +public: + bool isAnagram(string s, string t) { + int m = s.size(); + int n = t.size(); + if (m != n || s == t) { + return false; + } + vector cnt(26); + for (int i = 0; i < m; ++i) { + ++cnt[s[i] - 'a']; + --cnt[t[i] - 'a']; + } + for (int x : cnt) { + if (x) { + return false; + } + } + return true; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 032. \346\234\211\346\225\210\347\232\204\345\217\230\344\275\215\350\257\215/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 032. \346\234\211\346\225\210\347\232\204\345\217\230\344\275\215\350\257\215/Solution.java" index 2608d1b876d45..c20b1d87d2f32 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 032. \346\234\211\346\225\210\347\232\204\345\217\230\344\275\215\350\257\215/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 032. \346\234\211\346\225\210\347\232\204\345\217\230\344\275\215\350\257\215/Solution.java" @@ -1,20 +1,20 @@ -class Solution { - public boolean isAnagram(String s, String t) { - int m = s.length(); - int n = t.length(); - if (m != n || s.equals(t)) { - return false; - } - int[] cnt = new int[26]; - for (int i = 0; i < m; ++i) { - ++cnt[s.charAt(i) - 'a']; - --cnt[t.charAt(i) - 'a']; - } - for (int x : cnt) { - if (x != 0) { - return false; - } - } - return true; - } +class Solution { + public boolean isAnagram(String s, String t) { + int m = s.length(); + int n = t.length(); + if (m != n || s.equals(t)) { + return false; + } + int[] cnt = new int[26]; + for (int i = 0; i < m; ++i) { + ++cnt[s.charAt(i) - 'a']; + --cnt[t.charAt(i) - 'a']; + } + for (int x : cnt) { + if (x != 0) { + return false; + } + } + return true; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 032. \346\234\211\346\225\210\347\232\204\345\217\230\344\275\215\350\257\215/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 032. \346\234\211\346\225\210\347\232\204\345\217\230\344\275\215\350\257\215/Solution.py" index e68d84875e2aa..9d5fcbd82aec8 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 032. \346\234\211\346\225\210\347\232\204\345\217\230\344\275\215\350\257\215/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 032. \346\234\211\346\225\210\347\232\204\345\217\230\344\275\215\350\257\215/Solution.py" @@ -1,5 +1,5 @@ -class Solution: - def isAnagram(self, s: str, t: str) -> bool: - if len(s) != len(t) or s == t: - return False - return Counter(s) == Counter(t) +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + if len(s) != len(t) or s == t: + return False + return Counter(s) == Counter(t) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.cpp" index ceee5097ced2d..e500aed86c96e 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.cpp" @@ -1,21 +1,14 @@ -class Solution { -public: - vector> groupAnagrams(vector& strs) { - unordered_map> d; - for (auto& s : strs) { - int cnt[26] = {0}; - for (auto& c : s) ++cnt[c - 'a']; - string k; - for (int i = 0; i < 26; ++i) { - if (cnt[i]) { - k += 'a' + i; - k += to_string(cnt[i]); - } - } - d[k].emplace_back(s); - } - vector> ans; - for (auto& [_, v] : d) ans.emplace_back(v); - return ans; - } +class Solution { +public: + vector> groupAnagrams(vector& strs) { + unordered_map> d; + for (auto& s : strs) { + string k = s; + sort(k.begin(), k.end()); + d[k].emplace_back(s); + } + vector> ans; + for (auto& [_, v] : d) ans.emplace_back(v); + return ans; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.go" "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.go" index 9396f0f8edd0b..c42060501b99e 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.go" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.go" @@ -1,11 +1,10 @@ func groupAnagrams(strs []string) (ans [][]string) { - d := map[[26]int][]string{} + d := map[string][]string{} for _, s := range strs { - cnt := [26]int{} - for _, c := range s { - cnt[c-'a']++ - } - d[cnt] = append(d[cnt], s) + t := []byte(s) + sort.Slice(t, func(i, j int) bool { return t[i] < t[j] }) + k := string(t) + d[k] = append(d[k], s) } for _, v := range d { ans = append(ans, v) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.java" index 244b3305c2052..e294d577cc6cc 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.java" @@ -1,20 +1,12 @@ -class Solution { - public List> groupAnagrams(String[] strs) { - Map> d = new HashMap<>(); - for (String s : strs) { - int[] cnt = new int[26]; - for (int i = 0; i < s.length(); ++i) { - ++cnt[s.charAt(i) - 'a']; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < 26; ++i) { - if (cnt[i] > 0) { - sb.append((char) ('a' + i)).append(cnt[i]); - } - } - String k = sb.toString(); - d.computeIfAbsent(k, key -> new ArrayList<>()).add(s); - } - return new ArrayList<>(d.values()); - } +class Solution { + public List> groupAnagrams(String[] strs) { + Map> d = new HashMap<>(); + for (String s : strs) { + char[] t = s.toCharArray(); + Arrays.sort(t); + String k = String.valueOf(t); + d.computeIfAbsent(k, key -> new ArrayList<>()).add(s); + } + return new ArrayList<>(d.values()); + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.py" index 623f1cf32cc1d..f98245354208b 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.py" @@ -1,9 +1,7 @@ -class Solution: - def groupAnagrams(self, strs: List[str]) -> List[List[str]]: - d = defaultdict(list) - for s in strs: - cnt = [0] * 26 - for c in s: - cnt[ord(c) - ord("a")] += 1 - d[tuple(cnt)].append(s) - return list(d.values()) +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + d = defaultdict(list) + for s in strs: + k = ''.join(sorted(s)) + d[k].append(s) + return list(d.values()) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.ts" index f2469ceb10559..848ba0a135e10 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.ts" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution.ts" @@ -1,8 +1,11 @@ function groupAnagrams(strs: string[]): string[][] { - const map = new Map(); - for (const str of strs) { - const k = str.split('').sort().join(''); - map.set(k, (map.get(k) ?? []).concat([str])); + const d: Map = new Map(); + for (const s of strs) { + const k = s.split('').sort().join(''); + if (!d.has(k)) { + d.set(k, []); + } + d.get(k)!.push(s); } - return [...map.values()]; + return Array.from(d.values()); } diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution2.cpp" new file mode 100644 index 0000000000000..f7b808097864a --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution2.cpp" @@ -0,0 +1,21 @@ +class Solution { +public: + vector> groupAnagrams(vector& strs) { + unordered_map> d; + for (auto& s : strs) { + int cnt[26] = {0}; + for (auto& c : s) ++cnt[c - 'a']; + string k; + for (int i = 0; i < 26; ++i) { + if (cnt[i]) { + k += 'a' + i; + k += to_string(cnt[i]); + } + } + d[k].emplace_back(s); + } + vector> ans; + for (auto& [_, v] : d) ans.emplace_back(v); + return ans; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution2.go" new file mode 100644 index 0000000000000..9396f0f8edd0b --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution2.go" @@ -0,0 +1,14 @@ +func groupAnagrams(strs []string) (ans [][]string) { + d := map[[26]int][]string{} + for _, s := range strs { + cnt := [26]int{} + for _, c := range s { + cnt[c-'a']++ + } + d[cnt] = append(d[cnt], s) + } + for _, v := range d { + ans = append(ans, v) + } + return +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution2.java" new file mode 100644 index 0000000000000..891392c74d008 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution2.java" @@ -0,0 +1,20 @@ +class Solution { + public List> groupAnagrams(String[] strs) { + Map> d = new HashMap<>(); + for (String s : strs) { + int[] cnt = new int[26]; + for (int i = 0; i < s.length(); ++i) { + ++cnt[s.charAt(i) - 'a']; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 26; ++i) { + if (cnt[i] > 0) { + sb.append((char) ('a' + i)).append(cnt[i]); + } + } + String k = sb.toString(); + d.computeIfAbsent(k, key -> new ArrayList<>()).add(s); + } + return new ArrayList<>(d.values()); + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution2.py" new file mode 100644 index 0000000000000..9c9ed6a8df8b6 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution2.py" @@ -0,0 +1,9 @@ +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + d = defaultdict(list) + for s in strs: + cnt = [0] * 26 + for c in s: + cnt[ord(c) - ord('a')] += 1 + d[tuple(cnt)].append(s) + return list(d.values()) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution2.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution2.ts" new file mode 100644 index 0000000000000..f2469ceb10559 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/Solution2.ts" @@ -0,0 +1,8 @@ +function groupAnagrams(strs: string[]): string[][] { + const map = new Map(); + for (const str of strs) { + const k = str.split('').sort().join(''); + map.set(k, (map.get(k) ?? []).concat([str])); + } + return [...map.values()]; +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 034. \345\244\226\346\230\237\350\257\255\350\250\200\346\230\257\345\220\246\346\216\222\345\272\217/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 034. \345\244\226\346\230\237\350\257\255\350\250\200\346\230\257\345\220\246\346\216\222\345\272\217/Solution.cpp" index 33fadc246be08..fae167459c62e 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 034. \345\244\226\346\230\237\350\257\255\350\250\200\346\230\257\345\220\246\346\216\222\345\272\217/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 034. \345\244\226\346\230\237\350\257\255\350\250\200\346\230\257\345\220\246\346\216\222\345\272\217/Solution.cpp" @@ -1,4 +1,4 @@ -class Solution { +class Solution { public: bool isAlienSorted(vector& words, string order) { vector index(26); diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 034. \345\244\226\346\230\237\350\257\255\350\250\200\346\230\257\345\220\246\346\216\222\345\272\217/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 034. \345\244\226\346\230\237\350\257\255\350\250\200\346\230\257\345\220\246\346\216\222\345\272\217/Solution.java" index 662736502b262..3e5c54a74b8bc 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 034. \345\244\226\346\230\237\350\257\255\350\250\200\346\230\257\345\220\246\346\216\222\345\272\217/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 034. \345\244\226\346\230\237\350\257\255\350\250\200\346\230\257\345\220\246\346\216\222\345\272\217/Solution.java" @@ -12,9 +12,11 @@ public boolean isAlienSorted(String[] words, String order) { int i1 = j >= l1 ? -1 : index[w1.charAt(j) - 'a']; int i2 = j >= l2 ? -1 : index[w2.charAt(j) - 'a']; if (i1 > i2) { + // 说明不是按字典序排序,直接返回False return false; } if (i1 < i2) { + // 说明当前两单词是按字典序排序,无需再往下进行循环比较 break; } } diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 034. \345\244\226\346\230\237\350\257\255\350\250\200\346\230\257\345\220\246\346\216\222\345\272\217/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 034. \345\244\226\346\230\237\350\257\255\350\250\200\346\230\257\345\220\246\346\216\222\345\272\217/Solution.py" index 5ba560c287955..e58956bf21275 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 034. \345\244\226\346\230\237\350\257\255\350\250\200\346\230\257\345\220\246\346\216\222\345\272\217/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 034. \345\244\226\346\230\237\350\257\255\350\250\200\346\230\257\345\220\246\346\216\222\345\272\217/Solution.py" @@ -11,7 +11,9 @@ def isAlienSorted(self, words: List[str], order: str) -> bool: -1 if j >= l2 else index[w2[j]], ) if i1 > i2: + # 说明不是按字典序排序,直接返回False return False if i1 < i2: + # 说明当前两单词是按字典序排序,无需再往下进行循环比较 break return True diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 035. \346\234\200\345\260\217\346\227\266\351\227\264\345\267\256/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 035. \346\234\200\345\260\217\346\227\266\351\227\264\345\267\256/Solution.cpp" index 33186886a2db1..9b1b92d005781 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 035. \346\234\200\345\260\217\346\227\266\351\227\264\345\267\256/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 035. \346\234\200\345\260\217\346\227\266\351\227\264\345\267\256/Solution.cpp" @@ -1,19 +1,19 @@ -class Solution { -public: - int findMinDifference(vector& timePoints) { - if (timePoints.size() > 24 * 60) { - return 0; - } - vector mins; - for (auto& t : timePoints) { - mins.push_back(stoi(t.substr(0, 2)) * 60 + stoi(t.substr(3))); - } - sort(mins.begin(), mins.end()); - mins.push_back(mins[0] + 24 * 60); - int ans = 1 << 30; - for (int i = 1; i < mins.size(); ++i) { - ans = min(ans, mins[i] - mins[i - 1]); - } - return ans; - } +class Solution { +public: + int findMinDifference(vector& timePoints) { + if (timePoints.size() > 24 * 60) { + return 0; + } + vector mins; + for (auto& t : timePoints) { + mins.push_back(stoi(t.substr(0, 2)) * 60 + stoi(t.substr(3))); + } + sort(mins.begin(), mins.end()); + mins.push_back(mins[0] + 24 * 60); + int ans = 1 << 30; + for (int i = 1; i < mins.size(); ++i) { + ans = min(ans, mins[i] - mins[i - 1]); + } + return ans; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 035. \346\234\200\345\260\217\346\227\266\351\227\264\345\267\256/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 035. \346\234\200\345\260\217\346\227\266\351\227\264\345\267\256/Solution.java" index 379122a442254..9d8bb922de5a5 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 035. \346\234\200\345\260\217\346\227\266\351\227\264\345\267\256/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 035. \346\234\200\345\260\217\346\227\266\351\227\264\345\267\256/Solution.java" @@ -1,19 +1,19 @@ -class Solution { - public int findMinDifference(List timePoints) { - if (timePoints.size() > 24 * 60) { - return 0; - } - List mins = new ArrayList<>(); - for (String t : timePoints) { - String[] time = t.split(":"); - mins.add(Integer.parseInt(time[0]) * 60 + Integer.parseInt(time[1])); - } - Collections.sort(mins); - mins.add(mins.get(0) + 24 * 60); - int ans = 1 << 30; - for (int i = 1; i < mins.size(); ++i) { - ans = Math.min(ans, mins.get(i) - mins.get(i - 1)); - } - return ans; - } +class Solution { + public int findMinDifference(List timePoints) { + if (timePoints.size() > 24 * 60) { + return 0; + } + List mins = new ArrayList<>(); + for (String t : timePoints) { + String[] time = t.split(":"); + mins.add(Integer.parseInt(time[0]) * 60 + Integer.parseInt(time[1])); + } + Collections.sort(mins); + mins.add(mins.get(0) + 24 * 60); + int ans = 1 << 30; + for (int i = 1; i < mins.size(); ++i) { + ans = Math.min(ans, mins.get(i) - mins.get(i - 1)); + } + return ans; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 035. \346\234\200\345\260\217\346\227\266\351\227\264\345\267\256/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 035. \346\234\200\345\260\217\346\227\266\351\227\264\345\267\256/Solution.py" index 033a0c4769e12..56c1ded892922 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 035. \346\234\200\345\260\217\346\227\266\351\227\264\345\267\256/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 035. \346\234\200\345\260\217\346\227\266\351\227\264\345\267\256/Solution.py" @@ -1,7 +1,7 @@ -class Solution: - def findMinDifference(self, timePoints: List[str]) -> int: - if len(timePoints) > 24 * 60: - return 0 - mins = sorted(int(t[:2]) * 60 + int(t[3:]) for t in timePoints) - mins.append(mins[0] + 24 * 60) - return min(b - a for a, b in pairwise(mins)) +class Solution: + def findMinDifference(self, timePoints: List[str]) -> int: + if len(timePoints) > 24 * 60: + return 0 + mins = sorted(int(t[:2]) * 60 + int(t[3:]) for t in timePoints) + mins.append(mins[0] + 24 * 60) + return min(b - a for a, b in pairwise(mins)) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/Solution.cpp" index 768f03fc6a28c..b0f72d73376ad 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/Solution.cpp" @@ -1,21 +1,21 @@ -class Solution { -public: - vector asteroidCollision(vector& asteroids) { - vector stk; - for (int x : asteroids) { - if (x > 0) { - stk.push_back(x); - } else { - while (stk.size() && stk.back() > 0 && stk.back() < -x) { - stk.pop_back(); - } - if (stk.size() && stk.back() == -x) { - stk.pop_back(); - } else if (stk.empty() || stk.back() < 0) { - stk.push_back(x); - } - } - } - return stk; - } +class Solution { +public: + vector asteroidCollision(vector& asteroids) { + vector stk; + for (int x : asteroids) { + if (x > 0) { + stk.push_back(x); + } else { + while (stk.size() && stk.back() > 0 && stk.back() < -x) { + stk.pop_back(); + } + if (stk.size() && stk.back() == -x) { + stk.pop_back(); + } else if (stk.empty() || stk.back() < 0) { + stk.push_back(x); + } + } + } + return stk; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/Solution.java" index 2482fab648a88..a7fe353b8ae41 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/Solution.java" @@ -1,20 +1,20 @@ -class Solution { - public int[] asteroidCollision(int[] asteroids) { - Deque stk = new ArrayDeque<>(); - for (int x : asteroids) { - if (x > 0) { - stk.offerLast(x); - } else { - while (!stk.isEmpty() && stk.peekLast() > 0 && stk.peekLast() < -x) { - stk.pollLast(); - } - if (!stk.isEmpty() && stk.peekLast() == -x) { - stk.pollLast(); - } else if (stk.isEmpty() || stk.peekLast() < 0) { - stk.offerLast(x); - } - } - } - return stk.stream().mapToInt(Integer::valueOf).toArray(); - } +class Solution { + public int[] asteroidCollision(int[] asteroids) { + Deque stk = new ArrayDeque<>(); + for (int x : asteroids) { + if (x > 0) { + stk.offerLast(x); + } else { + while (!stk.isEmpty() && stk.peekLast() > 0 && stk.peekLast() < -x) { + stk.pollLast(); + } + if (!stk.isEmpty() && stk.peekLast() == -x) { + stk.pollLast(); + } else if (stk.isEmpty() || stk.peekLast() < 0) { + stk.offerLast(x); + } + } + } + return stk.stream().mapToInt(Integer::valueOf).toArray(); + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/Solution.py" index 01660c5098ec8..1049a39e6c463 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/Solution.py" @@ -1,14 +1,14 @@ -class Solution: - def asteroidCollision(self, asteroids: List[int]) -> List[int]: - stk = [] - for x in asteroids: - if x > 0: - stk.append(x) - else: - while stk and stk[-1] > 0 and stk[-1] < -x: - stk.pop() - if stk and stk[-1] == -x: - stk.pop() - elif not stk or stk[-1] < 0: - stk.append(x) - return stk +class Solution: + def asteroidCollision(self, asteroids: List[int]) -> List[int]: + stk = [] + for x in asteroids: + if x > 0: + stk.append(x) + else: + while stk and stk[-1] > 0 and stk[-1] < -x: + stk.pop() + if stk and stk[-1] == -x: + stk.pop() + elif not stk or stk[-1] < 0: + stk.append(x) + return stk diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution.rs" "b/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution.rs" index 1ec231fe83a01..e0ab31eea7d5b 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution.rs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution.rs" @@ -3,11 +3,11 @@ impl Solution { let n = temperatures.len(); let mut res = vec![0; n]; let mut stack = Vec::new(); - for i in 0..n { - while !stack.is_empty() && temperatures[*stack.last().unwrap()] < temperatures[i] { - let j = stack.pop().unwrap(); - res[j] = (i - j) as i32; + for i in (0..n).rev() { + while !stack.is_empty() && temperatures[*stack.last().unwrap()] <= temperatures[i] { + stack.pop(); } + res[i] = if stack.is_empty() { 0 } else { (stack.last().unwrap() - i) as i32 }; stack.push(i); } res diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution.ts" index f0331024088a8..1524097c373db 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution.ts" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution.ts" @@ -1,13 +1,12 @@ function dailyTemperatures(temperatures: number[]): number[] { const n = temperatures.length; - const res = new Array(n).fill(0); + const res = new Array(n); const stack = []; - for (let i = 0; i < n; i++) { - const temperature = temperatures[i]; - while (stack.length !== 0 && temperatures[stack[stack.length - 1]] < temperature) { - const j = stack.pop(); - res[j] = i - j; + for (let i = n - 1; i >= 0; i--) { + while (stack.length !== 0 && temperatures[stack[stack.length - 1]] <= temperatures[i]) { + stack.pop(); } + res[i] = stack.length === 0 ? 0 : stack[stack.length - 1] - i; stack.push(i); } return res; diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution2.cpp" new file mode 100644 index 0000000000000..3ad97088685ab --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution2.cpp" @@ -0,0 +1,14 @@ +class Solution { +public: + vector dailyTemperatures(vector& temperatures) { + int n = temperatures.size(); + vector ans(n); + stack stk; + for (int i = n - 1; ~i; --i) { + while (!stk.empty() && temperatures[stk.top()] <= temperatures[i]) stk.pop(); + if (!stk.empty()) ans[i] = stk.top() - i; + stk.push(i); + } + return ans; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution2.go" new file mode 100644 index 0000000000000..ff6cf7e4efb4f --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution2.go" @@ -0,0 +1,15 @@ +func dailyTemperatures(temperatures []int) []int { + n := len(temperatures) + ans := make([]int, n) + var stk []int + for i := n - 1; i >= 0; i-- { + for len(stk) > 0 && temperatures[stk[len(stk)-1]] <= temperatures[i] { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + ans[i] = stk[len(stk)-1] - i + } + stk = append(stk, i) + } + return ans +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution2.java" new file mode 100644 index 0000000000000..7eda02cd99b08 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution2.java" @@ -0,0 +1,17 @@ +class Solution { + public int[] dailyTemperatures(int[] temperatures) { + int n = temperatures.length; + Deque stk = new ArrayDeque<>(); + int[] ans = new int[n]; + for (int i = n - 1; i >= 0; --i) { + while (!stk.isEmpty() && temperatures[stk.peek()] <= temperatures[i]) { + stk.pop(); + } + if (!stk.isEmpty()) { + ans[i] = stk.peek() - i; + } + stk.push(i); + } + return ans; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution2.py" new file mode 100644 index 0000000000000..e5a9ba4f87332 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution2.py" @@ -0,0 +1,12 @@ +class Solution: + def dailyTemperatures(self, temperatures: List[int]) -> List[int]: + n = len(temperatures) + stk = [] + ans = [0] * n + for i in range(n - 1, -1, -1): + while stk and temperatures[stk[-1]] <= temperatures[i]: + stk.pop() + if stk: + ans[i] = stk[-1] - i + stk.append(i) + return ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution2.rs" "b/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution2.rs" new file mode 100644 index 0000000000000..1ec231fe83a01 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution2.rs" @@ -0,0 +1,15 @@ +impl Solution { + pub fn daily_temperatures(temperatures: Vec) -> Vec { + let n = temperatures.len(); + let mut res = vec![0; n]; + let mut stack = Vec::new(); + for i in 0..n { + while !stack.is_empty() && temperatures[*stack.last().unwrap()] < temperatures[i] { + let j = stack.pop().unwrap(); + res[j] = (i - j) as i32; + } + stack.push(i); + } + res + } +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution2.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution2.ts" new file mode 100644 index 0000000000000..f0331024088a8 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/Solution2.ts" @@ -0,0 +1,14 @@ +function dailyTemperatures(temperatures: number[]): number[] { + const n = temperatures.length; + const res = new Array(n).fill(0); + const stack = []; + for (let i = 0; i < n; i++) { + const temperature = temperatures[i]; + while (stack.length !== 0 && temperatures[stack[stack.length - 1]] < temperature) { + const j = stack.pop(); + res[j] = i - j; + } + stack.push(i); + } + return res; +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 039. \347\233\264\346\226\271\345\233\276\346\234\200\345\244\247\347\237\251\345\275\242\351\235\242\347\247\257/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 039. \347\233\264\346\226\271\345\233\276\346\234\200\345\244\247\347\237\251\345\275\242\351\235\242\347\247\257/Solution.cpp" index bce9a75f56a37..4820b6d6ed2fb 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 039. \347\233\264\346\226\271\345\233\276\346\234\200\345\244\247\347\237\251\345\275\242\351\235\242\347\247\257/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 039. \347\233\264\346\226\271\345\233\276\346\234\200\345\244\247\347\237\251\345\275\242\351\235\242\347\247\257/Solution.cpp" @@ -1,32 +1,32 @@ -class Solution { -public: - int largestRectangleArea(vector& heights) { - int n = heights.size(); - vector left(n, -1), right(n, n); - stack stk; - for (int i = 0; i < n; ++i) { - while (!stk.empty() && heights[stk.top()] >= heights[i]) { - stk.pop(); - } - if (!stk.empty()) { - left[i] = stk.top(); - } - stk.push(i); - } - stk = stack(); - for (int i = n - 1; ~i; --i) { - while (!stk.empty() && heights[stk.top()] >= heights[i]) { - stk.pop(); - } - if (!stk.empty()) { - right[i] = stk.top(); - } - stk.push(i); - } - int ans = 0; - for (int i = 0; i < n; ++i) { - ans = max(ans, (right[i] - left[i] - 1) * heights[i]); - } - return ans; - } +class Solution { +public: + int largestRectangleArea(vector& heights) { + int n = heights.size(); + vector left(n, -1), right(n, n); + stack stk; + for (int i = 0; i < n; ++i) { + while (!stk.empty() && heights[stk.top()] >= heights[i]) { + stk.pop(); + } + if (!stk.empty()) { + left[i] = stk.top(); + } + stk.push(i); + } + stk = stack(); + for (int i = n - 1; ~i; --i) { + while (!stk.empty() && heights[stk.top()] >= heights[i]) { + stk.pop(); + } + if (!stk.empty()) { + right[i] = stk.top(); + } + stk.push(i); + } + int ans = 0; + for (int i = 0; i < n; ++i) { + ans = max(ans, (right[i] - left[i] - 1) * heights[i]); + } + return ans; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 039. \347\233\264\346\226\271\345\233\276\346\234\200\345\244\247\347\237\251\345\275\242\351\235\242\347\247\257/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 039. \347\233\264\346\226\271\345\233\276\346\234\200\345\244\247\347\237\251\345\275\242\351\235\242\347\247\257/Solution.java" index d70aa3520938e..17ffa120a5801 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 039. \347\233\264\346\226\271\345\233\276\346\234\200\345\244\247\347\237\251\345\275\242\351\235\242\347\247\257/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 039. \347\233\264\346\226\271\345\233\276\346\234\200\345\244\247\347\237\251\345\275\242\351\235\242\347\247\257/Solution.java" @@ -1,36 +1,36 @@ -class Solution { - public int largestRectangleArea(int[] heights) { - int n = heights.length; - int[] left = new int[n]; - int[] right = new int[n]; - for (int i = 0; i < n; ++i) { - left[i] = -1; - right[i] = n; - } - Deque stk = new ArrayDeque<>(); - for (int i = 0; i < n; ++i) { - while (!stk.isEmpty() && heights[stk.peek()] >= heights[i]) { - stk.pop(); - } - if (!stk.isEmpty()) { - left[i] = stk.peek(); - } - stk.push(i); - } - stk.clear(); - for (int i = n - 1; i >= 0; --i) { - while (!stk.isEmpty() && heights[stk.peek()] >= heights[i]) { - stk.pop(); - } - if (!stk.isEmpty()) { - right[i] = stk.peek(); - } - stk.push(i); - } - int ans = 0; - for (int i = 0; i < n; ++i) { - ans = Math.max(ans, (right[i] - left[i] - 1) * heights[i]); - } - return ans; - } +class Solution { + public int largestRectangleArea(int[] heights) { + int n = heights.length; + int[] left = new int[n]; + int[] right = new int[n]; + for (int i = 0; i < n; ++i) { + left[i] = -1; + right[i] = n; + } + Deque stk = new ArrayDeque<>(); + for (int i = 0; i < n; ++i) { + while (!stk.isEmpty() && heights[stk.peek()] >= heights[i]) { + stk.pop(); + } + if (!stk.isEmpty()) { + left[i] = stk.peek(); + } + stk.push(i); + } + stk.clear(); + for (int i = n - 1; i >= 0; --i) { + while (!stk.isEmpty() && heights[stk.peek()] >= heights[i]) { + stk.pop(); + } + if (!stk.isEmpty()) { + right[i] = stk.peek(); + } + stk.push(i); + } + int ans = 0; + for (int i = 0; i < n; ++i) { + ans = Math.max(ans, (right[i] - left[i] - 1) * heights[i]); + } + return ans; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 039. \347\233\264\346\226\271\345\233\276\346\234\200\345\244\247\347\237\251\345\275\242\351\235\242\347\247\257/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 039. \347\233\264\346\226\271\345\233\276\346\234\200\345\244\247\347\237\251\345\275\242\351\235\242\347\247\257/Solution.py" index f124022a852af..02a39185bfe35 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 039. \347\233\264\346\226\271\345\233\276\346\234\200\345\244\247\347\237\251\345\275\242\351\235\242\347\247\257/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 039. \347\233\264\346\226\271\345\233\276\346\234\200\345\244\247\347\237\251\345\275\242\351\235\242\347\247\257/Solution.py" @@ -1,20 +1,20 @@ -class Solution: - def largestRectangleArea(self, heights: List[int]) -> int: - n = len(heights) - left = [-1] * n - right = [n] * n - stk = [] - for i, x in enumerate(heights): - while stk and heights[stk[-1]] >= x: - stk.pop() - if stk: - left[i] = stk[-1] - stk.append(i) - stk = [] - for i in range(n - 1, -1, -1): - while stk and heights[stk[-1]] >= heights[i]: - stk.pop() - if stk: - right[i] = stk[-1] - stk.append(i) - return max(x * (r - l - 1) for x, l, r in zip(heights, left, right)) +class Solution: + def largestRectangleArea(self, heights: List[int]) -> int: + n = len(heights) + left = [-1] * n + right = [n] * n + stk = [] + for i, x in enumerate(heights): + while stk and heights[stk[-1]] >= x: + stk.pop() + if stk: + left[i] = stk[-1] + stk.append(i) + stk = [] + for i in range(n - 1, -1, -1): + while stk and heights[stk[-1]] >= heights[i]: + stk.pop() + if stk: + right[i] = stk[-1] + stk.append(i) + return max(x * (r - l - 1) for x, l, r in zip(heights, left, right)) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 040. \347\237\251\351\230\265\344\270\255\346\234\200\345\244\247\347\232\204\347\237\251\345\275\242/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 040. \347\237\251\351\230\265\344\270\255\346\234\200\345\244\247\347\232\204\347\237\251\345\275\242/Solution.cpp" index f4c34b7ea737d..8424f5cef56a4 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 040. \347\237\251\351\230\265\344\270\255\346\234\200\345\244\247\347\232\204\347\237\251\345\275\242/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 040. \347\237\251\351\230\265\344\270\255\346\234\200\345\244\247\347\232\204\347\237\251\345\275\242/Solution.cpp" @@ -28,4 +28,4 @@ class Solution { } return ans; } -}; +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 040. \347\237\251\351\230\265\344\270\255\346\234\200\345\244\247\347\232\204\347\237\251\345\275\242/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 040. \347\237\251\351\230\265\344\270\255\346\234\200\345\244\247\347\232\204\347\237\251\345\275\242/Solution2.cpp" new file mode 100644 index 0000000000000..f86a4f879d355 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 040. \347\237\251\351\230\265\344\270\255\346\234\200\345\244\247\347\232\204\347\237\251\345\275\242/Solution2.cpp" @@ -0,0 +1,37 @@ +class Solution { +public: + int maximalRectangle(vector& matrix) { + if (matrix.empty()) return 0; + int n = matrix[0].size(); + vector heights(n); + int ans = 0; + for (auto& row : matrix) { + for (int j = 0; j < n; ++j) { + if (row[j] == '1') + ++heights[j]; + else + heights[j] = 0; + } + ans = max(ans, largestRectangleArea(heights)); + } + return ans; + } + + int largestRectangleArea(vector& heights) { + int res = 0, n = heights.size(); + stack stk; + vector left(n, -1); + vector right(n, n); + for (int i = 0; i < n; ++i) { + while (!stk.empty() && heights[stk.top()] >= heights[i]) { + right[stk.top()] = i; + stk.pop(); + } + if (!stk.empty()) left[i] = stk.top(); + stk.push(i); + } + for (int i = 0; i < n; ++i) + res = max(res, heights[i] * (right[i] - left[i] - 1)); + return res; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 041. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\345\271\263\345\235\207\345\200\274/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 041. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\345\271\263\345\235\207\345\200\274/Solution2.cpp" new file mode 100644 index 0000000000000..123bfc20cd73b --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 041. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\345\271\263\345\235\207\345\200\274/Solution2.cpp" @@ -0,0 +1,27 @@ +class MovingAverage { +public: + MovingAverage(int size) { + n = size; + } + + double next(int val) { + if (q.size() == n) { + s -= q.front(); + q.pop(); + } + q.push(val); + s += val; + return (double) s / q.size(); + } + +private: + queue q; + int s = 0; + int n; +}; + +/** + * Your MovingAverage object will be instantiated and called as such: + * MovingAverage* obj = new MovingAverage(size); + * double param_1 = obj->next(val); + */ \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 041. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\345\271\263\345\235\207\345\200\274/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 041. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\345\271\263\345\235\207\345\200\274/Solution2.go" new file mode 100644 index 0000000000000..a6e2255b7c187 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 041. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\345\271\263\345\235\207\345\200\274/Solution2.go" @@ -0,0 +1,25 @@ +type MovingAverage struct { + q []int + s int + n int +} + +func Constructor(size int) MovingAverage { + return MovingAverage{n: size} +} + +func (this *MovingAverage) Next(val int) float64 { + if len(this.q) == this.n { + this.s -= this.q[0] + this.q = this.q[1:] + } + this.q = append(this.q, val) + this.s += val + return float64(this.s) / float64(len(this.q)) +} + +/** + * Your MovingAverage object will be instantiated and called as such: + * obj := Constructor(size); + * param_1 := obj.Next(val); + */ \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 041. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\345\271\263\345\235\207\345\200\274/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 041. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\345\271\263\345\235\207\345\200\274/Solution2.java" new file mode 100644 index 0000000000000..32d2b1b3cafce --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 041. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\345\271\263\345\235\207\345\200\274/Solution2.java" @@ -0,0 +1,24 @@ +class MovingAverage { + private Deque q = new ArrayDeque<>(); + private int n; + private int s; + + public MovingAverage(int size) { + n = size; + } + + public double next(int val) { + if (q.size() == n) { + s -= q.pollFirst(); + } + q.offer(val); + s += val; + return s * 1.0 / q.size(); + } +} + +/** + * Your MovingAverage object will be instantiated and called as such: + * MovingAverage obj = new MovingAverage(size); + * double param_1 = obj.next(val); + */ \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 041. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\345\271\263\345\235\207\345\200\274/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 041. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\345\271\263\345\235\207\345\200\274/Solution2.py" new file mode 100644 index 0000000000000..42684d122ee37 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 041. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\345\271\263\345\235\207\345\200\274/Solution2.py" @@ -0,0 +1,17 @@ +class MovingAverage: + def __init__(self, size: int): + self.n = size + self.s = 0 + self.q = deque() + + def next(self, val: int) -> float: + if len(self.q) == self.n: + self.s -= self.q.popleft() + self.q.append(val) + self.s += val + return self.s / len(self.q) + + +# Your MovingAverage object will be instantiated and called as such: +# obj = MovingAverage(size) +# param_1 = obj.next(val) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 042. \346\234\200\350\277\221\350\257\267\346\261\202\346\254\241\346\225\260/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 042. \346\234\200\350\277\221\350\257\267\346\261\202\346\254\241\346\225\260/Solution.java" index 54b986398f9cd..f7896c1646c57 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 042. \346\234\200\350\277\221\350\257\267\346\261\202\346\254\241\346\225\260/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 042. \346\234\200\350\277\221\350\257\267\346\261\202\346\254\241\346\225\260/Solution.java" @@ -1,9 +1,8 @@ class RecentCounter { - private Deque q; public RecentCounter() { - q = new ArrayDeque<>(); + q = new LinkedList<>(); } public int ping(int t) { diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 044. \344\272\214\345\217\211\346\240\221\346\257\217\345\261\202\347\232\204\346\234\200\345\244\247\345\200\274/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 044. \344\272\214\345\217\211\346\240\221\346\257\217\345\261\202\347\232\204\346\234\200\345\244\247\345\200\274/Solution.py" index 84a32ea8980af..ad43500973057 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 044. \344\272\214\345\217\211\346\240\221\346\257\217\345\261\202\347\232\204\346\234\200\345\244\247\345\200\274/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 044. \344\272\214\345\217\211\346\240\221\346\257\217\345\261\202\347\232\204\346\234\200\345\244\247\345\200\274/Solution.py" @@ -1,23 +1,23 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def largestValues(self, root: TreeNode) -> List[int]: - if root is None: - return [] - q = deque([root]) - ans = [] - while q: - t = -inf - for _ in range(len(q)): - node = q.popleft() - t = max(t, node.val) - if node.left: - q.append(node.left) - if node.right: - q.append(node.right) - ans.append(t) - return ans +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def largestValues(self, root: TreeNode) -> List[int]: + if root is None: + return [] + q = deque([root]) + ans = [] + while q: + t = -inf + for _ in range(len(q)): + node = q.popleft() + t = max(t, node.val) + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + ans.append(t) + return ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 045. \344\272\214\345\217\211\346\240\221\346\234\200\345\272\225\345\261\202\346\234\200\345\267\246\350\276\271\347\232\204\345\200\274/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 045. \344\272\214\345\217\211\346\240\221\346\234\200\345\272\225\345\261\202\346\234\200\345\267\246\350\276\271\347\232\204\345\200\274/Solution.java" index 34d87158e3367..78caf9989283d 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 045. \344\272\214\345\217\211\346\240\221\346\234\200\345\272\225\345\261\202\346\234\200\345\267\246\350\276\271\347\232\204\345\200\274/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 045. \344\272\214\345\217\211\346\240\221\346\234\200\345\272\225\345\261\202\346\234\200\345\267\246\350\276\271\347\232\204\345\200\274/Solution.java" @@ -35,4 +35,4 @@ public int findBottomLeftValue(TreeNode root) { } return ans; } -} +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 047. \344\272\214\345\217\211\346\240\221\345\211\252\346\236\235/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 047. \344\272\214\345\217\211\346\240\221\345\211\252\346\236\235/Solution.java" index b3a2bdcddc25e..5d26b15ddd550 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 047. \344\272\214\345\217\211\346\240\221\345\211\252\346\236\235/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 047. \344\272\214\345\217\211\346\240\221\345\211\252\346\236\235/Solution.java" @@ -25,4 +25,4 @@ public TreeNode pruneTree(TreeNode root) { } return root; } -} +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 048. \345\272\217\345\210\227\345\214\226\344\270\216\345\217\215\345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 048. \345\272\217\345\210\227\345\214\226\344\270\216\345\217\215\345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/Solution.cpp" index a55345bc92edf..0fccee9619eb2 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 048. \345\272\217\345\210\227\345\214\226\344\270\216\345\217\215\345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 048. \345\272\217\345\210\227\345\214\226\344\270\216\345\217\215\345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/Solution.cpp" @@ -47,4 +47,4 @@ class Codec { // Your Codec object will be instantiated and called as such: // Codec ser, deser; -// TreeNode* ans = deser.deserialize(ser.serialize(root)); +// TreeNode* ans = deser.deserialize(ser.serialize(root)); \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/Solution.cpp" index 466357a6006e3..c11b28c7d5cea 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/Solution.cpp" @@ -1,28 +1,28 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int maxPathSum(TreeNode* root) { - int ans = -1001; - function dfs = [&](TreeNode* root) { - if (!root) { - return 0; - } - int left = max(0, dfs(root->left)); - int right = max(0, dfs(root->right)); - ans = max(ans, left + right + root->val); - return root->val + max(left, right); - }; - dfs(root); - return ans; - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int maxPathSum(TreeNode* root) { + int ans = -1001; + function dfs = [&](TreeNode* root) { + if (!root) { + return 0; + } + int left = max(0, dfs(root->left)); + int right = max(0, dfs(root->right)); + ans = max(ans, left + right + root->val); + return root->val + max(left, right); + }; + dfs(root); + return ans; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/Solution.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/Solution.cs" index 40b0d3dc2bc60..0d6436df998ad 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/Solution.cs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/Solution.cs" @@ -1,31 +1,31 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -public class Solution { - private int ans = -1001; - - public int MaxPathSum(TreeNode root) { - dfs(root); - return ans; - } - - private int dfs(TreeNode root) { - if (root == null) { - return 0; - } - int left = Math.Max(0, dfs(root.left)); - int right = Math.Max(0, dfs(root.right)); - ans = Math.Max(ans, left + right + root.val); - return root.val + Math.Max(left, right); - } -} \ No newline at end of file +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + private int ans = -1001; + + public int MaxPathSum(TreeNode root) { + dfs(root); + return ans; + } + + private int dfs(TreeNode root) { + if (root == null) { + return 0; + } + int left = Math.Max(0, dfs(root.left)); + int right = Math.Max(0, dfs(root.right)); + ans = Math.Max(ans, left + right + root.val); + return root.val + Math.Max(left, right); + } +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/Solution.java" index 608ec5183e72f..c211867929b68 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/Solution.java" @@ -1,33 +1,33 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private int ans = -1001; - - public int maxPathSum(TreeNode root) { - dfs(root); - return ans; - } - - private int dfs(TreeNode root) { - if (root == null) { - return 0; - } - int left = Math.max(0, dfs(root.left)); - int right = Math.max(0, dfs(root.right)); - ans = Math.max(ans, root.val + left + right); - return root.val + Math.max(left, right); - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int ans = -1001; + + public int maxPathSum(TreeNode root) { + dfs(root); + return ans; + } + + private int dfs(TreeNode root) { + if (root == null) { + return 0; + } + int left = Math.max(0, dfs(root.left)); + int right = Math.max(0, dfs(root.right)); + ans = Math.max(ans, root.val + left + right); + return root.val + Math.max(left, right); + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/Solution.py" index 2d718b215b91f..6f909001c4cc3 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/Solution.py" @@ -1,20 +1,20 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def maxPathSum(self, root: Optional[TreeNode]) -> int: - def dfs(root: Optional[TreeNode]) -> int: - if root is None: - return 0 - left = max(0, dfs(root.left)) - right = max(0, dfs(root.right)) - nonlocal ans - ans = max(ans, root.val + left + right) - return root.val + max(left, right) - - ans = -inf - dfs(root) - return ans +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def maxPathSum(self, root: Optional[TreeNode]) -> int: + def dfs(root: Optional[TreeNode]) -> int: + if root is None: + return 0 + left = max(0, dfs(root.left)) + right = max(0, dfs(root.right)) + nonlocal ans + ans = max(ans, root.val + left + right) + return root.val + max(left, right) + + ans = -inf + dfs(root) + return ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution.c" "b/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution.c" index 9cf49c3d1402e..158bf651af2dc 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution.c" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution.c" @@ -24,4 +24,4 @@ struct TreeNode* increasingBST(struct TreeNode* root) { struct TreeNode* dummy = malloc(sizeof(struct TreeNode)); dfs(root, dummy); return dummy->right; -} +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution.cpp" index 14890ee571d19..c38b1191aeb42 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution.cpp" @@ -33,4 +33,4 @@ class Solution { } return head; } -}; +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution.java" index 089311bd702d0..6b96811019695 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution.java" @@ -35,4 +35,4 @@ public TreeNode increasingBST(TreeNode root) { } return head; } -} +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution2.cpp" new file mode 100644 index 0000000000000..447e98dd74c94 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution2.cpp" @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* increasingBST(TreeNode* root) { + TreeNode* dummy = new TreeNode(); + TreeNode* cur = dummy; + function dfs = [&](TreeNode* root) { + if (!root) { + return; + } + dfs(root->left); + cur->right = root; + root->left = nullptr; + cur = cur->right; + dfs(root->right); + }; + dfs(root); + return dummy->right; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution2.go" new file mode 100644 index 0000000000000..293c642561f2e --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution2.go" @@ -0,0 +1,25 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func increasingBST(root *TreeNode) *TreeNode { + dummy := &TreeNode{} + cur := dummy + var dfs func(*TreeNode) + dfs = func(root *TreeNode) { + if root == nil { + return + } + dfs(root.Left) + root.Left = nil + cur.Right = root + cur = root + dfs(root.Right) + } + dfs(root) + return dummy.Right +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution2.java" new file mode 100644 index 0000000000000..3c2e756fcc155 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution2.java" @@ -0,0 +1,36 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private TreeNode cur; + + public TreeNode increasingBST(TreeNode root) { + TreeNode dummy = new TreeNode(); + cur = dummy; + dfs(root); + return dummy.right; + } + + private void dfs(TreeNode root) { + if (root == null) { + return; + } + dfs(root.left); + cur.right = root; + root.left = null; + cur = cur.right; + dfs(root.right); + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution2.py" new file mode 100644 index 0000000000000..4fb458a164799 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/Solution2.py" @@ -0,0 +1,24 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def increasingBST(self, root: TreeNode) -> TreeNode: + def dfs(root: TreeNode): + if root is None: + return + + dfs(root.left) + + nonlocal cur + cur.right = root + root.left = None + cur = cur.right + + dfs(root.right) + + cur = dummy = TreeNode() + dfs(root) + return dummy.right diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 053. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\270\255\345\272\217\345\220\216\347\273\247/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 053. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\270\255\345\272\217\345\220\216\347\273\247/Solution.cpp" index 3f122352cbcfb..5f6d680b97a1a 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 053. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\270\255\345\272\217\345\220\216\347\273\247/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 053. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\270\255\345\272\217\345\220\216\347\273\247/Solution.cpp" @@ -1,24 +1,24 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { - TreeNode* ans = nullptr; - while (root) { - if (root->val > p->val) { - ans = root; - root = root->left; - } else { - root = root->right; - } - } - return ans; - } -}; +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { + TreeNode* ans = nullptr; + while (root) { + if (root->val > p->val) { + ans = root; + root = root->left; + } else { + root = root->right; + } + } + return ans; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 053. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\270\255\345\272\217\345\220\216\347\273\247/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 053. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\270\255\345\272\217\345\220\216\347\273\247/Solution.java" index 313e0f609ee0e..e388d684d44fc 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 053. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\270\255\345\272\217\345\220\216\347\273\247/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 053. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\270\255\345\272\217\345\220\216\347\273\247/Solution.java" @@ -1,23 +1,23 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -class Solution { - public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { - TreeNode ans = null; - while (root != null) { - if (root.val > p.val) { - ans = root; - root = root.left; - } else { - root = root.right; - } - } - return ans; - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { + TreeNode ans = null; + while (root != null) { + if (root.val > p.val) { + ans = root; + root = root.left; + } else { + root = root.right; + } + } + return ans; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 053. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\270\255\345\272\217\345\220\216\347\273\247/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 053. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\270\255\345\272\217\345\220\216\347\273\247/Solution.py" index 0ebc490763f1a..6ff53f4cfb45f 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 053. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\270\255\345\272\217\345\220\216\347\273\247/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 053. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\270\255\345\272\217\345\220\216\347\273\247/Solution.py" @@ -1,18 +1,18 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None - - -class Solution: - def inorderSuccessor(self, root: "TreeNode", p: "TreeNode") -> "TreeNode": - ans = None - while root: - if root.val > p.val: - ans = root - root = root.left - else: - root = root.right - return ans +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution: + def inorderSuccessor(self, root: "TreeNode", p: "TreeNode") -> "TreeNode": + ans = None + while root: + if root.val > p.val: + ans = root + root = root.left + else: + root = root.right + return ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution.cpp" index 4f15c632cf1ad..d09946d08af8c 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution.cpp" @@ -11,30 +11,18 @@ */ class Solution { public: + int s = 0; + TreeNode* convertBST(TreeNode* root) { - int s = 0; - TreeNode* node = root; - while (root) { - if (root->right == nullptr) { - s += root->val; - root->val = s; - root = root->left; - } else { - TreeNode* next = root->right; - while (next->left && next->left != root) { - next = next->left; - } - if (next->left == nullptr) { - next->left = root; - root = root->right; - } else { - s += root->val; - root->val = s; - next->left = nullptr; - root = root->left; - } - } - } - return node; + dfs(root); + return root; + } + + void dfs(TreeNode* root) { + if (!root) return; + dfs(root->right); + s += root->val; + root->val = s; + dfs(root->left); } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution.go" "b/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution.go" index 0d65242a64844..0d1de756b71f9 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution.go" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution.go" @@ -8,27 +8,16 @@ */ func convertBST(root *TreeNode) *TreeNode { s := 0 - node := root - for root != nil { - if root.Right == nil { - s += root.Val - root.Val = s - root = root.Left - } else { - next := root.Right - for next.Left != nil && next.Left != root { - next = next.Left - } - if next.Left == nil { - next.Left = root - root = root.Right - } else { - s += root.Val - root.Val = s - next.Left = nil - root = root.Left - } + var dfs func(*TreeNode) + dfs = func(root *TreeNode) { + if root == nil { + return } + dfs(root.Right) + s += root.Val + root.Val = s + dfs(root.Left) } - return node + dfs(root) + return root } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution.java" index 113824439a80e..36ca53db916b0 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution.java" @@ -14,30 +14,20 @@ * } */ class Solution { + private int s; + public TreeNode convertBST(TreeNode root) { - int s = 0; - TreeNode node = root; - while (root != null) { - if (root.right == null) { - s += root.val; - root.val = s; - root = root.left; - } else { - TreeNode next = root.right; - while (next.left != null && next.left != root) { - next = next.left; - } - if (next.left == null) { - next.left = root; - root = root.right; - } else { - s += root.val; - root.val = s; - next.left = null; - root = root.left; - } - } + dfs(root); + return root; + } + + private void dfs(TreeNode root) { + if (root == null) { + return; } - return node; + dfs(root.right); + s += root.val; + root.val = s; + dfs(root.left); } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution.py" index 85480fbfd5341..841ac059c67fb 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution.py" @@ -6,23 +6,15 @@ # self.right = right class Solution: def convertBST(self, root: TreeNode) -> TreeNode: + def dfs(root): + nonlocal s + if root is None: + return + dfs(root.right) + s += root.val + root.val = s + dfs(root.left) + s = 0 - node = root - while root: - if root.right is None: - s += root.val - root.val = s - root = root.left - else: - next = root.right - while next.left and next.left != root: - next = next.left - if next.left is None: - next.left = root - root = root.right - else: - s += root.val - root.val = s - next.left = None - root = root.left - return node + dfs(root) + return root diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution2.cpp" new file mode 100644 index 0000000000000..4f15c632cf1ad --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution2.cpp" @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* convertBST(TreeNode* root) { + int s = 0; + TreeNode* node = root; + while (root) { + if (root->right == nullptr) { + s += root->val; + root->val = s; + root = root->left; + } else { + TreeNode* next = root->right; + while (next->left && next->left != root) { + next = next->left; + } + if (next->left == nullptr) { + next->left = root; + root = root->right; + } else { + s += root->val; + root->val = s; + next->left = nullptr; + root = root->left; + } + } + } + return node; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution2.go" new file mode 100644 index 0000000000000..0d65242a64844 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution2.go" @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func convertBST(root *TreeNode) *TreeNode { + s := 0 + node := root + for root != nil { + if root.Right == nil { + s += root.Val + root.Val = s + root = root.Left + } else { + next := root.Right + for next.Left != nil && next.Left != root { + next = next.Left + } + if next.Left == nil { + next.Left = root + root = root.Right + } else { + s += root.Val + root.Val = s + next.Left = nil + root = root.Left + } + } + } + return node +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution2.java" new file mode 100644 index 0000000000000..113824439a80e --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution2.java" @@ -0,0 +1,43 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode convertBST(TreeNode root) { + int s = 0; + TreeNode node = root; + while (root != null) { + if (root.right == null) { + s += root.val; + root.val = s; + root = root.left; + } else { + TreeNode next = root.right; + while (next.left != null && next.left != root) { + next = next.left; + } + if (next.left == null) { + next.left = root; + root = root.right; + } else { + s += root.val; + root.val = s; + next.left = null; + root = root.left; + } + } + } + return node; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution2.py" new file mode 100644 index 0000000000000..85480fbfd5341 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/Solution2.py" @@ -0,0 +1,28 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def convertBST(self, root: TreeNode) -> TreeNode: + s = 0 + node = root + while root: + if root.right is None: + s += root.val + root.val = s + root = root.left + else: + next = root.right + while next.left and next.left != root: + next = next.left + if next.left is None: + next.left = root + root = root.right + else: + s += root.val + root.val = s + next.left = None + root = root.left + return node diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution.cpp" index 1e9939f2773f1..0eed13a02fa89 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution.cpp" @@ -11,25 +11,27 @@ */ class BSTIterator { public: - stack stack; + vector vals; + int cur; BSTIterator(TreeNode* root) { - for (; root != nullptr; root = root->left) { - stack.push(root); - } + cur = 0; + inorder(root); } int next() { - TreeNode* cur = stack.top(); - stack.pop(); - TreeNode* node = cur->right; - for (; node != nullptr; node = node->left) { - stack.push(node); - } - return cur->val; + return vals[cur++]; } bool hasNext() { - return !stack.empty(); + return cur < vals.size(); + } + + void inorder(TreeNode* root) { + if (root) { + inorder(root->left); + vals.push_back(root->val); + inorder(root->right); + } } }; diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution.java" index 6c3360256ff92..c505606d664fa 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution.java" @@ -14,24 +14,27 @@ * } */ class BSTIterator { - private Deque stack = new LinkedList<>(); + private int cur = 0; + private List vals = new ArrayList<>(); public BSTIterator(TreeNode root) { - for (; root != null; root = root.left) { - stack.offerLast(root); - } + inorder(root); } public int next() { - TreeNode cur = stack.pollLast(); - for (TreeNode node = cur.right; node != null; node = node.left) { - stack.offerLast(node); - } - return cur.val; + return vals.get(cur++); } public boolean hasNext() { - return !stack.isEmpty(); + return cur < vals.size(); + } + + private void inorder(TreeNode root) { + if (root != null) { + inorder(root.left); + vals.add(root.val); + inorder(root.right); + } } } diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution.py" index a8b20b7895704..1452325073795 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution.py" @@ -6,21 +6,23 @@ # self.right = right class BSTIterator: def __init__(self, root: TreeNode): - self.stack = [] - while root: - self.stack.append(root) - root = root.left + def inorder(root): + if root: + inorder(root.left) + self.vals.append(root.val) + inorder(root.right) + + self.cur = 0 + self.vals = [] + inorder(root) def next(self) -> int: - cur = self.stack.pop() - node = cur.right - while node: - self.stack.append(node) - node = node.left - return cur.val + res = self.vals[self.cur] + self.cur += 1 + return res def hasNext(self) -> bool: - return len(self.stack) > 0 + return self.cur < len(self.vals) # Your BSTIterator object will be instantiated and called as such: diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution2.cpp" new file mode 100644 index 0000000000000..1e9939f2773f1 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution2.cpp" @@ -0,0 +1,41 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class BSTIterator { +public: + stack stack; + BSTIterator(TreeNode* root) { + for (; root != nullptr; root = root->left) { + stack.push(root); + } + } + + int next() { + TreeNode* cur = stack.top(); + stack.pop(); + TreeNode* node = cur->right; + for (; node != nullptr; node = node->left) { + stack.push(node); + } + return cur->val; + } + + bool hasNext() { + return !stack.empty(); + } +}; + +/** + * Your BSTIterator object will be instantiated and called as such: + * BSTIterator* obj = new BSTIterator(root); + * int param_1 = obj->next(); + * bool param_2 = obj->hasNext(); + */ \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution2.java" new file mode 100644 index 0000000000000..6c3360256ff92 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution2.java" @@ -0,0 +1,43 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class BSTIterator { + private Deque stack = new LinkedList<>(); + + public BSTIterator(TreeNode root) { + for (; root != null; root = root.left) { + stack.offerLast(root); + } + } + + public int next() { + TreeNode cur = stack.pollLast(); + for (TreeNode node = cur.right; node != null; node = node.left) { + stack.offerLast(node); + } + return cur.val; + } + + public boolean hasNext() { + return !stack.isEmpty(); + } +} + +/** + * Your BSTIterator object will be instantiated and called as such: + * BSTIterator obj = new BSTIterator(root); + * int param_1 = obj.next(); + * boolean param_2 = obj.hasNext(); + */ \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution2.py" new file mode 100644 index 0000000000000..a8b20b7895704 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/Solution2.py" @@ -0,0 +1,29 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class BSTIterator: + def __init__(self, root: TreeNode): + self.stack = [] + while root: + self.stack.append(root) + root = root.left + + def next(self) -> int: + cur = self.stack.pop() + node = cur.right + while node: + self.stack.append(node) + node = node.left + return cur.val + + def hasNext(self) -> bool: + return len(self.stack) > 0 + + +# Your BSTIterator object will be instantiated and called as such: +# obj = BSTIterator(root) +# param_1 = obj.next() +# param_2 = obj.hasNext() diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 058. \346\227\245\347\250\213\350\241\250/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 058. \346\227\245\347\250\213\350\241\250/Solution.java" index 8f66a7bdf5599..3d04816dc4b2e 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 058. \346\227\245\347\250\213\350\241\250/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 058. \346\227\245\347\250\213\350\241\250/Solution.java" @@ -25,4 +25,4 @@ public boolean book(int start, int end) { /** * Your MyCalendar object will be instantiated and called as such: MyCalendar * obj = new MyCalendar(); boolean param_1 = obj.book(start,end); - */ + */ \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/Solution.java" index 2c51bdcb0e84e..2dd78e1c6fdbc 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/Solution.java" @@ -11,4 +11,4 @@ public int[] topKFrequent(int[] nums, int k) { } return queue.stream().mapToInt(Map.Entry::getKey).toArray(); } -} +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/Solution.py" index 37e7fac77f36d..bb2e27754c5f0 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/Solution.py" @@ -1,9 +1,4 @@ class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: cnt = Counter(nums) - hp = [] - for num, freq in cnt.items(): - heappush(hp, (freq, num)) - if len(hp) > k: - heappop(hp) - return [v[1] for v in hp] + return [v[0] for v in cnt.most_common(k)] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/Solution2.java" new file mode 100644 index 0000000000000..50579ba0ce6b6 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/Solution2.java" @@ -0,0 +1,20 @@ +class Solution { + public int[] topKFrequent(int[] nums, int k) { + Map cnt = new HashMap<>(); + for (int v : nums) { + cnt.put(v, cnt.getOrDefault(v, 0) + 1); + } + PriorityQueue pq = new PriorityQueue<>((a, b) -> a[1] - b[1]); + for (var e : cnt.entrySet()) { + pq.offer(new int[] {e.getKey(), e.getValue()}); + if (pq.size() > k) { + pq.poll(); + } + } + int[] ans = new int[k]; + for (int i = 0; i < k; ++i) { + ans[i] = pq.poll()[0]; + } + return ans; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/Solution2.py" new file mode 100644 index 0000000000000..37e7fac77f36d --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/Solution2.py" @@ -0,0 +1,9 @@ +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + cnt = Counter(nums) + hp = [] + for num, freq in cnt.items(): + heappush(hp, (freq, num)) + if len(hp) > k: + heappop(hp) + return [v[1] for v in hp] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/Solution2.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/Solution2.ts" new file mode 100644 index 0000000000000..9001644391a42 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/Solution2.ts" @@ -0,0 +1,20 @@ +function topKFrequent(nums: number[], k: number): number[] { + const map = new Map(); + let maxCount = 0; + for (const num of nums) { + map.set(num, (map.get(num) ?? 0) + 1); + maxCount = Math.max(maxCount, map.get(num)); + } + + const res = []; + while (k > 0) { + for (const key of map.keys()) { + if (map.get(key) === maxCount) { + res.push(key); + k--; + } + } + maxCount--; + } + return res; +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 061. \345\222\214\346\234\200\345\260\217\347\232\204 k \344\270\252\346\225\260\345\257\271/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 061. \345\222\214\346\234\200\345\260\217\347\232\204 k \344\270\252\346\225\260\345\257\271/Solution.cpp" index 0f0617bbc2613..5f7c95e462e9f 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 061. \345\222\214\346\234\200\345\260\217\347\232\204 k \344\270\252\346\225\260\345\257\271/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 061. \345\222\214\346\234\200\345\260\217\347\232\204 k \344\270\252\346\225\260\345\257\271/Solution.cpp" @@ -18,4 +18,4 @@ class Solution { } return ans; } -}; +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 061. \345\222\214\346\234\200\345\260\217\347\232\204 k \344\270\252\346\225\260\345\257\271/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 061. \345\222\214\346\234\200\345\260\217\347\232\204 k \344\270\252\346\225\260\345\257\271/Solution.java" index 83c7222b1040b..03514f5e7db71 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 061. \345\222\214\346\234\200\345\260\217\347\232\204 k \344\270\252\346\225\260\345\257\271/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 061. \345\222\214\346\234\200\345\260\217\347\232\204 k \344\270\252\346\225\260\345\257\271/Solution.java" @@ -12,4 +12,4 @@ public List> kSmallestPairs(int[] nums1, int[] nums2, int k) { } return new ArrayList<>(pq); } -} +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 062. \345\256\236\347\216\260\345\211\215\347\274\200\346\240\221/Solution.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 062. \345\256\236\347\216\260\345\211\215\347\274\200\346\240\221/Solution.cs" index 6ea2f9f61bf0a..e2e0eb0f60679 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 062. \345\256\236\347\216\260\345\211\215\347\274\200\346\240\221/Solution.cs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 062. \345\256\236\347\216\260\345\211\215\347\274\200\346\240\221/Solution.cs" @@ -48,4 +48,4 @@ private Trie SearchPrefix(string s) { * obj.Insert(word); * bool param_2 = obj.Search(word); * bool param_3 = obj.StartsWith(prefix); - */ \ No newline at end of file + */ diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution.cpp" index 77c84a0505705..9fac5b8363381 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution.cpp" @@ -1,44 +1,23 @@ -class Trie { -public: - vector children; - string v; - Trie() - : children(26) - , v("") {} - - void insert(string word) { - Trie* node = this; - for (char c : word) { - c -= 'a'; - if (!node->children[c]) node->children[c] = new Trie(); - node = node->children[c]; - } - node->v = word; - } - - string search(string word) { - Trie* node = this; - for (char c : word) { - c -= 'a'; - if (!node->children[c]) break; - node = node->children[c]; - if (node->v != "") return node->v; - } - return word; - } -}; - class Solution { public: string replaceWords(vector& dictionary, string sentence) { - Trie* trie = new Trie(); - for (auto& v : dictionary) trie->insert(v); - string ans = ""; + unordered_set s(dictionary.begin(), dictionary.end()); istringstream is(sentence); - vector ss; - string s; - while (is >> s) ss.push_back(s); - for (auto word : ss) ans += trie->search(word) + " "; + vector words; + string ss; + while (is >> ss) words.push_back(ss); + for (int i = 0; i < words.size(); ++i) { + string word = words[i]; + for (int j = 1; j <= word.size(); ++j) { + string t = word.substr(0, j); + if (s.count(t)) { + words[i] = t; + break; + } + } + } + string ans = ""; + for (string& word : words) ans += word + " "; ans.pop_back(); return ans; } diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution.go" "b/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution.go" index ab95a5e59b244..172fb1fe472d0 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution.go" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution.go" @@ -1,46 +1,17 @@ -type Trie struct { - children [26]*Trie - v string -} - -func newTrie() *Trie { - return &Trie{} -} -func (this *Trie) insert(word string) { - node := this - for _, c := range word { - c -= 'a' - if node.children[c] == nil { - node.children[c] = newTrie() - } - node = node.children[c] - } - node.v = word -} - -func (this *Trie) search(word string) string { - node := this - for _, c := range word { - c -= 'a' - if node.children[c] == nil { - break - } - node = node.children[c] - if node.v != "" { - return node.v - } - } - return word -} - func replaceWords(dictionary []string, sentence string) string { - trie := newTrie() + s := map[string]bool{} for _, v := range dictionary { - trie.insert(v) + s[v] = true } - var ans []string - for _, v := range strings.Split(sentence, " ") { - ans = append(ans, trie.search(v)) + words := strings.Split(sentence, " ") + for i, word := range words { + for j := 1; j <= len(word); j++ { + t := word[:j] + if s[t] { + words[i] = t + break + } + } } - return strings.Join(ans, " ") + return strings.Join(words, " ") } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution.java" index 95d94523ef8be..ad7971ab23a32 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution.java" @@ -1,45 +1,17 @@ -class Trie { - Trie[] children = new Trie[26]; - String v; - - void insert(String word) { - Trie node = this; - for (char c : word.toCharArray()) { - c -= 'a'; - if (node.children[c] == null) { - node.children[c] = new Trie(); - } - node = node.children[c]; - } - node.v = word; - } - - String search(String word) { - Trie node = this; - for (char c : word.toCharArray()) { - c -= 'a'; - if (node.children[c] == null) { - return word; - } - node = node.children[c]; - if (node.v != null) { - return node.v; - } - } - return word; - } -} - class Solution { public String replaceWords(List dictionary, String sentence) { - Trie trie = new Trie(); - for (String v : dictionary) { - trie.insert(v); - } - List ans = new ArrayList<>(); - for (String v : sentence.split("\\s")) { - ans.add(trie.search(v)); + Set s = new HashSet<>(dictionary); + String[] words = sentence.split(" "); + for (int i = 0; i < words.length; ++i) { + String word = words[i]; + for (int j = 1; j <= word.length(); ++j) { + String t = word.substring(0, j); + if (s.contains(t)) { + words[i] = t; + break; + } + } } - return String.join(" ", ans); + return String.join(" ", words); } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution.py" index 13c0eae2b021e..c17dccfca89ef 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution.py" @@ -1,32 +1,10 @@ -class Trie: - def __init__(self): - self.children = [None] * 26 - self.v = None - - def insert(self, word): - node = self - for c in word: - idx = ord(c) - ord('a') - if node.children[idx] is None: - node.children[idx] = Trie() - node = node.children[idx] - node.v = word - - def search(self, word): - node = self - for c in word: - idx = ord(c) - ord('a') - if node.children[idx] is None: - break - node = node.children[idx] - if node.v: - return node.v - return word - - class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: - trie = Trie() - for v in dictionary: - trie.insert(v) - return ' '.join(trie.search(v) for v in sentence.split()) + s = set(dictionary) + words = sentence.split() + for i, word in enumerate(words): + for j in range(1, len(word) + 1): + if word[:j] in s: + words[i] = word[:j] + break + return ' '.join(words) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution2.cpp" new file mode 100644 index 0000000000000..77c84a0505705 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution2.cpp" @@ -0,0 +1,45 @@ +class Trie { +public: + vector children; + string v; + Trie() + : children(26) + , v("") {} + + void insert(string word) { + Trie* node = this; + for (char c : word) { + c -= 'a'; + if (!node->children[c]) node->children[c] = new Trie(); + node = node->children[c]; + } + node->v = word; + } + + string search(string word) { + Trie* node = this; + for (char c : word) { + c -= 'a'; + if (!node->children[c]) break; + node = node->children[c]; + if (node->v != "") return node->v; + } + return word; + } +}; + +class Solution { +public: + string replaceWords(vector& dictionary, string sentence) { + Trie* trie = new Trie(); + for (auto& v : dictionary) trie->insert(v); + string ans = ""; + istringstream is(sentence); + vector ss; + string s; + while (is >> s) ss.push_back(s); + for (auto word : ss) ans += trie->search(word) + " "; + ans.pop_back(); + return ans; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution2.go" new file mode 100644 index 0000000000000..ab95a5e59b244 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution2.go" @@ -0,0 +1,46 @@ +type Trie struct { + children [26]*Trie + v string +} + +func newTrie() *Trie { + return &Trie{} +} +func (this *Trie) insert(word string) { + node := this + for _, c := range word { + c -= 'a' + if node.children[c] == nil { + node.children[c] = newTrie() + } + node = node.children[c] + } + node.v = word +} + +func (this *Trie) search(word string) string { + node := this + for _, c := range word { + c -= 'a' + if node.children[c] == nil { + break + } + node = node.children[c] + if node.v != "" { + return node.v + } + } + return word +} + +func replaceWords(dictionary []string, sentence string) string { + trie := newTrie() + for _, v := range dictionary { + trie.insert(v) + } + var ans []string + for _, v := range strings.Split(sentence, " ") { + ans = append(ans, trie.search(v)) + } + return strings.Join(ans, " ") +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution2.java" new file mode 100644 index 0000000000000..95d94523ef8be --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution2.java" @@ -0,0 +1,45 @@ +class Trie { + Trie[] children = new Trie[26]; + String v; + + void insert(String word) { + Trie node = this; + for (char c : word.toCharArray()) { + c -= 'a'; + if (node.children[c] == null) { + node.children[c] = new Trie(); + } + node = node.children[c]; + } + node.v = word; + } + + String search(String word) { + Trie node = this; + for (char c : word.toCharArray()) { + c -= 'a'; + if (node.children[c] == null) { + return word; + } + node = node.children[c]; + if (node.v != null) { + return node.v; + } + } + return word; + } +} + +class Solution { + public String replaceWords(List dictionary, String sentence) { + Trie trie = new Trie(); + for (String v : dictionary) { + trie.insert(v); + } + List ans = new ArrayList<>(); + for (String v : sentence.split("\\s")) { + ans.add(trie.search(v)); + } + return String.join(" ", ans); + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution2.py" new file mode 100644 index 0000000000000..13c0eae2b021e --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/Solution2.py" @@ -0,0 +1,32 @@ +class Trie: + def __init__(self): + self.children = [None] * 26 + self.v = None + + def insert(self, word): + node = self + for c in word: + idx = ord(c) - ord('a') + if node.children[idx] is None: + node.children[idx] = Trie() + node = node.children[idx] + node.v = word + + def search(self, word): + node = self + for c in word: + idx = ord(c) - ord('a') + if node.children[idx] is None: + break + node = node.children[idx] + if node.v: + return node.v + return word + + +class Solution: + def replaceWords(self, dictionary: List[str], sentence: str) -> str: + trie = Trie() + for v in dictionary: + trie.insert(v) + return ' '.join(trie.search(v) for v in sentence.split()) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution.cpp" index e1a647698d5a9..054a535ce46bd 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution.cpp" @@ -33,4 +33,4 @@ class Solution { } return ans; } -}; +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution.java" index 5a469ee7814c0..63e2da57c5916 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution.java" @@ -32,4 +32,4 @@ private int dfs(Trie cur, int l) { } return ans; } -} +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution2.cpp" new file mode 100644 index 0000000000000..6b815b982ff9b --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution2.cpp" @@ -0,0 +1,34 @@ +class Trie { +public: + vector children; + Trie() + : children(26) {} + + int insert(string w) { + Trie* node = this; + bool pref = true; + for (char c : w) { + c -= 'a'; + if (!node->children[c]) { + pref = false; + node->children[c] = new Trie(); + } + node = node->children[c]; + } + return pref ? 0 : w.size() + 1; + } +}; + +class Solution { +public: + int minimumLengthEncoding(vector& words) { + sort(words.begin(), words.end(), [](string& a, string& b) { return a.size() > b.size(); }); + Trie* trie = new Trie(); + int ans = 0; + for (auto& w : words) { + reverse(w.begin(), w.end()); + ans += trie->insert(w); + } + return ans; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution2.go" new file mode 100644 index 0000000000000..581a16f9de885 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution2.go" @@ -0,0 +1,34 @@ +type Trie struct { + children [26]*Trie +} + +func newTrie() *Trie { + return &Trie{} +} + +func (this *Trie) insert(w string) int { + node := this + pref := true + for i := len(w) - 1; i >= 0; i-- { + idx := w[i] - 'a' + if node.children[idx] == nil { + pref = false + node.children[idx] = newTrie() + } + node = node.children[idx] + } + if pref { + return 0 + } + return len(w) + 1 +} + +func minimumLengthEncoding(words []string) int { + sort.Slice(words, func(i, j int) bool { return len(words[i]) > len(words[j]) }) + trie := newTrie() + ans := 0 + for _, w := range words { + ans += trie.insert(w) + } + return ans +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution2.java" new file mode 100644 index 0000000000000..b800c33dc04db --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution2.java" @@ -0,0 +1,29 @@ +class Trie { + Trie[] children = new Trie[26]; + + int insert(String w) { + Trie node = this; + boolean pref = true; + for (int i = w.length() - 1; i >= 0; --i) { + int idx = w.charAt(i) - 'a'; + if (node.children[idx] == null) { + pref = false; + node.children[idx] = new Trie(); + } + node = node.children[idx]; + } + return pref ? 0 : w.length() + 1; + } +} + +class Solution { + public int minimumLengthEncoding(String[] words) { + Arrays.sort(words, (a, b) -> b.length() - a.length()); + int ans = 0; + Trie trie = new Trie(); + for (String w : words) { + ans += trie.insert(w); + } + return ans; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution2.py" new file mode 100644 index 0000000000000..0b31f6d6b2218 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution2.py" @@ -0,0 +1,21 @@ +class Trie: + def __init__(self): + self.children = [None] * 26 + + def insert(self, w): + node = self + pref = True + for c in w: + idx = ord(c) - ord("a") + if node.children[idx] is None: + node.children[idx] = Trie() + pref = False + node = node.children[idx] + return 0 if pref else len(w) + 1 + + +class Solution: + def minimumLengthEncoding(self, words: List[str]) -> int: + words.sort(key=lambda x: -len(x)) + trie = Trie() + return sum(trie.insert(w[::-1]) for w in words) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 067. \346\234\200\345\244\247\347\232\204\345\274\202\346\210\226/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 067. \346\234\200\345\244\247\347\232\204\345\274\202\346\210\226/Solution.java" index 6b556b1def977..aaa1e60f1adc8 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 067. \346\234\200\345\244\247\347\232\204\345\274\202\346\210\226/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 067. \346\234\200\345\244\247\347\232\204\345\274\202\346\210\226/Solution.java" @@ -5,11 +5,14 @@ public int findMaximumXOR(int[] numbers) { int mask = 0; for (int i = 30; i >= 0; i--) { int current = 1 << i; + // 期望的二进制前缀 mask = mask ^ current; + // 在当前前缀下, 数组内的前缀位数所有情况集合 Set set = new HashSet<>(); for (int j = 0, k = numbers.length; j < k; j++) { set.add(mask & numbers[j]); } + // 期望最终异或值的从右数第i位为1, 再根据异或运算的特性推算假设是否成立 int flag = max | current; for (Integer prefix : set) { if (set.contains(prefix ^ flag)) { @@ -20,4 +23,4 @@ public int findMaximumXOR(int[] numbers) { } return max; } -} +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 067. \346\234\200\345\244\247\347\232\204\345\274\202\346\210\226/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 067. \346\234\200\345\244\247\347\232\204\345\274\202\346\210\226/Solution.py" index 316c113b0e4de..4354418f8d5d9 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 067. \346\234\200\345\244\247\347\232\204\345\274\202\346\210\226/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 067. \346\234\200\345\244\247\347\232\204\345\274\202\346\210\226/Solution.py" @@ -4,10 +4,13 @@ def findMaximumXOR(self, nums: List[int]) -> int: mask = 0 for i in range(30, -1, -1): current = 1 << i + # 期望的二进制前缀 mask = mask ^ current + # 在当前前缀下, 数组内的前缀位数所有情况集合 s = set() for num in nums: s.add(num & mask) + # 期望最终异或值的从右数第i位为1, 再根据异或运算的特性推算假设是否成立 flag = max | current for prefix in s: if prefix ^ flag in s: diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 067. \346\234\200\345\244\247\347\232\204\345\274\202\346\210\226/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 067. \346\234\200\345\244\247\347\232\204\345\274\202\346\210\226/Solution2.java" new file mode 100644 index 0000000000000..51d9a640ccbaa --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 067. \346\234\200\345\244\247\347\232\204\345\274\202\346\210\226/Solution2.java" @@ -0,0 +1,42 @@ +class Trie { + Trie[] children = new Trie[2]; + + void insert(int x) { + Trie node = this; + for (int i = 30; i >= 0; --i) { + int v = (x >> i) & 1; + if (node.children[v] == null) { + node.children[v] = new Trie(); + } + node = node.children[v]; + } + } + + int search(int x) { + Trie node = this; + int res = 0; + for (int i = 30; i >= 0; --i) { + int v = (x >> i) & 1; + if (node.children[v ^ 1] != null) { + res = res << 1 | 1; + node = node.children[v ^ 1]; + } else { + res <<= 1; + node = node.children[v]; + } + } + return res; + } +} + +class Solution { + public int findMaximumXOR(int[] nums) { + Trie trie = new Trie(); + int ans = 0; + for (int v : nums) { + trie.insert(v); + ans = Math.max(ans, trie.search(v)); + } + return ans; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 067. \346\234\200\345\244\247\347\232\204\345\274\202\346\210\226/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 067. \346\234\200\345\244\247\347\232\204\345\274\202\346\210\226/Solution2.py" new file mode 100644 index 0000000000000..b006e2504aa9f --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 067. \346\234\200\345\244\247\347\232\204\345\274\202\346\210\226/Solution2.py" @@ -0,0 +1,32 @@ +class Trie: + def __init__(self): + self.children = [None] * 2 + + def insert(self, x): + node = self + for i in range(30, -1, -1): + v = (x >> i) & 1 + if node.children[v] is None: + node.children[v] = Trie() + node = node.children[v] + + def search(self, x): + node = self + res = 0 + for i in range(30, -1, -1): + v = (x >> i) & 1 + if node.children[v ^ 1]: + res = res << 1 | 1 + node = node.children[v ^ 1] + else: + res <<= 1 + node = node.children[v] + return res + + +class Solution: + def findMaximumXOR(self, nums: List[int]) -> int: + trie = Trie() + for v in nums: + trie.insert(v) + return max(trie.search(v) for v in nums) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 069. \345\261\261\345\263\260\346\225\260\347\273\204\347\232\204\351\241\266\351\203\250/Solution.js" "b/lcof2/\345\211\221\346\214\207 Offer II 069. \345\261\261\345\263\260\346\225\260\347\273\204\347\232\204\351\241\266\351\203\250/Solution.js" index 52fafb321cdcb..50890104043c9 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 069. \345\261\261\345\263\260\346\225\260\347\273\204\347\232\204\351\241\266\351\203\250/Solution.js" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 069. \345\261\261\345\263\260\346\225\260\347\273\204\347\232\204\351\241\266\351\203\250/Solution.js" @@ -7,10 +7,10 @@ var peakIndexInMountainArray = function (arr) { let right = arr.length - 2; while (left < right) { const mid = (left + right) >> 1; - if (arr[mid] > arr[mid + 1]) { - right = mid; - } else { + if (arr[mid] < arr[mid + 1]) { left = mid + 1; + } else { + right = mid; } } return left; diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 072. \346\261\202\345\271\263\346\226\271\346\240\271/Solution.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 072. \346\261\202\345\271\263\346\226\271\346\240\271/Solution.cs" index df9dd04a18a41..2dcf1bf29ae2c 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 072. \346\261\202\345\271\263\346\226\271\346\240\271/Solution.cs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 072. \346\261\202\345\271\263\346\226\271\346\240\271/Solution.cs" @@ -15,4 +15,4 @@ public int MySqrt(int x) { } return left; } -} \ No newline at end of file +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 073. \347\213\222\347\213\222\345\220\203\351\246\231\350\225\211/Solution.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 073. \347\213\222\347\213\222\345\220\203\351\246\231\350\225\211/Solution.cs" index fb1be7d77049d..c7a8f8c1322da 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 073. \347\213\222\347\213\222\345\220\203\351\246\231\350\225\211/Solution.cs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 073. \347\213\222\347\213\222\345\220\203\351\246\231\350\225\211/Solution.cs" @@ -20,4 +20,4 @@ public int MinEatingSpeed(int[] piles, int h) { } return left; } -} \ No newline at end of file +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 073. \347\213\222\347\213\222\345\220\203\351\246\231\350\225\211/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 073. \347\213\222\347\213\222\345\220\203\351\246\231\350\225\211/Solution.py" index 5b78123b759dd..8d8f468d9e750 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 073. \347\213\222\347\213\222\345\220\203\351\246\231\350\225\211/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 073. \347\213\222\347\213\222\345\220\203\351\246\231\350\225\211/Solution.py" @@ -3,7 +3,7 @@ def minEatingSpeed(self, piles: List[int], h: int) -> int: left, right = 1, max(piles) while left < right: mid = (left + right) >> 1 - s = sum([(pile + mid - 1) // mid for pile in piles]) + s = sum((pile + mid - 1) // mid for pile in piles) if s <= h: right = mid else: diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 074. \345\220\210\345\271\266\345\214\272\351\227\264/Solution.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 074. \345\220\210\345\271\266\345\214\272\351\227\264/Solution.cs" index a864e11d4dea8..94e9c6479d2d0 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 074. \345\220\210\345\271\266\345\214\272\351\227\264/Solution.cs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 074. \345\220\210\345\271\266\345\214\272\351\227\264/Solution.cs" @@ -20,4 +20,4 @@ public int[][] Merge(int[][] intervals) { ans.Add(new int[]{st, ed}); return ans.ToArray(); } -} \ No newline at end of file +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 075. \346\225\260\347\273\204\347\233\270\345\257\271\346\216\222\345\272\217/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 075. \346\225\260\347\273\204\347\233\270\345\257\271\346\216\222\345\272\217/Solution.py" index fc44d1f6ea545..2d57297cd3d65 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 075. \346\225\260\347\273\204\347\233\270\345\257\271\346\216\222\345\272\217/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 075. \346\225\260\347\273\204\347\233\270\345\257\271\346\216\222\345\272\217/Solution.py" @@ -1,16 +1,5 @@ class Solution: def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: - mp = [0] * 1001 - for x in arr1: - mp[x] += 1 - i = 0 - for x in arr2: - while mp[x] > 0: - arr1[i] = x - mp[x] -= 1 - i += 1 - for x, cnt in enumerate(mp): - for _ in range(cnt): - arr1[i] = x - i += 1 + mp = {num: i for i, num in enumerate(arr2)} + arr1.sort(key=lambda x: (mp.get(x, 10000), x)) return arr1 diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 075. \346\225\260\347\273\204\347\233\270\345\257\271\346\216\222\345\272\217/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 075. \346\225\260\347\273\204\347\233\270\345\257\271\346\216\222\345\272\217/Solution2.py" new file mode 100644 index 0000000000000..fc44d1f6ea545 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 075. \346\225\260\347\273\204\347\233\270\345\257\271\346\216\222\345\272\217/Solution2.py" @@ -0,0 +1,16 @@ +class Solution: + def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: + mp = [0] * 1001 + for x in arr1: + mp[x] += 1 + i = 0 + for x in arr2: + while mp[x] > 0: + arr1[i] = x + mp[x] -= 1 + i += 1 + for x, cnt in enumerate(mp): + for _ in range(cnt): + arr1[i] = x + i += 1 + return arr1 diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 077. \351\223\276\350\241\250\346\216\222\345\272\217/Solution.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 077. \351\223\276\350\241\250\346\216\222\345\272\217/Solution.cs" index 6cd02f2490770..fc6c6d8c95300 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 077. \351\223\276\350\241\250\346\216\222\345\272\217/Solution.cs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 077. \351\223\276\350\241\250\346\216\222\345\272\217/Solution.cs" @@ -44,4 +44,4 @@ public ListNode SortList(ListNode head) { cur.next = l1 == null ? l2 : l1; return dummy.next; } -} \ No newline at end of file +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/Solution.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/Solution.cs" index d9502cadf2173..c69165d7a4cb5 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/Solution.cs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/Solution.cs" @@ -37,4 +37,4 @@ private ListNode MergeTwoLists(ListNode l1, ListNode l2) { cur.next = l1 == null ? l2 : l1; return dummy.next; } -} \ No newline at end of file +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/Solution.rb" "b/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/Solution.rb" index 35d8be5f94fe1..5b6612c92b840 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/Solution.rb" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/Solution.rb" @@ -9,28 +9,28 @@ # @param {ListNode[]} lists # @return {ListNode} def merge_k_lists(lists) - n = lists.length - i = 1 - while i < n - lists[i] = merge_two_lists(lists[i - 1], lists[i]) - i += 1 - end - lists[n - 1] + n = lists.length + i = 1 + while i < n + lists[i] = merge_two_lists(lists[i - 1], lists[i]) + i += 1 + end + lists[n - 1] end def merge_two_lists(l1, l2) -dummy = ListNode.new() -cur = dummy -while l1 && l2 - if l1.val <= l2.val - cur.next = l1 - l1 = l1.next - else - cur.next = l2 - l2 = l2.next - end - cur = cur.next + dummy = ListNode.new() + cur = dummy + while l1 && l2 + if l1.val <= l2.val + cur.next = l1 + l1 = l1.next + else + cur.next = l2 + l2 = l2.next + end + cur = cur.next + end + cur.next = l1 || l2 + dummy.next end -cur.next = l1 || l2 -dummy.next -end \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/Solution.cpp" index f98e5408f031d..e5397fdbf168c 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/Solution.cpp" @@ -1,30 +1,30 @@ -class Solution { -public: - vector> partition(string s) { - int n = s.size(); - bool f[n][n]; - memset(f, true, sizeof(f)); - for (int i = n - 1; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - f[i][j] = s[i] == s[j] && f[i + 1][j - 1]; - } - } - vector> ans; - vector t; - function dfs = [&](int i) { - if (i == n) { - ans.push_back(t); - return; - } - for (int j = i; j < n; ++j) { - if (f[i][j]) { - t.push_back(s.substr(i, j - i + 1)); - dfs(j + 1); - t.pop_back(); - } - } - }; - dfs(0); - return ans; - } +class Solution { +public: + vector> partition(string s) { + int n = s.size(); + bool f[n][n]; + memset(f, true, sizeof(f)); + for (int i = n - 1; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + f[i][j] = s[i] == s[j] && f[i + 1][j - 1]; + } + } + vector> ans; + vector t; + function dfs = [&](int i) { + if (i == n) { + ans.push_back(t); + return; + } + for (int j = i; j < n; ++j) { + if (f[i][j]) { + t.push_back(s.substr(i, j - i + 1)); + dfs(j + 1); + t.pop_back(); + } + } + }; + dfs(0); + return ans; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/Solution.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/Solution.cs" index 3a342bbe0ab84..cd30c546517df 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/Solution.cs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/Solution.cs" @@ -1,39 +1,39 @@ -public class Solution { - private int n; - private string s; - private bool[,] f; - private IList> ans = new List>(); - private IList t = new List(); - - public IList> Partition(string s) { - n = s.Length; - this.s = s; - f = new bool[n, n]; - for (int i = 0; i < n; ++i) { - for (int j = 0; j <= i; ++j) { - f[i, j] = true; - } - } - for (int i = n - 1; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - f[i, j] = s[i] == s[j] && f[i + 1, j - 1]; - } - } - dfs(0); - return ans; - } - - private void dfs(int i) { - if (i == n) { - ans.Add(new List(t)); - return; - } - for (int j = i; j < n; ++j) { - if (f[i, j]) { - t.Add(s.Substring(i, j + 1 - i)); - dfs(j + 1); - t.RemoveAt(t.Count - 1); - } - } - } -} \ No newline at end of file +public class Solution { + private int n; + private string s; + private bool[,] f; + private IList> ans = new List>(); + private IList t = new List(); + + public IList> Partition(string s) { + n = s.Length; + this.s = s; + f = new bool[n, n]; + for (int i = 0; i < n; ++i) { + for (int j = 0; j <= i; ++j) { + f[i, j] = true; + } + } + for (int i = n - 1; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + f[i, j] = s[i] == s[j] && f[i + 1, j - 1]; + } + } + dfs(0); + return ans; + } + + private void dfs(int i) { + if (i == n) { + ans.Add(new List(t)); + return; + } + for (int j = i; j < n; ++j) { + if (f[i, j]) { + t.Add(s.Substring(i, j + 1 - i)); + dfs(j + 1); + t.RemoveAt(t.Count - 1); + } + } + } +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/Solution.java" index d35464144ad4c..f3863098b1536 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/Solution.java" @@ -1,37 +1,37 @@ -class Solution { - private int n; - private String s; - private boolean[][] f; - private List t = new ArrayList<>(); - private List> ans = new ArrayList<>(); - - public List> partition(String s) { - n = s.length(); - f = new boolean[n][n]; - for (int i = 0; i < n; ++i) { - Arrays.fill(f[i], true); - } - for (int i = n - 1; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - f[i][j] = s.charAt(i) == s.charAt(j) && f[i + 1][j - 1]; - } - } - this.s = s; - dfs(0); - return ans; - } - - private void dfs(int i) { - if (i == s.length()) { - ans.add(new ArrayList<>(t)); - return; - } - for (int j = i; j < n; ++j) { - if (f[i][j]) { - t.add(s.substring(i, j + 1)); - dfs(j + 1); - t.remove(t.size() - 1); - } - } - } +class Solution { + private int n; + private String s; + private boolean[][] f; + private List t = new ArrayList<>(); + private List> ans = new ArrayList<>(); + + public List> partition(String s) { + n = s.length(); + f = new boolean[n][n]; + for (int i = 0; i < n; ++i) { + Arrays.fill(f[i], true); + } + for (int i = n - 1; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + f[i][j] = s.charAt(i) == s.charAt(j) && f[i + 1][j - 1]; + } + } + this.s = s; + dfs(0); + return ans; + } + + private void dfs(int i) { + if (i == s.length()) { + ans.add(new ArrayList<>(t)); + return; + } + for (int j = i; j < n; ++j) { + if (f[i][j]) { + t.add(s.substring(i, j + 1)); + dfs(j + 1); + t.remove(t.size() - 1); + } + } + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/Solution.py" index b50f5eb91e2bf..53392deeab18a 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/Solution.py" @@ -1,21 +1,21 @@ -class Solution: - def partition(self, s: str) -> List[List[str]]: - def dfs(i: int): - if i == n: - ans.append(t[:]) - return - for j in range(i, n): - if f[i][j]: - t.append(s[i : j + 1]) - dfs(j + 1) - t.pop() - - n = len(s) - f = [[True] * n for _ in range(n)] - for i in range(n - 1, -1, -1): - for j in range(i + 1, n): - f[i][j] = s[i] == s[j] and f[i + 1][j - 1] - ans = [] - t = [] - dfs(0) - return ans +class Solution: + def partition(self, s: str) -> List[List[str]]: + def dfs(i: int): + if i == n: + ans.append(t[:]) + return + for j in range(i, n): + if f[i][j]: + t.append(s[i : j + 1]) + dfs(j + 1) + t.pop() + + n = len(s) + f = [[True] * n for _ in range(n)] + for i in range(n - 1, -1, -1): + for j in range(i + 1, n): + f[i][j] = s[i] == s[j] and f[i + 1][j - 1] + ans = [] + t = [] + dfs(0) + return ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.cpp" index bd30bf8a1d575..dc9ff6773f0b3 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.cpp" @@ -1,29 +1,29 @@ -class Solution { -public: - vector restoreIpAddresses(string s) { - int n = s.size(); - vector ans; - vector t; - function dfs = [&](int i) { - if (i >= n && t.size() == 4) { - ans.push_back(t[0] + "." + t[1] + "." + t[2] + "." + t[3]); - return; - } - if (i >= n || t.size() >= 4) { - return; - } - int x = 0; - for (int j = i; j < min(n, i + 3); ++j) { - x = x * 10 + s[j] - '0'; - if (x > 255 || (j > i && s[i] == '0')) { - break; - } - t.push_back(s.substr(i, j - i + 1)); - dfs(j + 1); - t.pop_back(); - } - }; - dfs(0); - return ans; - } +class Solution { +public: + vector restoreIpAddresses(string s) { + int n = s.size(); + vector ans; + vector t; + function dfs = [&](int i) { + if (i >= n && t.size() == 4) { + ans.push_back(t[0] + "." + t[1] + "." + t[2] + "." + t[3]); + return; + } + if (i >= n || t.size() >= 4) { + return; + } + int x = 0; + for (int j = i; j < min(n, i + 3); ++j) { + x = x * 10 + s[j] - '0'; + if (x > 255 || (j > i && s[i] == '0')) { + break; + } + t.push_back(s.substr(i, j - i + 1)); + dfs(j + 1); + t.pop_back(); + } + }; + dfs(0); + return ans; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.cs" index 366b6d8e64f5a..cad6031422c2b 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.cs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.cs" @@ -1,33 +1,33 @@ -public class Solution { - private IList ans = new List(); - private IList t = new List(); - private int n; - private string s; - - public IList RestoreIpAddresses(string s) { - n = s.Length; - this.s = s; - dfs(0); - return ans; - } - - private void dfs(int i) { - if (i >= n && t.Count == 4) { - ans.Add(string.Join(".", t)); - return; - } - if (i >= n || t.Count == 4) { - return; - } - int x = 0; - for (int j = i; j < i + 3 && j < n; ++j) { - x = x * 10 + (s[j] - '0'); - if (x > 255 || (j > i && s[i] == '0')) { - break; - } - t.Add(x.ToString()); - dfs(j + 1); - t.RemoveAt(t.Count - 1); - } - } -} \ No newline at end of file +public class Solution { + private IList ans = new List(); + private IList t = new List(); + private int n; + private string s; + + public IList RestoreIpAddresses(string s) { + n = s.Length; + this.s = s; + dfs(0); + return ans; + } + + private void dfs(int i) { + if (i >= n && t.Count == 4) { + ans.Add(string.Join(".", t)); + return; + } + if (i >= n || t.Count == 4) { + return; + } + int x = 0; + for (int j = i; j < i + 3 && j < n; ++j) { + x = x * 10 + (s[j] - '0'); + if (x > 255 || (j > i && s[i] == '0')) { + break; + } + t.Add(x.ToString()); + dfs(j + 1); + t.RemoveAt(t.Count - 1); + } + } +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.java" index 84bd9b8888e9e..1d2033031c387 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.java" @@ -1,33 +1,33 @@ -class Solution { - private int n; - private String s; - private List ans = new ArrayList<>(); - private List t = new ArrayList<>(); - - public List restoreIpAddresses(String s) { - n = s.length(); - this.s = s; - dfs(0); - return ans; - } - - private void dfs(int i) { - if (i >= n && t.size() == 4) { - ans.add(String.join(".", t)); - return; - } - if (i >= n || t.size() >= 4) { - return; - } - int x = 0; - for (int j = i; j < Math.min(i + 3, n); ++j) { - x = x * 10 + s.charAt(j) - '0'; - if (x > 255 || (s.charAt(i) == '0' && i != j)) { - break; - } - t.add(s.substring(i, j + 1)); - dfs(j + 1); - t.remove(t.size() - 1); - } - } +class Solution { + private int n; + private String s; + private List ans = new ArrayList<>(); + private List t = new ArrayList<>(); + + public List restoreIpAddresses(String s) { + n = s.length(); + this.s = s; + dfs(0); + return ans; + } + + private void dfs(int i) { + if (i >= n && t.size() == 4) { + ans.add(String.join(".", t)); + return; + } + if (i >= n || t.size() >= 4) { + return; + } + int x = 0; + for (int j = i; j < Math.min(i + 3, n); ++j) { + x = x * 10 + s.charAt(j) - '0'; + if (x > 255 || (s.charAt(i) == '0' && i != j)) { + break; + } + t.add(s.substring(i, j + 1)); + dfs(j + 1); + t.remove(t.size() - 1); + } + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.py" index c7150e6003caa..ec040afb985af 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.py" @@ -1,24 +1,24 @@ -class Solution: - def restoreIpAddresses(self, s: str) -> List[str]: - def check(i: int, j: int) -> int: - if s[i] == "0" and i != j: - return False - return 0 <= int(s[i : j + 1]) <= 255 - - def dfs(i: int): - if i >= n and len(t) == 4: - ans.append(".".join(t)) - return - if i >= n or len(t) >= 4: - return - for j in range(i, min(i + 3, n)): - if check(i, j): - t.append(s[i : j + 1]) - dfs(j + 1) - t.pop() - - n = len(s) - ans = [] - t = [] - dfs(0) - return ans +class Solution: + def restoreIpAddresses(self, s: str) -> List[str]: + def check(i: int, j: int) -> int: + if s[i] == "0" and i != j: + return False + return 0 <= int(s[i : j + 1]) <= 255 + + def dfs(i: int): + if i >= n and len(t) == 4: + ans.append(".".join(t)) + return + if i >= n or len(t) >= 4: + return + for j in range(i, min(i + 3, n)): + if check(i, j): + t.append(s[i : j + 1]) + dfs(j + 1) + t.pop() + + n = len(s) + ans = [] + t = [] + dfs(0) + return ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.cpp" index 4908ed9e240d4..9809cd9221720 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.cpp" @@ -1,12 +1,11 @@ class Solution { public: int minCostClimbingStairs(vector& cost) { - int a = 0, b = 0; - for (int i = 1; i < cost.size(); ++i) { - int c = min(a + cost[i - 1], b + cost[i]); - a = b; - b = c; + int n = cost.size(); + vector dp(n + 1); + for (int i = 2; i <= n; ++i) { + dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); } - return b; + return dp[n]; } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.go" "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.go" index 5eeec3b9006e3..bc9e4f2c7253c 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.go" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.go" @@ -1,7 +1,8 @@ func minCostClimbingStairs(cost []int) int { - a, b := 0, 0 - for i := 1; i < len(cost); i++ { - a, b = b, min(a+cost[i-1], b+cost[i]) + n := len(cost) + dp := make([]int, n+1) + for i := 2; i <= n; i++ { + dp[i] = min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2]) } - return b + return dp[n] } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.java" index 85369621c102e..98abad43997e3 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.java" @@ -1,11 +1,10 @@ class Solution { public int minCostClimbingStairs(int[] cost) { - int a = 0, b = 0; - for (int i = 1; i < cost.length; ++i) { - int c = Math.min(a + cost[i - 1], b + cost[i]); - a = b; - b = c; + int n = cost.length; + int[] dp = new int[n + 1]; + for (int i = 2; i <= n; ++i) { + dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); } - return b; + return dp[n]; } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.py" index 5166afc4fd42e..7dac4292a488a 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.py" @@ -1,6 +1,7 @@ class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: - a = b = 0 - for i in range(1, len(cost)): - a, b = b, min(a + cost[i - 1], b + cost[i]) - return b + n = len(cost) + dp = [0] * (n + 1) + for i in range(2, n + 1): + dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]) + return dp[-1] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.ts" index 2b133cba36647..9b47b262a8bd1 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.ts" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution.ts" @@ -1,8 +1,8 @@ function minCostClimbingStairs(cost: number[]): number { - let a = 0, - b = 0; - for (let i = 1; i < cost.length; ++i) { - [a, b] = [b, Math.min(a + cost[i - 1], b + cost[i])]; + const n = cost.length; + const dp = new Array(n + 1).fill(0); + for (let i = 2; i <= n; ++i) { + dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); } - return b; + return dp[n]; } diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution2.cpp" new file mode 100644 index 0000000000000..4908ed9e240d4 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution2.cpp" @@ -0,0 +1,12 @@ +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + int a = 0, b = 0; + for (int i = 1; i < cost.size(); ++i) { + int c = min(a + cost[i - 1], b + cost[i]); + a = b; + b = c; + } + return b; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution2.go" new file mode 100644 index 0000000000000..5eeec3b9006e3 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution2.go" @@ -0,0 +1,7 @@ +func minCostClimbingStairs(cost []int) int { + a, b := 0, 0 + for i := 1; i < len(cost); i++ { + a, b = b, min(a+cost[i-1], b+cost[i]) + } + return b +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution2.java" new file mode 100644 index 0000000000000..85369621c102e --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution2.java" @@ -0,0 +1,11 @@ +class Solution { + public int minCostClimbingStairs(int[] cost) { + int a = 0, b = 0; + for (int i = 1; i < cost.length; ++i) { + int c = Math.min(a + cost[i - 1], b + cost[i]); + a = b; + b = c; + } + return b; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution2.py" new file mode 100644 index 0000000000000..5166afc4fd42e --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution2.py" @@ -0,0 +1,6 @@ +class Solution: + def minCostClimbingStairs(self, cost: List[int]) -> int: + a = b = 0 + for i in range(1, len(cost)): + a, b = b, min(a + cost[i - 1], b + cost[i]) + return b diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution2.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution2.ts" new file mode 100644 index 0000000000000..2b133cba36647 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/Solution2.ts" @@ -0,0 +1,8 @@ +function minCostClimbingStairs(cost: number[]): number { + let a = 0, + b = 0; + for (let i = 1; i < cost.length; ++i) { + [a, b] = [b, Math.min(a + cost[i - 1], b + cost[i])]; + } + return b; +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.cpp" index e76e67863d859..2ecfee368e8fa 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.cpp" @@ -1,12 +1,13 @@ -class Solution { -public: - int rob(vector& nums) { - int f = 0, g = 0; - for (int& x : nums) { - int ff = max(f, g); - g = f + x; - f = ff; - } - return max(f, g); - } +class Solution { +public: + int rob(vector& nums) { + int n = nums.size(); + int f[n + 1]; + memset(f, 0, sizeof(f)); + f[1] = nums[0]; + for (int i = 2; i <= n; ++i) { + f[i] = max(f[i - 1], f[i - 2] + nums[i - 1]); + } + return f[n]; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.go" "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.go" index 35cc30969e50b..52f08ae2d5f14 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.go" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.go" @@ -1,7 +1,9 @@ func rob(nums []int) int { - f, g := 0, 0 - for _, x := range nums { - f, g = max(f, g), f+x + n := len(nums) + f := make([]int, n+1) + f[1] = nums[0] + for i := 2; i <= n; i++ { + f[i] = max(f[i-1], f[i-2]+nums[i-1]) } - return max(f, g) + return f[n] } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.java" index b5ae78ad1e391..e493219c3617c 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.java" @@ -1,11 +1,11 @@ -class Solution { - public int rob(int[] nums) { - int f = 0, g = 0; - for (int x : nums) { - int ff = Math.max(f, g); - g = f + x; - f = ff; - } - return Math.max(f, g); - } +class Solution { + public int rob(int[] nums) { + int n = nums.length; + int[] f = new int[n + 1]; + f[1] = nums[0]; + for (int i = 2; i <= n; ++i) { + f[i] = Math.max(f[i - 1], f[i - 2] + nums[i - 1]); + } + return f[n]; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.py" index 6bba868883e66..c270a36802c3a 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.py" @@ -1,6 +1,8 @@ -class Solution: - def rob(self, nums: List[int]) -> int: - f = g = 0 - for x in nums: - f, g = max(f, g), f + x - return max(f, g) +class Solution: + def rob(self, nums: List[int]) -> int: + n = len(nums) + f = [0] * (n + 1) + f[1] = nums[0] + for i in range(2, n + 1): + f[i] = max(f[i - 1], f[i - 2] + nums[i - 1]) + return f[n] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.ts" index 37f93d27df129..f603cd3876e25 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.ts" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution.ts" @@ -1,7 +1,9 @@ function rob(nums: number[]): number { - let [f, g] = [0, 0]; - for (const x of nums) { - [f, g] = [Math.max(f, g), f + x]; + const n = nums.length; + const f: number[] = Array(n + 1).fill(0); + f[1] = nums[0]; + for (let i = 2; i <= n; ++i) { + f[i] = Math.max(f[i - 1], f[i - 2] + nums[i - 1]); } - return Math.max(f, g); + return f[n]; } diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution2.cpp" new file mode 100644 index 0000000000000..10928ea139406 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution2.cpp" @@ -0,0 +1,12 @@ +class Solution { +public: + int rob(vector& nums) { + int f = 0, g = 0; + for (int& x : nums) { + int ff = max(f, g); + g = f + x; + f = ff; + } + return max(f, g); + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution2.go" new file mode 100644 index 0000000000000..35cc30969e50b --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution2.go" @@ -0,0 +1,7 @@ +func rob(nums []int) int { + f, g := 0, 0 + for _, x := range nums { + f, g = max(f, g), f+x + } + return max(f, g) +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution2.java" new file mode 100644 index 0000000000000..d6491685a06e3 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution2.java" @@ -0,0 +1,11 @@ +class Solution { + public int rob(int[] nums) { + int f = 0, g = 0; + for (int x : nums) { + int ff = Math.max(f, g); + g = f + x; + f = ff; + } + return Math.max(f, g); + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution2.py" new file mode 100644 index 0000000000000..b1afd4af8730f --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution2.py" @@ -0,0 +1,6 @@ +class Solution: + def rob(self, nums: List[int]) -> int: + f = g = 0 + for x in nums: + f, g = max(f, g), f + x + return max(f, g) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution2.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution2.ts" new file mode 100644 index 0000000000000..37f93d27df129 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/Solution2.ts" @@ -0,0 +1,7 @@ +function rob(nums: number[]): number { + let [f, g] = [0, 0]; + for (const x of nums) { + [f, g] = [Math.max(f, g), f + x]; + } + return Math.max(f, g); +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/Solution.cpp" index b69d883e07085..b84dd4418d600 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/Solution.cpp" @@ -1,20 +1,20 @@ -class Solution { -public: - int rob(vector& nums) { - int n = nums.size(); - if (n == 1) { - return nums[0]; - } - return max(robRange(nums, 0, n - 2), robRange(nums, 1, n - 1)); - } - - int robRange(vector& nums, int l, int r) { - int f = 0, g = 0; - for (; l <= r; ++l) { - int ff = max(f, g); - g = f + nums[l]; - f = ff; - } - return max(f, g); - } +class Solution { +public: + int rob(vector& nums) { + int n = nums.size(); + if (n == 1) { + return nums[0]; + } + return max(robRange(nums, 0, n - 2), robRange(nums, 1, n - 1)); + } + + int robRange(vector& nums, int l, int r) { + int f = 0, g = 0; + for (; l <= r; ++l) { + int ff = max(f, g); + g = f + nums[l]; + f = ff; + } + return max(f, g); + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/Solution.java" index 49e0303e1d69c..223d1a667f6d9 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/Solution.java" @@ -1,19 +1,19 @@ -class Solution { - public int rob(int[] nums) { - int n = nums.length; - if (n == 1) { - return nums[0]; - } - return Math.max(rob(nums, 0, n - 2), rob(nums, 1, n - 1)); - } - - private int rob(int[] nums, int l, int r) { - int f = 0, g = 0; - for (; l <= r; ++l) { - int ff = Math.max(f, g); - g = f + nums[l]; - f = ff; - } - return Math.max(f, g); - } +class Solution { + public int rob(int[] nums) { + int n = nums.length; + if (n == 1) { + return nums[0]; + } + return Math.max(rob(nums, 0, n - 2), rob(nums, 1, n - 1)); + } + + private int rob(int[] nums, int l, int r) { + int f = 0, g = 0; + for (; l <= r; ++l) { + int ff = Math.max(f, g); + g = f + nums[l]; + f = ff; + } + return Math.max(f, g); + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/Solution.py" index 866aacd7585f9..844328f427344 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/Solution.py" @@ -1,11 +1,11 @@ -class Solution: - def rob(self, nums: List[int]) -> int: - def _rob(nums): - f = g = 0 - for x in nums: - f, g = max(f, g), f + x - return max(f, g) - - if len(nums) == 1: - return nums[0] - return max(_rob(nums[1:]), _rob(nums[:-1])) +class Solution: + def rob(self, nums: List[int]) -> int: + def _rob(nums): + f = g = 0 + for x in nums: + f, g = max(f, g), f + x + return max(f, g) + + if len(nums) == 1: + return nums[0] + return max(_rob(nums[1:]), _rob(nums[:-1])) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 091. \347\262\211\345\210\267\346\210\277\345\255\220/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 091. \347\262\211\345\210\267\346\210\277\345\255\220/Solution.cpp" index 6fe98738d9949..3044d747236a6 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 091. \347\262\211\345\210\267\346\210\277\345\255\220/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 091. \347\262\211\345\210\267\346\210\277\345\255\220/Solution.cpp" @@ -10,4 +10,4 @@ class Solution { } return min(r, min(g, b)); } -}; +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 091. \347\262\211\345\210\267\346\210\277\345\255\220/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 091. \347\262\211\345\210\267\346\210\277\345\255\220/Solution.java" index ae3818897c538..880acb4df9fea 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 091. \347\262\211\345\210\267\346\210\277\345\255\220/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 091. \347\262\211\345\210\267\346\210\277\345\255\220/Solution.java" @@ -9,4 +9,4 @@ public int minCost(int[][] costs) { } return Math.min(r, Math.min(g, b)); } -} +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 092. \347\277\273\350\275\254\345\255\227\347\254\246/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 092. \347\277\273\350\275\254\345\255\227\347\254\246/Solution.cpp" index f0c24041edf6f..3328006df278c 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 092. \347\277\273\350\275\254\345\255\227\347\254\246/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 092. \347\277\273\350\275\254\345\255\227\347\254\246/Solution.cpp" @@ -1,18 +1,18 @@ -class Solution { -public: - int minFlipsMonoIncr(string s) { - int n = s.size(); - int left0 = 0, right0 = 0; - for (char& c : s) { - right0 += c == '0'; - } - int ans = min(right0, n - right0); - for (int i = 1; i <= n; ++i) { - int x = s[i - 1] == '1'; - right0 -= x ^ 1; - left0 += x ^ 1; - ans = min(ans, i - left0 + right0); - } - return ans; - } +class Solution { +public: + int minFlipsMonoIncr(string s) { + int n = s.size(); + int left0 = 0, right0 = 0; + for (char& c : s) { + right0 += c == '0'; + } + int ans = min(right0, n - right0); + for (int i = 1; i <= n; ++i) { + int x = s[i - 1] == '1'; + right0 -= x ^ 1; + left0 += x ^ 1; + ans = min(ans, i - left0 + right0); + } + return ans; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 092. \347\277\273\350\275\254\345\255\227\347\254\246/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 092. \347\277\273\350\275\254\345\255\227\347\254\246/Solution.java" index 73c7afa8d9fbd..f01845dd1f7b5 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 092. \347\277\273\350\275\254\345\255\227\347\254\246/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 092. \347\277\273\350\275\254\345\255\227\347\254\246/Solution.java" @@ -1,19 +1,19 @@ -class Solution { - public int minFlipsMonoIncr(String s) { - int n = s.length(); - int left0 = 0, right0 = 0; - for (int i = 0; i < n; ++i) { - if (s.charAt(i) == '0') { - ++right0; - } - } - int ans = Math.min(right0, n - right0); - for (int i = 1; i <= n; ++i) { - int x = s.charAt(i - 1) == '0' ? 0 : 1; - right0 -= x ^ 1; - left0 += x ^ 1; - ans = Math.min(ans, i - left0 + right0); - } - return ans; - } +class Solution { + public int minFlipsMonoIncr(String s) { + int n = s.length(); + int left0 = 0, right0 = 0; + for (int i = 0; i < n; ++i) { + if (s.charAt(i) == '0') { + ++right0; + } + } + int ans = Math.min(right0, n - right0); + for (int i = 1; i <= n; ++i) { + int x = s.charAt(i - 1) == '0' ? 0 : 1; + right0 -= x ^ 1; + left0 += x ^ 1; + ans = Math.min(ans, i - left0 + right0); + } + return ans; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 092. \347\277\273\350\275\254\345\255\227\347\254\246/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 092. \347\277\273\350\275\254\345\255\227\347\254\246/Solution.py" index bca2e75f97a36..30c9bfbb71f3d 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 092. \347\277\273\350\275\254\345\255\227\347\254\246/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 092. \347\277\273\350\275\254\345\255\227\347\254\246/Solution.py" @@ -1,11 +1,11 @@ -class Solution: - def minFlipsMonoIncr(self, s: str) -> int: - left0, right0 = 0, s.count("0") - n = len(s) - ans = min(right0, n - right0) - for i, c in enumerate(s, 1): - x = int(c) - right0 -= x ^ 1 - left0 += x ^ 1 - ans = min(ans, i - left0 + right0) - return ans +class Solution: + def minFlipsMonoIncr(self, s: str) -> int: + left0, right0 = 0, s.count("0") + n = len(s) + ans = min(right0, n - right0) + for i, c in enumerate(s, 1): + x = int(c) + right0 -= x ^ 1 + left0 += x ^ 1 + ans = min(ans, i - left0 + right0) + return ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/Solution.cpp" index 5a23e3990b687..05402be952676 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/Solution.cpp" @@ -1,23 +1,23 @@ -class Solution { -public: - int minCut(string s) { - int n = s.size(); - bool g[n][n]; - memset(g, true, sizeof(g)); - for (int i = n - 1; ~i; --i) { - for (int j = i + 1; j < n; ++j) { - g[i][j] = s[i] == s[j] && g[i + 1][j - 1]; - } - } - int f[n]; - iota(f, f + n, 0); - for (int i = 1; i < n; ++i) { - for (int j = 0; j <= i; ++j) { - if (g[j][i]) { - f[i] = min(f[i], j ? 1 + f[j - 1] : 0); - } - } - } - return f[n - 1]; - } -}; +class Solution { +public: + int minCut(string s) { + int n = s.size(); + bool g[n][n]; + memset(g, true, sizeof(g)); + for (int i = n - 1; ~i; --i) { + for (int j = i + 1; j < n; ++j) { + g[i][j] = s[i] == s[j] && g[i + 1][j - 1]; + } + } + int f[n]; + iota(f, f + n, 0); + for (int i = 1; i < n; ++i) { + for (int j = 0; j <= i; ++j) { + if (g[j][i]) { + f[i] = min(f[i], j ? 1 + f[j - 1] : 0); + } + } + } + return f[n - 1]; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/Solution.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/Solution.cs" index 6a3e6be7ba41d..0c582524df1c3 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/Solution.cs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/Solution.cs" @@ -1,26 +1,26 @@ -public class Solution { - public int MinCut(string s) { - int n = s.Length; - bool[,] g = new bool[n,n]; - int[] f = new int[n]; - for (int i = 0; i < n; ++i) { - f[i] = i; - for (int j = 0; j < n; ++j) { - g[i,j] = true; - } - } - for (int i = n - 1; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - g[i,j] = s[i] == s[j] && g[i + 1,j - 1]; - } - } - for (int i = 1; i < n; ++i) { - for (int j = 0; j <= i; ++j) { - if (g[j,i]) { - f[i] = Math.Min(f[i], j > 0 ? 1 + f[j - 1] : 0); - } - } - } - return f[n - 1]; - } -} \ No newline at end of file +public class Solution { + public int MinCut(string s) { + int n = s.Length; + bool[,] g = new bool[n,n]; + int[] f = new int[n]; + for (int i = 0; i < n; ++i) { + f[i] = i; + for (int j = 0; j < n; ++j) { + g[i,j] = true; + } + } + for (int i = n - 1; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + g[i,j] = s[i] == s[j] && g[i + 1,j - 1]; + } + } + for (int i = 1; i < n; ++i) { + for (int j = 0; j <= i; ++j) { + if (g[j,i]) { + f[i] = Math.Min(f[i], j > 0 ? 1 + f[j - 1] : 0); + } + } + } + return f[n - 1]; + } +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/Solution.java" index 6bb02d8a2b459..b424efd8d65e2 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/Solution.java" @@ -1,26 +1,26 @@ -class Solution { - public int minCut(String s) { - int n = s.length(); - boolean[][] g = new boolean[n][n]; - for (var row : g) { - Arrays.fill(row, true); - } - for (int i = n - 1; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - g[i][j] = s.charAt(i) == s.charAt(j) && g[i + 1][j - 1]; - } - } - int[] f = new int[n]; - for (int i = 0; i < n; ++i) { - f[i] = i; - } - for (int i = 1; i < n; ++i) { - for (int j = 0; j <= i; ++j) { - if (g[j][i]) { - f[i] = Math.min(f[i], j > 0 ? 1 + f[j - 1] : 0); - } - } - } - return f[n - 1]; - } +class Solution { + public int minCut(String s) { + int n = s.length(); + boolean[][] g = new boolean[n][n]; + for (var row : g) { + Arrays.fill(row, true); + } + for (int i = n - 1; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + g[i][j] = s.charAt(i) == s.charAt(j) && g[i + 1][j - 1]; + } + } + int[] f = new int[n]; + for (int i = 0; i < n; ++i) { + f[i] = i; + } + for (int i = 1; i < n; ++i) { + for (int j = 0; j <= i; ++j) { + if (g[j][i]) { + f[i] = Math.min(f[i], j > 0 ? 1 + f[j - 1] : 0); + } + } + } + return f[n - 1]; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/Solution.py" index d2a7b44ffc9a0..39e56e61a23ee 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/Solution.py" @@ -1,13 +1,13 @@ -class Solution: - def minCut(self, s: str) -> int: - n = len(s) - g = [[True] * n for _ in range(n)] - for i in range(n - 1, -1, -1): - for j in range(i + 1, n): - g[i][j] = s[i] == s[j] and g[i + 1][j - 1] - f = list(range(n)) - for i in range(1, n): - for j in range(i + 1): - if g[j][i]: - f[i] = min(f[i], 1 + f[j - 1] if j else 0) - return f[-1] +class Solution: + def minCut(self, s: str) -> int: + n = len(s) + g = [[True] * n for _ in range(n)] + for i in range(n - 1, -1, -1): + for j in range(i + 1, n): + g[i][j] = s[i] == s[j] and g[i + 1][j - 1] + f = list(range(n)) + for i in range(1, n): + for j in range(i + 1): + if g[j][i]: + f[i] = min(f[i], 1 + f[j - 1] if j else 0) + return f[-1] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/Solution.cpp" index d8f3f6ea6ae64..7ee880763966d 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/Solution.cpp" @@ -1,17 +1,17 @@ -class Solution { -public: - int longestCommonSubsequence(string text1, string text2) { - int m = text1.size(), n = text2.size(); - vector> f(m + 1, vector(n + 1)); - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (text1[i - 1] == text2[j - 1]) { - f[i][j] = f[i - 1][j - 1] + 1; - } else { - f[i][j] = max(f[i - 1][j], f[i][j - 1]); - } - } - } - return f[m][n]; - } +class Solution { +public: + int longestCommonSubsequence(string text1, string text2) { + int m = text1.size(), n = text2.size(); + vector> f(m + 1, vector(n + 1)); + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (text1[i - 1] == text2[j - 1]) { + f[i][j] = f[i - 1][j - 1] + 1; + } else { + f[i][j] = max(f[i - 1][j], f[i][j - 1]); + } + } + } + return f[m][n]; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/Solution.java" index 546da2e4ae51a..320fe2c7b316e 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/Solution.java" @@ -1,16 +1,16 @@ -class Solution { - public int longestCommonSubsequence(String text1, String text2) { - int m = text1.length(), n = text2.length(); - int[][] f = new int[m + 1][n + 1]; - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (text1.charAt(i - 1) == text2.charAt(j - 1)) { - f[i][j] = f[i - 1][j - 1] + 1; - } else { - f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]); - } - } - } - return f[m][n]; - } +class Solution { + public int longestCommonSubsequence(String text1, String text2) { + int m = text1.length(), n = text2.length(); + int[][] f = new int[m + 1][n + 1]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (text1.charAt(i - 1) == text2.charAt(j - 1)) { + f[i][j] = f[i - 1][j - 1] + 1; + } else { + f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]); + } + } + } + return f[m][n]; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/Solution.py" index f5bc75c36c893..b35b70dfdeedd 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/Solution.py" @@ -1,11 +1,11 @@ -class Solution: - def longestCommonSubsequence(self, text1: str, text2: str) -> int: - m, n = len(text1), len(text2) - f = [[0] * (n + 1) for _ in range(m + 1)] - for i in range(1, m + 1): - for j in range(1, n + 1): - if text1[i - 1] == text2[j - 1]: - f[i][j] = f[i - 1][j - 1] + 1 - else: - f[i][j] = max(f[i - 1][j], f[i][j - 1]) - return f[-1][-1] +class Solution: + def longestCommonSubsequence(self, text1: str, text2: str) -> int: + m, n = len(text1), len(text2) + f = [[0] * (n + 1) for _ in range(m + 1)] + for i in range(1, m + 1): + for j in range(1, n + 1): + if text1[i - 1] == text2[j - 1]: + f[i][j] = f[i - 1][j - 1] + 1 + else: + f[i][j] = max(f[i - 1][j], f[i][j - 1]) + return f[-1][-1] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.cpp" index 352af91c98b82..8847e9660235c 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.cpp" @@ -5,20 +5,24 @@ class Solution { if (m + n != s3.size()) { return false; } - bool f[n + 1]; - memset(f, false, sizeof(f)); - f[0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - int k = i + j - 1; - if (i) { - f[j] &= s1[i - 1] == s3[k]; - } - if (j) { - f[j] |= (s2[j - 1] == s3[k] && f[j - 1]); - } + vector> f(m + 1, vector(n + 1, -1)); + function dfs = [&](int i, int j) { + if (i >= m && j >= n) { + return true; } - } - return f[n]; + if (f[i][j] != -1) { + return f[i][j] == 1; + } + f[i][j] = 0; + int k = i + j; + if (i < m && s1[i] == s3[k] && dfs(i + 1, j)) { + f[i][j] = 1; + } + if (!f[i][j] && j < n && s2[j] == s3[k] && dfs(i, j + 1)) { + f[i][j] = 1; + } + return f[i][j] == 1; + }; + return dfs(0, 0); } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.cs" index b930965b32f7d..32a77cdd6bbf4 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.cs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.cs" @@ -1,22 +1,38 @@ public class Solution { + private int m; + private int n; + private string s1; + private string s2; + private string s3; + private int[,] f; + public bool IsInterleave(string s1, string s2, string s3) { - int m = s1.Length, n = s2.Length; + m = s1.Length; + n = s2.Length; if (m + n != s3.Length) { return false; } - bool[] f = new bool[n + 1]; - f[0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - int k = i + j - 1; - if (i > 0) { - f[j] &= s1[i - 1] == s3[k]; - } - if (j > 0) { - f[j] |= (f[j - 1] & s2[j - 1] == s3[k]); - } - } + this.s1 = s1; + this.s2 = s2; + this.s3 = s3; + f = new int[m + 1, n + 1]; + return dfs(0, 0); + } + + private bool dfs(int i, int j) { + if (i >= m && j >= n) { + return true; + } + if (f[i, j] != 0) { + return f[i, j] == 1; + } + f[i, j] = -1; + if (i < m && s1[i] == s3[i + j] && dfs(i + 1, j)) { + f[i, j] = 1; + } + if (f[i, j] == -1 && j < n && s2[j] == s3[i + j] && dfs(i, j + 1)) { + f[i, j] = 1; } - return f[n]; + return f[i, j] == 1; } -} \ No newline at end of file +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.go" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.go" index 6edbffd1c3cbf..a244bee4934da 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.go" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.go" @@ -3,18 +3,19 @@ func isInterleave(s1 string, s2 string, s3 string) bool { if m+n != len(s3) { return false } - f := make([]bool, n+1) - f[0] = true - for i := 0; i <= m; i++ { - for j := 0; j <= n; j++ { - k := i + j - 1 - if i > 0 { - f[j] = (f[j] && s1[i-1] == s3[k]) - } - if j > 0 { - f[j] = (f[j] || (s2[j-1] == s3[k] && f[j-1])) - } + + f := map[int]bool{} + var dfs func(int, int) bool + dfs = func(i, j int) bool { + if i >= m && j >= n { + return true } + if v, ok := f[i*200+j]; ok { + return v + } + k := i + j + f[i*200+j] = (i < m && s1[i] == s3[k] && dfs(i+1, j)) || (j < n && s2[j] == s3[k] && dfs(i, j+1)) + return f[i*200+j] } - return f[n] + return dfs(0, 0) } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.java" index f60c0122b4e95..f831ee066ef61 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.java" @@ -1,22 +1,40 @@ class Solution { + private Map, Boolean> f = new HashMap<>(); + private String s1; + private String s2; + private String s3; + private int m; + private int n; + public boolean isInterleave(String s1, String s2, String s3) { - int m = s1.length(), n = s2.length(); + m = s1.length(); + n = s2.length(); if (m + n != s3.length()) { return false; } - boolean[] f = new boolean[n + 1]; - f[0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - int k = i + j - 1; - if (i > 0) { - f[j] &= s1.charAt(i - 1) == s3.charAt(k); - } - if (j > 0) { - f[j] |= (f[j - 1] & s2.charAt(j - 1) == s3.charAt(k)); - } - } + this.s1 = s1; + this.s2 = s2; + this.s3 = s3; + return dfs(0, 0); + } + + private boolean dfs(int i, int j) { + if (i >= m && j >= n) { + return true; + } + var key = List.of(i, j); + if (f.containsKey(key)) { + return f.get(key); + } + int k = i + j; + boolean ans = false; + if (i < m && s1.charAt(i) == s3.charAt(k) && dfs(i + 1, j)) { + ans = true; + } + if (!ans && j < n && s2.charAt(j) == s3.charAt(k) && dfs(i, j + 1)) { + ans = true; } - return f[n]; + f.put(key, ans); + return ans; } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.py" index 1f17ed5709878..b79604f1ea770 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.py" @@ -1,14 +1,17 @@ class Solution: def isInterleave(self, s1: str, s2: str, s3: str) -> bool: + @cache + def dfs(i: int, j: int) -> bool: + if i >= m and j >= n: + return True + k = i + j + if i < m and s1[i] == s3[k] and dfs(i + 1, j): + return True + if j < n and s2[j] == s3[k] and dfs(i, j + 1): + return True + return False + m, n = len(s1), len(s2) if m + n != len(s3): return False - f = [True] + [False] * n - for i in range(m + 1): - for j in range(n + 1): - k = i + j - 1 - if i: - f[j] &= s1[i - 1] == s3[k] - if j: - f[j] |= f[j - 1] and s2[j - 1] == s3[k] - return f[n] + return dfs(0, 0) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.ts" index 04b168eedfda8..3469ba561a219 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.ts" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution.ts" @@ -4,18 +4,22 @@ function isInterleave(s1: string, s2: string, s3: string): boolean { if (m + n !== s3.length) { return false; } - const f: boolean[] = new Array(n + 1).fill(false); - f[0] = true; - for (let i = 0; i <= m; ++i) { - for (let j = 0; j <= n; ++j) { - const k = i + j - 1; - if (i) { - f[j] = f[j] && s1[i - 1] === s3[k]; - } - if (j) { - f[j] = f[j] || (f[j - 1] && s2[j - 1] === s3[k]); - } + const f: number[][] = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); + const dfs = (i: number, j: number): boolean => { + if (i >= m && j >= n) { + return true; } - } - return f[n]; + if (f[i][j]) { + return f[i][j] === 1; + } + f[i][j] = -1; + if (i < m && s1[i] === s3[i + j] && dfs(i + 1, j)) { + f[i][j] = 1; + } + if (f[i][j] === -1 && j < n && s2[j] === s3[i + j] && dfs(i, j + 1)) { + f[i][j] = 1; + } + return f[i][j] === 1; + }; + return dfs(0, 0); } diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution2.cpp" new file mode 100644 index 0000000000000..a88428e3b1f3d --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution2.cpp" @@ -0,0 +1,24 @@ +class Solution { +public: + bool isInterleave(string s1, string s2, string s3) { + int m = s1.size(), n = s2.size(); + if (m + n != s3.size()) { + return false; + } + bool f[m + 1][n + 1]; + memset(f, false, sizeof(f)); + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0 && s1[i - 1] == s3[k]) { + f[i][j] = f[i - 1][j]; + } + if (j > 0 && s2[j - 1] == s3[k]) { + f[i][j] |= f[i][j - 1]; + } + } + } + return f[m][n]; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution2.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution2.cs" new file mode 100644 index 0000000000000..04ab33e811624 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution2.cs" @@ -0,0 +1,22 @@ +public class Solution { + public bool IsInterleave(string s1, string s2, string s3) { + int m = s1.Length, n = s2.Length; + if (m + n != s3.Length) { + return false; + } + bool[,] f = new bool[m + 1, n + 1]; + f[0, 0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0 && s1[i - 1] == s3[k]) { + f[i, j] = f[i - 1, j]; + } + if (j > 0 && s2[j - 1] == s3[k]) { + f[i, j] |= f[i, j - 1]; + } + } + } + return f[m, n]; + } +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution2.go" new file mode 100644 index 0000000000000..183596d1ba535 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution2.go" @@ -0,0 +1,23 @@ +func isInterleave(s1 string, s2 string, s3 string) bool { + m, n := len(s1), len(s2) + if m+n != len(s3) { + return false + } + f := make([][]bool, m+1) + for i := range f { + f[i] = make([]bool, n+1) + } + f[0][0] = true + for i := 0; i <= m; i++ { + for j := 0; j <= n; j++ { + k := i + j - 1 + if i > 0 && s1[i-1] == s3[k] { + f[i][j] = f[i-1][j] + } + if j > 0 && s2[j-1] == s3[k] { + f[i][j] = (f[i][j] || f[i][j-1]) + } + } + } + return f[m][n] +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution2.java" new file mode 100644 index 0000000000000..5808f488cfaab --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution2.java" @@ -0,0 +1,22 @@ +class Solution { + public boolean isInterleave(String s1, String s2, String s3) { + int m = s1.length(), n = s2.length(); + if (m + n != s3.length()) { + return false; + } + boolean[][] f = new boolean[m + 1][n + 1]; + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0 && s1.charAt(i - 1) == s3.charAt(k)) { + f[i][j] = f[i - 1][j]; + } + if (j > 0 && s2.charAt(j - 1) == s3.charAt(k)) { + f[i][j] |= f[i][j - 1]; + } + } + } + return f[m][n]; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution2.py" new file mode 100644 index 0000000000000..8e164d25cb14f --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution2.py" @@ -0,0 +1,15 @@ +class Solution: + def isInterleave(self, s1: str, s2: str, s3: str) -> bool: + m, n = len(s1), len(s2) + if m + n != len(s3): + return False + f = [[False] * (n + 1) for _ in range(m + 1)] + f[0][0] = True + for i in range(m + 1): + for j in range(n + 1): + k = i + j - 1 + if i and s1[i - 1] == s3[k]: + f[i][j] = f[i - 1][j] + if j and s2[j - 1] == s3[k]: + f[i][j] |= f[i][j - 1] + return f[m][n] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution2.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution2.ts" new file mode 100644 index 0000000000000..5c1cb78bf8ec1 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution2.ts" @@ -0,0 +1,21 @@ +function isInterleave(s1: string, s2: string, s3: string): boolean { + const m = s1.length; + const n = s2.length; + if (m + n !== s3.length) { + return false; + } + const f: boolean[][] = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(false)); + f[0][0] = true; + for (let i = 0; i <= m; ++i) { + for (let j = 0; j <= n; ++j) { + const k = i + j - 1; + if (i > 0 && s1[i - 1] === s3[k]) { + f[i][j] = f[i - 1][j]; + } + if (j > 0 && s2[j - 1] === s3[k]) { + f[i][j] = f[i][j] || f[i][j - 1]; + } + } + } + return f[m][n]; +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution3.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution3.cpp" new file mode 100644 index 0000000000000..352af91c98b82 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution3.cpp" @@ -0,0 +1,24 @@ +class Solution { +public: + bool isInterleave(string s1, string s2, string s3) { + int m = s1.size(), n = s2.size(); + if (m + n != s3.size()) { + return false; + } + bool f[n + 1]; + memset(f, false, sizeof(f)); + f[0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i) { + f[j] &= s1[i - 1] == s3[k]; + } + if (j) { + f[j] |= (s2[j - 1] == s3[k] && f[j - 1]); + } + } + } + return f[n]; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution3.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution3.cs" new file mode 100644 index 0000000000000..1dba3cca4cdce --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution3.cs" @@ -0,0 +1,22 @@ +public class Solution { + public bool IsInterleave(string s1, string s2, string s3) { + int m = s1.Length, n = s2.Length; + if (m + n != s3.Length) { + return false; + } + bool[] f = new bool[n + 1]; + f[0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0) { + f[j] &= s1[i - 1] == s3[k]; + } + if (j > 0) { + f[j] |= (f[j - 1] & s2[j - 1] == s3[k]); + } + } + } + return f[n]; + } +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution3.go" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution3.go" new file mode 100644 index 0000000000000..6edbffd1c3cbf --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution3.go" @@ -0,0 +1,20 @@ +func isInterleave(s1 string, s2 string, s3 string) bool { + m, n := len(s1), len(s2) + if m+n != len(s3) { + return false + } + f := make([]bool, n+1) + f[0] = true + for i := 0; i <= m; i++ { + for j := 0; j <= n; j++ { + k := i + j - 1 + if i > 0 { + f[j] = (f[j] && s1[i-1] == s3[k]) + } + if j > 0 { + f[j] = (f[j] || (s2[j-1] == s3[k] && f[j-1])) + } + } + } + return f[n] +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution3.java" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution3.java" new file mode 100644 index 0000000000000..f60c0122b4e95 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution3.java" @@ -0,0 +1,22 @@ +class Solution { + public boolean isInterleave(String s1, String s2, String s3) { + int m = s1.length(), n = s2.length(); + if (m + n != s3.length()) { + return false; + } + boolean[] f = new boolean[n + 1]; + f[0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0) { + f[j] &= s1.charAt(i - 1) == s3.charAt(k); + } + if (j > 0) { + f[j] |= (f[j - 1] & s2.charAt(j - 1) == s3.charAt(k)); + } + } + } + return f[n]; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution3.py" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution3.py" new file mode 100644 index 0000000000000..1f17ed5709878 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution3.py" @@ -0,0 +1,14 @@ +class Solution: + def isInterleave(self, s1: str, s2: str, s3: str) -> bool: + m, n = len(s1), len(s2) + if m + n != len(s3): + return False + f = [True] + [False] * n + for i in range(m + 1): + for j in range(n + 1): + k = i + j - 1 + if i: + f[j] &= s1[i - 1] == s3[k] + if j: + f[j] |= f[j - 1] and s2[j - 1] == s3[k] + return f[n] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution3.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution3.ts" new file mode 100644 index 0000000000000..04b168eedfda8 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/Solution3.ts" @@ -0,0 +1,21 @@ +function isInterleave(s1: string, s2: string, s3: string): boolean { + const m = s1.length; + const n = s2.length; + if (m + n !== s3.length) { + return false; + } + const f: boolean[] = new Array(n + 1).fill(false); + f[0] = true; + for (let i = 0; i <= m; ++i) { + for (let j = 0; j <= n; ++j) { + const k = i + j - 1; + if (i) { + f[j] = f[j] && s1[i - 1] === s3[k]; + } + if (j) { + f[j] = f[j] || (f[j - 1] && s2[j - 1] === s3[k]); + } + } + } + return f[n]; +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.cpp" index eff3166f6e6e6..06a52cbcc8c5e 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.cpp" @@ -1,18 +1,20 @@ -class Solution { -public: - int numDistinct(string s, string t) { - int n = t.size(); - unsigned long long f[n + 1]; - memset(f, 0, sizeof(f)); - f[0] = 1; - for (char& a : s) { - for (int j = n; j; --j) { - char b = t[j - 1]; - if (a == b) { - f[j] += f[j - 1]; - } - } - } - return f[n]; - } +class Solution { +public: + int numDistinct(string s, string t) { + int m = s.size(), n = t.size(); + unsigned long long f[m + 1][n + 1]; + memset(f, 0, sizeof(f)); + for (int i = 0; i < m + 1; ++i) { + f[i][0] = 1; + } + for (int i = 1; i < m + 1; ++i) { + for (int j = 1; j < n + 1; ++j) { + f[i][j] = f[i - 1][j]; + if (s[i - 1] == t[j - 1]) { + f[i][j] += f[i - 1][j - 1]; + } + } + } + return f[m][n]; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.go" "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.go" index 3b1eed97f2db4..47af7378388af 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.go" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.go" @@ -1,13 +1,19 @@ func numDistinct(s string, t string) int { - n := len(t) - f := make([]int, n+1) - f[0] = 1 - for _, a := range s { - for j := n; j > 0; j-- { - if b := t[j-1]; byte(a) == b { - f[j] += f[j-1] + m, n := len(s), len(t) + f := make([][]int, m+1) + for i := range f { + f[i] = make([]int, n+1) + } + for i := 0; i <= m; i++ { + f[i][0] = 1 + } + for i := 1; i <= m; i++ { + for j := 1; j <= n; j++ { + f[i][j] = f[i-1][j] + if s[i-1] == t[j-1] { + f[i][j] += f[i-1][j-1] } } } - return f[n] + return f[m][n] } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.java" index 0c90de4f2d637..7f169917fc1dd 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.java" @@ -1,16 +1,18 @@ -class Solution { - public int numDistinct(String s, String t) { - int n = t.length(); - int[] f = new int[n + 1]; - f[0] = 1; - for (char a : s.toCharArray()) { - for (int j = n; j > 0; --j) { - char b = t.charAt(j - 1); - if (a == b) { - f[j] += f[j - 1]; - } - } - } - return f[n]; - } +class Solution { + public int numDistinct(String s, String t) { + int m = s.length(), n = t.length(); + int[][] f = new int[m + 1][n + 1]; + for (int i = 0; i < m + 1; ++i) { + f[i][0] = 1; + } + for (int i = 1; i < m + 1; ++i) { + for (int j = 1; j < n + 1; ++j) { + f[i][j] = f[i - 1][j]; + if (s.charAt(i - 1) == t.charAt(j - 1)) { + f[i][j] += f[i - 1][j - 1]; + } + } + } + return f[m][n]; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.py" index 9e7e02af1363e..e569169624c83 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.py" @@ -1,9 +1,12 @@ -class Solution: - def numDistinct(self, s: str, t: str) -> int: - n = len(t) - f = [1] + [0] * n - for a in s: - for j in range(n, 0, -1): - if a == t[j - 1]: - f[j] += f[j - 1] - return f[n] +class Solution: + def numDistinct(self, s: str, t: str) -> int: + m, n = len(s), len(t) + f = [[0] * (n + 1) for _ in range(m + 1)] + for i in range(m + 1): + f[i][0] = 1 + for i, a in enumerate(s, 1): + for j, b in enumerate(t, 1): + f[i][j] = f[i - 1][j] + if a == b: + f[i][j] += f[i - 1][j - 1] + return f[m][n] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.ts" index f254f30e9f3f8..792189f8e6954 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.ts" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution.ts" @@ -1,14 +1,17 @@ function numDistinct(s: string, t: string): number { + const m = s.length; const n = t.length; - const f: number[] = new Array(n + 1).fill(0); - f[0] = 1; - for (const a of s) { - for (let j = n; j; --j) { - const b = t[j - 1]; - if (a === b) { - f[j] += f[j - 1]; + const f: number[][] = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); + for (let i = 0; i <= m; ++i) { + f[i][0] = 1; + } + for (let i = 1; i <= m; ++i) { + for (let j = 1; j <= n; ++j) { + f[i][j] = f[i - 1][j]; + if (s[i - 1] === t[j - 1]) { + f[i][j] += f[i - 1][j - 1]; } } } - return f[n]; + return f[m][n]; } diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution2.cpp" new file mode 100644 index 0000000000000..30d8d498fcb96 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution2.cpp" @@ -0,0 +1,18 @@ +class Solution { +public: + int numDistinct(string s, string t) { + int n = t.size(); + unsigned long long f[n + 1]; + memset(f, 0, sizeof(f)); + f[0] = 1; + for (char& a : s) { + for (int j = n; j; --j) { + char b = t[j - 1]; + if (a == b) { + f[j] += f[j - 1]; + } + } + } + return f[n]; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution2.go" new file mode 100644 index 0000000000000..3b1eed97f2db4 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution2.go" @@ -0,0 +1,13 @@ +func numDistinct(s string, t string) int { + n := len(t) + f := make([]int, n+1) + f[0] = 1 + for _, a := range s { + for j := n; j > 0; j-- { + if b := t[j-1]; byte(a) == b { + f[j] += f[j-1] + } + } + } + return f[n] +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution2.java" new file mode 100644 index 0000000000000..c8d2d4c51c681 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution2.java" @@ -0,0 +1,16 @@ +class Solution { + public int numDistinct(String s, String t) { + int n = t.length(); + int[] f = new int[n + 1]; + f[0] = 1; + for (char a : s.toCharArray()) { + for (int j = n; j > 0; --j) { + char b = t.charAt(j - 1); + if (a == b) { + f[j] += f[j - 1]; + } + } + } + return f[n]; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution2.py" new file mode 100644 index 0000000000000..b6dad9021840e --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution2.py" @@ -0,0 +1,9 @@ +class Solution: + def numDistinct(self, s: str, t: str) -> int: + n = len(t) + f = [1] + [0] * n + for a in s: + for j in range(n, 0, -1): + if a == t[j - 1]: + f[j] += f[j - 1] + return f[n] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution2.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution2.ts" new file mode 100644 index 0000000000000..f254f30e9f3f8 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/Solution2.ts" @@ -0,0 +1,14 @@ +function numDistinct(s: string, t: string): number { + const n = t.length; + const f: number[] = new Array(n + 1).fill(0); + f[0] = 1; + for (const a of s) { + for (let j = n; j; --j) { + const b = t[j - 1]; + if (a === b) { + f[j] += f[j - 1]; + } + } + } + return f[n]; +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.cpp" index 44adfd0b04fac..97ab7c9f30376 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.cpp" @@ -1,12 +1,18 @@ -class Solution { -public: - int uniquePaths(int m, int n) { - vector f(n, 1); - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - f[j] += f[j - 1]; - } - } - return f[n - 1]; - } +class Solution { +public: + int uniquePaths(int m, int n) { + vector> f(m, vector(n)); + f[0][0] = 1; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (i) { + f[i][j] += f[i - 1][j]; + } + if (j) { + f[i][j] += f[i][j - 1]; + } + } + } + return f[m - 1][n - 1]; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.go" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.go" index d8be9bf206fba..a24ae81946451 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.go" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.go" @@ -1,12 +1,18 @@ func uniquePaths(m int, n int) int { - f := make([]int, n+1) + f := make([][]int, m) for i := range f { - f[i] = 1 + f[i] = make([]int, n) } - for i := 1; i < m; i++ { - for j := 1; j < n; j++ { - f[j] += f[j-1] + f[0][0] = 1 + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if i > 0 { + f[i][j] += f[i-1][j] + } + if j > 0 { + f[i][j] += f[i][j-1] + } } } - return f[n-1] + return f[m-1][n-1] } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.java" index 8200544e6b54a..e498a681dedd7 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.java" @@ -1,12 +1,17 @@ -class Solution { - public int uniquePaths(int m, int n) { - int[] f = new int[n]; - Arrays.fill(f, 1); - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - f[j] += f[j - 1]; - } - } - return f[n - 1]; - } +class Solution { + public int uniquePaths(int m, int n) { + var f = new int[m][n]; + f[0][0] = 1; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (i > 0) { + f[i][j] += f[i - 1][j]; + } + if (j > 0) { + f[i][j] += f[i][j - 1]; + } + } + } + return f[m - 1][n - 1]; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.js" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.js" index 8853e8f24afc5..12576e257380a 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.js" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.js" @@ -4,11 +4,19 @@ * @return {number} */ var uniquePaths = function (m, n) { - const f = Array(n).fill(1); - for (let i = 1; i < m; ++i) { - for (let j = 1; j < n; ++j) { - f[j] += f[j - 1]; + const f = Array(m) + .fill(0) + .map(() => Array(n).fill(0)); + f[0][0] = 1; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (i > 0) { + f[i][j] += f[i - 1][j]; + } + if (j > 0) { + f[i][j] += f[i][j - 1]; + } } } - return f[n - 1]; + return f[m - 1][n - 1]; }; diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.py" index 125d910221d98..cbeed6832f606 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.py" @@ -1,7 +1,11 @@ -class Solution: - def uniquePaths(self, m: int, n: int) -> int: - f = [1] * n - for _ in range(1, m): - for j in range(1, n): - f[j] += f[j - 1] - return f[-1] +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + f = [[0] * n for _ in range(m)] + f[0][0] = 1 + for i in range(m): + for j in range(n): + if i: + f[i][j] += f[i - 1][j] + if j: + f[i][j] += f[i][j - 1] + return f[-1][-1] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.ts" index 6dae713f485bd..4b55fcf8dcddf 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.ts" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution.ts" @@ -1,9 +1,17 @@ function uniquePaths(m: number, n: number): number { - const f: number[] = Array(n).fill(1); - for (let i = 1; i < m; ++i) { - for (let j = 1; j < n; ++j) { - f[j] += f[j - 1]; + const f: number[][] = Array(m) + .fill(0) + .map(() => Array(n).fill(0)); + f[0][0] = 1; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (i > 0) { + f[i][j] += f[i - 1][j]; + } + if (j > 0) { + f[i][j] += f[i][j - 1]; + } } } - return f[n - 1]; + return f[m - 1][n - 1]; } diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution2.cpp" new file mode 100644 index 0000000000000..2c8161b2ac5f2 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution2.cpp" @@ -0,0 +1,12 @@ +class Solution { +public: + int uniquePaths(int m, int n) { + vector> f(m, vector(n, 1)); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + f[i][j] = f[i - 1][j] + f[i][j - 1]; + } + } + return f[m - 1][n - 1]; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution2.go" new file mode 100644 index 0000000000000..62eb31203dfa4 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution2.go" @@ -0,0 +1,15 @@ +func uniquePaths(m int, n int) int { + f := make([][]int, m) + for i := range f { + f[i] = make([]int, n) + for j := range f[i] { + f[i][j] = 1 + } + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + f[i][j] = f[i-1][j] + f[i][j-1] + } + } + return f[m-1][n-1] +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution2.java" new file mode 100644 index 0000000000000..1d5c65794d8e1 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution2.java" @@ -0,0 +1,14 @@ +class Solution { + public int uniquePaths(int m, int n) { + var f = new int[m][n]; + for (var g : f) { + Arrays.fill(g, 1); + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; j++) { + f[i][j] = f[i - 1][j] + f[i][j - 1]; + } + } + return f[m - 1][n - 1]; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution2.js" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution2.js" new file mode 100644 index 0000000000000..ffc8b03570664 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution2.js" @@ -0,0 +1,16 @@ +/** + * @param {number} m + * @param {number} n + * @return {number} + */ +var uniquePaths = function (m, n) { + const f = Array(m) + .fill(0) + .map(() => Array(n).fill(1)); + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + f[i][j] = f[i - 1][j] + f[i][j - 1]; + } + } + return f[m - 1][n - 1]; +}; diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution2.py" new file mode 100644 index 0000000000000..68b287d621cc9 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution2.py" @@ -0,0 +1,7 @@ +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + f = [[1] * n for _ in range(m)] + for i in range(1, m): + for j in range(1, n): + f[i][j] = f[i - 1][j] + f[i][j - 1] + return f[-1][-1] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution2.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution2.ts" new file mode 100644 index 0000000000000..ec1856c09b50f --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution2.ts" @@ -0,0 +1,11 @@ +function uniquePaths(m: number, n: number): number { + const f: number[][] = Array(m) + .fill(0) + .map(() => Array(n).fill(1)); + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + f[i][j] = f[i - 1][j] + f[i][j - 1]; + } + } + return f[m - 1][n - 1]; +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution3.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution3.cpp" new file mode 100644 index 0000000000000..a935d4ba6895a --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution3.cpp" @@ -0,0 +1,12 @@ +class Solution { +public: + int uniquePaths(int m, int n) { + vector f(n, 1); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + f[j] += f[j - 1]; + } + } + return f[n - 1]; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution3.go" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution3.go" new file mode 100644 index 0000000000000..d8be9bf206fba --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution3.go" @@ -0,0 +1,12 @@ +func uniquePaths(m int, n int) int { + f := make([]int, n+1) + for i := range f { + f[i] = 1 + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + f[j] += f[j-1] + } + } + return f[n-1] +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution3.java" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution3.java" new file mode 100644 index 0000000000000..162c3b4ad34c4 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution3.java" @@ -0,0 +1,12 @@ +class Solution { + public int uniquePaths(int m, int n) { + int[] f = new int[n]; + Arrays.fill(f, 1); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + f[j] += f[j - 1]; + } + } + return f[n - 1]; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution3.js" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution3.js" new file mode 100644 index 0000000000000..8853e8f24afc5 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution3.js" @@ -0,0 +1,14 @@ +/** + * @param {number} m + * @param {number} n + * @return {number} + */ +var uniquePaths = function (m, n) { + const f = Array(n).fill(1); + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + f[j] += f[j - 1]; + } + } + return f[n - 1]; +}; diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution3.py" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution3.py" new file mode 100644 index 0000000000000..98fb5ac1af0c6 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution3.py" @@ -0,0 +1,7 @@ +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + f = [1] * n + for _ in range(1, m): + for j in range(1, n): + f[j] += f[j - 1] + return f[-1] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution3.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution3.ts" new file mode 100644 index 0000000000000..6dae713f485bd --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/Solution3.ts" @@ -0,0 +1,9 @@ +function uniquePaths(m: number, n: number): number { + const f: number[] = Array(n).fill(1); + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + f[j] += f[j - 1]; + } + } + return f[n - 1]; +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 099. \346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/Solution.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 099. \346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/Solution.cs" index 581d7fef5389f..3f867e6f23a5a 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 099. \346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/Solution.cs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 099. \346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/Solution.cs" @@ -20,4 +20,4 @@ public int MinPathSum(int[][] grid) { } return dp[m- 1, n - 1]; } -} \ No newline at end of file +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 100. \344\270\211\350\247\222\345\275\242\344\270\255\346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 100. \344\270\211\350\247\222\345\275\242\344\270\255\346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/Solution.java" index 329c02aaca4ad..eef5a52318399 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 100. \344\270\211\350\247\222\345\275\242\344\270\255\346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 100. \344\270\211\350\247\222\345\275\242\344\270\255\346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/Solution.java" @@ -1,4 +1,5 @@ class Solution { + public int minimumTotal(List> triangle) { int n = triangle.size(); int[] dp = new int[n + 1]; diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 100. \344\270\211\350\247\222\345\275\242\344\270\255\346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 100. \344\270\211\350\247\222\345\275\242\344\270\255\346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/Solution.py" index c9e5159d4424c..b6fa5b52388ae 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 100. \344\270\211\350\247\222\345\275\242\344\270\255\346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 100. \344\270\211\350\247\222\345\275\242\344\270\255\346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/Solution.py" @@ -1,8 +1,8 @@ class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: n = len(triangle) - dp = [0] * (n + 1) + dp = [[0] * (n + 1) for _ in range(n + 1)] for i in range(n - 1, -1, -1): for j in range(i + 1): - dp[j] = min(dp[j], dp[j + 1]) + triangle[i][j] - return dp[0] + dp[i][j] = min(dp[i + 1][j], dp[i + 1][j + 1]) + triangle[i][j] + return dp[0][0] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 100. \344\270\211\350\247\222\345\275\242\344\270\255\346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 100. \344\270\211\350\247\222\345\275\242\344\270\255\346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/Solution2.py" new file mode 100644 index 0000000000000..c9e5159d4424c --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 100. \344\270\211\350\247\222\345\275\242\344\270\255\346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/Solution2.py" @@ -0,0 +1,8 @@ +class Solution: + def minimumTotal(self, triangle: List[List[int]]) -> int: + n = len(triangle) + dp = [0] * (n + 1) + for i in range(n - 1, -1, -1): + for j in range(i + 1): + dp[j] = min(dp[j], dp[j + 1]) + triangle[i][j] + return dp[0] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/Solution.py" index 8179d30170f42..32dbc3b4977f8 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/Solution.py" @@ -5,12 +5,15 @@ def canPartition(self, nums: List[int]) -> bool: return False m, n = len(nums), (s >> 1) + 1 - dp = [False] * n - dp[0] = True + dp = [[False] * n for _ in range(m)] + for i in range(m): + dp[i][0] = True if nums[0] < n: - dp[nums[0]] = True + dp[0][nums[0]] = True for i in range(1, m): - for j in range(n - 1, nums[i] - 1, -1): - dp[j] = dp[j] or dp[j - nums[i]] - return dp[-1] + for j in range(n): + dp[i][j] = dp[i - 1][j] + if not dp[i][j] and nums[i] <= j: + dp[i][j] = dp[i - 1][j - nums[i]] + return dp[-1][-1] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/Solution2.py" new file mode 100644 index 0000000000000..8179d30170f42 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/Solution2.py" @@ -0,0 +1,16 @@ +class Solution: + def canPartition(self, nums: List[int]) -> bool: + s = sum(nums) + if s % 2 != 0: + return False + + m, n = len(nums), (s >> 1) + 1 + dp = [False] * n + dp[0] = True + if nums[0] < n: + dp[nums[0]] = True + + for i in range(1, m): + for j in range(n - 1, nums[i] - 1, -1): + dp[j] = dp[j] or dp[j - nums[i]] + return dp[-1] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/Solution3.py" "b/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/Solution3.py" new file mode 100644 index 0000000000000..fff4342f39a6d --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/Solution3.py" @@ -0,0 +1,17 @@ +class Solution: + def canPartition(self, nums: List[int]) -> bool: + s = sum(nums) + if s % 2 != 0: + return False + target = s >> 1 + + @cache + def dfs(i, s): + nonlocal target + if s > target or i >= len(nums): + return False + if s == target: + return True + return dfs(i + 1, s) or dfs(i + 1, s + nums[i]) + + return dfs(0, 0) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution.go" "b/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution.go" index 737ae9ec22603..cf04b2ad77942 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution.go" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution.go" @@ -1,18 +1,21 @@ func findTargetSumWays(nums []int, target int) int { - s := 0 - for _, x := range nums { - s += x - } - if s-target < 0 || (s-target)%2 != 0 { + if target < -1000 || target > 1000 { return 0 } - target = (s-target)/2 + 1 - dp := make([]int, target) - dp[0] = 1 - for i := 1; i < len(nums)+1; i++ { - for j := target - 1; j >= nums[i-1]; j-- { - dp[j] += dp[j-nums[i-1]] + n := len(nums) + dp := make([][]int, n) + for i := 0; i < n; i++ { + dp[i] = make([]int, 2001) + } + dp[0][nums[0]+1000] += 1 + dp[0][-nums[0]+1000] += 1 + for i := 1; i < n; i++ { + for j := -1000; j <= 1000; j++ { + if dp[i-1][j+1000] > 0 { + dp[i][j+nums[i]+1000] += dp[i-1][j+1000] + dp[i][j-nums[i]+1000] += dp[i-1][j+1000] + } } } - return dp[target-1] + return dp[n-1][target+1000] } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution.java" index b84cfeff81972..167b5821c416b 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution.java" @@ -1,20 +1,23 @@ class Solution { public int findTargetSumWays(int[] nums, int target) { - int s = 0; - for (int x : nums) { - s += x; - } - if (s - target < 0 || (s - target) % 2 != 0) { + if (target < -1000 || target > 1000) { return 0; } - target = (s - target) / 2 + 1; - int[] dp = new int[target]; - dp[0] = 1; - for (int i = 1; i < nums.length + 1; ++i) { - for (int j = target - 1; j >= nums[i - 1]; --j) { - dp[j] += dp[j - nums[i - 1]]; + + int n = nums.length; + int[][] dp = new int[n][2001]; + + dp[0][nums[0] + 1000] += 1; + dp[0][-nums[0] + 1000] += 1; + + for (int i = 1; i < n; i++) { + for (int j = -1000; j <= 1000; j++) { + if (dp[i - 1][j + 1000] > 0) { + dp[i][j + nums[i] + 1000] += dp[i - 1][j + 1000]; + dp[i][j - nums[i] + 1000] += dp[i - 1][j + 1000]; + } } } - return dp[target - 1]; + return dp[n - 1][target + 1000]; } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution.py" index ea952c3af3808..d268c29a0766d 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution.py" @@ -1,13 +1,14 @@ class Solution: def findTargetSumWays(self, nums: List[int], target: int) -> int: - s = sum(nums) - if s - target < 0 or (s - target) % 2 != 0: + if target < -1000 or target > 1000: return 0 - target = (s - target) // 2 + 1 - n = len(nums) + 1 - dp = [0] * target - dp[0] = 1 + n = len(nums) + dp = [[0] * 2001 for i in range(n)] + dp[0][nums[0] + 1000] += 1 + dp[0][-nums[0] + 1000] += 1 for i in range(1, n): - for j in range(target - 1, nums[i - 1] - 1, -1): - dp[j] += dp[j - nums[i - 1]] - return dp[-1] + for j in range(-1000, 1001): + if dp[i - 1][j + 1000] > 0: + dp[i][j + nums[i] + 1000] += dp[i - 1][j + 1000] + dp[i][j - nums[i] + 1000] += dp[i - 1][j + 1000] + return dp[n - 1][target + 1000] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution2.go" new file mode 100644 index 0000000000000..737ae9ec22603 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution2.go" @@ -0,0 +1,18 @@ +func findTargetSumWays(nums []int, target int) int { + s := 0 + for _, x := range nums { + s += x + } + if s-target < 0 || (s-target)%2 != 0 { + return 0 + } + target = (s-target)/2 + 1 + dp := make([]int, target) + dp[0] = 1 + for i := 1; i < len(nums)+1; i++ { + for j := target - 1; j >= nums[i-1]; j-- { + dp[j] += dp[j-nums[i-1]] + } + } + return dp[target-1] +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution2.java" new file mode 100644 index 0000000000000..b84cfeff81972 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution2.java" @@ -0,0 +1,20 @@ +class Solution { + public int findTargetSumWays(int[] nums, int target) { + int s = 0; + for (int x : nums) { + s += x; + } + if (s - target < 0 || (s - target) % 2 != 0) { + return 0; + } + target = (s - target) / 2 + 1; + int[] dp = new int[target]; + dp[0] = 1; + for (int i = 1; i < nums.length + 1; ++i) { + for (int j = target - 1; j >= nums[i - 1]; --j) { + dp[j] += dp[j - nums[i - 1]]; + } + } + return dp[target - 1]; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution2.py" new file mode 100644 index 0000000000000..4af5dff311e14 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution2.py" @@ -0,0 +1,15 @@ +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + s = sum(nums) + if s - target < 0 or (s - target) % 2 != 0: + return 0 + target = (s - target) // 2 + 1 + n = len(nums) + 1 + dp = [[0] * target for _ in range(n)] + dp[0][0] = 1 + for i in range(1, n): + for j in range(target): + dp[i][j] = dp[i - 1][j] + if nums[i - 1] <= j: + dp[i][j] += dp[i - 1][j - nums[i - 1]] + return dp[-1][-1] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution3.py" "b/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution3.py" new file mode 100644 index 0000000000000..ea952c3af3808 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution3.py" @@ -0,0 +1,13 @@ +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + s = sum(nums) + if s - target < 0 or (s - target) % 2 != 0: + return 0 + target = (s - target) // 2 + 1 + n = len(nums) + 1 + dp = [0] * target + dp[0] = 1 + for i in range(1, n): + for j in range(target - 1, nums[i - 1] - 1, -1): + dp[j] += dp[j - nums[i - 1]] + return dp[-1] diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution4.py" "b/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution4.py" new file mode 100644 index 0000000000000..36ad4e2f7b43a --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/Solution4.py" @@ -0,0 +1,12 @@ +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + @cache + def dfs(i, t): + if i == n: + if t == target: + return 1 + return 0 + return dfs(i + 1, t + nums[i]) + dfs(i + 1, t - nums[i]) + + ans, n = 0, len(nums) + return dfs(0, 0) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 103. \346\234\200\345\260\221\347\232\204\347\241\254\345\270\201\346\225\260\347\233\256/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 103. \346\234\200\345\260\221\347\232\204\347\241\254\345\270\201\346\225\260\347\233\256/Solution.java" index 11152f4d7f309..6f2119d499b8e 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 103. \346\234\200\345\260\221\347\232\204\347\241\254\345\270\201\346\225\260\347\233\256/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 103. \346\234\200\345\260\221\347\232\204\347\241\254\345\270\201\346\225\260\347\233\256/Solution.java" @@ -1,13 +1,20 @@ class Solution { + public int coinChange(int[] coins, int amount) { - int[] dp = new int[amount + 1]; - Arrays.fill(dp, amount + 1); - dp[0] = 0; - for (int coin : coins) { - for (int j = coin; j <= amount; j++) { - dp[j] = Math.min(dp[j], dp[j - coin] + 1); + int m = coins.length; + int[][] dp = new int[m + 1][amount + 1]; + for (int i = 0; i <= m; ++i) { + Arrays.fill(dp[i], amount + 1); + } + dp[0][0] = 0; + for (int i = 1; i <= m; ++i) { + int v = coins[i - 1]; + for (int j = 0; j <= amount; ++j) { + for (int k = 0; k * v <= j; ++k) { + dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - k * v] + k); + } } } - return dp[amount] > amount ? -1 : dp[amount]; + return dp[m][amount] > amount ? -1 : dp[m][amount]; } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 103. \346\234\200\345\260\221\347\232\204\347\241\254\345\270\201\346\225\260\347\233\256/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 103. \346\234\200\345\260\221\347\232\204\347\241\254\345\270\201\346\225\260\347\233\256/Solution2.java" new file mode 100644 index 0000000000000..ca8231ff60994 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 103. \346\234\200\345\260\221\347\232\204\347\241\254\345\270\201\346\225\260\347\233\256/Solution2.java" @@ -0,0 +1,21 @@ +class Solution { + + public int coinChange(int[] coins, int amount) { + int m = coins.length; + int[][] dp = new int[m + 1][amount + 1]; + for (int i = 0; i <= m; ++i) { + Arrays.fill(dp[i], amount + 1); + } + dp[0][0] = 0; + for (int i = 1; i <= m; ++i) { + int v = coins[i - 1]; + for (int j = 0; j <= amount; ++j) { + dp[i][j] = dp[i - 1][j]; + if (j >= v) { + dp[i][j] = Math.min(dp[i][j], dp[i][j - v] + 1); + } + } + } + return dp[m][amount] > amount ? -1 : dp[m][amount]; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 103. \346\234\200\345\260\221\347\232\204\347\241\254\345\270\201\346\225\260\347\233\256/Solution3.java" "b/lcof2/\345\211\221\346\214\207 Offer II 103. \346\234\200\345\260\221\347\232\204\347\241\254\345\270\201\346\225\260\347\233\256/Solution3.java" new file mode 100644 index 0000000000000..7e28bd7b7154d --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 103. \346\234\200\345\260\221\347\232\204\347\241\254\345\270\201\346\225\260\347\233\256/Solution3.java" @@ -0,0 +1,14 @@ +class Solution { + + public int coinChange(int[] coins, int amount) { + int[] dp = new int[amount + 1]; + Arrays.fill(dp, amount + 1); + dp[0] = 0; + for (int coin : coins) { + for (int j = coin; j <= amount; j++) { + dp[j] = Math.min(dp[j], dp[j - coin] + 1); + } + } + return dp[amount] > amount ? -1 : dp[amount]; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 104. \346\216\222\345\210\227\347\232\204\346\225\260\347\233\256/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 104. \346\216\222\345\210\227\347\232\204\346\225\260\347\233\256/Solution.java" index f4866a74dd627..b594c4bb025ab 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 104. \346\216\222\345\210\227\347\232\204\346\225\260\347\233\256/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 104. \346\216\222\345\210\227\347\232\204\346\225\260\347\233\256/Solution.java" @@ -1,4 +1,5 @@ class Solution { + public int combinationSum4(int[] nums, int target) { int[] dp = new int[target + 1]; dp[0] = 1; diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 105. \345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 105. \345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257/Solution.cpp" index ce3c17b6f64e3..6377276aa4e94 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 105. \345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 105. \345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257/Solution.cpp" @@ -1,28 +1,28 @@ -class Solution { -public: - int maxAreaOfIsland(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - int dirs[5] = {-1, 0, 1, 0, -1}; - int ans = 0; - function dfs = [&](int i, int j) { - if (grid[i][j] == 0) { - return 0; - } - int ans = 1; - grid[i][j] = 0; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n) { - ans += dfs(x, y); - } - } - return ans; - }; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - ans = max(ans, dfs(i, j)); - } - } - return ans; - } +class Solution { +public: + int maxAreaOfIsland(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int dirs[5] = {-1, 0, 1, 0, -1}; + int ans = 0; + function dfs = [&](int i, int j) { + if (grid[i][j] == 0) { + return 0; + } + int ans = 1; + grid[i][j] = 0; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n) { + ans += dfs(x, y); + } + } + return ans; + }; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans = max(ans, dfs(i, j)); + } + } + return ans; + } }; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 105. \345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 105. \345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257/Solution.java" index 8250650f724f1..7e75932296920 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 105. \345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 105. \345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257/Solution.java" @@ -1,34 +1,34 @@ -class Solution { - private int m; - private int n; - private int[][] grid; - - public int maxAreaOfIsland(int[][] grid) { - m = grid.length; - n = grid[0].length; - this.grid = grid; - int ans = 0; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - ans = Math.max(ans, dfs(i, j)); - } - } - return ans; - } - - private int dfs(int i, int j) { - if (grid[i][j] == 0) { - return 0; - } - int ans = 1; - grid[i][j] = 0; - int[] dirs = {-1, 0, 1, 0, -1}; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n) { - ans += dfs(x, y); - } - } - return ans; - } +class Solution { + private int m; + private int n; + private int[][] grid; + + public int maxAreaOfIsland(int[][] grid) { + m = grid.length; + n = grid[0].length; + this.grid = grid; + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans = Math.max(ans, dfs(i, j)); + } + } + return ans; + } + + private int dfs(int i, int j) { + if (grid[i][j] == 0) { + return 0; + } + int ans = 1; + grid[i][j] = 0; + int[] dirs = {-1, 0, 1, 0, -1}; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n) { + ans += dfs(x, y); + } + } + return ans; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 105. \345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 105. \345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257/Solution.py" index cbaf00bae009d..c94710af5bd22 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 105. \345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 105. \345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257/Solution.py" @@ -1,16 +1,16 @@ -class Solution: - def maxAreaOfIsland(self, grid: List[List[int]]) -> int: - def dfs(i: int, j: int) -> int: - if grid[i][j] == 0: - return 0 - ans = 1 - grid[i][j] = 0 - dirs = (-1, 0, 1, 0, -1) - for a, b in pairwise(dirs): - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n: - ans += dfs(x, y) - return ans - - m, n = len(grid), len(grid[0]) - return max(dfs(i, j) for i in range(m) for j in range(n)) +class Solution: + def maxAreaOfIsland(self, grid: List[List[int]]) -> int: + def dfs(i: int, j: int) -> int: + if grid[i][j] == 0: + return 0 + ans = 1 + grid[i][j] = 0 + dirs = (-1, 0, 1, 0, -1) + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n: + ans += dfs(x, y) + return ans + + m, n = len(grid), len(grid[0]) + return max(dfs(i, j) for i in range(m) for j in range(n)) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 107. \347\237\251\351\230\265\344\270\255\347\232\204\350\267\235\347\246\273/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 107. \347\237\251\351\230\265\344\270\255\347\232\204\350\267\235\347\246\273/Solution.java" index ec113a4ae1dc7..1afa741424cb8 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 107. \347\237\251\351\230\265\344\270\255\347\232\204\350\267\235\347\246\273/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 107. \347\237\251\351\230\265\344\270\255\347\232\204\350\267\235\347\246\273/Solution.java" @@ -1,4 +1,5 @@ class Solution { + public int[][] updateMatrix(int[][] mat) { int m = mat.length, n = mat[0].length; int[][] ans = new int[m][n]; diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 108. \345\215\225\350\257\215\346\274\224\345\217\230/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 108. \345\215\225\350\257\215\346\274\224\345\217\230/Solution.java" index c860c3a479844..20e612f41133f 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 108. \345\215\225\350\257\215\346\274\224\345\217\230/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 108. \345\215\225\350\257\215\346\274\224\345\217\230/Solution.java" @@ -1,4 +1,5 @@ class Solution { + public int ladderLength(String beginWord, String endWord, List wordList) { Set words = new HashSet<>(wordList); Queue q = new LinkedList<>(); diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 113. \350\257\276\347\250\213\351\241\272\345\272\217/Solution.cs" "b/lcof2/\345\211\221\346\214\207 Offer II 113. \350\257\276\347\250\213\351\241\272\345\272\217/Solution.cs" index 362c54a8a02b6..ba360f7a31921 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 113. \350\257\276\347\250\213\351\241\272\345\272\217/Solution.cs" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 113. \350\257\276\347\250\213\351\241\272\345\272\217/Solution.cs" @@ -30,4 +30,4 @@ public int[] FindOrder(int numCourses, int[][] prerequisites) { } return cnt == numCourses ? ans : new int[0]; } -} \ No newline at end of file +} diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 114. \345\244\226\346\230\237\346\226\207\345\255\227\345\205\270/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 114. \345\244\226\346\230\237\346\226\207\345\255\227\345\205\270/Solution.java" index 6892b9d99f5ab..b21fb7cf681c8 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 114. \345\244\226\346\230\237\346\226\207\345\255\227\345\205\270/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 114. \345\244\226\346\230\237\346\226\207\345\255\227\345\205\270/Solution.java" @@ -1,4 +1,5 @@ class Solution { + public String alienOrder(String[] words) { boolean[][] g = new boolean[26][26]; boolean[] s = new boolean[26]; diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 116. \346\234\213\345\217\213\345\234\210/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 116. \346\234\213\345\217\213\345\234\210/Solution2.cpp" new file mode 100644 index 0000000000000..2a443feeae62c --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 116. \346\234\213\345\217\213\345\234\210/Solution2.cpp" @@ -0,0 +1,24 @@ +class Solution { +public: + vector p; + + int findCircleNum(vector>& isConnected) { + int n = isConnected.size(); + p.resize(n); + for (int i = 0; i < n; ++i) p[i] = i; + for (int i = 0; i < n; ++i) + for (int j = i + 1; j < n; ++j) + if (isConnected[i][j]) + p[find(i)] = find(j); + int ans = 0; + for (int i = 0; i < n; ++i) + if (i == p[i]) + ++ans; + return ans; + } + + int find(int x) { + if (p[x] != x) p[x] = find(p[x]); + return p[x]; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 116. \346\234\213\345\217\213\345\234\210/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 116. \346\234\213\345\217\213\345\234\210/Solution2.go" new file mode 100644 index 0000000000000..1c0f163efdd45 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 116. \346\234\213\345\217\213\345\234\210/Solution2.go" @@ -0,0 +1,28 @@ +func findCircleNum(isConnected [][]int) int { + n := len(isConnected) + p := make([]int, n) + for i := range p { + p[i] = i + } + var find func(x int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + for i := 0; i < n; i++ { + for j := i + 1; j < n; j++ { + if isConnected[i][j] == 1 { + p[find(i)] = find(j) + } + } + } + ans := 0 + for i := range p { + if p[i] == i { + ans++ + } + } + return ans +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 116. \346\234\213\345\217\213\345\234\210/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 116. \346\234\213\345\217\213\345\234\210/Solution2.java" new file mode 100644 index 0000000000000..7e6ef79aed024 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 116. \346\234\213\345\217\213\345\234\210/Solution2.java" @@ -0,0 +1,32 @@ +class Solution { + private int[] p; + + public int findCircleNum(int[][] isConnected) { + int n = isConnected.length; + p = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + } + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + if (isConnected[i][j] == 1) { + p[find(i)] = find(j); + } + } + } + int ans = 0; + for (int i = 0; i < n; ++i) { + if (i == p[i]) { + ++ans; + } + } + return ans; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 116. \346\234\213\345\217\213\345\234\210/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 116. \346\234\213\345\217\213\345\234\210/Solution2.py" new file mode 100644 index 0000000000000..d73f2b524f57c --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 116. \346\234\213\345\217\213\345\234\210/Solution2.py" @@ -0,0 +1,14 @@ +class Solution: + def findCircleNum(self, isConnected: List[List[int]]) -> int: + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + n = len(isConnected) + p = list(range(n)) + for i in range(n): + for j in range(i + 1, n): + if isConnected[i][j]: + p[find(i)] = find(j) + return sum(i == v for i, v in enumerate(p)) diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 117. \347\233\270\344\274\274\347\232\204\345\255\227\347\254\246\344\270\262/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 117. \347\233\270\344\274\274\347\232\204\345\255\227\347\254\246\344\270\262/Solution.java" index 05d22b0040d32..b0ddcc219b9b5 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 117. \347\233\270\344\274\274\347\232\204\345\255\227\347\254\246\344\270\262/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 117. \347\233\270\344\274\274\347\232\204\345\255\227\347\254\246\344\270\262/Solution.java" @@ -14,29 +14,30 @@ public int numSimilarGroups(String[] strs) { } } } - int ans = 0; + int res = 0; for (int i = 0; i < n; ++i) { if (i == find(i)) { - ++ans; + ++res; } } - return ans; - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; + return res; } private boolean check(String a, String b) { int cnt = 0; - for (int i = 0; i < a.length(); ++i) { + int n = a.length(); + for (int i = 0; i < n; ++i) { if (a.charAt(i) != b.charAt(i)) { ++cnt; } } return cnt <= 2; } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.cpp" index 63963f9f4512b..a3c9a84ec208c 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.cpp" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.cpp" @@ -1,15 +1,20 @@ class Solution { public: int longestConsecutive(vector& nums) { - unordered_set s(nums.begin(), nums.end()); - int ans = 0; - for (int x : nums) { - if (!s.count(x - 1)) { - int y = x + 1; - while (s.count(y)) { - y++; - } - ans = max(ans, y - x); + int n = nums.size(); + if (n < 2) { + return n; + } + sort(nums.begin(), nums.end()); + int ans = 1, t = 1; + for (int i = 1; i < n; ++i) { + if (nums[i] == nums[i - 1]) { + continue; + } + if (nums[i] == nums[i - 1] + 1) { + ans = max(ans, ++t); + } else { + t = 1; } } return ans; diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.go" "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.go" index 1a38e03b11467..272692b96d9ad 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.go" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.go" @@ -1,16 +1,20 @@ -func longestConsecutive(nums []int) (ans int) { - s := map[int]bool{} - for _, x := range nums { - s[x] = true +func longestConsecutive(nums []int) int { + n := len(nums) + if n < 2 { + return n } - for _, x := range nums { - if !s[x-1] { - y := x + 1 - for s[y] { - y++ - } - ans = max(ans, y-x) + sort.Ints(nums) + ans, t := 1, 1 + for i, x := range nums[1:] { + if x == nums[i] { + continue + } + if x == nums[i]+1 { + t++ + ans = max(ans, t) + } else { + t = 1 } } - return + return ans } \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.java" "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.java" index 9fbf604320adb..511b5cc8b24b0 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.java" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.java" @@ -1,17 +1,19 @@ class Solution { public int longestConsecutive(int[] nums) { - Set s = new HashSet<>(); - for (int x : nums) { - s.add(x); + int n = nums.length; + if (n < 2) { + return n; } - int ans = 0; - for (int x : nums) { - if (!s.contains(x - 1)) { - int y = x + 1; - while (s.contains(y)) { - ++y; - } - ans = Math.max(ans, y - x); + Arrays.sort(nums); + int ans = 1, t = 1; + for (int i = 1; i < n; ++i) { + if (nums[i] == nums[i - 1]) { + continue; + } + if (nums[i] == nums[i - 1] + 1) { + ans = Math.max(ans, ++t); + } else { + t = 1; } } return ans; diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.js" "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.js" index 9fcb550988044..626571486477c 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.js" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.js" @@ -3,15 +3,21 @@ * @return {number} */ var longestConsecutive = function (nums) { - const s = new Set(nums); - let ans = 0; - for (const x of nums) { - if (!s.has(x - 1)) { - let y = x + 1; - while (s.has(y)) { - y++; - } - ans = Math.max(ans, y - x); + const n = nums.length; + if (n < 2) { + return n; + } + nums.sort((a, b) => a - b); + let ans = 1; + let t = 1; + for (let i = 1; i < n; ++i) { + if (nums[i] === nums[i - 1]) { + continue; + } + if (nums[i] === nums[i - 1] + 1) { + ans = Math.max(ans, ++t); + } else { + t = 1; } } return ans; diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.py" "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.py" index cd60849601a20..2f769cf2e22de 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.py" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.py" @@ -1,11 +1,16 @@ class Solution: def longestConsecutive(self, nums: List[int]) -> int: - s = set(nums) - ans = 0 - for x in nums: - if x - 1 not in s: - y = x + 1 - while y in s: - y += 1 - ans = max(ans, y - x) + n = len(nums) + if n < 2: + return n + nums.sort() + ans = t = 1 + for a, b in pairwise(nums): + if a == b: + continue + if a + 1 == b: + t += 1 + ans = max(ans, t) + else: + t = 1 return ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.ts" index 7e593ca8830d1..fb0fc69cfc134 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.ts" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution.ts" @@ -1,13 +1,19 @@ function longestConsecutive(nums: number[]): number { - const s: Set = new Set(nums); - let ans = 0; - for (const x of s) { - if (!s.has(x - 1)) { - let y = x + 1; - while (s.has(y)) { - y++; - } - ans = Math.max(ans, y - x); + const n = nums.length; + if (n < 2) { + return n; + } + let ans = 1; + let t = 1; + nums.sort((a, b) => a - b); + for (let i = 1; i < n; ++i) { + if (nums[i] === nums[i - 1]) { + continue; + } + if (nums[i] === nums[i - 1] + 1) { + ans = Math.max(ans, ++t); + } else { + t = 1; } } return ans; diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution2.cpp" "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution2.cpp" new file mode 100644 index 0000000000000..63963f9f4512b --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution2.cpp" @@ -0,0 +1,17 @@ +class Solution { +public: + int longestConsecutive(vector& nums) { + unordered_set s(nums.begin(), nums.end()); + int ans = 0; + for (int x : nums) { + if (!s.count(x - 1)) { + int y = x + 1; + while (s.count(y)) { + y++; + } + ans = max(ans, y - x); + } + } + return ans; + } +}; \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution2.go" "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution2.go" new file mode 100644 index 0000000000000..1a38e03b11467 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution2.go" @@ -0,0 +1,16 @@ +func longestConsecutive(nums []int) (ans int) { + s := map[int]bool{} + for _, x := range nums { + s[x] = true + } + for _, x := range nums { + if !s[x-1] { + y := x + 1 + for s[y] { + y++ + } + ans = max(ans, y-x) + } + } + return +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution2.java" "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution2.java" new file mode 100644 index 0000000000000..9fbf604320adb --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution2.java" @@ -0,0 +1,19 @@ +class Solution { + public int longestConsecutive(int[] nums) { + Set s = new HashSet<>(); + for (int x : nums) { + s.add(x); + } + int ans = 0; + for (int x : nums) { + if (!s.contains(x - 1)) { + int y = x + 1; + while (s.contains(y)) { + ++y; + } + ans = Math.max(ans, y - x); + } + } + return ans; + } +} \ No newline at end of file diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution2.js" "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution2.js" new file mode 100644 index 0000000000000..9fcb550988044 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution2.js" @@ -0,0 +1,18 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var longestConsecutive = function (nums) { + const s = new Set(nums); + let ans = 0; + for (const x of nums) { + if (!s.has(x - 1)) { + let y = x + 1; + while (s.has(y)) { + y++; + } + ans = Math.max(ans, y - x); + } + } + return ans; +}; diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution2.py" "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution2.py" new file mode 100644 index 0000000000000..cd60849601a20 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution2.py" @@ -0,0 +1,11 @@ +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + s = set(nums) + ans = 0 + for x in nums: + if x - 1 not in s: + y = x + 1 + while y in s: + y += 1 + ans = max(ans, y - x) + return ans diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution2.ts" "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution2.ts" new file mode 100644 index 0000000000000..7e593ca8830d1 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/Solution2.ts" @@ -0,0 +1,14 @@ +function longestConsecutive(nums: number[]): number { + const s: Set = new Set(nums); + let ans = 0; + for (const x of s) { + if (!s.has(x - 1)) { + let y = x + 1; + while (s.has(y)) { + y++; + } + ans = Math.max(ans, y - x); + } + } + return ans; +} diff --git "a/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution.c" "b/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution.c" index 0fb11d5e10cce..e1aaee202472f 100644 --- "a/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution.c" +++ "b/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution.c" @@ -6,4 +6,4 @@ int game(int* guess, int guessSize, int* answer, int answerSize) { } } return res; -} +} \ No newline at end of file diff --git "a/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution.cpp" "b/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution.cpp" index dcf00c84e6402..b16ca436b4244 100644 --- "a/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution.cpp" +++ "b/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution.cpp" @@ -1,10 +1,10 @@ -class Solution { -public: - int game(vector& guess, vector& answer) { - int ans = 0; - for (int i = 0; i < 3; ++i) { - ans += guess[i] == answer[i]; - } - return ans; - } +class Solution { +public: + int game(vector& guess, vector& answer) { + int ans = 0; + for (int i = 0; i < 3; ++i) { + ans += guess[i] == answer[i]; + } + return ans; + } }; \ No newline at end of file diff --git "a/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution.java" "b/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution.java" index 56b2cf34a3892..2f3113586e289 100644 --- "a/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution.java" +++ "b/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution.java" @@ -1,11 +1,11 @@ -class Solution { - public int game(int[] guess, int[] answer) { - int ans = 0; - for (int i = 0; i < 3; ++i) { - if (guess[i] == answer[i]) { - ++ans; - } - } - return ans; - } +class Solution { + public int game(int[] guess, int[] answer) { + int ans = 0; + for (int i = 0; i < 3; ++i) { + if (guess[i] == answer[i]) { + ++ans; + } + } + return ans; + } } \ No newline at end of file diff --git "a/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution.py" "b/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution.py" index c737679c8f8c2..827ba33e80f85 100644 --- "a/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution.py" +++ "b/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution.py" @@ -1,3 +1,3 @@ -class Solution: - def game(self, guess: List[int], answer: List[int]) -> int: - return sum(a == b for a, b in zip(guess, answer)) +class Solution: + def game(self, guess: List[int], answer: List[int]) -> int: + return sum(a == b for a, b in zip(guess, answer)) diff --git "a/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution2.ts" "b/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution2.ts" new file mode 100644 index 0000000000000..7e93e21e9089a --- /dev/null +++ "b/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/Solution2.ts" @@ -0,0 +1,3 @@ +function game(guess: number[], answer: number[]): number { + return guess.reduce((acc, cur, index) => (cur === answer[index] ? acc + 1 : acc), 0); +} diff --git "a/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.cpp" "b/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.cpp" index b4cae3afa1d4b..76b2250ac1a24 100644 --- "a/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.cpp" +++ "b/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.cpp" @@ -1,17 +1,17 @@ -class Solution { -public: - vector fraction(vector& cont) { - function(int)> dfs = [&](int i) { - if (i == cont.size() - 1) { - return vector{cont[i], 1}; - } - vector next = dfs(i + 1); - int a = next[0], b = next[1]; - int x = a * cont[i] + b; - int y = a; - int g = __gcd(x, y); - return vector{x / g, y / g}; - }; - return dfs(0); - } +class Solution { +public: + vector fraction(vector& cont) { + function(int)> dfs = [&](int i) { + if (i == cont.size() - 1) { + return vector{cont[i], 1}; + } + vector next = dfs(i + 1); + int a = next[0], b = next[1]; + int x = a * cont[i] + b; + int y = a; + int g = __gcd(x, y); + return vector{x / g, y / g}; + }; + return dfs(0); + } }; \ No newline at end of file diff --git "a/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.go" "b/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.go" index be51efda2bc31..34a0fa07288c0 100644 --- "a/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.go" +++ "b/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.go" @@ -1,21 +1,12 @@ func fraction(cont []int) []int { - var dfs func(int) []int + var dfs func(i int) []int dfs = func(i int) []int { if i == len(cont)-1 { return []int{cont[i], 1} } - next := dfs(i + 1) - a, b := next[0], next[1] - x, y := a*cont[i]+b, a - g := gcd(x, y) - return []int{x / g, y / g} + ans := dfs(i + 1) + a, b := ans[0], ans[1] + return []int{a*cont[i] + b, a} } return dfs(0) -} - -func gcd(a, b int) int { - if b == 0 { - return a - } - return gcd(b, a%b) } \ No newline at end of file diff --git "a/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.java" "b/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.java" index 3c17f0fc0e908..ad07d44d9cc3f 100644 --- "a/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.java" +++ "b/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.java" @@ -1,23 +1,23 @@ -class Solution { - private int[] cont; - - public int[] fraction(int[] cont) { - this.cont = cont; - return dfs(0); - } - - private int[] dfs(int i) { - if (i == cont.length - 1) { - return new int[] {cont[i], 1}; - } - int[] next = dfs(i + 1); - int a = next[0], b = next[1]; - int x = a * cont[i] + b, y = a; - int g = gcd(x, y); - return new int[] {x / g, y / g}; - } - - private int gcd(int a, int b) { - return b == 0 ? a : gcd(b, a % b); - } +class Solution { + private int[] cont; + + public int[] fraction(int[] cont) { + this.cont = cont; + return dfs(0); + } + + private int[] dfs(int i) { + if (i == cont.length - 1) { + return new int[] {cont[i], 1}; + } + int[] next = dfs(i + 1); + int a = next[0], b = next[1]; + int x = a * cont[i] + b, y = a; + int g = gcd(x, y); + return new int[] {x / g, y / g}; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } } \ No newline at end of file diff --git "a/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.py" "b/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.py" index 1aaf142565c4e..2c2b9e662c6d9 100644 --- "a/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.py" +++ "b/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.py" @@ -1,11 +1,11 @@ -class Solution: - def fraction(self, cont: List[int]) -> List[int]: - def dfs(i: int) -> List[int]: - if i == len(cont) - 1: - return [cont[i], 1] - a, b = dfs(i + 1) - x, y = a * cont[i] + b, a - g = gcd(x, y) - return [x // g, y // g] - - return dfs(0) +class Solution: + def fraction(self, cont: List[int]) -> List[int]: + def dfs(i: int) -> List[int]: + if i == len(cont) - 1: + return [cont[i], 1] + a, b = dfs(i + 1) + x, y = a * cont[i] + b, a + g = gcd(x, y) + return [x // g, y // g] + + return dfs(0) diff --git "a/lcp/LCP 03. \346\234\272\345\231\250\344\272\272\345\244\247\345\206\222\351\231\251/Solution.cpp" "b/lcp/LCP 03. \346\234\272\345\231\250\344\272\272\345\244\247\345\206\222\351\231\251/Solution.cpp" index eae04fdb9a7e2..563ec4dbaadb3 100644 --- "a/lcp/LCP 03. \346\234\272\345\231\250\344\272\272\345\244\247\345\206\222\351\231\251/Solution.cpp" +++ "b/lcp/LCP 03. \346\234\272\345\231\250\344\272\272\345\244\247\345\206\222\351\231\251/Solution.cpp" @@ -1,30 +1,30 @@ -class Solution { -public: - bool robot(string command, vector>& obstacles, int x, int y) { - set> vis; - int i = 0, j = 0; - vis.insert({i, j}); - for (char c : command) { - if (c == 'U') { - ++j; - } else { - ++i; - } - vis.insert({i, j}); - } - int k = min(x / i, y / j); - if (!vis.count({x - k * i, y - k * j})) { - return false; - } - for (auto& ob : obstacles) { - if (ob[0] > x || ob[1] > y) { - continue; - } - k = min(ob[0] / i, ob[1] / j); - if (vis.count({ob[0] - k * i, ob[1] - k * j})) { - return false; - } - } - return true; - } +class Solution { +public: + bool robot(string command, vector>& obstacles, int x, int y) { + set> vis; + int i = 0, j = 0; + vis.insert({i, j}); + for (char c : command) { + if (c == 'U') { + ++j; + } else { + ++i; + } + vis.insert({i, j}); + } + int k = min(x / i, y / j); + if (!vis.count({x - k * i, y - k * j})) { + return false; + } + for (auto& ob : obstacles) { + if (ob[0] > x || ob[1] > y) { + continue; + } + k = min(ob[0] / i, ob[1] / j); + if (vis.count({ob[0] - k * i, ob[1] - k * j})) { + return false; + } + } + return true; + } }; \ No newline at end of file diff --git "a/lcp/LCP 03. \346\234\272\345\231\250\344\272\272\345\244\247\345\206\222\351\231\251/Solution.java" "b/lcp/LCP 03. \346\234\272\345\231\250\344\272\272\345\244\247\345\206\222\351\231\251/Solution.java" index fadd7ed076b7d..fe097df6d5c34 100644 --- "a/lcp/LCP 03. \346\234\272\345\231\250\344\272\272\345\244\247\345\206\222\351\231\251/Solution.java" +++ "b/lcp/LCP 03. \346\234\272\345\231\250\344\272\272\345\244\247\345\206\222\351\231\251/Solution.java" @@ -1,29 +1,29 @@ -class Solution { - public boolean robot(String command, int[][] obstacles, int x, int y) { - Set> vis = new HashSet<>(); - int i = 0, j = 0; - vis.add(List.of(i, j)); - for (char c : command.toCharArray()) { - if (c == 'U') { - ++j; - } else { - ++i; - } - vis.add(List.of(i, j)); - } - int k = Math.min(x / i, y / j); - if (!vis.contains(List.of(x - k * i, y - k * j))) { - return false; - } - for (int[] ob : obstacles) { - if (ob[0] > x || ob[1] > y) { - continue; - } - k = Math.min(ob[0] / i, ob[1] / j); - if (vis.contains(List.of(ob[0] - k * i, ob[1] - k * j))) { - return false; - } - } - return true; - } +class Solution { + public boolean robot(String command, int[][] obstacles, int x, int y) { + Set> vis = new HashSet<>(); + int i = 0, j = 0; + vis.add(List.of(i, j)); + for (char c : command.toCharArray()) { + if (c == 'U') { + ++j; + } else { + ++i; + } + vis.add(List.of(i, j)); + } + int k = Math.min(x / i, y / j); + if (!vis.contains(List.of(x - k * i, y - k * j))) { + return false; + } + for (int[] ob : obstacles) { + if (ob[0] > x || ob[1] > y) { + continue; + } + k = Math.min(ob[0] / i, ob[1] / j); + if (vis.contains(List.of(ob[0] - k * i, ob[1] - k * j))) { + return false; + } + } + return true; + } } \ No newline at end of file diff --git "a/lcp/LCP 03. \346\234\272\345\231\250\344\272\272\345\244\247\345\206\222\351\231\251/Solution.py" "b/lcp/LCP 03. \346\234\272\345\231\250\344\272\272\345\244\247\345\206\222\351\231\251/Solution.py" index 52c35abcea86f..257d88613f9bd 100644 --- "a/lcp/LCP 03. \346\234\272\345\231\250\344\272\272\345\244\247\345\206\222\351\231\251/Solution.py" +++ "b/lcp/LCP 03. \346\234\272\345\231\250\344\272\272\345\244\247\345\206\222\351\231\251/Solution.py" @@ -1,21 +1,21 @@ -class Solution: - def robot(self, command: str, obstacles: List[List[int]], x: int, y: int) -> bool: - vis = {(0, 0)} - i = j = 0 - for c in command: - match c: - case "U": - j += 1 - case "R": - i += 1 - vis.add((i, j)) - k = min(x // i, y // j) - if (x - k * i, y - k * j) not in vis: - return False - for a, b in obstacles: - if a > x or b > y: - continue - k = min(a // i, b // j) - if (a - k * i, b - k * j) in vis: - return False - return True +class Solution: + def robot(self, command: str, obstacles: List[List[int]], x: int, y: int) -> bool: + vis = {(0, 0)} + i = j = 0 + for c in command: + match c: + case "U": + j += 1 + case "R": + i += 1 + vis.add((i, j)) + k = min(x // i, y // j) + if (x - k * i, y - k * j) not in vis: + return False + for a, b in obstacles: + if a > x or b > y: + continue + k = min(a // i, b // j) + if (a - k * i, b - k * j) in vis: + return False + return True diff --git "a/lcp/LCP 05. \345\217\221 LeetCoin/Solution.cpp" "b/lcp/LCP 05. \345\217\221 LeetCoin/Solution.cpp" index 6615497722ca5..e9d56c699c4ce 100644 --- "a/lcp/LCP 05. \345\217\221 LeetCoin/Solution.cpp" +++ "b/lcp/LCP 05. \345\217\221 LeetCoin/Solution.cpp" @@ -1,115 +1,115 @@ -const int MOD = 1e9 + 7; - -class Node { -public: - Node* left; - Node* right; - int l; - int r; - int mid; - int v; - int add; - - Node(int l, int r) { - this->l = l; - this->r = r; - this->mid = (l + r) >> 1; - this->left = this->right = nullptr; - v = add = 0; - } -}; - -class SegmentTree { -private: - Node* root; - -public: - SegmentTree(int n) { - root = new Node(1, n); - } - - void modify(int l, int r, int v) { - modify(l, r, v, root); - } - - void modify(int l, int r, int v, Node* node) { - if (l > r) return; - if (node->l >= l && node->r <= r) { - node->v = (node->v + (node->r - node->l + 1) * v) % MOD; - node->add += v; - return; - } - pushdown(node); - if (l <= node->mid) modify(l, r, v, node->left); - if (r > node->mid) modify(l, r, v, node->right); - pushup(node); - } - - int query(int l, int r) { - return query(l, r, root); - } - - int query(int l, int r, Node* node) { - if (l > r) return 0; - if (node->l >= l && node->r <= r) return node->v; - pushdown(node); - int v = 0; - if (l <= node->mid) v += query(l, r, node->left); - if (r > node->mid) v += query(l, r, node->right); - return v % MOD; - } - - void pushup(Node* node) { - node->v = (node->left->v + node->right->v) % MOD; - } - - void pushdown(Node* node) { - if (!node->left) node->left = new Node(node->l, node->mid); - if (!node->right) node->right = new Node(node->mid + 1, node->r); - if (node->add) { - Node* left = node->left; - Node* right = node->right; - left->v = (left->v + (left->r - left->l + 1) * node->add) % MOD; - right->v = (right->v + (right->r - right->l + 1) * node->add) % MOD; - left->add += node->add; - right->add += node->add; - node->add = 0; - } - } -}; - -class Solution { -public: - int idx; - - vector bonus(int n, vector>& leadership, vector>& operations) { - vector> g(n + 1); - for (auto& l : leadership) { - int a = l[0], b = l[1]; - g[a].push_back(b); - } - vector begin(n + 1); - vector end(n + 1); - idx = 1; - dfs(1, begin, end, g); - vector ans; - SegmentTree* tree = new SegmentTree(n); - for (auto& op : operations) { - int p = op[0], v = op[1]; - if (p == 1) - tree->modify(end[v], end[v], op[2]); - else if (p == 2) - tree->modify(begin[v], end[v], op[2]); - else - ans.push_back(tree->query(begin[v], end[v])); - } - return ans; - } - - void dfs(int u, vector& begin, vector& end, vector>& g) { - begin[u] = idx; - for (int v : g[u]) dfs(v, begin, end, g); - end[u] = idx; - ++idx; - } +const int MOD = 1e9 + 7; + +class Node { +public: + Node* left; + Node* right; + int l; + int r; + int mid; + int v; + int add; + + Node(int l, int r) { + this->l = l; + this->r = r; + this->mid = (l + r) >> 1; + this->left = this->right = nullptr; + v = add = 0; + } +}; + +class SegmentTree { +private: + Node* root; + +public: + SegmentTree(int n) { + root = new Node(1, n); + } + + void modify(int l, int r, int v) { + modify(l, r, v, root); + } + + void modify(int l, int r, int v, Node* node) { + if (l > r) return; + if (node->l >= l && node->r <= r) { + node->v = (node->v + (node->r - node->l + 1) * v) % MOD; + node->add += v; + return; + } + pushdown(node); + if (l <= node->mid) modify(l, r, v, node->left); + if (r > node->mid) modify(l, r, v, node->right); + pushup(node); + } + + int query(int l, int r) { + return query(l, r, root); + } + + int query(int l, int r, Node* node) { + if (l > r) return 0; + if (node->l >= l && node->r <= r) return node->v; + pushdown(node); + int v = 0; + if (l <= node->mid) v += query(l, r, node->left); + if (r > node->mid) v += query(l, r, node->right); + return v % MOD; + } + + void pushup(Node* node) { + node->v = (node->left->v + node->right->v) % MOD; + } + + void pushdown(Node* node) { + if (!node->left) node->left = new Node(node->l, node->mid); + if (!node->right) node->right = new Node(node->mid + 1, node->r); + if (node->add) { + Node* left = node->left; + Node* right = node->right; + left->v = (left->v + (left->r - left->l + 1) * node->add) % MOD; + right->v = (right->v + (right->r - right->l + 1) * node->add) % MOD; + left->add += node->add; + right->add += node->add; + node->add = 0; + } + } +}; + +class Solution { +public: + int idx; + + vector bonus(int n, vector>& leadership, vector>& operations) { + vector> g(n + 1); + for (auto& l : leadership) { + int a = l[0], b = l[1]; + g[a].push_back(b); + } + vector begin(n + 1); + vector end(n + 1); + idx = 1; + dfs(1, begin, end, g); + vector ans; + SegmentTree* tree = new SegmentTree(n); + for (auto& op : operations) { + int p = op[0], v = op[1]; + if (p == 1) + tree->modify(end[v], end[v], op[2]); + else if (p == 2) + tree->modify(begin[v], end[v], op[2]); + else + ans.push_back(tree->query(begin[v], end[v])); + } + return ans; + } + + void dfs(int u, vector& begin, vector& end, vector>& g) { + begin[u] = idx; + for (int v : g[u]) dfs(v, begin, end, g); + end[u] = idx; + ++idx; + } }; \ No newline at end of file diff --git "a/lcp/LCP 05. \345\217\221 LeetCoin/Solution.java" "b/lcp/LCP 05. \345\217\221 LeetCoin/Solution.java" index c530f8bca54fa..6e98d3fbfe977 100644 --- "a/lcp/LCP 05. \345\217\221 LeetCoin/Solution.java" +++ "b/lcp/LCP 05. \345\217\221 LeetCoin/Solution.java" @@ -1,131 +1,131 @@ -class Node { - Node left; - Node right; - int l; - int r; - int mid; - int v; - int add; - public Node(int l, int r) { - this.l = l; - this.r = r; - this.mid = (l + r) >> 1; - } -} - -class SegmentTree { - private Node root; - private static final int MOD = (int) 1e9 + 7; - - public SegmentTree(int n) { - root = new Node(1, n); - } - - public void modify(int l, int r, int v) { - modify(l, r, v, root); - } - - public void modify(int l, int r, int v, Node node) { - if (l > r) { - return; - } - if (node.l >= l && node.r <= r) { - node.v = (node.v + (node.r - node.l + 1) * v) % MOD; - node.add += v; - return; - } - pushdown(node); - if (l <= node.mid) { - modify(l, r, v, node.left); - } - if (r > node.mid) { - modify(l, r, v, node.right); - } - pushup(node); - } - - public int query(int l, int r) { - return query(l, r, root); - } - - public int query(int l, int r, Node node) { - if (l > r) { - return 0; - } - if (node.l >= l && node.r <= r) { - return node.v; - } - pushdown(node); - int v = 0; - if (l <= node.mid) { - v = (v + query(l, r, node.left)) % MOD; - } - if (r > node.mid) { - v = (v + query(l, r, node.right)) % MOD; - } - return v; - } - - public void pushup(Node node) { - node.v = (node.left.v + node.right.v) % MOD; - } - - public void pushdown(Node node) { - if (node.left == null) { - node.left = new Node(node.l, node.mid); - } - if (node.right == null) { - node.right = new Node(node.mid + 1, node.r); - } - if (node.add != 0) { - Node left = node.left, right = node.right; - left.v = (left.v + (left.r - left.l + 1) * node.add) % MOD; - right.v = (right.v + (right.r - right.l + 1) * node.add) % MOD; - left.add += node.add; - right.add += node.add; - node.add = 0; - } - } -} - -class Solution { - private List[] g; - private int[] begin; - private int[] end; - private int idx; - - public int[] bonus(int n, int[][] leadership, int[][] operations) { - g = new List[n + 1]; - Arrays.setAll(g, k -> new ArrayList<>()); - for (int[] l : leadership) { - int a = l[0], b = l[1]; - g[a].add(b); - } - begin = new int[n + 1]; - end = new int[n + 1]; - idx = 1; - dfs(1); - List ans = new ArrayList<>(); - SegmentTree tree = new SegmentTree(n); - for (int[] op : operations) { - int p = op[0], v = op[1]; - if (p == 1) { - tree.modify(end[v], end[v], op[2]); - } else if (p == 2) { - tree.modify(begin[v], end[v], op[2]); - } else { - ans.add(tree.query(begin[v], end[v])); - } - } - return ans.stream().mapToInt(Integer::intValue).toArray(); - } - - private void dfs(int u) { - begin[u] = idx; - for (int v : g[u]) { - dfs(v); - } - end[u] = idx; - ++idx; - } +class Node { + Node left; + Node right; + int l; + int r; + int mid; + int v; + int add; + public Node(int l, int r) { + this.l = l; + this.r = r; + this.mid = (l + r) >> 1; + } +} + +class SegmentTree { + private Node root; + private static final int MOD = (int) 1e9 + 7; + + public SegmentTree(int n) { + root = new Node(1, n); + } + + public void modify(int l, int r, int v) { + modify(l, r, v, root); + } + + public void modify(int l, int r, int v, Node node) { + if (l > r) { + return; + } + if (node.l >= l && node.r <= r) { + node.v = (node.v + (node.r - node.l + 1) * v) % MOD; + node.add += v; + return; + } + pushdown(node); + if (l <= node.mid) { + modify(l, r, v, node.left); + } + if (r > node.mid) { + modify(l, r, v, node.right); + } + pushup(node); + } + + public int query(int l, int r) { + return query(l, r, root); + } + + public int query(int l, int r, Node node) { + if (l > r) { + return 0; + } + if (node.l >= l && node.r <= r) { + return node.v; + } + pushdown(node); + int v = 0; + if (l <= node.mid) { + v = (v + query(l, r, node.left)) % MOD; + } + if (r > node.mid) { + v = (v + query(l, r, node.right)) % MOD; + } + return v; + } + + public void pushup(Node node) { + node.v = (node.left.v + node.right.v) % MOD; + } + + public void pushdown(Node node) { + if (node.left == null) { + node.left = new Node(node.l, node.mid); + } + if (node.right == null) { + node.right = new Node(node.mid + 1, node.r); + } + if (node.add != 0) { + Node left = node.left, right = node.right; + left.v = (left.v + (left.r - left.l + 1) * node.add) % MOD; + right.v = (right.v + (right.r - right.l + 1) * node.add) % MOD; + left.add += node.add; + right.add += node.add; + node.add = 0; + } + } +} + +class Solution { + private List[] g; + private int[] begin; + private int[] end; + private int idx; + + public int[] bonus(int n, int[][] leadership, int[][] operations) { + g = new List[n + 1]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (int[] l : leadership) { + int a = l[0], b = l[1]; + g[a].add(b); + } + begin = new int[n + 1]; + end = new int[n + 1]; + idx = 1; + dfs(1); + List ans = new ArrayList<>(); + SegmentTree tree = new SegmentTree(n); + for (int[] op : operations) { + int p = op[0], v = op[1]; + if (p == 1) { + tree.modify(end[v], end[v], op[2]); + } else if (p == 2) { + tree.modify(begin[v], end[v], op[2]); + } else { + ans.add(tree.query(begin[v], end[v])); + } + } + return ans.stream().mapToInt(Integer::intValue).toArray(); + } + + private void dfs(int u) { + begin[u] = idx; + for (int v : g[u]) { + dfs(v); + } + end[u] = idx; + ++idx; + } } \ No newline at end of file diff --git "a/lcp/LCP 05. \345\217\221 LeetCoin/Solution.py" "b/lcp/LCP 05. \345\217\221 LeetCoin/Solution.py" index 20465cd329135..d8888dcf1cc2a 100644 --- "a/lcp/LCP 05. \345\217\221 LeetCoin/Solution.py" +++ "b/lcp/LCP 05. \345\217\221 LeetCoin/Solution.py" @@ -1,96 +1,96 @@ -MOD = int(1e9 + 7) - - -class Node: - def __init__(self, l, r): - self.left = None - self.right = None - self.l = l - self.r = r - self.mid = (l + r) >> 1 - self.v = 0 - self.add = 0 - - -class SegmentTree: - def __init__(self, n): - self.root = Node(1, n) - - def modify(self, l, r, v, node=None): - if l > r: - return - if node is None: - node = self.root - if node.l >= l and node.r <= r: - node.v = (node.v + (node.r - node.l + 1) * v) % MOD - node.add += v - return - self.pushdown(node) - if l <= node.mid: - self.modify(l, r, v, node.left) - if r > node.mid: - self.modify(l, r, v, node.right) - self.pushup(node) - - def query(self, l, r, node=None): - if l > r: - return 0 - if node is None: - node = self.root - if node.l >= l and node.r <= r: - return node.v - self.pushdown(node) - v = 0 - if l <= node.mid: - v += self.query(l, r, node.left) - if r > node.mid: - v += self.query(l, r, node.right) - return v % MOD - - def pushup(self, node): - node.v = (node.left.v + node.right.v) % MOD - - def pushdown(self, node): - if node.left is None: - node.left = Node(node.l, node.mid) - if node.right is None: - node.right = Node(node.mid + 1, node.r) - if node.add: - left, right = node.left, node.right - left.v = (left.v + (left.r - left.l + 1) * node.add) % MOD - right.v = (right.v + (right.r - right.l + 1) * node.add) % MOD - left.add += node.add - right.add += node.add - node.add = 0 - - -class Solution: - def bonus( - self, n: int, leadership: List[List[int]], operations: List[List[int]] - ) -> List[int]: - def dfs(u): - nonlocal idx - begin[u] = idx - for v in g[u]: - dfs(v) - end[u] = idx - idx += 1 - - g = defaultdict(list) - for a, b in leadership: - g[a].append(b) - begin = [0] * (n + 1) - end = [0] * (n + 1) - idx = 1 - dfs(1) - ans = [] - tree = SegmentTree(n) - for op in operations: - p, v = op[:2] - if p == 1: - tree.modify(end[v], end[v], op[2]) - elif p == 2: - tree.modify(begin[v], end[v], op[2]) - else: - ans.append(tree.query(begin[v], end[v])) - return ans +MOD = int(1e9 + 7) + + +class Node: + def __init__(self, l, r): + self.left = None + self.right = None + self.l = l + self.r = r + self.mid = (l + r) >> 1 + self.v = 0 + self.add = 0 + + +class SegmentTree: + def __init__(self, n): + self.root = Node(1, n) + + def modify(self, l, r, v, node=None): + if l > r: + return + if node is None: + node = self.root + if node.l >= l and node.r <= r: + node.v = (node.v + (node.r - node.l + 1) * v) % MOD + node.add += v + return + self.pushdown(node) + if l <= node.mid: + self.modify(l, r, v, node.left) + if r > node.mid: + self.modify(l, r, v, node.right) + self.pushup(node) + + def query(self, l, r, node=None): + if l > r: + return 0 + if node is None: + node = self.root + if node.l >= l and node.r <= r: + return node.v + self.pushdown(node) + v = 0 + if l <= node.mid: + v += self.query(l, r, node.left) + if r > node.mid: + v += self.query(l, r, node.right) + return v % MOD + + def pushup(self, node): + node.v = (node.left.v + node.right.v) % MOD + + def pushdown(self, node): + if node.left is None: + node.left = Node(node.l, node.mid) + if node.right is None: + node.right = Node(node.mid + 1, node.r) + if node.add: + left, right = node.left, node.right + left.v = (left.v + (left.r - left.l + 1) * node.add) % MOD + right.v = (right.v + (right.r - right.l + 1) * node.add) % MOD + left.add += node.add + right.add += node.add + node.add = 0 + + +class Solution: + def bonus( + self, n: int, leadership: List[List[int]], operations: List[List[int]] + ) -> List[int]: + def dfs(u): + nonlocal idx + begin[u] = idx + for v in g[u]: + dfs(v) + end[u] = idx + idx += 1 + + g = defaultdict(list) + for a, b in leadership: + g[a].append(b) + begin = [0] * (n + 1) + end = [0] * (n + 1) + idx = 1 + dfs(1) + ans = [] + tree = SegmentTree(n) + for op in operations: + p, v = op[:2] + if p == 1: + tree.modify(end[v], end[v], op[2]) + elif p == 2: + tree.modify(begin[v], end[v], op[2]) + else: + ans.append(tree.query(begin[v], end[v])) + return ans diff --git "a/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.c" "b/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.c" index 574ebaec9fd13..71f3b752dd80b 100644 --- "a/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.c" +++ "b/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.c" @@ -1,7 +1,7 @@ -int minCount(int* coins, int coinsSize) { - int ans = 0; - for (int i = 0; i < coinsSize; ++i) { - ans += (coins[i] + 1) >> 1; - } - return ans; -} +int minCount(int* coins, int coinsSize) { + int ans = 0; + for (int i = 0; i < coinsSize; ++i) { + ans += (coins[i] + 1) >> 1; + } + return ans; +} \ No newline at end of file diff --git "a/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.cpp" "b/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.cpp" index df83766f5bd46..72de2ccefbff2 100644 --- "a/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.cpp" +++ "b/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.cpp" @@ -1,10 +1,10 @@ -class Solution { -public: - int minCount(vector& coins) { - int ans = 0; - for (int x : coins) { - ans += (x + 1) >> 1; - } - return ans; - } +class Solution { +public: + int minCount(vector& coins) { + int ans = 0; + for (int x : coins) { + ans += (x + 1) >> 1; + } + return ans; + } }; \ No newline at end of file diff --git "a/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.java" "b/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.java" index d161f48579e3a..ccf522d2f7e09 100644 --- "a/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.java" +++ "b/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.java" @@ -1,9 +1,9 @@ -class Solution { - public int minCount(int[] coins) { - int ans = 0; - for (int x : coins) { - ans += (x + 1) >> 1; - } - return ans; - } +class Solution { + public int minCount(int[] coins) { + int ans = 0; + for (int x : coins) { + ans += (x + 1) >> 1; + } + return ans; + } } \ No newline at end of file diff --git "a/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.php" "b/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.php" index fad936e2ae3a4..fea0d6e236a52 100644 --- "a/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.php" +++ "b/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.php" @@ -10,4 +10,4 @@ function minCount($coins) { } return $ans; } -} \ No newline at end of file +} diff --git "a/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.py" "b/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.py" index 353670e0c9cae..54fb710417bb1 100644 --- "a/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.py" +++ "b/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/Solution.py" @@ -1,3 +1,3 @@ -class Solution: - def minCount(self, coins: List[int]) -> int: - return sum((x + 1) >> 1 for x in coins) +class Solution: + def minCount(self, coins: List[int]) -> int: + return sum((x + 1) >> 1 for x in coins) diff --git "a/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.cpp" "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.cpp" index 043cbd94491d0..9a13583693d29 100644 --- "a/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.cpp" +++ "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.cpp" @@ -1,16 +1,15 @@ -class Solution { -public: - int numWays(int n, vector>& relation, int k) { - vector f(n); - f[0] = 1; - while (k--) { - vector g(n); - for (auto& r : relation) { - int a = r[0], b = r[1]; - g[b] += f[a]; - } - f = move(g); - } - return f[n - 1]; - } +class Solution { +public: + int numWays(int n, vector>& relation, int k) { + int f[k + 1][n]; + memset(f, 0, sizeof(f)); + f[0][0] = 1; + for (int i = 1; i <= k; ++i) { + for (auto& r : relation) { + int a = r[0], b = r[1]; + f[i][b] += f[i - 1][a]; + } + } + return f[k][n - 1]; + } }; \ No newline at end of file diff --git "a/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.go" "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.go" index c5254fc271972..f1bb283ac26c3 100644 --- "a/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.go" +++ "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.go" @@ -1,13 +1,14 @@ func numWays(n int, relation [][]int, k int) int { - f := make([]int, n) - f[0] = 1 - for ; k > 0; k-- { - g := make([]int, n) + f := make([][]int, k+1) + for i := range f { + f[i] = make([]int, n) + } + f[0][0] = 1 + for i := 1; i <= k; i++ { for _, r := range relation { a, b := r[0], r[1] - g[b] += f[a] + f[i][b] += f[i-1][a] } - f = g } - return f[n-1] + return f[k][n-1] } \ No newline at end of file diff --git "a/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.java" "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.java" index 1b4b9c512f714..79e2e5ac4fe55 100644 --- "a/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.java" +++ "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.java" @@ -1,15 +1,13 @@ -class Solution { - public int numWays(int n, int[][] relation, int k) { - int[] f = new int[n]; - f[0] = 1; - while (k-- > 0) { - int[] g = new int[n]; - for (int[] r : relation) { - int a = r[0], b = r[1]; - g[b] += f[a]; - } - f = g; - } - return f[n - 1]; - } +class Solution { + public int numWays(int n, int[][] relation, int k) { + int[][] f = new int[k + 1][n]; + f[0][0] = 1; + for (int i = 1; i <= k; ++i) { + for (int[] r : relation) { + int a = r[0], b = r[1]; + f[i][b] += f[i - 1][a]; + } + } + return f[k][n - 1]; + } } \ No newline at end of file diff --git "a/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.py" "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.py" index f3daa4a992089..67b30fd907ff5 100644 --- "a/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.py" +++ "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.py" @@ -1,9 +1,8 @@ -class Solution: - def numWays(self, n: int, relation: List[List[int]], k: int) -> int: - f = [1] + [0] * (n - 1) - for _ in range(k): - g = [0] * n - for a, b in relation: - g[b] += f[a] - f = g - return f[-1] +class Solution: + def numWays(self, n: int, relation: List[List[int]], k: int) -> int: + f = [[0] * n for _ in range(k + 1)] + f[0][0] = 1 + for i in range(1, k + 1): + for a, b in relation: + f[i][b] += f[i - 1][a] + return f[-1][-1] diff --git "a/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.ts" "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.ts" index 76c6849eb1790..7ab3e7c2f7933 100644 --- "a/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.ts" +++ "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution.ts" @@ -1,12 +1,10 @@ function numWays(n: number, relation: number[][], k: number): number { - let f: number[] = new Array(n).fill(0); - f[0] = 1; - while (k--) { - const g: number[] = new Array(n).fill(0); + const f: number[][] = new Array(k + 1).fill(0).map(() => new Array(n).fill(0)); + f[0][0] = 1; + for (let i = 1; i <= k; ++i) { for (const [a, b] of relation) { - g[b] += f[a]; + f[i][b] += f[i - 1][a]; } - f = g; } - return f[n - 1]; + return f[k][n - 1]; } diff --git "a/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution2.cpp" "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution2.cpp" new file mode 100644 index 0000000000000..27244f8afb536 --- /dev/null +++ "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution2.cpp" @@ -0,0 +1,16 @@ +class Solution { +public: + int numWays(int n, vector>& relation, int k) { + vector f(n); + f[0] = 1; + while (k--) { + vector g(n); + for (auto& r : relation) { + int a = r[0], b = r[1]; + g[b] += f[a]; + } + f = move(g); + } + return f[n - 1]; + } +}; \ No newline at end of file diff --git "a/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution2.go" "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution2.go" new file mode 100644 index 0000000000000..c5254fc271972 --- /dev/null +++ "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution2.go" @@ -0,0 +1,13 @@ +func numWays(n int, relation [][]int, k int) int { + f := make([]int, n) + f[0] = 1 + for ; k > 0; k-- { + g := make([]int, n) + for _, r := range relation { + a, b := r[0], r[1] + g[b] += f[a] + } + f = g + } + return f[n-1] +} \ No newline at end of file diff --git "a/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution2.java" "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution2.java" new file mode 100644 index 0000000000000..bd15853ea8a82 --- /dev/null +++ "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution2.java" @@ -0,0 +1,15 @@ +class Solution { + public int numWays(int n, int[][] relation, int k) { + int[] f = new int[n]; + f[0] = 1; + while (k-- > 0) { + int[] g = new int[n]; + for (int[] r : relation) { + int a = r[0], b = r[1]; + g[b] += f[a]; + } + f = g; + } + return f[n - 1]; + } +} \ No newline at end of file diff --git "a/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution2.py" "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution2.py" new file mode 100644 index 0000000000000..216fe5192d552 --- /dev/null +++ "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution2.py" @@ -0,0 +1,9 @@ +class Solution: + def numWays(self, n: int, relation: List[List[int]], k: int) -> int: + f = [1] + [0] * (n - 1) + for _ in range(k): + g = [0] * n + for a, b in relation: + g[b] += f[a] + f = g + return f[-1] diff --git "a/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution2.ts" "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution2.ts" new file mode 100644 index 0000000000000..76c6849eb1790 --- /dev/null +++ "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/Solution2.ts" @@ -0,0 +1,12 @@ +function numWays(n: number, relation: number[][], k: number): number { + let f: number[] = new Array(n).fill(0); + f[0] = 1; + while (k--) { + const g: number[] = new Array(n).fill(0); + for (const [a, b] of relation) { + g[b] += f[a]; + } + f = g; + } + return f[n - 1]; +} diff --git "a/lcp/LCP 08. \345\211\247\346\203\205\350\247\246\345\217\221\346\227\266\351\227\264/Solution.java" "b/lcp/LCP 08. \345\211\247\346\203\205\350\247\246\345\217\221\346\227\266\351\227\264/Solution.java" index 912d07ba327e6..b4e7ec86cfa06 100644 --- "a/lcp/LCP 08. \345\211\247\346\203\205\350\247\246\345\217\221\346\227\266\351\227\264/Solution.java" +++ "b/lcp/LCP 08. \345\211\247\346\203\205\350\247\246\345\217\221\346\227\266\351\227\264/Solution.java" @@ -33,4 +33,4 @@ private boolean check(int[] a, int[] b) { } return true; } -} +} \ No newline at end of file diff --git "a/lcp/LCP 17. \351\200\237\347\256\227\346\234\272\345\231\250\344\272\272/Solution.cpp" "b/lcp/LCP 17. \351\200\237\347\256\227\346\234\272\345\231\250\344\272\272/Solution.cpp" index faeaf5209cbbe..7684d4f9fb21d 100644 --- "a/lcp/LCP 17. \351\200\237\347\256\227\346\234\272\345\231\250\344\272\272/Solution.cpp" +++ "b/lcp/LCP 17. \351\200\237\347\256\227\346\234\272\345\231\250\344\272\272/Solution.cpp" @@ -1,13 +1,13 @@ -class Solution { -public: - int calculate(string s) { - int x = 1, y = 0; - for (char& c : s) { - if (c == 'A') - x = x * 2 + y; - else - y = y * 2 + x; - } - return x + y; - } +class Solution { +public: + int calculate(string s) { + int x = 1, y = 0; + for (char& c : s) { + if (c == 'A') + x = x * 2 + y; + else + y = y * 2 + x; + } + return x + y; + } }; \ No newline at end of file diff --git "a/lcp/LCP 17. \351\200\237\347\256\227\346\234\272\345\231\250\344\272\272/Solution.java" "b/lcp/LCP 17. \351\200\237\347\256\227\346\234\272\345\231\250\344\272\272/Solution.java" index 1ce069d368378..e537436d170a5 100644 --- "a/lcp/LCP 17. \351\200\237\347\256\227\346\234\272\345\231\250\344\272\272/Solution.java" +++ "b/lcp/LCP 17. \351\200\237\347\256\227\346\234\272\345\231\250\344\272\272/Solution.java" @@ -1,13 +1,13 @@ -class Solution { - public int calculate(String s) { - int x = 1, y = 0; - for (char c : s.toCharArray()) { - if (c == 'A') { - x = x * 2 + y; - } else { - y = y * 2 + x; - } - } - return x + y; - } +class Solution { + public int calculate(String s) { + int x = 1, y = 0; + for (char c : s.toCharArray()) { + if (c == 'A') { + x = x * 2 + y; + } else { + y = y * 2 + x; + } + } + return x + y; + } } \ No newline at end of file diff --git "a/lcp/LCP 17. \351\200\237\347\256\227\346\234\272\345\231\250\344\272\272/Solution.py" "b/lcp/LCP 17. \351\200\237\347\256\227\346\234\272\345\231\250\344\272\272/Solution.py" index c76ccb14a5c0e..c6ea57444676a 100644 --- "a/lcp/LCP 17. \351\200\237\347\256\227\346\234\272\345\231\250\344\272\272/Solution.py" +++ "b/lcp/LCP 17. \351\200\237\347\256\227\346\234\272\345\231\250\344\272\272/Solution.py" @@ -1,9 +1,9 @@ -class Solution: - def calculate(self, s: str) -> int: - x, y = 1, 0 - for c in s: - if c == 'A': - x = x * 2 + y - else: - y = y * 2 + x - return x + y +class Solution: + def calculate(self, s: str) -> int: + x, y = 1, 0 + for c in s: + if c == 'A': + x = x * 2 + y + else: + y = y * 2 + x + return x + y diff --git "a/lcp/LCP 19. \347\247\213\345\217\266\346\224\266\350\227\217\351\233\206/Solution.cpp" "b/lcp/LCP 19. \347\247\213\345\217\266\346\224\266\350\227\217\351\233\206/Solution.cpp" index 31682deb1fe79..c2df2fcc2d648 100644 --- "a/lcp/LCP 19. \347\247\213\345\217\266\346\224\266\350\227\217\351\233\206/Solution.cpp" +++ "b/lcp/LCP 19. \347\247\213\345\217\266\346\224\266\350\227\217\351\233\206/Solution.cpp" @@ -1,21 +1,21 @@ -class Solution { -public: - int minimumOperations(string leaves) { - int n = leaves.size(); - int f[n][3]; - memset(f, 0x3f, sizeof(f)); - f[0][0] = leaves[0] == 'y'; - for (int i = 1; i < n; ++i) { - if (leaves[i] == 'r') { - f[i][0] = f[i - 1][0]; - f[i][1] = min(f[i - 1][0], f[i - 1][1]) + 1; - f[i][2] = min(f[i - 1][2], f[i - 1][1]); - } else { - f[i][0] = f[i - 1][0] + 1; - f[i][1] = min(f[i - 1][0], f[i - 1][1]); - f[i][2] = min(f[i - 1][2], f[i - 1][1]) + 1; - } - } - return f[n - 1][2]; - } +class Solution { +public: + int minimumOperations(string leaves) { + int n = leaves.size(); + int f[n][3]; + memset(f, 0x3f, sizeof(f)); + f[0][0] = leaves[0] == 'y'; + for (int i = 1; i < n; ++i) { + if (leaves[i] == 'r') { + f[i][0] = f[i - 1][0]; + f[i][1] = min(f[i - 1][0], f[i - 1][1]) + 1; + f[i][2] = min(f[i - 1][2], f[i - 1][1]); + } else { + f[i][0] = f[i - 1][0] + 1; + f[i][1] = min(f[i - 1][0], f[i - 1][1]); + f[i][2] = min(f[i - 1][2], f[i - 1][1]) + 1; + } + } + return f[n - 1][2]; + } }; \ No newline at end of file diff --git "a/lcp/LCP 19. \347\247\213\345\217\266\346\224\266\350\227\217\351\233\206/Solution.java" "b/lcp/LCP 19. \347\247\213\345\217\266\346\224\266\350\227\217\351\233\206/Solution.java" index 6879d98b28f32..2139088db54dd 100644 --- "a/lcp/LCP 19. \347\247\213\345\217\266\346\224\266\350\227\217\351\233\206/Solution.java" +++ "b/lcp/LCP 19. \347\247\213\345\217\266\346\224\266\350\227\217\351\233\206/Solution.java" @@ -1,23 +1,23 @@ -class Solution { - public int minimumOperations(String leaves) { - int n = leaves.length(); - final int inf = 1 << 30; - var f = new int[n][3]; - for (var g : f) { - Arrays.fill(g, inf); - } - f[0][0] = leaves.charAt(0) == 'r' ? 0 : 1; - for (int i = 1; i < n; ++i) { - if (leaves.charAt(i) == 'r') { - f[i][0] = f[i - 1][0]; - f[i][1] = Math.min(f[i - 1][0], f[i - 1][1]) + 1; - f[i][2] = Math.min(f[i - 1][2], f[i - 1][1]); - } else { - f[i][0] = f[i - 1][0] + 1; - f[i][1] = Math.min(f[i - 1][0], f[i - 1][1]); - f[i][2] = Math.min(f[i - 1][2], f[i - 1][1]) + 1; - } - } - return f[n - 1][2]; - } +class Solution { + public int minimumOperations(String leaves) { + int n = leaves.length(); + final int inf = 1 << 30; + var f = new int[n][3]; + for (var g : f) { + Arrays.fill(g, inf); + } + f[0][0] = leaves.charAt(0) == 'r' ? 0 : 1; + for (int i = 1; i < n; ++i) { + if (leaves.charAt(i) == 'r') { + f[i][0] = f[i - 1][0]; + f[i][1] = Math.min(f[i - 1][0], f[i - 1][1]) + 1; + f[i][2] = Math.min(f[i - 1][2], f[i - 1][1]); + } else { + f[i][0] = f[i - 1][0] + 1; + f[i][1] = Math.min(f[i - 1][0], f[i - 1][1]); + f[i][2] = Math.min(f[i - 1][2], f[i - 1][1]) + 1; + } + } + return f[n - 1][2]; + } } \ No newline at end of file diff --git "a/lcp/LCP 19. \347\247\213\345\217\266\346\224\266\350\227\217\351\233\206/Solution.py" "b/lcp/LCP 19. \347\247\213\345\217\266\346\224\266\350\227\217\351\233\206/Solution.py" index b65618e95090c..74d74893451b5 100644 --- "a/lcp/LCP 19. \347\247\213\345\217\266\346\224\266\350\227\217\351\233\206/Solution.py" +++ "b/lcp/LCP 19. \347\247\213\345\217\266\346\224\266\350\227\217\351\233\206/Solution.py" @@ -1,15 +1,15 @@ -class Solution: - def minimumOperations(self, leaves: str) -> int: - n = len(leaves) - f = [[inf] * 3 for _ in range(n)] - f[0][0] = int(leaves[0] == "y") - for i in range(1, n): - if leaves[i] == "r": - f[i][0] = f[i - 1][0] - f[i][1] = min(f[i - 1][0], f[i - 1][1]) + 1 - f[i][2] = min(f[i - 1][2], f[i - 1][1]) - else: - f[i][0] = f[i - 1][0] + 1 - f[i][1] = min(f[i - 1][0], f[i - 1][1]) - f[i][2] = min(f[i - 1][2], f[i - 1][1]) + 1 - return f[n - 1][2] +class Solution: + def minimumOperations(self, leaves: str) -> int: + n = len(leaves) + f = [[inf] * 3 for _ in range(n)] + f[0][0] = int(leaves[0] == "y") + for i in range(1, n): + if leaves[i] == "r": + f[i][0] = f[i - 1][0] + f[i][1] = min(f[i - 1][0], f[i - 1][1]) + 1 + f[i][2] = min(f[i - 1][2], f[i - 1][1]) + else: + f[i][0] = f[i - 1][0] + 1 + f[i][1] = min(f[i - 1][0], f[i - 1][1]) + f[i][2] = min(f[i - 1][2], f[i - 1][1]) + 1 + return f[n - 1][2] diff --git "a/lcp/LCP 22. \351\273\221\347\231\275\346\226\271\346\240\274\347\224\273/Solution.cpp" "b/lcp/LCP 22. \351\273\221\347\231\275\346\226\271\346\240\274\347\224\273/Solution.cpp" index 45213798f14df..6684c793dc6df 100644 --- "a/lcp/LCP 22. \351\273\221\347\231\275\346\226\271\346\240\274\347\224\273/Solution.cpp" +++ "b/lcp/LCP 22. \351\273\221\347\231\275\346\226\271\346\240\274\347\224\273/Solution.cpp" @@ -1,25 +1,25 @@ -class Solution { -public: - int paintingPlan(int n, int k) { - if (k == n * n) { - return 1; - } - int c[n + 1][n + 1]; - memset(c, 0, sizeof(c)); - for (int i = 0; i <= n; ++i) { - c[i][0] = 1; - for (int j = 1; j <= i; ++j) { - c[i][j] = c[i - 1][j - 1] + c[i - 1][j]; - } - } - int ans = 0; - for (int i = 0; i <= n; ++i) { - for (int j = 0; j <= n; ++j) { - if (n * (i + j) - i * j == k) { - ans += c[n][i] * c[n][j]; - } - } - } - return ans; - } +class Solution { +public: + int paintingPlan(int n, int k) { + if (k == n * n) { + return 1; + } + int c[n + 1][n + 1]; + memset(c, 0, sizeof(c)); + for (int i = 0; i <= n; ++i) { + c[i][0] = 1; + for (int j = 1; j <= i; ++j) { + c[i][j] = c[i - 1][j - 1] + c[i - 1][j]; + } + } + int ans = 0; + for (int i = 0; i <= n; ++i) { + for (int j = 0; j <= n; ++j) { + if (n * (i + j) - i * j == k) { + ans += c[n][i] * c[n][j]; + } + } + } + return ans; + } }; \ No newline at end of file diff --git "a/lcp/LCP 22. \351\273\221\347\231\275\346\226\271\346\240\274\347\224\273/Solution.java" "b/lcp/LCP 22. \351\273\221\347\231\275\346\226\271\346\240\274\347\224\273/Solution.java" index 17e1ec7d119c3..195ab66376abd 100644 --- "a/lcp/LCP 22. \351\273\221\347\231\275\346\226\271\346\240\274\347\224\273/Solution.java" +++ "b/lcp/LCP 22. \351\273\221\347\231\275\346\226\271\346\240\274\347\224\273/Solution.java" @@ -1,23 +1,23 @@ -class Solution { - public int paintingPlan(int n, int k) { - if (k == n * n) { - return 1; - } - int[][] c = new int[n + 1][n + 1]; - for (int i = 0; i <= n; ++i) { - c[i][0] = 1; - for (int j = 1; j <= i; ++j) { - c[i][j] = c[i - 1][j - 1] + c[i - 1][j]; - } - } - int ans = 0; - for (int i = 0; i <= n; ++i) { - for (int j = 0; j <= n; ++j) { - if (n * (i + j) - i * j == k) { - ans += c[n][i] * c[n][j]; - } - } - } - return ans; - } +class Solution { + public int paintingPlan(int n, int k) { + if (k == n * n) { + return 1; + } + int[][] c = new int[n + 1][n + 1]; + for (int i = 0; i <= n; ++i) { + c[i][0] = 1; + for (int j = 1; j <= i; ++j) { + c[i][j] = c[i - 1][j - 1] + c[i - 1][j]; + } + } + int ans = 0; + for (int i = 0; i <= n; ++i) { + for (int j = 0; j <= n; ++j) { + if (n * (i + j) - i * j == k) { + ans += c[n][i] * c[n][j]; + } + } + } + return ans; + } } \ No newline at end of file diff --git "a/lcp/LCP 22. \351\273\221\347\231\275\346\226\271\346\240\274\347\224\273/Solution.py" "b/lcp/LCP 22. \351\273\221\347\231\275\346\226\271\346\240\274\347\224\273/Solution.py" index 41df5516f6da7..ffb24a4b2b6fd 100644 --- "a/lcp/LCP 22. \351\273\221\347\231\275\346\226\271\346\240\274\347\224\273/Solution.py" +++ "b/lcp/LCP 22. \351\273\221\347\231\275\346\226\271\346\240\274\347\224\273/Solution.py" @@ -1,10 +1,10 @@ -class Solution: - def paintingPlan(self, n: int, k: int) -> int: - if k == n * n: - return 1 - ans = 0 - for i in range(n + 1): - for j in range(n + 1): - if n * (i + j) - i * j == k: - ans += comb(n, i) * comb(n, j) - return ans +class Solution: + def paintingPlan(self, n: int, k: int) -> int: + if k == n * n: + return 1 + ans = 0 + for i in range(n + 1): + for j in range(n + 1): + if n * (i + j) - i * j == k: + ans += comb(n, i) * comb(n, j) + return ans diff --git "a/lcp/LCP 28. \351\207\207\350\264\255\346\226\271\346\241\210/Solution.java" "b/lcp/LCP 28. \351\207\207\350\264\255\346\226\271\346\241\210/Solution.java" index cfed4dbb7eef8..29020571194d9 100644 --- "a/lcp/LCP 28. \351\207\207\350\264\255\346\226\271\346\241\210/Solution.java" +++ "b/lcp/LCP 28. \351\207\207\350\264\255\346\226\271\346\241\210/Solution.java" @@ -10,6 +10,6 @@ public int purchasePlans(int[] nums, int target) { res = (res + j - i) % mod; } } - return res % mod; + return res; } } \ No newline at end of file diff --git "a/lcp/LCP 33. \350\223\204\346\260\264/Solution.ts" "b/lcp/LCP 33. \350\223\204\346\260\264/Solution.ts" new file mode 100644 index 0000000000000..69fd687937140 --- /dev/null +++ "b/lcp/LCP 33. \350\223\204\346\260\264/Solution.ts" @@ -0,0 +1,16 @@ +function storeWater(bucket: number[], vat: number[]): number { + const mx = Math.max(...vat); + if (mx === 0) { + return 0; + } + const n = vat.length; + let ans = 1 << 30; + for (let x = 1; x <= mx; ++x) { + let y = 0; + for (let i = 0; i < n; ++i) { + y += Math.max(0, Math.ceil(vat[i] / x) - bucket[i]); + } + ans = Math.min(ans, x + y); + } + return ans; +} diff --git "a/lcp/LCP 39. \346\227\240\344\272\272\346\234\272\346\226\271\351\230\265/Solution.cpp" "b/lcp/LCP 39. \346\227\240\344\272\272\346\234\272\346\226\271\351\230\265/Solution.cpp" index 256d0586dcca4..5953aedb885fc 100644 --- "a/lcp/LCP 39. \346\227\240\344\272\272\346\234\272\346\226\271\351\230\265/Solution.cpp" +++ "b/lcp/LCP 39. \346\227\240\344\272\272\346\234\272\346\226\271\351\230\265/Solution.cpp" @@ -1,21 +1,21 @@ -class Solution { -public: - int minimumSwitchingTimes(vector>& source, vector>& target) { - unordered_map cnt; - for (auto& row : source) { - for (int& x : row) { - ++cnt[x]; - } - } - for (auto& row : target) { - for (int& x : row) { - --cnt[x]; - } - } - int ans = 0; - for (auto& [_, v] : cnt) { - ans += abs(v); - } - return ans / 2; - } +class Solution { +public: + int minimumSwitchingTimes(vector>& source, vector>& target) { + unordered_map cnt; + for (auto& row : source) { + for (int& x : row) { + ++cnt[x]; + } + } + for (auto& row : target) { + for (int& x : row) { + --cnt[x]; + } + } + int ans = 0; + for (auto& [_, v] : cnt) { + ans += abs(v); + } + return ans / 2; + } }; \ No newline at end of file diff --git "a/lcp/LCP 39. \346\227\240\344\272\272\346\234\272\346\226\271\351\230\265/Solution.java" "b/lcp/LCP 39. \346\227\240\344\272\272\346\234\272\346\226\271\351\230\265/Solution.java" index 67f856de120e0..361871d7163d5 100644 --- "a/lcp/LCP 39. \346\227\240\344\272\272\346\234\272\346\226\271\351\230\265/Solution.java" +++ "b/lcp/LCP 39. \346\227\240\344\272\272\346\234\272\346\226\271\351\230\265/Solution.java" @@ -1,20 +1,20 @@ -class Solution { - public int minimumSwitchingTimes(int[][] source, int[][] target) { - Map cnt = new HashMap<>(); - for (int[] row : source) { - for (int x : row) { - cnt.merge(x, 1, Integer::sum); - } - } - for (int[] row : target) { - for (int x : row) { - cnt.merge(x, -1, Integer::sum); - } - } - int ans = 0; - for (int v : cnt.values()) { - ans += Math.abs(v); - } - return ans / 2; - } +class Solution { + public int minimumSwitchingTimes(int[][] source, int[][] target) { + Map cnt = new HashMap<>(); + for (int[] row : source) { + for (int x : row) { + cnt.merge(x, 1, Integer::sum); + } + } + for (int[] row : target) { + for (int x : row) { + cnt.merge(x, -1, Integer::sum); + } + } + int ans = 0; + for (int v : cnt.values()) { + ans += Math.abs(v); + } + return ans / 2; + } } \ No newline at end of file diff --git "a/lcp/LCP 39. \346\227\240\344\272\272\346\234\272\346\226\271\351\230\265/Solution.py" "b/lcp/LCP 39. \346\227\240\344\272\272\346\234\272\346\226\271\351\230\265/Solution.py" index c6fc9d2736bdb..ddac978dc8243 100644 --- "a/lcp/LCP 39. \346\227\240\344\272\272\346\234\272\346\226\271\351\230\265/Solution.py" +++ "b/lcp/LCP 39. \346\227\240\344\272\272\346\234\272\346\226\271\351\230\265/Solution.py" @@ -1,12 +1,12 @@ -class Solution: - def minimumSwitchingTimes( - self, source: List[List[int]], target: List[List[int]] - ) -> int: - cnt = Counter() - for row in source: - for x in row: - cnt[x] += 1 - for row in target: - for x in row: - cnt[x] -= 1 - return sum(abs(x) for x in cnt.values()) // 2 +class Solution: + def minimumSwitchingTimes( + self, source: List[List[int]], target: List[List[int]] + ) -> int: + cnt = Counter() + for row in source: + for x in row: + cnt[x] += 1 + for row in target: + for x in row: + cnt[x] -= 1 + return sum(abs(x) for x in cnt.values()) // 2 diff --git "a/lcp/LCP 41. \351\273\221\347\231\275\347\277\273\350\275\254\346\243\213/Solution.cpp" "b/lcp/LCP 41. \351\273\221\347\231\275\347\277\273\350\275\254\346\243\213/Solution.cpp" index 0f6c839a265cc..e100772ea2d56 100644 --- "a/lcp/LCP 41. \351\273\221\347\231\275\347\277\273\350\275\254\346\243\213/Solution.cpp" +++ "b/lcp/LCP 41. \351\273\221\347\231\275\347\277\273\350\275\254\346\243\213/Solution.cpp" @@ -1,54 +1,54 @@ -class Solution { -public: - int flipChess(vector& chessboard) { - int m = chessboard.size(); - int n = chessboard[0].size(); - auto bfs = [&](int i, int j) -> int { - queue> q; - q.emplace(i, j); - auto g = chessboard; - g[i][j] = 'X'; - int cnt = 0; - while (q.size()) { - auto p = q.front(); - q.pop(); - i = p.first; - j = p.second; - for (int a = -1; a <= 1; ++a) { - for (int b = -1; b <= 1; ++b) { - if (a == 0 && b == 0) { - continue; - } - int x = i + a, y = j + b; - while (x >= 0 && x < m && y >= 0 && y < n && g[x][y] == 'O') { - x += a; - y += b; - } - if (x >= 0 && x < m && y >= 0 && y < n && g[x][y] == 'X') { - x -= a; - y -= b; - cnt += max(abs(x - i), abs(y - j)); - while (x != i || y != j) { - g[x][y] = 'X'; - q.emplace(x, y); - x -= a; - y -= b; - } - } - } - } - } - return cnt; - }; - - int ans = 0; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (chessboard[i][j] == '.') { - ans = max(ans, bfs(i, j)); - } - } - } - return ans; - } +class Solution { +public: + int flipChess(vector& chessboard) { + int m = chessboard.size(); + int n = chessboard[0].size(); + auto bfs = [&](int i, int j) -> int { + queue> q; + q.emplace(i, j); + auto g = chessboard; + g[i][j] = 'X'; + int cnt = 0; + while (q.size()) { + auto p = q.front(); + q.pop(); + i = p.first; + j = p.second; + for (int a = -1; a <= 1; ++a) { + for (int b = -1; b <= 1; ++b) { + if (a == 0 && b == 0) { + continue; + } + int x = i + a, y = j + b; + while (x >= 0 && x < m && y >= 0 && y < n && g[x][y] == 'O') { + x += a; + y += b; + } + if (x >= 0 && x < m && y >= 0 && y < n && g[x][y] == 'X') { + x -= a; + y -= b; + cnt += max(abs(x - i), abs(y - j)); + while (x != i || y != j) { + g[x][y] = 'X'; + q.emplace(x, y); + x -= a; + y -= b; + } + } + } + } + } + return cnt; + }; + + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (chessboard[i][j] == '.') { + ans = max(ans, bfs(i, j)); + } + } + } + return ans; + } }; \ No newline at end of file diff --git "a/lcp/LCP 41. \351\273\221\347\231\275\347\277\273\350\275\254\346\243\213/Solution.java" "b/lcp/LCP 41. \351\273\221\347\231\275\347\277\273\350\275\254\346\243\213/Solution.java" index be01131f01928..4307e7e5e232c 100644 --- "a/lcp/LCP 41. \351\273\221\347\231\275\347\277\273\350\275\254\346\243\213/Solution.java" +++ "b/lcp/LCP 41. \351\273\221\347\231\275\347\277\273\350\275\254\346\243\213/Solution.java" @@ -1,60 +1,60 @@ -class Solution { - private int m; - private int n; - private String[] chessboard; - - public int flipChess(String[] chessboard) { - m = chessboard.length; - n = chessboard[0].length(); - this.chessboard = chessboard; - int ans = 0; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (chessboard[i].charAt(j) == '.') { - ans = Math.max(ans, bfs(i, j)); - } - } - } - return ans; - } - - private int bfs(int i, int j) { - Deque q = new ArrayDeque<>(); - q.offer(new int[] {i, j}); - char[][] g = new char[m][0]; - for (int k = 0; k < m; ++k) { - g[k] = chessboard[k].toCharArray(); - } - g[i][j] = 'X'; - int cnt = 0; - while (!q.isEmpty()) { - var p = q.poll(); - i = p[0]; - j = p[1]; - for (int a = -1; a <= 1; ++a) { - for (int b = -1; b <= 1; ++b) { - if (a == 0 && b == 0) { - continue; - } - int x = i + a, y = j + b; - while (x >= 0 && x < m && y >= 0 && y < n && g[x][y] == 'O') { - x += a; - y += b; - } - if (x >= 0 && x < m && y >= 0 && y < n && g[x][y] == 'X') { - x -= a; - y -= b; - cnt += Math.max(Math.abs(x - i), Math.abs(y - j)); - while (x != i || y != j) { - g[x][y] = 'X'; - q.offer(new int[] {x, y}); - x -= a; - y -= b; - } - } - } - } - } - return cnt; - } +class Solution { + private int m; + private int n; + private String[] chessboard; + + public int flipChess(String[] chessboard) { + m = chessboard.length; + n = chessboard[0].length(); + this.chessboard = chessboard; + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (chessboard[i].charAt(j) == '.') { + ans = Math.max(ans, bfs(i, j)); + } + } + } + return ans; + } + + private int bfs(int i, int j) { + Deque q = new ArrayDeque<>(); + q.offer(new int[] {i, j}); + char[][] g = new char[m][0]; + for (int k = 0; k < m; ++k) { + g[k] = chessboard[k].toCharArray(); + } + g[i][j] = 'X'; + int cnt = 0; + while (!q.isEmpty()) { + var p = q.poll(); + i = p[0]; + j = p[1]; + for (int a = -1; a <= 1; ++a) { + for (int b = -1; b <= 1; ++b) { + if (a == 0 && b == 0) { + continue; + } + int x = i + a, y = j + b; + while (x >= 0 && x < m && y >= 0 && y < n && g[x][y] == 'O') { + x += a; + y += b; + } + if (x >= 0 && x < m && y >= 0 && y < n && g[x][y] == 'X') { + x -= a; + y -= b; + cnt += Math.max(Math.abs(x - i), Math.abs(y - j)); + while (x != i || y != j) { + g[x][y] = 'X'; + q.offer(new int[] {x, y}); + x -= a; + y -= b; + } + } + } + } + } + return cnt; + } } \ No newline at end of file diff --git "a/lcp/LCP 41. \351\273\221\347\231\275\347\277\273\350\275\254\346\243\213/Solution.py" "b/lcp/LCP 41. \351\273\221\347\231\275\347\277\273\350\275\254\346\243\213/Solution.py" index 04b16624b792e..dc81410f7b47c 100644 --- "a/lcp/LCP 41. \351\273\221\347\231\275\347\277\273\350\275\254\346\243\213/Solution.py" +++ "b/lcp/LCP 41. \351\273\221\347\231\275\347\277\273\350\275\254\346\243\213/Solution.py" @@ -1,27 +1,27 @@ -class Solution: - def flipChess(self, chessboard: List[str]) -> int: - def bfs(i: int, j: int) -> int: - q = deque([(i, j)]) - g = [list(row) for row in chessboard] - g[i][j] = "X" - cnt = 0 - while q: - i, j = q.popleft() - for a, b in dirs: - x, y = i + a, j + b - while 0 <= x < m and 0 <= y < n and g[x][y] == "O": - x, y = x + a, y + b - if 0 <= x < m and 0 <= y < n and g[x][y] == "X": - x, y = x - a, y - b - cnt += max(abs(x - i), abs(y - j)) - while x != i or y != j: - g[x][y] = "X" - q.append((x, y)) - x, y = x - a, y - b - return cnt - - m, n = len(chessboard), len(chessboard[0]) - dirs = [(a, b) for a in range(-1, 2) for b in range(-1, 2) if a != 0 or b != 0] - return max( - bfs(i, j) for i in range(m) for j in range(n) if chessboard[i][j] == "." - ) +class Solution: + def flipChess(self, chessboard: List[str]) -> int: + def bfs(i: int, j: int) -> int: + q = deque([(i, j)]) + g = [list(row) for row in chessboard] + g[i][j] = "X" + cnt = 0 + while q: + i, j = q.popleft() + for a, b in dirs: + x, y = i + a, j + b + while 0 <= x < m and 0 <= y < n and g[x][y] == "O": + x, y = x + a, y + b + if 0 <= x < m and 0 <= y < n and g[x][y] == "X": + x, y = x - a, y - b + cnt += max(abs(x - i), abs(y - j)) + while x != i or y != j: + g[x][y] = "X" + q.append((x, y)) + x, y = x - a, y - b + return cnt + + m, n = len(chessboard), len(chessboard[0]) + dirs = [(a, b) for a in range(-1, 2) for b in range(-1, 2) if a != 0 or b != 0] + return max( + bfs(i, j) for i in range(m) for j in range(n) if chessboard[i][j] == "." + ) diff --git "a/lcp/LCP 50. \345\256\235\347\237\263\350\241\245\347\273\231/Solution.cpp" "b/lcp/LCP 50. \345\256\235\347\237\263\350\241\245\347\273\231/Solution.cpp" index b44465d101468..afc9cd39a617c 100644 --- "a/lcp/LCP 50. \345\256\235\347\237\263\350\241\245\347\273\231/Solution.cpp" +++ "b/lcp/LCP 50. \345\256\235\347\237\263\350\241\245\347\273\231/Solution.cpp" @@ -1,14 +1,14 @@ -class Solution { -public: - int giveGem(vector& gem, vector>& operations) { - for (auto& op : operations) { - int x = op[0], y = op[1]; - int v = gem[x] >> 1; - gem[y] += v; - gem[x] -= v; - } - int mx = *max_element(gem.begin(), gem.end()); - int mi = *min_element(gem.begin(), gem.end()); - return mx - mi; - } +class Solution { +public: + int giveGem(vector& gem, vector>& operations) { + for (auto& op : operations) { + int x = op[0], y = op[1]; + int v = gem[x] >> 1; + gem[y] += v; + gem[x] -= v; + } + int mx = *max_element(gem.begin(), gem.end()); + int mi = *min_element(gem.begin(), gem.end()); + return mx - mi; + } }; \ No newline at end of file diff --git "a/lcp/LCP 50. \345\256\235\347\237\263\350\241\245\347\273\231/Solution.java" "b/lcp/LCP 50. \345\256\235\347\237\263\350\241\245\347\273\231/Solution.java" index c524687874de7..bf881d2a2caaa 100644 --- "a/lcp/LCP 50. \345\256\235\347\237\263\350\241\245\347\273\231/Solution.java" +++ "b/lcp/LCP 50. \345\256\235\347\237\263\350\241\245\347\273\231/Solution.java" @@ -1,16 +1,16 @@ -class Solution { - public int giveGem(int[] gem, int[][] operations) { - for (var op : operations) { - int x = op[0], y = op[1]; - int v = gem[x] >> 1; - gem[y] += v; - gem[x] -= v; - } - int mx = 0, mi = 1 << 30; - for (int x : gem) { - mx = Math.max(mx, x); - mi = Math.min(mi, x); - } - return mx - mi; - } +class Solution { + public int giveGem(int[] gem, int[][] operations) { + for (var op : operations) { + int x = op[0], y = op[1]; + int v = gem[x] >> 1; + gem[y] += v; + gem[x] -= v; + } + int mx = 0, mi = 1 << 30; + for (int x : gem) { + mx = Math.max(mx, x); + mi = Math.min(mi, x); + } + return mx - mi; + } } \ No newline at end of file diff --git "a/lcp/LCP 50. \345\256\235\347\237\263\350\241\245\347\273\231/Solution.py" "b/lcp/LCP 50. \345\256\235\347\237\263\350\241\245\347\273\231/Solution.py" index 3e74939f83402..95fb005503e39 100644 --- "a/lcp/LCP 50. \345\256\235\347\237\263\350\241\245\347\273\231/Solution.py" +++ "b/lcp/LCP 50. \345\256\235\347\237\263\350\241\245\347\273\231/Solution.py" @@ -1,7 +1,7 @@ -class Solution: - def giveGem(self, gem: List[int], operations: List[List[int]]) -> int: - for x, y in operations: - v = gem[x] >> 1 - gem[y] += v - gem[x] -= v - return max(gem) - min(gem) +class Solution: + def giveGem(self, gem: List[int], operations: List[List[int]]) -> int: + for x, y in operations: + v = gem[x] >> 1 + gem[y] += v + gem[x] -= v + return max(gem) - min(gem) diff --git "a/lcp/LCP 51. \347\203\271\351\245\252\346\226\231\347\220\206/Solution.cpp" "b/lcp/LCP 51. \347\203\271\351\245\252\346\226\231\347\220\206/Solution.cpp" index d95efc74c8028..57ecaa1ac550c 100644 --- "a/lcp/LCP 51. \347\203\271\351\245\252\346\226\231\347\220\206/Solution.cpp" +++ "b/lcp/LCP 51. \347\203\271\351\245\252\346\226\231\347\220\206/Solution.cpp" @@ -1,30 +1,30 @@ -class Solution { -public: - int perfectMenu(vector& materials, vector>& cookbooks, vector>& attribute, int limit) { - int n = cookbooks.size(); - int ans = -1; - for (int mask = 0; mask < 1 << n; ++mask) { - int a = 0, b = 0; - vector cnt(5); - for (int i = 0; i < n; ++i) { - if (mask >> i & 1) { - int x = attribute[i][0]; - int y = attribute[i][1]; - a += x; - b += y; - for (int j = 0; j < cookbooks[i].size(); ++j) { - cnt[j] += cookbooks[i][j]; - } - } - bool ok = true; - for (int i = 0; i < 5 && ok; ++i) { - ok = cnt[i] <= materials[i]; - } - if (b >= limit && ans < a && ok) { - ans = a; - } - } - } - return ans; - } +class Solution { +public: + int perfectMenu(vector& materials, vector>& cookbooks, vector>& attribute, int limit) { + int n = cookbooks.size(); + int ans = -1; + for (int mask = 0; mask < 1 << n; ++mask) { + int a = 0, b = 0; + vector cnt(5); + for (int i = 0; i < n; ++i) { + if (mask >> i & 1) { + int x = attribute[i][0]; + int y = attribute[i][1]; + a += x; + b += y; + for (int j = 0; j < cookbooks[i].size(); ++j) { + cnt[j] += cookbooks[i][j]; + } + } + bool ok = true; + for (int i = 0; i < 5 && ok; ++i) { + ok = cnt[i] <= materials[i]; + } + if (b >= limit && ans < a && ok) { + ans = a; + } + } + } + return ans; + } }; \ No newline at end of file diff --git "a/lcp/LCP 51. \347\203\271\351\245\252\346\226\231\347\220\206/Solution.java" "b/lcp/LCP 51. \347\203\271\351\245\252\346\226\231\347\220\206/Solution.java" index 78448a4541662..a2474302efc06 100644 --- "a/lcp/LCP 51. \347\203\271\351\245\252\346\226\231\347\220\206/Solution.java" +++ "b/lcp/LCP 51. \347\203\271\351\245\252\346\226\231\347\220\206/Solution.java" @@ -1,29 +1,29 @@ -class Solution { - public int perfectMenu(int[] materials, int[][] cookbooks, int[][] attribute, int limit) { - int n = cookbooks.length; - int ans = -1; - for (int mask = 0; mask < 1 << n; ++mask) { - int a = 0, b = 0; - int[] cnt = new int[5]; - for (int i = 0; i < n; ++i) { - if ((mask >> i & 1) == 1) { - int x = attribute[i][0]; - int y = attribute[i][1]; - a += x; - b += y; - for (int j = 0; j < cookbooks[i].length; ++j) { - cnt[j] += cookbooks[i][j]; - } - } - } - boolean ok = true; - for (int i = 0; i < 5 && ok; ++i) { - ok = cnt[i] <= materials[i]; - } - if (b >= limit && ans < a && ok) { - ans = a; - } - } - return ans; - } +class Solution { + public int perfectMenu(int[] materials, int[][] cookbooks, int[][] attribute, int limit) { + int n = cookbooks.length; + int ans = -1; + for (int mask = 0; mask < 1 << n; ++mask) { + int a = 0, b = 0; + int[] cnt = new int[5]; + for (int i = 0; i < n; ++i) { + if ((mask >> i & 1) == 1) { + int x = attribute[i][0]; + int y = attribute[i][1]; + a += x; + b += y; + for (int j = 0; j < cookbooks[i].length; ++j) { + cnt[j] += cookbooks[i][j]; + } + } + } + boolean ok = true; + for (int i = 0; i < 5 && ok; ++i) { + ok = cnt[i] <= materials[i]; + } + if (b >= limit && ans < a && ok) { + ans = a; + } + } + return ans; + } } \ No newline at end of file diff --git "a/lcp/LCP 51. \347\203\271\351\245\252\346\226\231\347\220\206/Solution.py" "b/lcp/LCP 51. \347\203\271\351\245\252\346\226\231\347\220\206/Solution.py" index fb42fbb2d3f6f..cff8317115ccc 100644 --- "a/lcp/LCP 51. \347\203\271\351\245\252\346\226\231\347\220\206/Solution.py" +++ "b/lcp/LCP 51. \347\203\271\351\245\252\346\226\231\347\220\206/Solution.py" @@ -1,23 +1,23 @@ -class Solution: - def perfectMenu( - self, - materials: List[int], - cookbooks: List[List[int]], - attribute: List[List[int]], - limit: int, - ) -> int: - n = len(cookbooks) - ans = -1 - for mask in range(1 << n): - a = b = 0 - cnt = [0] * 5 - for i in range(n): - if mask >> i & 1: - x, y = attribute[i] - a += x - b += y - for j, v in enumerate(cookbooks[i]): - cnt[j] += v - if b >= limit and ans < a and all(c <= d for c, d in zip(cnt, materials)): - ans = a - return ans +class Solution: + def perfectMenu( + self, + materials: List[int], + cookbooks: List[List[int]], + attribute: List[List[int]], + limit: int, + ) -> int: + n = len(cookbooks) + ans = -1 + for mask in range(1 << n): + a = b = 0 + cnt = [0] * 5 + for i in range(n): + if mask >> i & 1: + x, y = attribute[i] + a += x + b += y + for j, v in enumerate(cookbooks[i]): + cnt[j] += v + if b >= limit and ans < a and all(c <= d for c, d in zip(cnt, materials)): + ans = a + return ans diff --git "a/lcp/LCP 52. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\346\237\223\350\211\262/Solution.cpp" "b/lcp/LCP 52. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\346\237\223\350\211\262/Solution.cpp" index ea5dc16578ccc..419b545f64f58 100644 --- "a/lcp/LCP 52. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\346\237\223\350\211\262/Solution.cpp" +++ "b/lcp/LCP 52. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\346\237\223\350\211\262/Solution.cpp" @@ -1,35 +1,35 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - int getNumber(TreeNode* root, vector>& ops) { - set ts; - function dfs = [&](TreeNode* root) { - if (root == nullptr) { - return; - } - ts.insert(root->val); - dfs(root->left); - dfs(root->right); - }; - dfs(root); - int ans = 0; - for (int i = ops.size() - 1; ~i; --i) { - int t = ops[i][0]; - int x = ops[i][1], y = ops[i][2]; - auto it = ts.lower_bound(x); - while (it != ts.end() && *it <= y) { - ts.erase(it++); - ans += t; - } - } - return ans; - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + int getNumber(TreeNode* root, vector>& ops) { + set ts; + function dfs = [&](TreeNode* root) { + if (root == nullptr) { + return; + } + ts.insert(root->val); + dfs(root->left); + dfs(root->right); + }; + dfs(root); + int ans = 0; + for (int i = ops.size() - 1; ~i; --i) { + int t = ops[i][0]; + int x = ops[i][1], y = ops[i][2]; + auto it = ts.lower_bound(x); + while (it != ts.end() && *it <= y) { + ts.erase(it++); + ans += t; + } + } + return ans; + } }; \ No newline at end of file diff --git "a/lcp/LCP 52. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\346\237\223\350\211\262/Solution.java" "b/lcp/LCP 52. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\346\237\223\350\211\262/Solution.java" index 000dd366b35c4..ba7ed208560b6 100644 --- "a/lcp/LCP 52. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\346\237\223\350\211\262/Solution.java" +++ "b/lcp/LCP 52. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\346\237\223\350\211\262/Solution.java" @@ -1,37 +1,37 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -class Solution { - private TreeSet ts = new TreeSet<>(); - - public int getNumber(TreeNode root, int[][] ops) { - dfs(root); - int ans = 0; - for (int i = ops.length - 1; i >= 0; --i) { - int t = ops[i][0]; - int x = ops[i][1], y = ops[i][2]; - Integer ceiling = ts.ceiling(x); - while (ceiling != null && ceiling <= y) { - ts.remove(ceiling); - ceiling = ts.ceiling(x); - ans += t; - } - } - return ans; - } - - private void dfs(TreeNode root) { - if (root == null) { - return; - } - ts.add(root.val); - dfs(root.left); - dfs(root.right); - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + private TreeSet ts = new TreeSet<>(); + + public int getNumber(TreeNode root, int[][] ops) { + dfs(root); + int ans = 0; + for (int i = ops.length - 1; i >= 0; --i) { + int t = ops[i][0]; + int x = ops[i][1], y = ops[i][2]; + Integer ceiling = ts.ceiling(x); + while (ceiling != null && ceiling <= y) { + ts.remove(ceiling); + ceiling = ts.ceiling(x); + ans += t; + } + } + return ans; + } + + private void dfs(TreeNode root) { + if (root == null) { + return; + } + ts.add(root.val); + dfs(root.left); + dfs(root.right); + } } \ No newline at end of file diff --git "a/lcp/LCP 52. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\346\237\223\350\211\262/Solution.py" "b/lcp/LCP 52. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\346\237\223\350\211\262/Solution.py" index 00f3d0769c279..2e140bdb7fd66 100644 --- "a/lcp/LCP 52. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\346\237\223\350\211\262/Solution.py" +++ "b/lcp/LCP 52. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\346\237\223\350\211\262/Solution.py" @@ -1,28 +1,28 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None - -from sortedcontainers import SortedList - - -class Solution: - def getNumber(self, root: Optional[TreeNode], ops: List[List[int]]) -> int: - def dfs(root): - if root is None: - return - sl.add(root.val) - dfs(root.left) - dfs(root.right) - - sl = SortedList() - dfs(root) - ans = 0 - for t, x, y in ops[::-1]: - i = sl.bisect_left(x) - while i < len(sl) and sl[i] <= y: - sl.pop(i) - ans += t == 1 - return ans +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +from sortedcontainers import SortedList + + +class Solution: + def getNumber(self, root: Optional[TreeNode], ops: List[List[int]]) -> int: + def dfs(root): + if root is None: + return + sl.add(root.val) + dfs(root.left) + dfs(root.right) + + sl = SortedList() + dfs(root) + ans = 0 + for t, x, y in ops[::-1]: + i = sl.bisect_left(x) + while i < len(sl) and sl[i] <= y: + sl.pop(i) + ans += t == 1 + return ans diff --git "a/lcp/LCP 55. \351\207\207\351\233\206\346\236\234\345\256\236/Solution.cpp" "b/lcp/LCP 55. \351\207\207\351\233\206\346\236\234\345\256\236/Solution.cpp" index ffd5019a88c48..97741479d019b 100644 --- "a/lcp/LCP 55. \351\207\207\351\233\206\346\236\234\345\256\236/Solution.cpp" +++ "b/lcp/LCP 55. \351\207\207\351\233\206\346\236\234\345\256\236/Solution.cpp" @@ -1,11 +1,11 @@ -class Solution { -public: - int getMinimumTime(vector& time, vector>& fruits, int limit) { - int ans = 0; - for (auto& f : fruits) { - int i = f[0], num = f[1]; - ans += (num + limit - 1) / limit * time[i]; - } - return ans; - } +class Solution { +public: + int getMinimumTime(vector& time, vector>& fruits, int limit) { + int ans = 0; + for (auto& f : fruits) { + int i = f[0], num = f[1]; + ans += (num + limit - 1) / limit * time[i]; + } + return ans; + } }; \ No newline at end of file diff --git "a/lcp/LCP 55. \351\207\207\351\233\206\346\236\234\345\256\236/Solution.java" "b/lcp/LCP 55. \351\207\207\351\233\206\346\236\234\345\256\236/Solution.java" index f5affa73b1345..4d6edf1bab61e 100644 --- "a/lcp/LCP 55. \351\207\207\351\233\206\346\236\234\345\256\236/Solution.java" +++ "b/lcp/LCP 55. \351\207\207\351\233\206\346\236\234\345\256\236/Solution.java" @@ -1,10 +1,10 @@ -class Solution { - public int getMinimumTime(int[] time, int[][] fruits, int limit) { - int ans = 0; - for (int[] f : fruits) { - int i = f[0], num = f[1]; - ans += (num + limit - 1) / limit * time[i]; - } - return ans; - } +class Solution { + public int getMinimumTime(int[] time, int[][] fruits, int limit) { + int ans = 0; + for (int[] f : fruits) { + int i = f[0], num = f[1]; + ans += (num + limit - 1) / limit * time[i]; + } + return ans; + } } \ No newline at end of file diff --git "a/lcp/LCP 55. \351\207\207\351\233\206\346\236\234\345\256\236/Solution.py" "b/lcp/LCP 55. \351\207\207\351\233\206\346\236\234\345\256\236/Solution.py" index 25911d5077a26..8b9f1c66c4c1d 100644 --- "a/lcp/LCP 55. \351\207\207\351\233\206\346\236\234\345\256\236/Solution.py" +++ "b/lcp/LCP 55. \351\207\207\351\233\206\346\236\234\345\256\236/Solution.py" @@ -1,5 +1,5 @@ -class Solution: - def getMinimumTime( - self, time: List[int], fruits: List[List[int]], limit: int - ) -> int: - return sum((num + limit - 1) // limit * time[i] for i, num in fruits) +class Solution: + def getMinimumTime( + self, time: List[int], fruits: List[List[int]], limit: int + ) -> int: + return sum((num + limit - 1) // limit * time[i] for i, num in fruits) diff --git "a/lcp/LCP 56. \344\277\241\347\211\251\344\274\240\351\200\201/Solution.cpp" "b/lcp/LCP 56. \344\277\241\347\211\251\344\274\240\351\200\201/Solution.cpp" index 876c05895aeb0..87ea5efb12828 100644 --- "a/lcp/LCP 56. \344\277\241\347\211\251\344\274\240\351\200\201/Solution.cpp" +++ "b/lcp/LCP 56. \344\277\241\347\211\251\344\274\240\351\200\201/Solution.cpp" @@ -1,36 +1,36 @@ -class Solution { -public: - int conveyorBelt(vector& matrix, vector& start, vector& end) { - int dirs[5] = {-1, 0, 1, 0, -1}; - unordered_map d; - d['^'] = 0; - d['>'] = 1; - d['v'] = 2; - d['<'] = 3; - deque> q; - q.emplace_back(start[0], start[1]); - int m = matrix.size(), n = matrix[0].size(); - int dist[m][n]; - memset(dist, 0x3f, sizeof(dist)); - dist[start[0]][start[1]] = 0; - while (1) { - auto [i, j] = q.front(); - q.pop_front(); - if (i == end[0] && j == end[1]) { - return dist[i][j]; - } - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - int t = dist[i][j] + (k == d[matrix[i][j]] ? 0 : 1); - if (x >= 0 && x < m && y >= 0 && y < n && t < dist[x][y]) { - dist[x][y] = t; - if (dist[x][y] == dist[i][j]) { - q.emplace_front(x, y); - } else { - q.emplace_back(x, y); - } - } - } - } - } +class Solution { +public: + int conveyorBelt(vector& matrix, vector& start, vector& end) { + int dirs[5] = {-1, 0, 1, 0, -1}; + unordered_map d; + d['^'] = 0; + d['>'] = 1; + d['v'] = 2; + d['<'] = 3; + deque> q; + q.emplace_back(start[0], start[1]); + int m = matrix.size(), n = matrix[0].size(); + int dist[m][n]; + memset(dist, 0x3f, sizeof(dist)); + dist[start[0]][start[1]] = 0; + while (1) { + auto [i, j] = q.front(); + q.pop_front(); + if (i == end[0] && j == end[1]) { + return dist[i][j]; + } + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + int t = dist[i][j] + (k == d[matrix[i][j]] ? 0 : 1); + if (x >= 0 && x < m && y >= 0 && y < n && t < dist[x][y]) { + dist[x][y] = t; + if (dist[x][y] == dist[i][j]) { + q.emplace_front(x, y); + } else { + q.emplace_back(x, y); + } + } + } + } + } }; \ No newline at end of file diff --git "a/lcp/LCP 56. \344\277\241\347\211\251\344\274\240\351\200\201/Solution.java" "b/lcp/LCP 56. \344\277\241\347\211\251\344\274\240\351\200\201/Solution.java" index 6ad1471787000..0363fb2aaa095 100644 --- "a/lcp/LCP 56. \344\277\241\347\211\251\344\274\240\351\200\201/Solution.java" +++ "b/lcp/LCP 56. \344\277\241\347\211\251\344\274\240\351\200\201/Solution.java" @@ -1,37 +1,37 @@ -class Solution { - public int conveyorBelt(String[] matrix, int[] start, int[] end) { - int[] dirs = {-1, 0, 1, 0, -1}; - Map d = new HashMap<>(4); - d.put('^', 0); - d.put('>', 1); - d.put('v', 2); - d.put('<', 3); - Deque q = new ArrayDeque<>(); - q.offer(new int[] {start[0], start[1]}); - int m = matrix.length, n = matrix[0].length(); - int[][] dist = new int[m][n]; - for (int[] row : dist) { - Arrays.fill(row, 1 << 30); - } - dist[start[0]][start[1]] = 0; - while (true) { - int[] p = q.poll(); - int i = p[0], j = p[1]; - if (i == end[0] && j == end[1]) { - return dist[i][j]; - } - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - int t = dist[i][j] + (k == d.get(matrix[i].charAt(j)) ? 0 : 1); - if (x >= 0 && x < m && y >= 0 && y < n && t < dist[x][y]) { - dist[x][y] = t; - if (dist[x][y] == dist[i][j]) { - q.offerFirst(new int[] {x, y}); - } else { - q.offerLast(new int[] {x, y}); - } - } - } - } - } +class Solution { + public int conveyorBelt(String[] matrix, int[] start, int[] end) { + int[] dirs = {-1, 0, 1, 0, -1}; + Map d = new HashMap<>(4); + d.put('^', 0); + d.put('>', 1); + d.put('v', 2); + d.put('<', 3); + Deque q = new ArrayDeque<>(); + q.offer(new int[] {start[0], start[1]}); + int m = matrix.length, n = matrix[0].length(); + int[][] dist = new int[m][n]; + for (int[] row : dist) { + Arrays.fill(row, 1 << 30); + } + dist[start[0]][start[1]] = 0; + while (true) { + int[] p = q.poll(); + int i = p[0], j = p[1]; + if (i == end[0] && j == end[1]) { + return dist[i][j]; + } + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + int t = dist[i][j] + (k == d.get(matrix[i].charAt(j)) ? 0 : 1); + if (x >= 0 && x < m && y >= 0 && y < n && t < dist[x][y]) { + dist[x][y] = t; + if (dist[x][y] == dist[i][j]) { + q.offerFirst(new int[] {x, y}); + } else { + q.offerLast(new int[] {x, y}); + } + } + } + } + } } \ No newline at end of file diff --git "a/lcp/LCP 56. \344\277\241\347\211\251\344\274\240\351\200\201/Solution.py" "b/lcp/LCP 56. \344\277\241\347\211\251\344\274\240\351\200\201/Solution.py" index e71f0b0d8c55d..cfc90db24e5d7 100644 --- "a/lcp/LCP 56. \344\277\241\347\211\251\344\274\240\351\200\201/Solution.py" +++ "b/lcp/LCP 56. \344\277\241\347\211\251\344\274\240\351\200\201/Solution.py" @@ -1,22 +1,22 @@ -class Solution: - def conveyorBelt(self, matrix: List[str], start: List[int], end: List[int]) -> int: - dirs = (-1, 0, 1, 0, -1) - d = {"^": 0, "v": 2, "<": 3, ">": 1} - i, j = start - q = deque([(i, j)]) - m, n = len(matrix), len(matrix[0]) - dist = [[inf] * n for _ in range(m)] - dist[i][j] = 0 - while 1: - i, j = q.popleft() - if i == end[0] and j == end[1]: - return int(dist[i][j]) - for k in range(4): - x, y = i + dirs[k], j + dirs[k + 1] - t = dist[i][j] + int(k != d[matrix[i][j]]) - if 0 <= x < m and 0 <= y < n and t < dist[x][y]: - dist[x][y] = t - if dist[x][y] == dist[i][j]: - q.appendleft((x, y)) - else: - q.append((x, y)) +class Solution: + def conveyorBelt(self, matrix: List[str], start: List[int], end: List[int]) -> int: + dirs = (-1, 0, 1, 0, -1) + d = {"^": 0, "v": 2, "<": 3, ">": 1} + i, j = start + q = deque([(i, j)]) + m, n = len(matrix), len(matrix[0]) + dist = [[inf] * n for _ in range(m)] + dist[i][j] = 0 + while 1: + i, j = q.popleft() + if i == end[0] and j == end[1]: + return int(dist[i][j]) + for k in range(4): + x, y = i + dirs[k], j + dirs[k + 1] + t = dist[i][j] + int(k != d[matrix[i][j]]) + if 0 <= x < m and 0 <= y < n and t < dist[x][y]: + dist[x][y] = t + if dist[x][y] == dist[i][j]: + q.appendleft((x, y)) + else: + q.append((x, y)) diff --git "a/lcp/LCP 77. \347\254\246\346\226\207\345\202\250\345\244\207/Solution.cpp" "b/lcp/LCP 77. \347\254\246\346\226\207\345\202\250\345\244\207/Solution.cpp" index 1882c54a64740..396947d960a44 100644 --- "a/lcp/LCP 77. \347\254\246\346\226\207\345\202\250\345\244\207/Solution.cpp" +++ "b/lcp/LCP 77. \347\254\246\346\226\207\345\202\250\345\244\207/Solution.cpp" @@ -1,15 +1,15 @@ -class Solution { -public: - int runeReserve(vector& runes) { - sort(runes.begin(), runes.end()); - int ans = 0; - for (int i = 0, j = 0; j < runes.size(); ++j) { - if (j && runes[j] - runes[j - 1] > 1) { - i = j; - } else { - ans = max(ans, j - i + 1); - } - } - return ans; - } +class Solution { +public: + int runeReserve(vector& runes) { + sort(runes.begin(), runes.end()); + int ans = 0; + for (int i = 0, j = 0; j < runes.size(); ++j) { + if (j && runes[j] - runes[j - 1] > 1) { + i = j; + } else { + ans = max(ans, j - i + 1); + } + } + return ans; + } }; \ No newline at end of file diff --git "a/lcp/LCP 77. \347\254\246\346\226\207\345\202\250\345\244\207/Solution.java" "b/lcp/LCP 77. \347\254\246\346\226\207\345\202\250\345\244\207/Solution.java" index c59d32c06a8f7..ff4b8d5298f6e 100644 --- "a/lcp/LCP 77. \347\254\246\346\226\207\345\202\250\345\244\207/Solution.java" +++ "b/lcp/LCP 77. \347\254\246\346\226\207\345\202\250\345\244\207/Solution.java" @@ -1,14 +1,14 @@ -class Solution { - public int runeReserve(int[] runes) { - Arrays.sort(runes); - int ans = 0; - for (int i = 0, j = 0; j < runes.length; ++j) { - if (j > 0 && runes[j] - runes[j - 1] > 1) { - i = j; - } else { - ans = Math.max(ans, j - i + 1); - } - } - return ans; - } +class Solution { + public int runeReserve(int[] runes) { + Arrays.sort(runes); + int ans = 0; + for (int i = 0, j = 0; j < runes.length; ++j) { + if (j > 0 && runes[j] - runes[j - 1] > 1) { + i = j; + } else { + ans = Math.max(ans, j - i + 1); + } + } + return ans; + } } \ No newline at end of file diff --git "a/lcp/LCP 77. \347\254\246\346\226\207\345\202\250\345\244\207/Solution.py" "b/lcp/LCP 77. \347\254\246\346\226\207\345\202\250\345\244\207/Solution.py" index 66798a96cf6b2..df3115ee5bfa3 100644 --- "a/lcp/LCP 77. \347\254\246\346\226\207\345\202\250\345\244\207/Solution.py" +++ "b/lcp/LCP 77. \347\254\246\346\226\207\345\202\250\345\244\207/Solution.py" @@ -1,10 +1,10 @@ -class Solution: - def runeReserve(self, runes: List[int]) -> int: - runes.sort() - ans = i = 0 - for j, x in enumerate(runes): - if j and runes[j] - runes[j - 1] > 1: - i = j - else: - ans = max(ans, j - i + 1) - return ans +class Solution: + def runeReserve(self, runes: List[int]) -> int: + runes.sort() + ans = i = 0 + for j, x in enumerate(runes): + if j and runes[j] - runes[j - 1] > 1: + i = j + else: + ans = max(ans, j - i + 1) + return ans diff --git "a/lcp/LCP 78. \345\237\216\345\242\231\351\230\262\347\272\277/Solution.cpp" "b/lcp/LCP 78. \345\237\216\345\242\231\351\230\262\347\272\277/Solution.cpp" index 90cb86d7f0723..4c977266561eb 100644 --- "a/lcp/LCP 78. \345\237\216\345\242\231\351\230\262\347\272\277/Solution.cpp" +++ "b/lcp/LCP 78. \345\237\216\345\242\231\351\230\262\347\272\277/Solution.cpp" @@ -1,29 +1,29 @@ -class Solution { -public: - int rampartDefensiveLine(vector>& rampart) { - int left = 0, right = rampart[1][0] - rampart[0][1] + rampart[2][0] - rampart[1][1]; - auto check = [&](int w) { - int last = rampart[0][1]; - for (int i = 1; i < rampart.size() - 1; ++i) { - int x = rampart[i][0], y = rampart[i][1]; - int a = x - last; - int b = max(w - a, 0); - if (y + b > rampart[i + 1][0]) { - return false; - } - last = y + b; - } - return true; - }; - - while (left < right) { - int mid = (left + right + 1) >> 1; - if (check(mid)) { - left = mid; - } else { - right = mid - 1; - } - } - return left; - } +class Solution { +public: + int rampartDefensiveLine(vector>& rampart) { + int left = 0, right = rampart[1][0] - rampart[0][1] + rampart[2][0] - rampart[1][1]; + auto check = [&](int w) { + int last = rampart[0][1]; + for (int i = 1; i < rampart.size() - 1; ++i) { + int x = rampart[i][0], y = rampart[i][1]; + int a = x - last; + int b = max(w - a, 0); + if (y + b > rampart[i + 1][0]) { + return false; + } + last = y + b; + } + return true; + }; + + while (left < right) { + int mid = (left + right + 1) >> 1; + if (check(mid)) { + left = mid; + } else { + right = mid - 1; + } + } + return left; + } }; \ No newline at end of file diff --git "a/lcp/LCP 78. \345\237\216\345\242\231\351\230\262\347\272\277/Solution.java" "b/lcp/LCP 78. \345\237\216\345\242\231\351\230\262\347\272\277/Solution.java" index 9286f430f756e..a5cb1e0908896 100644 --- "a/lcp/LCP 78. \345\237\216\345\242\231\351\230\262\347\272\277/Solution.java" +++ "b/lcp/LCP 78. \345\237\216\345\242\231\351\230\262\347\272\277/Solution.java" @@ -1,31 +1,31 @@ -class Solution { - private int[][] rampart; - - public int rampartDefensiveLine(int[][] rampart) { - this.rampart = rampart; - int left = 0, right = rampart[1][0] - rampart[0][1] + rampart[2][0] - rampart[1][1]; - while (left < right) { - int mid = (left + right + 1) >> 1; - if (check(mid)) { - left = mid; - } else { - right = mid - 1; - } - } - return left; - } - - private boolean check(int w) { - int last = rampart[0][1]; - for (int i = 1; i < rampart.length - 1; ++i) { - int x = rampart[i][0], y = rampart[i][1]; - int a = x - last; - int b = Math.max(w - a, 0); - if (y + b > rampart[i + 1][0]) { - return false; - } - last = y + b; - } - return true; - } +class Solution { + private int[][] rampart; + + public int rampartDefensiveLine(int[][] rampart) { + this.rampart = rampart; + int left = 0, right = rampart[1][0] - rampart[0][1] + rampart[2][0] - rampart[1][1]; + while (left < right) { + int mid = (left + right + 1) >> 1; + if (check(mid)) { + left = mid; + } else { + right = mid - 1; + } + } + return left; + } + + private boolean check(int w) { + int last = rampart[0][1]; + for (int i = 1; i < rampart.length - 1; ++i) { + int x = rampart[i][0], y = rampart[i][1]; + int a = x - last; + int b = Math.max(w - a, 0); + if (y + b > rampart[i + 1][0]) { + return false; + } + last = y + b; + } + return true; + } } \ No newline at end of file diff --git "a/lcp/LCP 78. \345\237\216\345\242\231\351\230\262\347\272\277/Solution.py" "b/lcp/LCP 78. \345\237\216\345\242\231\351\230\262\347\272\277/Solution.py" index 4c9ed931a1389..30de140658787 100644 --- "a/lcp/LCP 78. \345\237\216\345\242\231\351\230\262\347\272\277/Solution.py" +++ "b/lcp/LCP 78. \345\237\216\345\242\231\351\230\262\347\272\277/Solution.py" @@ -1,21 +1,21 @@ -class Solution: - def rampartDefensiveLine(self, rampart: List[List[int]]) -> int: - def check(w: int) -> bool: - last = rampart[0][1] - for i in range(1, len(rampart) - 1): - x, y = rampart[i] - a = x - last - b = max(w - a, 0) - if y + b > rampart[i + 1][0]: - return False - last = y + b - return True - - left, right = 0, rampart[1][0] - rampart[0][1] + rampart[2][0] - rampart[1][1] - while left < right: - mid = (left + right + 1) >> 1 - if check(mid): - left = mid - else: - right = mid - 1 - return left +class Solution: + def rampartDefensiveLine(self, rampart: List[List[int]]) -> int: + def check(w: int) -> bool: + last = rampart[0][1] + for i in range(1, len(rampart) - 1): + x, y = rampart[i] + a = x - last + b = max(w - a, 0) + if y + b > rampart[i + 1][0]: + return False + last = y + b + return True + + left, right = 0, rampart[1][0] - rampart[0][1] + rampart[2][0] - rampart[1][1] + while left < right: + mid = (left + right + 1) >> 1 + if check(mid): + left = mid + else: + right = mid - 1 + return left diff --git "a/lcp/LCP 79. \346\217\220\345\217\226\345\222\222\346\226\207/Solution.cpp" "b/lcp/LCP 79. \346\217\220\345\217\226\345\222\222\346\226\207/Solution.cpp" index a4519f085e954..99bafcf049680 100644 --- "a/lcp/LCP 79. \346\217\220\345\217\226\345\222\222\346\226\207/Solution.cpp" +++ "b/lcp/LCP 79. \346\217\220\345\217\226\345\222\222\346\226\207/Solution.cpp" @@ -1,35 +1,35 @@ -class Solution { -public: - int extractMantra(vector& matrix, string mantra) { - int m = matrix.size(), n = matrix[0].size(); - int l = mantra.size(); - queue> q; - q.push({0, 0, 0}); - bool vis[m][n][l + 1]; - memset(vis, 0, sizeof(vis)); - int dirs[5] = {-1, 0, 1, 0, -1}; - int ans = 0; - for (; q.size(); ++ans) { - for (int size = q.size(); size; --size) { - auto [i, j, k] = q.front(); - q.pop(); - if (k == l) { - return ans; - } - if (matrix[i][j] == mantra[k] && !vis[i][j][k + 1]) { - vis[i][j][k + 1] = true; - q.push({i, j, k + 1}); - } else { - for (int c = 0; c < 4; ++c) { - int x = i + dirs[c], y = j + dirs[c + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y][k]) { - vis[x][y][k] = true; - q.push({x, y, k}); - } - } - } - } - } - return -1; - } +class Solution { +public: + int extractMantra(vector& matrix, string mantra) { + int m = matrix.size(), n = matrix[0].size(); + int l = mantra.size(); + queue> q; + q.push({0, 0, 0}); + bool vis[m][n][l + 1]; + memset(vis, 0, sizeof(vis)); + int dirs[5] = {-1, 0, 1, 0, -1}; + int ans = 0; + for (; q.size(); ++ans) { + for (int size = q.size(); size; --size) { + auto [i, j, k] = q.front(); + q.pop(); + if (k == l) { + return ans; + } + if (matrix[i][j] == mantra[k] && !vis[i][j][k + 1]) { + vis[i][j][k + 1] = true; + q.push({i, j, k + 1}); + } else { + for (int c = 0; c < 4; ++c) { + int x = i + dirs[c], y = j + dirs[c + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y][k]) { + vis[x][y][k] = true; + q.push({x, y, k}); + } + } + } + } + } + return -1; + } }; \ No newline at end of file diff --git "a/lcp/LCP 79. \346\217\220\345\217\226\345\222\222\346\226\207/Solution.java" "b/lcp/LCP 79. \346\217\220\345\217\226\345\222\222\346\226\207/Solution.java" index 43f61340a958b..708942c457248 100644 --- "a/lcp/LCP 79. \346\217\220\345\217\226\345\222\222\346\226\207/Solution.java" +++ "b/lcp/LCP 79. \346\217\220\345\217\226\345\222\222\346\226\207/Solution.java" @@ -1,34 +1,34 @@ -class Solution { - public int extractMantra(String[] matrix, String mantra) { - int m = matrix.length, n = matrix[0].length(); - int l = mantra.length(); - Deque q = new ArrayDeque<>(); - q.offer(new int[] {0, 0, 0}); - boolean[][][] vis = new boolean[m][n][l + 1]; - vis[0][0][0] = true; - int[] dirs = {-1, 0, 1, 0, -1}; - int ans = 0; - for (; !q.isEmpty(); ++ans) { - for (int size = q.size(); size > 0; --size) { - var p = q.poll(); - int i = p[0], j = p[1], k = p[2]; - if (k == l) { - return ans; - } - if (matrix[i].charAt(j) == mantra.charAt(k) && !vis[i][j][k + 1]) { - vis[i][j][k + 1] = true; - q.offer(new int[] {i, j, k + 1}); - } else { - for (int c = 0; c < 4; ++c) { - int x = i + dirs[c], y = j + dirs[c + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y][k]) { - vis[x][y][k] = true; - q.offer(new int[] {x, y, k}); - } - } - } - } - } - return -1; - } +class Solution { + public int extractMantra(String[] matrix, String mantra) { + int m = matrix.length, n = matrix[0].length(); + int l = mantra.length(); + Deque q = new ArrayDeque<>(); + q.offer(new int[] {0, 0, 0}); + boolean[][][] vis = new boolean[m][n][l + 1]; + vis[0][0][0] = true; + int[] dirs = {-1, 0, 1, 0, -1}; + int ans = 0; + for (; !q.isEmpty(); ++ans) { + for (int size = q.size(); size > 0; --size) { + var p = q.poll(); + int i = p[0], j = p[1], k = p[2]; + if (k == l) { + return ans; + } + if (matrix[i].charAt(j) == mantra.charAt(k) && !vis[i][j][k + 1]) { + vis[i][j][k + 1] = true; + q.offer(new int[] {i, j, k + 1}); + } else { + for (int c = 0; c < 4; ++c) { + int x = i + dirs[c], y = j + dirs[c + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y][k]) { + vis[x][y][k] = true; + q.offer(new int[] {x, y, k}); + } + } + } + } + } + return -1; + } } \ No newline at end of file diff --git "a/lcp/LCP 79. \346\217\220\345\217\226\345\222\222\346\226\207/Solution.py" "b/lcp/LCP 79. \346\217\220\345\217\226\345\222\222\346\226\207/Solution.py" index cad4a95aafbb9..e59371d9ce181 100644 --- "a/lcp/LCP 79. \346\217\220\345\217\226\345\222\222\346\226\207/Solution.py" +++ "b/lcp/LCP 79. \346\217\220\345\217\226\345\222\222\346\226\207/Solution.py" @@ -1,27 +1,27 @@ -class Solution: - def extractMantra(self, matrix: List[str], mantra: str) -> int: - m, n = len(matrix), len(matrix[0]) - q = deque([(0, 0, 0)]) - vis = {q[0]} - dirs = (-1, 0, 1, 0, -1) - ans = 0 - while q: - for _ in range(len(q)): - i, j, k = q.popleft() - if k == len(mantra): - return ans - if matrix[i][j] == mantra[k]: - t = (i, j, k + 1) - if t not in vis: - vis.add(t) - q.append(t) - else: - for a, b in pairwise(dirs): - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n: - t = (x, y, k) - if t not in vis: - vis.add(t) - q.append(t) - ans += 1 - return -1 +class Solution: + def extractMantra(self, matrix: List[str], mantra: str) -> int: + m, n = len(matrix), len(matrix[0]) + q = deque([(0, 0, 0)]) + vis = {q[0]} + dirs = (-1, 0, 1, 0, -1) + ans = 0 + while q: + for _ in range(len(q)): + i, j, k = q.popleft() + if k == len(mantra): + return ans + if matrix[i][j] == mantra[k]: + t = (i, j, k + 1) + if t not in vis: + vis.add(t) + q.append(t) + else: + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n: + t = (x, y, k) + if t not in vis: + vis.add(t) + q.append(t) + ans += 1 + return -1 diff --git "a/lcs/LCS 01. \344\270\213\350\275\275\346\217\222\344\273\266/Solution.py" "b/lcs/LCS 01. \344\270\213\350\275\275\346\217\222\344\273\266/Solution.py" index 775aaa5a57bc3..dd12ea43bed4d 100644 --- "a/lcs/LCS 01. \344\270\213\350\275\275\346\217\222\344\273\266/Solution.py" +++ "b/lcs/LCS 01. \344\270\213\350\275\275\346\217\222\344\273\266/Solution.py" @@ -1,7 +1,7 @@ class Solution: def leastMinutes(self, n: int) -> int: - speed = res = 1 + speed = ans = 1 while speed < n: speed <<= 1 - res += 1 - return res + ans += 1 + return ans diff --git a/main.py b/main.py new file mode 100644 index 0000000000000..af5c56dbe20e2 --- /dev/null +++ b/main.py @@ -0,0 +1,62 @@ +import os +import re + +code_block_dict = { + "python": ("Python3", "py"), + "java": ("Java", "java"), + "cpp": ("C++", "cpp"), + "c": ("C", "c"), + "go": ("Go", "go"), + "ts": ("TypeScript", "ts"), + "js": ("JavaScript", "js"), + "php": ("PHP", "php"), + "cs": ("C#", "cs"), + "rust": ("Rust", "rs"), + "sql": ("MySQL", "sql"), + "nim": ("Nim", "nim"), + "scala": ("Scala", "scala"), + "swift": ("Swift", "swift"), + "rb": ("Ruby", "rb"), + "kotlin": ("Kotlin", "kt"), +} + + +# 抽取代码块 +def extract_code(): + paths = [] + suffixes = [suf for _, (_, suf) in code_block_dict.items()] + for root, _, files in os.walk(os.getcwd()): + for file in files: + path = root + "/" + file + if "node_modules" in path or "__pycache__" in path or ".git" in path: + continue + if root == "D:\github-repo\leetcode": + continue + if path.endswith("README.md"): + paths.append(path) + for path in paths: + with open(path, "r", encoding="utf-8") as f: + content = f.read() + mark = "" + i = content.find(mark) + if i == -1: + continue + content = content[i + len(mark) :] + for suf, (_, suffix) in code_block_dict.items(): + res = re.findall(f"```{suf}\n(.*?)```", content, re.S) + if not res: + continue + cnt = 1 + for block in res: + if not block or not block.strip(): + continue + if suf in ["java", "cpp", "go", "c"]: + block = block.rstrip() + name = f"{path[:path.rfind('/')]}/Solution{'' if cnt == 1 else str(cnt)}.{suffix}" + with open(name, "w", encoding="utf-8") as f: + f.write(block) + cnt += 1 + + +if __name__ == "__main__": + extract_code() diff --git a/solution/0000-0099/0001.Two Sum/Solution.cs b/solution/0000-0099/0001.Two Sum/Solution.cs index 5564dbeab1f84..f01832c83837f 100644 --- a/solution/0000-0099/0001.Two Sum/Solution.cs +++ b/solution/0000-0099/0001.Two Sum/Solution.cs @@ -12,4 +12,4 @@ public int[] TwoSum(int[] nums, int target) { } } } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0001.Two Sum/Solution.nim b/solution/0000-0099/0001.Two Sum/Solution.nim index e510b433f986f..5d5dc18ff9b38 100644 --- a/solution/0000-0099/0001.Two Sum/Solution.nim +++ b/solution/0000-0099/0001.Two Sum/Solution.nim @@ -1,7 +1,3 @@ -#[ - Author: @joe733 -]# - import std/enumerate proc twoSum(nums: seq[int], target: int): seq[int] = diff --git a/solution/0000-0099/0001.Two Sum/Solution.php b/solution/0000-0099/0001.Two Sum/Solution.php index b6c5ff3ed94e5..525b923056574 100644 --- a/solution/0000-0099/0001.Two Sum/Solution.php +++ b/solution/0000-0099/0001.Two Sum/Solution.php @@ -13,4 +13,4 @@ function twoSum($nums, $target) { $hashtable[$x] = $key; } } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0001.Two Sum/Solution.swift b/solution/0000-0099/0001.Two Sum/Solution.swift index 5ade1b71655f4..6a84df9aaf965 100644 --- a/solution/0000-0099/0001.Two Sum/Solution.swift +++ b/solution/0000-0099/0001.Two Sum/Solution.swift @@ -12,4 +12,4 @@ class Solution { i += 1 } } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0002.Add Two Numbers/Solution.cs b/solution/0000-0099/0002.Add Two Numbers/Solution.cs index 04a9339da34c0..70eca2039a431 100644 --- a/solution/0000-0099/0002.Add Two Numbers/Solution.cs +++ b/solution/0000-0099/0002.Add Two Numbers/Solution.cs @@ -24,4 +24,4 @@ public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { } return dummy.next; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0002.Add Two Numbers/Solution.nim b/solution/0000-0099/0002.Add Two Numbers/Solution.nim index 149b2916d445c..fe4073d41cb23 100644 --- a/solution/0000-0099/0002.Add Two Numbers/Solution.nim +++ b/solution/0000-0099/0002.Add Two Numbers/Solution.nim @@ -1,30 +1,16 @@ -import std/[strutils, algorithm] - -type - Node[int] = ref object - value: int - next: Node[int] - - SinglyLinkedList[T] = object - head, tail: Node[T] - -proc append[T](list: var SinglyLinkedList[T], data: T = nil): void = - var node = Node[T](value: data) - if list.head.isNil: - list.head = node - list.tail = node - else: - list.tail.next = node - list.tail = node - -proc preview[T](list: SinglyLinkedList[T]): string = - var s: seq[T] - var n = list.head - while not n.isNil: - s.add n.value - n = n.next - result = s.join(" -> ") - +#[ + # Driver code in the solution file + # Definition for singly-linked list. + type + Node[int] = ref object + value: int + next: Node[int] + + SinglyLinkedList[T] = object + head, tail: Node[T] +]# + +# More efficient code churning ... proc addTwoNumbers(l1: var SinglyLinkedList, l2: var SinglyLinkedList): SinglyLinkedList[int] = var aggregate: SinglyLinkedList @@ -43,14 +29,3 @@ proc addTwoNumbers(l1: var SinglyLinkedList, l2: var SinglyLinkedList): SinglyLi for i in psum: aggregate.append(($i).parseInt()) result = aggregate - -var list1: SinglyLinkedList[int] -var list2: SinglyLinkedList[int] - -for i in @[2, 4, 3]: list1.append(i) -for i in @[5, 6, 4]: list2.append(i) - -echo(preview(list1)) -echo(preview(list2)) -echo(preview(addTwoNumbers(list1, list2))) - diff --git a/solution/0000-0099/0002.Add Two Numbers/Solution.php b/solution/0000-0099/0002.Add Two Numbers/Solution.php index 83b4f8c8d023b..f5f14f9b7d0dd 100644 --- a/solution/0000-0099/0002.Add Two Numbers/Solution.php +++ b/solution/0000-0099/0002.Add Two Numbers/Solution.php @@ -44,4 +44,4 @@ function addTwoNumbers($l1, $l2) { return $dummy->next; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0002.Add Two Numbers/Solution.rb b/solution/0000-0099/0002.Add Two Numbers/Solution.rb index 3f121b234768f..27cb1615a892a 100644 --- a/solution/0000-0099/0002.Add Two Numbers/Solution.rb +++ b/solution/0000-0099/0002.Add Two Numbers/Solution.rb @@ -10,16 +10,16 @@ # @param {ListNode} l2 # @return {ListNode} def add_two_numbers(l1, l2) - dummy = ListNode.new() - carry = 0 - cur = dummy - while !l1.nil? || !l2.nil? || carry > 0 - s = (l1.nil? ? 0 : l1.val) + (l2.nil? ? 0 : l2.val) + carry - carry = s / 10 - cur.next = ListNode.new(s % 10) - cur = cur.next - l1 = l1.nil? ? l1 : l1.next - l2 = l2.nil? ? l2 : l2.next - end - dummy.next -end \ No newline at end of file + dummy = ListNode.new() + carry = 0 + cur = dummy + while !l1.nil? || !l2.nil? || carry > 0 + s = (l1.nil? ? 0 : l1.val) + (l2.nil? ? 0 : l2.val) + carry + carry = s / 10 + cur.next = ListNode.new(s % 10) + cur = cur.next + l1 = l1.nil? ? l1 : l1.next + l2 = l2.nil? ? l2 : l2.next + end + dummy.next +end diff --git a/solution/0000-0099/0002.Add Two Numbers/Solution.ts b/solution/0000-0099/0002.Add Two Numbers/Solution.ts index 7788830f54788..219b5e598f651 100644 --- a/solution/0000-0099/0002.Add Two Numbers/Solution.ts +++ b/solution/0000-0099/0002.Add Two Numbers/Solution.ts @@ -14,7 +14,7 @@ function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | nul const dummy = new ListNode(); let cur = dummy; let sum = 0; - while (sum !== 0 || l1 != null || l2 != null) { + while (l1 != null || l2 != null || sum !== 0) { if (l1 != null) { sum += l1.val; l1 = l1.next; diff --git a/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution.cs b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution.cs index 81282ca9f5132..3457354f258cd 100644 --- a/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution.cs +++ b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution.cs @@ -13,4 +13,4 @@ public int LengthOfLongestSubstring(string s) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution.nim b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution.nim index 03058aac47058..1275a35bfbee6 100644 --- a/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution.nim +++ b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution.nim @@ -15,5 +15,3 @@ proc lengthOfLongestSubstring(s: string): int = i += 1 result = res # result has the default return value - -echo lengthOfLongestSubstring("abcddabcf") diff --git a/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution.php b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution.php index 1852d0018e3b2..e3d728856d3e9 100644 --- a/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution.php +++ b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution.php @@ -21,4 +21,4 @@ function lengthOfLongestSubstring($s) { } return $max; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution.swift b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution.swift index 83a39cdadd130..02462178bdfd5 100644 --- a/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution.swift +++ b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution.swift @@ -16,4 +16,4 @@ class Solution { } return max(maxLength, i - currentStartingIndex) } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution2.cpp b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution2.cpp new file mode 100644 index 0000000000000..880290ebf8141 --- /dev/null +++ b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int lengthOfLongestSubstring(string s) { + bool ss[128] = {false}; + int n = s.size(); + int ans = 0; + for (int i = 0, j = 0; i < n; ++i) { + while (ss[s[i]]) { + ss[s[j++]] = false; + } + ss[s[i]] = true; + ans = max(ans, i - j + 1); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution2.go b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution2.go new file mode 100644 index 0000000000000..aa5d5c36eced9 --- /dev/null +++ b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution2.go @@ -0,0 +1,13 @@ +func lengthOfLongestSubstring(s string) (ans int) { + ss := make([]bool, 128) + j := 0 + for i, c := range s { + for ss[c] { + ss[s[j]] = false + j++ + } + ss[c] = true + ans = max(ans, i-j+1) + } + return +} \ No newline at end of file diff --git a/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution2.java b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution2.java new file mode 100644 index 0000000000000..4ecaf7468b942 --- /dev/null +++ b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public int lengthOfLongestSubstring(String s) { + boolean[] ss = new boolean[128]; + int ans = 0, j = 0; + int n = s.length(); + for (int i = 0; i < n; ++i) { + char c = s.charAt(i); + while (ss[c]) { + ss[s.charAt(j++)] = false; + } + ans = Math.max(ans, i - j + 1); + ss[c] = true; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution2.ts b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution2.ts new file mode 100644 index 0000000000000..ec55dc4dab91a --- /dev/null +++ b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/Solution2.ts @@ -0,0 +1,13 @@ +function lengthOfLongestSubstring(s: string): number { + let ans = 0; + const n = s.length; + const ss: boolean[] = new Array(128).fill(false); + for (let i = 0, j = 0; i < n; ++i) { + while (ss[s[i]]) { + ss[s[j++]] = false; + } + ss[s[i]] = true; + ans = Math.max(ans, i - j + 1); + } + return ans; +} diff --git a/solution/0000-0099/0004.Median of Two Sorted Arrays/README.md b/solution/0000-0099/0004.Median of Two Sorted Arrays/README.md index e2b5f80334ca7..38bed5936b324 100644 --- a/solution/0000-0099/0004.Median of Two Sorted Arrays/README.md +++ b/solution/0000-0099/0004.Median of Two Sorted Arrays/README.md @@ -254,9 +254,9 @@ var findMedianSortedArrays = function (nums1, nums2) { }; ``` -### **TypeScript** +### **C#** -```ts +```cs public class Solution { private int m; private int n; diff --git a/solution/0000-0099/0004.Median of Two Sorted Arrays/README_EN.md b/solution/0000-0099/0004.Median of Two Sorted Arrays/README_EN.md index 10b0f148b2e6f..18dd287d08aec 100644 --- a/solution/0000-0099/0004.Median of Two Sorted Arrays/README_EN.md +++ b/solution/0000-0099/0004.Median of Two Sorted Arrays/README_EN.md @@ -242,9 +242,9 @@ var findMedianSortedArrays = function (nums1, nums2) { }; ``` -### **TypeScript** +### **C#** -```ts +```cs public class Solution { private int m; private int n; diff --git a/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.cpp b/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.cpp index eb7e295eeb90f..a030e8cf33de5 100644 --- a/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.cpp +++ b/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.cpp @@ -1,24 +1,24 @@ -class Solution { -public: - double findMedianSortedArrays(vector& nums1, vector& nums2) { - int m = nums1.size(), n = nums2.size(); - function f = [&](int i, int j, int k) { - if (i >= m) { - return nums2[j + k - 1]; - } - if (j >= n) { - return nums1[i + k - 1]; - } - if (k == 1) { - return min(nums1[i], nums2[j]); - } - int p = k / 2; - int x = i + p - 1 < m ? nums1[i + p - 1] : 1 << 30; - int y = j + p - 1 < n ? nums2[j + p - 1] : 1 << 30; - return x < y ? f(i + p, j, k - p) : f(i, j + p, k - p); - }; - int a = f(0, 0, (m + n + 1) / 2); - int b = f(0, 0, (m + n + 2) / 2); - return (a + b) / 2.0; - } +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + int m = nums1.size(), n = nums2.size(); + function f = [&](int i, int j, int k) { + if (i >= m) { + return nums2[j + k - 1]; + } + if (j >= n) { + return nums1[i + k - 1]; + } + if (k == 1) { + return min(nums1[i], nums2[j]); + } + int p = k / 2; + int x = i + p - 1 < m ? nums1[i + p - 1] : 1 << 30; + int y = j + p - 1 < n ? nums2[j + p - 1] : 1 << 30; + return x < y ? f(i + p, j, k - p) : f(i, j + p, k - p); + }; + int a = f(0, 0, (m + n + 1) / 2); + int b = f(0, 0, (m + n + 2) / 2); + return (a + b) / 2.0; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.cs b/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.cs index 652f1df0721e4..0cbe1b368a503 100644 --- a/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.cs +++ b/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.cs @@ -1,32 +1,32 @@ -public class Solution { - private int m; - private int n; - private int[] nums1; - private int[] nums2; - - public double FindMedianSortedArrays(int[] nums1, int[] nums2) { - m = nums1.Length; - n = nums2.Length; - this.nums1 = nums1; - this.nums2 = nums2; - int a = f(0, 0, (m + n + 1) / 2); - int b = f(0, 0, (m + n + 2) / 2); - return (a + b) / 2.0; - } - - private int f(int i, int j, int k) { - if (i >= m) { - return nums2[j + k - 1]; - } - if (j >= n) { - return nums1[i + k - 1]; - } - if (k == 1) { - return Math.Min(nums1[i], nums2[j]); - } - int p = k / 2; - int x = i + p - 1 < m ? nums1[i + p - 1] : 1 << 30; - int y = j + p - 1 < n ? nums2[j + p - 1] : 1 << 30; - return x < y ? f(i + p, j, k - p) : f(i, j + p, k - p); - } -} \ No newline at end of file +public class Solution { + private int m; + private int n; + private int[] nums1; + private int[] nums2; + + public double FindMedianSortedArrays(int[] nums1, int[] nums2) { + m = nums1.Length; + n = nums2.Length; + this.nums1 = nums1; + this.nums2 = nums2; + int a = f(0, 0, (m + n + 1) / 2); + int b = f(0, 0, (m + n + 2) / 2); + return (a + b) / 2.0; + } + + private int f(int i, int j, int k) { + if (i >= m) { + return nums2[j + k - 1]; + } + if (j >= n) { + return nums1[i + k - 1]; + } + if (k == 1) { + return Math.Min(nums1[i], nums2[j]); + } + int p = k / 2; + int x = i + p - 1 < m ? nums1[i + p - 1] : 1 << 30; + int y = j + p - 1 < n ? nums2[j + p - 1] : 1 << 30; + return x < y ? f(i + p, j, k - p) : f(i, j + p, k - p); + } +} diff --git a/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.java b/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.java index 61b1e7a5e70da..a4686b2aee26c 100644 --- a/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.java +++ b/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.java @@ -1,32 +1,32 @@ -class Solution { - private int m; - private int n; - private int[] nums1; - private int[] nums2; - - public double findMedianSortedArrays(int[] nums1, int[] nums2) { - m = nums1.length; - n = nums2.length; - this.nums1 = nums1; - this.nums2 = nums2; - int a = f(0, 0, (m + n + 1) / 2); - int b = f(0, 0, (m + n + 2) / 2); - return (a + b) / 2.0; - } - - private int f(int i, int j, int k) { - if (i >= m) { - return nums2[j + k - 1]; - } - if (j >= n) { - return nums1[i + k - 1]; - } - if (k == 1) { - return Math.min(nums1[i], nums2[j]); - } - int p = k / 2; - int x = i + p - 1 < m ? nums1[i + p - 1] : 1 << 30; - int y = j + p - 1 < n ? nums2[j + p - 1] : 1 << 30; - return x < y ? f(i + p, j, k - p) : f(i, j + p, k - p); - } +class Solution { + private int m; + private int n; + private int[] nums1; + private int[] nums2; + + public double findMedianSortedArrays(int[] nums1, int[] nums2) { + m = nums1.length; + n = nums2.length; + this.nums1 = nums1; + this.nums2 = nums2; + int a = f(0, 0, (m + n + 1) / 2); + int b = f(0, 0, (m + n + 2) / 2); + return (a + b) / 2.0; + } + + private int f(int i, int j, int k) { + if (i >= m) { + return nums2[j + k - 1]; + } + if (j >= n) { + return nums1[i + k - 1]; + } + if (k == 1) { + return Math.min(nums1[i], nums2[j]); + } + int p = k / 2; + int x = i + p - 1 < m ? nums1[i + p - 1] : 1 << 30; + int y = j + p - 1 < n ? nums2[j + p - 1] : 1 << 30; + return x < y ? f(i + p, j, k - p) : f(i, j + p, k - p); + } } \ No newline at end of file diff --git a/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.py b/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.py index 0111d879ed5b6..d40388c5a65f4 100644 --- a/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.py +++ b/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.py @@ -1,18 +1,18 @@ -class Solution: - def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: - def f(i: int, j: int, k: int) -> int: - if i >= m: - return nums2[j + k - 1] - if j >= n: - return nums1[i + k - 1] - if k == 1: - return min(nums1[i], nums2[j]) - p = k // 2 - x = nums1[i + p - 1] if i + p - 1 < m else inf - y = nums2[j + p - 1] if j + p - 1 < n else inf - return f(i + p, j, k - p) if x < y else f(i, j + p, k - p) - - m, n = len(nums1), len(nums2) - a = f(0, 0, (m + n + 1) // 2) - b = f(0, 0, (m + n + 2) // 2) - return (a + b) / 2 +class Solution: + def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: + def f(i: int, j: int, k: int) -> int: + if i >= m: + return nums2[j + k - 1] + if j >= n: + return nums1[i + k - 1] + if k == 1: + return min(nums1[i], nums2[j]) + p = k // 2 + x = nums1[i + p - 1] if i + p - 1 < m else inf + y = nums2[j + p - 1] if j + p - 1 < n else inf + return f(i + p, j, k - p) if x < y else f(i, j + p, k - p) + + m, n = len(nums1), len(nums2) + a = f(0, 0, (m + n + 1) // 2) + b = f(0, 0, (m + n + 2) // 2) + return (a + b) / 2 diff --git a/solution/0000-0099/0005.Longest Palindromic Substring/Solution.cpp b/solution/0000-0099/0005.Longest Palindromic Substring/Solution.cpp index 091016bb335dd..d065bf220db1f 100644 --- a/solution/0000-0099/0005.Longest Palindromic Substring/Solution.cpp +++ b/solution/0000-0099/0005.Longest Palindromic Substring/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - string longestPalindrome(string s) { - int n = s.size(); - vector> f(n, vector(n, true)); - int k = 0, mx = 1; - for (int i = n - 2; ~i; --i) { - for (int j = i + 1; j < n; ++j) { - f[i][j] = false; - if (s[i] == s[j]) { - f[i][j] = f[i + 1][j - 1]; - if (f[i][j] && mx < j - i + 1) { - mx = j - i + 1; - k = i; - } - } - } - } - return s.substr(k, mx); - } +class Solution { +public: + string longestPalindrome(string s) { + int n = s.size(); + vector> f(n, vector(n, true)); + int k = 0, mx = 1; + for (int i = n - 2; ~i; --i) { + for (int j = i + 1; j < n; ++j) { + f[i][j] = false; + if (s[i] == s[j]) { + f[i][j] = f[i + 1][j - 1]; + if (f[i][j] && mx < j - i + 1) { + mx = j - i + 1; + k = i; + } + } + } + } + return s.substr(k, mx); + } }; \ No newline at end of file diff --git a/solution/0000-0099/0005.Longest Palindromic Substring/Solution.cs b/solution/0000-0099/0005.Longest Palindromic Substring/Solution.cs index e2df11ac90ba2..d7863bdfe48b2 100644 --- a/solution/0000-0099/0005.Longest Palindromic Substring/Solution.cs +++ b/solution/0000-0099/0005.Longest Palindromic Substring/Solution.cs @@ -1,25 +1,25 @@ -public class Solution { - public string LongestPalindrome(string s) { - int n = s.Length; - bool[,] f = new bool[n, n]; - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; ++j) { - f[i, j] = true; - } - } - int k = 0, mx = 1; - for (int i = n - 2; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - f[i, j] = false; - if (s[i] == s[j]) { - f[i, j] = f[i + 1, j - 1]; - if (f[i, j] && mx < j - i + 1) { - mx = j - i + 1; - k = i; - } - } - } - } - return s.Substring(k, mx); - } -} \ No newline at end of file +public class Solution { + public string LongestPalindrome(string s) { + int n = s.Length; + bool[,] f = new bool[n, n]; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; ++j) { + f[i, j] = true; + } + } + int k = 0, mx = 1; + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + f[i, j] = false; + if (s[i] == s[j]) { + f[i, j] = f[i + 1, j - 1]; + if (f[i, j] && mx < j - i + 1) { + mx = j - i + 1; + k = i; + } + } + } + } + return s.Substring(k, mx); + } +} diff --git a/solution/0000-0099/0005.Longest Palindromic Substring/Solution.java b/solution/0000-0099/0005.Longest Palindromic Substring/Solution.java index 180dbc80b96ea..bccb969fa99eb 100644 --- a/solution/0000-0099/0005.Longest Palindromic Substring/Solution.java +++ b/solution/0000-0099/0005.Longest Palindromic Substring/Solution.java @@ -1,23 +1,23 @@ -class Solution { - public String longestPalindrome(String s) { - int n = s.length(); - boolean[][] f = new boolean[n][n]; - for (var g : f) { - Arrays.fill(g, true); - } - int k = 0, mx = 1; - for (int i = n - 2; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - f[i][j] = false; - if (s.charAt(i) == s.charAt(j)) { - f[i][j] = f[i + 1][j - 1]; - if (f[i][j] && mx < j - i + 1) { - mx = j - i + 1; - k = i; - } - } - } - } - return s.substring(k, k + mx); - } +class Solution { + public String longestPalindrome(String s) { + int n = s.length(); + boolean[][] f = new boolean[n][n]; + for (var g : f) { + Arrays.fill(g, true); + } + int k = 0, mx = 1; + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + f[i][j] = false; + if (s.charAt(i) == s.charAt(j)) { + f[i][j] = f[i + 1][j - 1]; + if (f[i][j] && mx < j - i + 1) { + mx = j - i + 1; + k = i; + } + } + } + } + return s.substring(k, k + mx); + } } \ No newline at end of file diff --git a/solution/0000-0099/0005.Longest Palindromic Substring/Solution.nim b/solution/0000-0099/0005.Longest Palindromic Substring/Solution.nim index 0e97be9c1c233..fdc5190bb87d4 100644 --- a/solution/0000-0099/0005.Longest Palindromic Substring/Solution.nim +++ b/solution/0000-0099/0005.Longest Palindromic Substring/Solution.nim @@ -19,6 +19,3 @@ proc longestPalindrome(s: string): string = mx = j - i + 1 result = s[start ..< start+mx] - -# Driver Code -# echo(longestPalindrome("adbdaba")) diff --git a/solution/0000-0099/0005.Longest Palindromic Substring/Solution.py b/solution/0000-0099/0005.Longest Palindromic Substring/Solution.py index 17e2ff1ad744e..a592a1afbfb1e 100644 --- a/solution/0000-0099/0005.Longest Palindromic Substring/Solution.py +++ b/solution/0000-0099/0005.Longest Palindromic Substring/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def longestPalindrome(self, s: str) -> str: - n = len(s) - f = [[True] * n for _ in range(n)] - k, mx = 0, 1 - for i in range(n - 2, -1, -1): - for j in range(i + 1, n): - f[i][j] = False - if s[i] == s[j]: - f[i][j] = f[i + 1][j - 1] - if f[i][j] and mx < j - i + 1: - k, mx = i, j - i + 1 - return s[k : k + mx] +class Solution: + def longestPalindrome(self, s: str) -> str: + n = len(s) + f = [[True] * n for _ in range(n)] + k, mx = 0, 1 + for i in range(n - 2, -1, -1): + for j in range(i + 1, n): + f[i][j] = False + if s[i] == s[j]: + f[i][j] = f[i + 1][j - 1] + if f[i][j] and mx < j - i + 1: + k, mx = i, j - i + 1 + return s[k : k + mx] diff --git a/solution/0000-0099/0005.Longest Palindromic Substring/Solution2.cpp b/solution/0000-0099/0005.Longest Palindromic Substring/Solution2.cpp new file mode 100644 index 0000000000000..5a95c28b378a4 --- /dev/null +++ b/solution/0000-0099/0005.Longest Palindromic Substring/Solution2.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + string longestPalindrome(string s) { + int n = s.size(); + int start = 0, mx = 1; + auto f = [&](int l, int r) { + while (l >= 0 && r < n && s[l] == s[r]) { + l--, r++; + } + return r - l - 1; + }; + for (int i = 0; i < n; ++i) { + int a = f(i, i); + int b = f(i, i + 1); + int t = max(a, b); + if (mx < t) { + mx = t; + start = i - (t - 1 >> 1); + } + } + return s.substr(start, mx); + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0005.Longest Palindromic Substring/Solution2.go b/solution/0000-0099/0005.Longest Palindromic Substring/Solution2.go new file mode 100644 index 0000000000000..57524b8b50c7b --- /dev/null +++ b/solution/0000-0099/0005.Longest Palindromic Substring/Solution2.go @@ -0,0 +1,19 @@ +func longestPalindrome(s string) string { + n := len(s) + start, mx := 0, 1 + f := func(l, r int) int { + for l >= 0 && r < n && s[l] == s[r] { + l, r = l-1, r+1 + } + return r - l - 1 + } + for i := range s { + a, b := f(i, i), f(i, i+1) + t := max(a, b) + if mx < t { + mx = t + start = i - ((t - 1) >> 1) + } + } + return s[start : start+mx] +} \ No newline at end of file diff --git a/solution/0000-0099/0005.Longest Palindromic Substring/Solution2.java b/solution/0000-0099/0005.Longest Palindromic Substring/Solution2.java new file mode 100644 index 0000000000000..124844db7a518 --- /dev/null +++ b/solution/0000-0099/0005.Longest Palindromic Substring/Solution2.java @@ -0,0 +1,28 @@ +class Solution { + private String s; + private int n; + + public String longestPalindrome(String s) { + this.s = s; + n = s.length(); + int start = 0, mx = 1; + for (int i = 0; i < n; ++i) { + int a = f(i, i); + int b = f(i, i + 1); + int t = Math.max(a, b); + if (mx < t) { + mx = t; + start = i - ((t - 1) >> 1); + } + } + return s.substring(start, start + mx); + } + + private int f(int l, int r) { + while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) { + --l; + ++r; + } + return r - l - 1; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0005.Longest Palindromic Substring/Solution2.py b/solution/0000-0099/0005.Longest Palindromic Substring/Solution2.py new file mode 100644 index 0000000000000..cb5828d7d6771 --- /dev/null +++ b/solution/0000-0099/0005.Longest Palindromic Substring/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def longestPalindrome(self, s: str) -> str: + def f(l, r): + while l >= 0 and r < n and s[l] == s[r]: + l, r = l - 1, r + 1 + return r - l - 1 + + n = len(s) + start, mx = 0, 1 + for i in range(n): + a = f(i, i) + b = f(i, i + 1) + t = max(a, b) + if mx < t: + mx = t + start = i - ((t - 1) >> 1) + return s[start : start + mx] diff --git a/solution/0000-0099/0005.Longest Palindromic Substring/Solution2.rs b/solution/0000-0099/0005.Longest Palindromic Substring/Solution2.rs new file mode 100644 index 0000000000000..6ce831f9e25de --- /dev/null +++ b/solution/0000-0099/0005.Longest Palindromic Substring/Solution2.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn is_palindrome(s: &str) -> bool { + let mut chars = s.chars(); + while let (Some(c1), Some(c2)) = (chars.next(), chars.next_back()) { + if c1 != c2 { + return false; + } + } + true + } + + pub fn longest_palindrome(s: String) -> String { + let size = s.len(); + let mut ans = &s[..1]; + for i in 0..size - 1 { + for j in (i + 1..size).rev() { + if ans.len() > j - i + 1 { + break; + } + if Solution::is_palindrome(&s[i..=j]) { + ans = &s[i..=j]; + } + } + } + return ans.to_string(); + } +} diff --git a/solution/0000-0099/0006.Zigzag Conversion/Solution.cpp b/solution/0000-0099/0006.Zigzag Conversion/Solution.cpp index f66b5d959b459..b166ab610ea6b 100644 --- a/solution/0000-0099/0006.Zigzag Conversion/Solution.cpp +++ b/solution/0000-0099/0006.Zigzag Conversion/Solution.cpp @@ -1,18 +1,21 @@ class Solution { public: string convert(string s, int numRows) { - if (numRows == 1) return s; - string ans; - int group = 2 * numRows - 2; - for (int i = 1; i <= numRows; ++i) { - int interval = i == numRows ? group : 2 * numRows - 2 * i; - int idx = i - 1; - while (idx < s.length()) { - ans.push_back(s[idx]); - idx += interval; - interval = group - interval; - if (interval == 0) interval = group; + if (numRows == 1) { + return s; + } + vector g(numRows); + int i = 0, k = -1; + for (char c : s) { + g[i] += c; + if (i == 0 || i == numRows - 1) { + k = -k; } + i += k; + } + string ans; + for (auto& t : g) { + ans += t; } return ans; } diff --git a/solution/0000-0099/0006.Zigzag Conversion/Solution.cs b/solution/0000-0099/0006.Zigzag Conversion/Solution.cs index cd684edd19346..3b35fdd34c1ea 100644 --- a/solution/0000-0099/0006.Zigzag Conversion/Solution.cs +++ b/solution/0000-0099/0006.Zigzag Conversion/Solution.cs @@ -22,4 +22,4 @@ public string Convert(string s, int numRows) { } return ans.ToString(); } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0006.Zigzag Conversion/Solution.go b/solution/0000-0099/0006.Zigzag Conversion/Solution.go index acc9934f620c5..c0170da1f292f 100644 --- a/solution/0000-0099/0006.Zigzag Conversion/Solution.go +++ b/solution/0000-0099/0006.Zigzag Conversion/Solution.go @@ -2,19 +2,14 @@ func convert(s string, numRows int) string { if numRows == 1 { return s } - n := len(s) - ans := make([]byte, n) - step := 2*numRows - 2 - count := 0 - for i := 0; i < numRows; i++ { - for j := 0; j+i < n; j += step { - ans[count] = s[i+j] - count++ - if i != 0 && i != numRows-1 && j+step-i < n { - ans[count] = s[j+step-i] - count++ - } + g := make([][]byte, numRows) + i, k := 0, -1 + for _, c := range s { + g[i] = append(g[i], byte(c)) + if i == 0 || i == numRows-1 { + k = -k } + i += k } - return string(ans) + return string(bytes.Join(g, nil)) } \ No newline at end of file diff --git a/solution/0000-0099/0006.Zigzag Conversion/Solution.java b/solution/0000-0099/0006.Zigzag Conversion/Solution.java index b2a9294d752f3..ecc1f6edfaa0e 100644 --- a/solution/0000-0099/0006.Zigzag Conversion/Solution.java +++ b/solution/0000-0099/0006.Zigzag Conversion/Solution.java @@ -3,20 +3,16 @@ public String convert(String s, int numRows) { if (numRows == 1) { return s; } - StringBuilder ans = new StringBuilder(); - int group = 2 * numRows - 2; - for (int i = 1; i <= numRows; i++) { - int interval = i == numRows ? group : 2 * numRows - 2 * i; - int idx = i - 1; - while (idx < s.length()) { - ans.append(s.charAt(idx)); - idx += interval; - interval = group - interval; - if (interval == 0) { - interval = group; - } + StringBuilder[] g = new StringBuilder[numRows]; + Arrays.setAll(g, k -> new StringBuilder()); + int i = 0, k = -1; + for (char c : s.toCharArray()) { + g[i].append(c); + if (i == 0 || i == numRows - 1) { + k = -k; } + i += k; } - return ans.toString(); + return String.join("", g); } } \ No newline at end of file diff --git a/solution/0000-0099/0006.Zigzag Conversion/Solution.py b/solution/0000-0099/0006.Zigzag Conversion/Solution.py index 5fc2f82ff1e5a..2a310319a2af4 100644 --- a/solution/0000-0099/0006.Zigzag Conversion/Solution.py +++ b/solution/0000-0099/0006.Zigzag Conversion/Solution.py @@ -2,15 +2,11 @@ class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s - group = 2 * numRows - 2 - ans = [] - for i in range(1, numRows + 1): - interval = group if i == numRows else 2 * numRows - 2 * i - idx = i - 1 - while idx < len(s): - ans.append(s[idx]) - idx += interval - interval = group - interval - if interval == 0: - interval = group - return ''.join(ans) + g = [[] for _ in range(numRows)] + i, k = 0, -1 + for c in s: + g[i].append(c) + if i == 0 or i == numRows - 1: + k = -k + i += k + return ''.join(chain(*g)) diff --git a/solution/0000-0099/0006.Zigzag Conversion/Solution.ts b/solution/0000-0099/0006.Zigzag Conversion/Solution.ts index 3085c8797be67..300cb827211e1 100644 --- a/solution/0000-0099/0006.Zigzag Conversion/Solution.ts +++ b/solution/0000-0099/0006.Zigzag Conversion/Solution.ts @@ -2,19 +2,15 @@ function convert(s: string, numRows: number): string { if (numRows === 1) { return s; } - const ss = new Array(numRows).fill(''); + const g: string[][] = new Array(numRows).fill(0).map(() => []); let i = 0; - let toDown = true; + let k = -1; for (const c of s) { - ss[i] += c; - if (toDown) { - i++; - } else { - i--; - } - if (i === 0 || i === numRows - 1) { - toDown = !toDown; + g[i].push(c); + if (i === numRows - 1 || i === 0) { + k = -k; } + i += k; } - return ss.reduce((r, s) => r + s); + return g.flat().join(''); } diff --git a/solution/0000-0099/0006.Zigzag Conversion/Solution2.cpp b/solution/0000-0099/0006.Zigzag Conversion/Solution2.cpp new file mode 100644 index 0000000000000..f66b5d959b459 --- /dev/null +++ b/solution/0000-0099/0006.Zigzag Conversion/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + string convert(string s, int numRows) { + if (numRows == 1) return s; + string ans; + int group = 2 * numRows - 2; + for (int i = 1; i <= numRows; ++i) { + int interval = i == numRows ? group : 2 * numRows - 2 * i; + int idx = i - 1; + while (idx < s.length()) { + ans.push_back(s[idx]); + idx += interval; + interval = group - interval; + if (interval == 0) interval = group; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0006.Zigzag Conversion/Solution2.go b/solution/0000-0099/0006.Zigzag Conversion/Solution2.go new file mode 100644 index 0000000000000..acc9934f620c5 --- /dev/null +++ b/solution/0000-0099/0006.Zigzag Conversion/Solution2.go @@ -0,0 +1,20 @@ +func convert(s string, numRows int) string { + if numRows == 1 { + return s + } + n := len(s) + ans := make([]byte, n) + step := 2*numRows - 2 + count := 0 + for i := 0; i < numRows; i++ { + for j := 0; j+i < n; j += step { + ans[count] = s[i+j] + count++ + if i != 0 && i != numRows-1 && j+step-i < n { + ans[count] = s[j+step-i] + count++ + } + } + } + return string(ans) +} \ No newline at end of file diff --git a/solution/0000-0099/0006.Zigzag Conversion/Solution2.java b/solution/0000-0099/0006.Zigzag Conversion/Solution2.java new file mode 100644 index 0000000000000..b2a9294d752f3 --- /dev/null +++ b/solution/0000-0099/0006.Zigzag Conversion/Solution2.java @@ -0,0 +1,22 @@ +class Solution { + public String convert(String s, int numRows) { + if (numRows == 1) { + return s; + } + StringBuilder ans = new StringBuilder(); + int group = 2 * numRows - 2; + for (int i = 1; i <= numRows; i++) { + int interval = i == numRows ? group : 2 * numRows - 2 * i; + int idx = i - 1; + while (idx < s.length()) { + ans.append(s.charAt(idx)); + idx += interval; + interval = group - interval; + if (interval == 0) { + interval = group; + } + } + } + return ans.toString(); + } +} \ No newline at end of file diff --git a/solution/0000-0099/0006.Zigzag Conversion/Solution2.js b/solution/0000-0099/0006.Zigzag Conversion/Solution2.js new file mode 100644 index 0000000000000..e291e38cb6b18 --- /dev/null +++ b/solution/0000-0099/0006.Zigzag Conversion/Solution2.js @@ -0,0 +1,26 @@ +/** + * @param {string} s + * @param {number} numRows + * @return {string} + */ +var convert = function (s, numRows) { + if (numRows == 1) return s; + const arr = new Array(numRows); + for (let i = 0; i < numRows; i++) arr[i] = []; + let mi = 0, + isDown = true; + for (const c of s) { + arr[mi].push(c); + + if (mi >= numRows - 1) isDown = false; + else if (mi <= 0) isDown = true; + + if (isDown) mi++; + else mi--; + } + let ans = []; + for (const item of arr) { + ans = ans.concat(item); + } + return ans.join(''); +}; diff --git a/solution/0000-0099/0006.Zigzag Conversion/Solution2.py b/solution/0000-0099/0006.Zigzag Conversion/Solution2.py new file mode 100644 index 0000000000000..5fc2f82ff1e5a --- /dev/null +++ b/solution/0000-0099/0006.Zigzag Conversion/Solution2.py @@ -0,0 +1,16 @@ +class Solution: + def convert(self, s: str, numRows: int) -> str: + if numRows == 1: + return s + group = 2 * numRows - 2 + ans = [] + for i in range(1, numRows + 1): + interval = group if i == numRows else 2 * numRows - 2 * i + idx = i - 1 + while idx < len(s): + ans.append(s[idx]) + idx += interval + interval = group - interval + if interval == 0: + interval = group + return ''.join(ans) diff --git a/solution/0000-0099/0006.Zigzag Conversion/Solution2.rs b/solution/0000-0099/0006.Zigzag Conversion/Solution2.rs new file mode 100644 index 0000000000000..f824b365dedec --- /dev/null +++ b/solution/0000-0099/0006.Zigzag Conversion/Solution2.rs @@ -0,0 +1,9 @@ +impl Solution { + pub fn convert(s: String, num_rows: i32) -> String { + let num_rows = num_rows as usize; + let mut rows = vec![String::new(); num_rows]; + let iter = (0..num_rows).chain((1..num_rows - 1).rev()).cycle(); + iter.zip(s.chars()).for_each(|(i, c)| rows[i].push(c)); + rows.into_iter().collect() + } +} diff --git a/solution/0000-0099/0006.Zigzag Conversion/Solution2.ts b/solution/0000-0099/0006.Zigzag Conversion/Solution2.ts new file mode 100644 index 0000000000000..3085c8797be67 --- /dev/null +++ b/solution/0000-0099/0006.Zigzag Conversion/Solution2.ts @@ -0,0 +1,20 @@ +function convert(s: string, numRows: number): string { + if (numRows === 1) { + return s; + } + const ss = new Array(numRows).fill(''); + let i = 0; + let toDown = true; + for (const c of s) { + ss[i] += c; + if (toDown) { + i++; + } else { + i--; + } + if (i === 0 || i === numRows - 1) { + toDown = !toDown; + } + } + return ss.reduce((r, s) => r + s); +} diff --git a/solution/0000-0099/0007.Reverse Integer/Solution.cs b/solution/0000-0099/0007.Reverse Integer/Solution.cs index 88f3fe8f40bbc..c79cce2d49da6 100644 --- a/solution/0000-0099/0007.Reverse Integer/Solution.cs +++ b/solution/0000-0099/0007.Reverse Integer/Solution.cs @@ -9,4 +9,4 @@ public int Reverse(int x) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0008.String to Integer (atoi)/Solution.java b/solution/0000-0099/0008.String to Integer (atoi)/Solution.java index 966a59c3daf9d..3c9290bfa50cd 100644 --- a/solution/0000-0099/0008.String to Integer (atoi)/Solution.java +++ b/solution/0000-0099/0008.String to Integer (atoi)/Solution.java @@ -5,17 +5,20 @@ public int myAtoi(String s) { if (n == 0) return 0; int i = 0; while (s.charAt(i) == ' ') { + // 仅包含空格 if (++i == n) return 0; } int sign = 1; if (s.charAt(i) == '-') sign = -1; if (s.charAt(i) == '-' || s.charAt(i) == '+') ++i; int res = 0, flag = Integer.MAX_VALUE / 10; - for (int j = i; j < n; ++j) { - if (s.charAt(j) < '0' || s.charAt(j) > '9') break; - if (res > flag || (res == flag && s.charAt(j) > '7')) + for (; i < n; ++i) { + // 非数字,跳出循环体 + if (s.charAt(i) < '0' || s.charAt(i) > '9') break; + // 溢出判断 + if (res > flag || (res == flag && s.charAt(i) > '7')) return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE; - res = res * 10 + (s.charAt(j) - '0'); + res = res * 10 + (s.charAt(i) - '0'); } return sign * res; } diff --git a/solution/0000-0099/0008.String to Integer (atoi)/Solution.py b/solution/0000-0099/0008.String to Integer (atoi)/Solution.py index 5f72f8d4f7a01..beb6806966ec4 100644 --- a/solution/0000-0099/0008.String to Integer (atoi)/Solution.py +++ b/solution/0000-0099/0008.String to Integer (atoi)/Solution.py @@ -8,7 +8,7 @@ def myAtoi(self, s: str) -> int: i = 0 while s[i] == ' ': i += 1 - # only contains blank space + # 仅包含空格 if i == n: return 0 sign = -1 if s[i] == '-' else 1 @@ -16,11 +16,11 @@ def myAtoi(self, s: str) -> int: i += 1 res, flag = 0, (2**31 - 1) // 10 while i < n: - # not a number, exit the loop + # 非数字,跳出循环体 if not s[i].isdigit(): break c = int(s[i]) - # if overflows + # 溢出判断 if res > flag or (res == flag and c > 7): return 2**31 - 1 if sign > 0 else -(2**31) res = res * 10 + c diff --git a/solution/0000-0099/0009.Palindrome Number/Solution.rs b/solution/0000-0099/0009.Palindrome Number/Solution.rs index c609536195d07..7163690151d08 100644 --- a/solution/0000-0099/0009.Palindrome Number/Solution.rs +++ b/solution/0000-0099/0009.Palindrome Number/Solution.rs @@ -1,14 +1,20 @@ impl Solution { - pub fn is_palindrome(mut x: i32) -> bool { - if x < 0 || (x % 10 == 0 && x != 0) { + pub fn is_palindrome(x: i32) -> bool { + if x < 0 { return false; } - let mut y = 0; - while x > y { - y *= 10; - y += x % 10; - x /= 10; + let s = x.to_string(); + let bs = s.as_bytes(); + let n = bs.len(); + let mut l = 0; + let mut r = n - 1; + while l < r { + if bs[l] != bs[r] { + return false; + } + l += 1; + r -= 1; } - x == y || x == y / 10 + true } } diff --git a/solution/0000-0099/0009.Palindrome Number/Solution2.rs b/solution/0000-0099/0009.Palindrome Number/Solution2.rs new file mode 100644 index 0000000000000..c609536195d07 --- /dev/null +++ b/solution/0000-0099/0009.Palindrome Number/Solution2.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn is_palindrome(mut x: i32) -> bool { + if x < 0 || (x % 10 == 0 && x != 0) { + return false; + } + let mut y = 0; + while x > y { + y *= 10; + y += x % 10; + x /= 10; + } + x == y || x == y / 10 + } +} diff --git a/solution/0000-0099/0010.Regular Expression Matching/Solution.cpp b/solution/0000-0099/0010.Regular Expression Matching/Solution.cpp index 5e172f02c21b6..17da3a5f8bfbd 100644 --- a/solution/0000-0099/0010.Regular Expression Matching/Solution.cpp +++ b/solution/0000-0099/0010.Regular Expression Matching/Solution.cpp @@ -2,21 +2,26 @@ class Solution { public: bool isMatch(string s, string p) { int m = s.size(), n = p.size(); - bool f[m + 1][n + 1]; - memset(f, false, sizeof f); - f[0][0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (p[j - 1] == '*') { - f[i][j] = f[i][j - 2]; - if (i && (p[j - 2] == '.' || p[j - 2] == s[i - 1])) { - f[i][j] |= f[i - 1][j]; - } - } else if (i && (p[j - 1] == '.' || p[j - 1] == s[i - 1])) { - f[i][j] = f[i - 1][j - 1]; + int f[m + 1][n + 1]; + memset(f, 0, sizeof f); + function dfs = [&](int i, int j) -> bool { + if (j >= n) { + return i == m; + } + if (f[i][j]) { + return f[i][j] == 1; + } + int res = -1; + if (j + 1 < n && p[j + 1] == '*') { + if (dfs(i, j + 2) or (i < m and (s[i] == p[j] or p[j] == '.') and dfs(i + 1, j))) { + res = 1; } + } else if (i < m and (s[i] == p[j] or p[j] == '.') and dfs(i + 1, j + 1)) { + res = 1; } - } - return f[m][n]; + f[i][j] = res; + return res == 1; + }; + return dfs(0, 0); } }; \ No newline at end of file diff --git a/solution/0000-0099/0010.Regular Expression Matching/Solution.cs b/solution/0000-0099/0010.Regular Expression Matching/Solution.cs index a97f8a0dcd0c6..e481761ed9e0e 100644 --- a/solution/0000-0099/0010.Regular Expression Matching/Solution.cs +++ b/solution/0000-0099/0010.Regular Expression Matching/Solution.cs @@ -1,20 +1,35 @@ public class Solution { + private string s; + private string p; + private int m; + private int n; + private int[,] f; + public bool IsMatch(string s, string p) { - int m = s.Length, n = p.Length; - bool[,] f = new bool[m + 1, n + 1]; - f[0, 0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (p[j - 1] == '*') { - f[i, j] = f[i, j - 2]; - if (i > 0 && (p[j - 2] == '.' || p[j - 2] == s[i - 1])) { - f[i, j] |= f[i - 1, j]; - } - } else if (i > 0 && (p[j - 1] == '.' || p[j - 1] == s[i - 1])) { - f[i, j] = f[i - 1, j - 1]; - } + m = s.Length; + n = p.Length; + f = new int[m + 1, n + 1]; + this.s = s; + this.p = p; + return dfs(0, 0); + } + + private bool dfs(int i, int j) { + if (j >= n) { + return i == m; + } + if (f[i, j] != 0) { + return f[i, j] == 1; + } + int res = -1; + if (j + 1 < n && p[j + 1] == '*') { + if (dfs(i, j + 2) || (i < m && (s[i] == p[j] || p[j] == '.') && dfs(i + 1, j))) { + res = 1; } + } else if (i < m && (s[i] == p[j] || p[j] == '.') && dfs(i + 1, j + 1)) { + res = 1; } - return f[m, n]; + f[i, j] = res; + return res == 1; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0010.Regular Expression Matching/Solution.go b/solution/0000-0099/0010.Regular Expression Matching/Solution.go index c162c1cc62a62..9154a39e738ec 100644 --- a/solution/0000-0099/0010.Regular Expression Matching/Solution.go +++ b/solution/0000-0099/0010.Regular Expression Matching/Solution.go @@ -1,21 +1,27 @@ func isMatch(s string, p string) bool { m, n := len(s), len(p) - f := make([][]bool, m+1) + f := make([][]int, m+1) for i := range f { - f[i] = make([]bool, n+1) + f[i] = make([]int, n+1) } - f[0][0] = true - for i := 0; i <= m; i++ { - for j := 1; j <= n; j++ { - if p[j-1] == '*' { - f[i][j] = f[i][j-2] - if i > 0 && (p[j-2] == '.' || p[j-2] == s[i-1]) { - f[i][j] = f[i][j] || f[i-1][j] - } - } else if i > 0 && (p[j-1] == '.' || p[j-1] == s[i-1]) { - f[i][j] = f[i-1][j-1] + var dfs func(i, j int) bool + dfs = func(i, j int) bool { + if j >= n { + return i == m + } + if f[i][j] != 0 { + return f[i][j] == 1 + } + res := -1 + if j+1 < n && p[j+1] == '*' { + if dfs(i, j+2) || (i < m && (s[i] == p[j] || p[j] == '.') && dfs(i+1, j)) { + res = 1 } + } else if i < m && (s[i] == p[j] || p[j] == '.') && dfs(i+1, j+1) { + res = 1 } + f[i][j] = res + return res == 1 } - return f[m][n] + return dfs(0, 0) } \ No newline at end of file diff --git a/solution/0000-0099/0010.Regular Expression Matching/Solution.java b/solution/0000-0099/0010.Regular Expression Matching/Solution.java index dfbc862318064..7b6048f5f1627 100644 --- a/solution/0000-0099/0010.Regular Expression Matching/Solution.java +++ b/solution/0000-0099/0010.Regular Expression Matching/Solution.java @@ -1,21 +1,33 @@ class Solution { + private Boolean[][] f; + private String s; + private String p; + private int m; + private int n; + public boolean isMatch(String s, String p) { - int m = s.length(), n = p.length(); - boolean[][] f = new boolean[m + 1][n + 1]; - f[0][0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (p.charAt(j - 1) == '*') { - f[i][j] = f[i][j - 2]; - if (i > 0 && (p.charAt(j - 2) == '.' || p.charAt(j - 2) == s.charAt(i - 1))) { - f[i][j] |= f[i - 1][j]; - } - } else if (i > 0 - && (p.charAt(j - 1) == '.' || p.charAt(j - 1) == s.charAt(i - 1))) { - f[i][j] = f[i - 1][j - 1]; - } - } + m = s.length(); + n = p.length(); + f = new Boolean[m + 1][n + 1]; + this.s = s; + this.p = p; + return dfs(0, 0); + } + + private boolean dfs(int i, int j) { + if (j >= n) { + return i == m; + } + if (f[i][j] != null) { + return f[i][j]; + } + boolean res = false; + if (j + 1 < n && p.charAt(j + 1) == '*') { + res = dfs(i, j + 2) + || (i < m && (s.charAt(i) == p.charAt(j) || p.charAt(j) == '.') && dfs(i + 1, j)); + } else { + res = i < m && (s.charAt(i) == p.charAt(j) || p.charAt(j) == '.') && dfs(i + 1, j + 1); } - return f[m][n]; + return f[i][j] = res; } } \ No newline at end of file diff --git a/solution/0000-0099/0010.Regular Expression Matching/Solution.js b/solution/0000-0099/0010.Regular Expression Matching/Solution.js index e5f371c322dae..26f833e462f56 100644 --- a/solution/0000-0099/0010.Regular Expression Matching/Solution.js +++ b/solution/0000-0099/0010.Regular Expression Matching/Solution.js @@ -6,19 +6,24 @@ var isMatch = function (s, p) { const m = s.length; const n = p.length; - const f = Array.from({ length: m + 1 }, () => Array(n + 1).fill(false)); - f[0][0] = true; - for (let i = 0; i <= m; ++i) { - for (let j = 1; j <= n; ++j) { - if (p[j - 1] === '*') { - f[i][j] = f[i][j - 2]; - if (i && (p[j - 2] === '.' || p[j - 2] === s[i - 1])) { - f[i][j] |= f[i - 1][j]; - } - } else if (i && (p[j - 1] === '.' || p[j - 1] === s[i - 1])) { - f[i][j] = f[i - 1][j - 1]; + const f = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); + const dfs = (i, j) => { + if (j >= n) { + return i === m; + } + if (f[i][j]) { + return f[i][j] === 1; + } + let res = -1; + if (j + 1 < n && p[j + 1] === '*') { + if (dfs(i, j + 2) || (i < m && (s[i] === p[j] || p[j] === '.') && dfs(i + 1, j))) { + res = 1; } + } else if (i < m && (s[i] === p[j] || p[j] === '.') && dfs(i + 1, j + 1)) { + res = 1; } - } - return f[m][n]; + f[i][j] = res; + return res === 1; + }; + return dfs(0, 0); }; diff --git a/solution/0000-0099/0010.Regular Expression Matching/Solution.py b/solution/0000-0099/0010.Regular Expression Matching/Solution.py index e2d563a26cc21..5b426ef2d958d 100644 --- a/solution/0000-0099/0010.Regular Expression Matching/Solution.py +++ b/solution/0000-0099/0010.Regular Expression Matching/Solution.py @@ -1,14 +1,14 @@ class Solution: def isMatch(self, s: str, p: str) -> bool: + @cache + def dfs(i, j): + if j >= n: + return i == m + if j + 1 < n and p[j + 1] == '*': + return dfs(i, j + 2) or ( + i < m and (s[i] == p[j] or p[j] == '.') and dfs(i + 1, j) + ) + return i < m and (s[i] == p[j] or p[j] == '.') and dfs(i + 1, j + 1) + m, n = len(s), len(p) - f = [[False] * (n + 1) for _ in range(m + 1)] - f[0][0] = True - for i in range(m + 1): - for j in range(1, n + 1): - if p[j - 1] == "*": - f[i][j] = f[i][j - 2] - if i > 0 and (p[j - 2] == "." or s[i - 1] == p[j - 2]): - f[i][j] |= f[i - 1][j] - elif i > 0 and (p[j - 1] == "." or s[i - 1] == p[j - 1]): - f[i][j] = f[i - 1][j - 1] - return f[m][n] + return dfs(0, 0) diff --git a/solution/0000-0099/0010.Regular Expression Matching/Solution2.cpp b/solution/0000-0099/0010.Regular Expression Matching/Solution2.cpp new file mode 100644 index 0000000000000..5e172f02c21b6 --- /dev/null +++ b/solution/0000-0099/0010.Regular Expression Matching/Solution2.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + bool isMatch(string s, string p) { + int m = s.size(), n = p.size(); + bool f[m + 1][n + 1]; + memset(f, false, sizeof f); + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (p[j - 1] == '*') { + f[i][j] = f[i][j - 2]; + if (i && (p[j - 2] == '.' || p[j - 2] == s[i - 1])) { + f[i][j] |= f[i - 1][j]; + } + } else if (i && (p[j - 1] == '.' || p[j - 1] == s[i - 1])) { + f[i][j] = f[i - 1][j - 1]; + } + } + } + return f[m][n]; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0010.Regular Expression Matching/Solution2.cs b/solution/0000-0099/0010.Regular Expression Matching/Solution2.cs new file mode 100644 index 0000000000000..b2a7c8e40061f --- /dev/null +++ b/solution/0000-0099/0010.Regular Expression Matching/Solution2.cs @@ -0,0 +1,20 @@ +public class Solution { + public bool IsMatch(string s, string p) { + int m = s.Length, n = p.Length; + bool[,] f = new bool[m + 1, n + 1]; + f[0, 0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (p[j - 1] == '*') { + f[i, j] = f[i, j - 2]; + if (i > 0 && (p[j - 2] == '.' || p[j - 2] == s[i - 1])) { + f[i, j] |= f[i - 1, j]; + } + } else if (i > 0 && (p[j - 1] == '.' || p[j - 1] == s[i - 1])) { + f[i, j] = f[i - 1, j - 1]; + } + } + } + return f[m, n]; + } +} diff --git a/solution/0000-0099/0010.Regular Expression Matching/Solution2.go b/solution/0000-0099/0010.Regular Expression Matching/Solution2.go new file mode 100644 index 0000000000000..c162c1cc62a62 --- /dev/null +++ b/solution/0000-0099/0010.Regular Expression Matching/Solution2.go @@ -0,0 +1,21 @@ +func isMatch(s string, p string) bool { + m, n := len(s), len(p) + f := make([][]bool, m+1) + for i := range f { + f[i] = make([]bool, n+1) + } + f[0][0] = true + for i := 0; i <= m; i++ { + for j := 1; j <= n; j++ { + if p[j-1] == '*' { + f[i][j] = f[i][j-2] + if i > 0 && (p[j-2] == '.' || p[j-2] == s[i-1]) { + f[i][j] = f[i][j] || f[i-1][j] + } + } else if i > 0 && (p[j-1] == '.' || p[j-1] == s[i-1]) { + f[i][j] = f[i-1][j-1] + } + } + } + return f[m][n] +} \ No newline at end of file diff --git a/solution/0000-0099/0010.Regular Expression Matching/Solution2.java b/solution/0000-0099/0010.Regular Expression Matching/Solution2.java new file mode 100644 index 0000000000000..dfbc862318064 --- /dev/null +++ b/solution/0000-0099/0010.Regular Expression Matching/Solution2.java @@ -0,0 +1,21 @@ +class Solution { + public boolean isMatch(String s, String p) { + int m = s.length(), n = p.length(); + boolean[][] f = new boolean[m + 1][n + 1]; + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (p.charAt(j - 1) == '*') { + f[i][j] = f[i][j - 2]; + if (i > 0 && (p.charAt(j - 2) == '.' || p.charAt(j - 2) == s.charAt(i - 1))) { + f[i][j] |= f[i - 1][j]; + } + } else if (i > 0 + && (p.charAt(j - 1) == '.' || p.charAt(j - 1) == s.charAt(i - 1))) { + f[i][j] = f[i - 1][j - 1]; + } + } + } + return f[m][n]; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0010.Regular Expression Matching/Solution2.js b/solution/0000-0099/0010.Regular Expression Matching/Solution2.js new file mode 100644 index 0000000000000..e5f371c322dae --- /dev/null +++ b/solution/0000-0099/0010.Regular Expression Matching/Solution2.js @@ -0,0 +1,24 @@ +/** + * @param {string} s + * @param {string} p + * @return {boolean} + */ +var isMatch = function (s, p) { + const m = s.length; + const n = p.length; + const f = Array.from({ length: m + 1 }, () => Array(n + 1).fill(false)); + f[0][0] = true; + for (let i = 0; i <= m; ++i) { + for (let j = 1; j <= n; ++j) { + if (p[j - 1] === '*') { + f[i][j] = f[i][j - 2]; + if (i && (p[j - 2] === '.' || p[j - 2] === s[i - 1])) { + f[i][j] |= f[i - 1][j]; + } + } else if (i && (p[j - 1] === '.' || p[j - 1] === s[i - 1])) { + f[i][j] = f[i - 1][j - 1]; + } + } + } + return f[m][n]; +}; diff --git a/solution/0000-0099/0010.Regular Expression Matching/Solution2.py b/solution/0000-0099/0010.Regular Expression Matching/Solution2.py new file mode 100644 index 0000000000000..e2d563a26cc21 --- /dev/null +++ b/solution/0000-0099/0010.Regular Expression Matching/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def isMatch(self, s: str, p: str) -> bool: + m, n = len(s), len(p) + f = [[False] * (n + 1) for _ in range(m + 1)] + f[0][0] = True + for i in range(m + 1): + for j in range(1, n + 1): + if p[j - 1] == "*": + f[i][j] = f[i][j - 2] + if i > 0 and (p[j - 2] == "." or s[i - 1] == p[j - 2]): + f[i][j] |= f[i - 1][j] + elif i > 0 and (p[j - 1] == "." or s[i - 1] == p[j - 1]): + f[i][j] = f[i - 1][j - 1] + return f[m][n] diff --git a/solution/0000-0099/0011.Container With Most Water/Solution.cs b/solution/0000-0099/0011.Container With Most Water/Solution.cs index b5068ff59abcf..41f36b567786c 100644 --- a/solution/0000-0099/0011.Container With Most Water/Solution.cs +++ b/solution/0000-0099/0011.Container With Most Water/Solution.cs @@ -13,4 +13,4 @@ public int MaxArea(int[] height) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0012.Integer to Roman/Solution.cs b/solution/0000-0099/0012.Integer to Roman/Solution.cs index f43e5197cd3fa..45d83d1f76e5c 100644 --- a/solution/0000-0099/0012.Integer to Roman/Solution.cs +++ b/solution/0000-0099/0012.Integer to Roman/Solution.cs @@ -11,4 +11,4 @@ public string IntToRoman(int num) { } return ans.ToString(); } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0013.Roman to Integer/Solution.cs b/solution/0000-0099/0013.Roman to Integer/Solution.cs index 2d6e6371c67f9..d4cf3a456ea34 100644 --- a/solution/0000-0099/0013.Roman to Integer/Solution.cs +++ b/solution/0000-0099/0013.Roman to Integer/Solution.cs @@ -15,4 +15,4 @@ public int RomanToInt(string s) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0013.Roman to Integer/Solution.php b/solution/0000-0099/0013.Roman to Integer/Solution.php index fa41aee6a88d6..d2dc525c62aee 100644 --- a/solution/0000-0099/0013.Roman to Integer/Solution.php +++ b/solution/0000-0099/0013.Roman to Integer/Solution.php @@ -25,4 +25,4 @@ function romanToInt($s) { } return $rs; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0014.Longest Common Prefix/Solution.cs b/solution/0000-0099/0014.Longest Common Prefix/Solution.cs index b30ea578420b1..59b7858b37a4e 100644 --- a/solution/0000-0099/0014.Longest Common Prefix/Solution.cs +++ b/solution/0000-0099/0014.Longest Common Prefix/Solution.cs @@ -10,4 +10,4 @@ public string LongestCommonPrefix(string[] strs) { } return strs[0]; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0014.Longest Common Prefix/Solution.php b/solution/0000-0099/0014.Longest Common Prefix/Solution.php index c1b7105717567..a1c9c17e727d8 100644 --- a/solution/0000-0099/0014.Longest Common Prefix/Solution.php +++ b/solution/0000-0099/0014.Longest Common Prefix/Solution.php @@ -15,4 +15,4 @@ function longestCommonPrefix($strs) { } return $rs; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0015.3Sum/Solution.cs b/solution/0000-0099/0015.3Sum/Solution.cs index 7b8d3cbe891cc..e79a80f700603 100644 --- a/solution/0000-0099/0015.3Sum/Solution.cs +++ b/solution/0000-0099/0015.3Sum/Solution.cs @@ -27,4 +27,4 @@ public IList> ThreeSum(int[] nums) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.cpp b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.cpp index 5be1938df3fb3..fc392f2308787 100644 --- a/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.cpp +++ b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - vector letterCombinations(string digits) { - if (digits.empty()) { - return {}; - } - vector d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; - vector ans = {""}; - for (auto& i : digits) { - string s = d[i - '2']; - vector t; - for (auto& a : ans) { - for (auto& b : s) { - t.push_back(a + b); - } - } - ans = move(t); - } - return ans; - } +class Solution { +public: + vector letterCombinations(string digits) { + if (digits.empty()) { + return {}; + } + vector d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + vector ans = {""}; + for (auto& i : digits) { + string s = d[i - '2']; + vector t; + for (auto& a : ans) { + for (auto& b : s) { + t.push_back(a + b); + } + } + ans = move(t); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.cs b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.cs index 76b4a24220292..449da525a665c 100644 --- a/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.cs +++ b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.cs @@ -18,4 +18,4 @@ public IList LetterCombinations(string digits) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.py b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.py index d76248076ff54..74047e12fc4cd 100644 --- a/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.py +++ b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def letterCombinations(self, digits: str) -> List[str]: - if not digits: - return [] - d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] - ans = [""] - for i in digits: - s = d[int(i) - 2] - ans = [a + b for a in ans for b in s] - return ans +class Solution: + def letterCombinations(self, digits: str) -> List[str]: + if not digits: + return [] + d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] + ans = [""] + for i in digits: + s = d[int(i) - 2] + ans = [a + b for a in ans for b in s] + return ans diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.cpp b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.cpp new file mode 100644 index 0000000000000..5350bfc8e1983 --- /dev/null +++ b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + vector letterCombinations(string digits) { + if (digits.empty()) { + return {}; + } + vector d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + vector ans; + string t; + function dfs = [&](int i) { + if (i >= digits.size()) { + ans.push_back(t); + return; + } + for (auto& c : d[digits[i] - '2']) { + t.push_back(c); + dfs(i + 1); + t.pop_back(); + } + }; + dfs(0); + return ans; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.cs b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.cs new file mode 100644 index 0000000000000..cd9ed2b9b022c --- /dev/null +++ b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.cs @@ -0,0 +1,28 @@ +public class Solution { + private readonly string[] d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + private string digits; + private List ans = new List(); + private System.Text.StringBuilder t = new System.Text.StringBuilder(); + + public IList LetterCombinations(string digits) { + if (digits.Length == 0) { + return ans; + } + this.digits = digits; + Dfs(0); + return ans; + } + + private void Dfs(int i) { + if (i >= digits.Length) { + ans.Add(t.ToString()); + return; + } + string s = d[digits[i] - '2']; + foreach (char c in s) { + t.Append(c); + Dfs(i + 1); + t.Remove(t.Length - 1, 1); + } + } +} diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.go b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.go new file mode 100644 index 0000000000000..fa8f84febea9a --- /dev/null +++ b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.go @@ -0,0 +1,21 @@ +func letterCombinations(digits string) (ans []string) { + d := []string{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"} + t := []rune{} + var dfs func(int) + dfs = func(i int) { + if i >= len(digits) { + ans = append(ans, string(t)) + return + } + for _, c := range d[digits[i]-'2'] { + t = append(t, c) + dfs(i + 1) + t = t[:len(t)-1] + } + } + if len(digits) == 0 { + return + } + dfs(0) + return +} \ No newline at end of file diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.java b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.java new file mode 100644 index 0000000000000..2688422a263cc --- /dev/null +++ b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.java @@ -0,0 +1,28 @@ +class Solution { + private final String[] d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + private String digits; + private List ans = new ArrayList<>(); + private StringBuilder t = new StringBuilder(); + + public List letterCombinations(String digits) { + if (digits.length() == 0) { + return ans; + } + this.digits = digits; + dfs(0); + return ans; + } + + private void dfs(int i) { + if (i >= digits.length()) { + ans.add(t.toString()); + return; + } + String s = d[digits.charAt(i) - '2']; + for (char c : s.toCharArray()) { + t.append(c); + dfs(i + 1); + t.deleteCharAt(t.length() - 1); + } + } +} \ No newline at end of file diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.js b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.js new file mode 100644 index 0000000000000..3ba4721ef1457 --- /dev/null +++ b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.js @@ -0,0 +1,26 @@ +/** + * @param {string} digits + * @return {string[]} + */ +var letterCombinations = function (digits) { + if (digits.length == 0) { + return []; + } + const ans = []; + const t = []; + const d = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']; + const dfs = i => { + if (i >= digits.length) { + ans.push(t.join('')); + return; + } + const s = d[parseInt(digits[i]) - 2]; + for (const c of s) { + t.push(c); + dfs(i + 1); + t.pop(); + } + }; + dfs(0); + return ans; +}; diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.py b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.py new file mode 100644 index 0000000000000..3979de11f90e7 --- /dev/null +++ b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def letterCombinations(self, digits: str) -> List[str]: + def dfs(i: int): + if i >= len(digits): + ans.append("".join(t)) + return + for c in d[int(digits[i]) - 2]: + t.append(c) + dfs(i + 1) + t.pop() + + if not digits: + return [] + d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] + ans = [] + t = [] + dfs(0) + return ans diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.rs b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.rs new file mode 100644 index 0000000000000..510ec4f1e63ea --- /dev/null +++ b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn letter_combinations(digits: String) -> Vec { + let d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]; + let mut ans = Vec::new(); + let mut t = String::new(); + if digits.is_empty() { + return ans; + } + Solution::dfs(&digits, &d, &mut t, &mut ans, 0); + ans + } + + fn dfs(digits: &String, d: &[&str; 8], t: &mut String, ans: &mut Vec, i: usize) { + if i >= digits.len() { + ans.push(t.clone()); + return; + } + let s = d[((digits.chars().nth(i).unwrap() as u8) - b'2') as usize]; + for c in s.chars() { + t.push(c); + Solution::dfs(digits, d, t, ans, i + 1); + t.pop(); + } + } +} diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.ts b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.ts new file mode 100644 index 0000000000000..3c6dce34cf09c --- /dev/null +++ b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution2.ts @@ -0,0 +1,22 @@ +function letterCombinations(digits: string): string[] { + if (digits.length == 0) { + return []; + } + const ans: string[] = []; + const t: string[] = []; + const d = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']; + const dfs = (i: number) => { + if (i >= digits.length) { + ans.push(t.join('')); + return; + } + const s = d[parseInt(digits[i]) - 2]; + for (const c of s) { + t.push(c); + dfs(i + 1); + t.pop(); + } + }; + dfs(0); + return ans; +} diff --git a/solution/0000-0099/0018.4Sum/Solution.cpp b/solution/0000-0099/0018.4Sum/Solution.cpp index 4d5f61eb1efb0..9a9b503f01dba 100644 --- a/solution/0000-0099/0018.4Sum/Solution.cpp +++ b/solution/0000-0099/0018.4Sum/Solution.cpp @@ -1,39 +1,39 @@ -class Solution { -public: - vector> fourSum(vector& nums, int target) { - int n = nums.size(); - vector> ans; - if (n < 4) { - return ans; - } - sort(nums.begin(), nums.end()); - for (int i = 0; i < n - 3; ++i) { - if (i && nums[i] == nums[i - 1]) { - continue; - } - for (int j = i + 1; j < n - 2; ++j) { - if (j > i + 1 && nums[j] == nums[j - 1]) { - continue; - } - int k = j + 1, l = n - 1; - while (k < l) { - long long x = (long long) nums[i] + nums[j] + nums[k] + nums[l]; - if (x < target) { - ++k; - } else if (x > target) { - --l; - } else { - ans.push_back({nums[i], nums[j], nums[k++], nums[l--]}); - while (k < l && nums[k] == nums[k - 1]) { - ++k; - } - while (k < l && nums[l] == nums[l + 1]) { - --l; - } - } - } - } - } - return ans; - } +class Solution { +public: + vector> fourSum(vector& nums, int target) { + int n = nums.size(); + vector> ans; + if (n < 4) { + return ans; + } + sort(nums.begin(), nums.end()); + for (int i = 0; i < n - 3; ++i) { + if (i && nums[i] == nums[i - 1]) { + continue; + } + for (int j = i + 1; j < n - 2; ++j) { + if (j > i + 1 && nums[j] == nums[j - 1]) { + continue; + } + int k = j + 1, l = n - 1; + while (k < l) { + long long x = (long long) nums[i] + nums[j] + nums[k] + nums[l]; + if (x < target) { + ++k; + } else if (x > target) { + --l; + } else { + ans.push_back({nums[i], nums[j], nums[k++], nums[l--]}); + while (k < l && nums[k] == nums[k - 1]) { + ++k; + } + while (k < l && nums[l] == nums[l + 1]) { + --l; + } + } + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0018.4Sum/Solution.cs b/solution/0000-0099/0018.4Sum/Solution.cs index ce5ad0a84df57..84acc33ea8c1d 100644 --- a/solution/0000-0099/0018.4Sum/Solution.cs +++ b/solution/0000-0099/0018.4Sum/Solution.cs @@ -1,38 +1,38 @@ -public class Solution { - public IList> FourSum(int[] nums, int target) { - int n = nums.Length; - var ans = new List>(); - if (n < 4) { - return ans; - } - Array.Sort(nums); - for (int i = 0; i < n - 3; ++i) { - if (i > 0 && nums[i] == nums[i - 1]) { - continue; - } - for (int j = i + 1; j < n - 2; ++j) { - if (j > i + 1 && nums[j] == nums[j - 1]) { - continue; - } - int k = j + 1, l = n - 1; - while (k < l) { - long x = (long) nums[i] + nums[j] + nums[k] + nums[l]; - if (x < target) { - ++k; - } else if (x > target) { - --l; - } else { - ans.Add(new List {nums[i], nums[j], nums[k++], nums[l--]}); - while (k < l && nums[k] == nums[k - 1]) { - ++k; - } - while (k < l && nums[l] == nums[l + 1]) { - --l; - } - } - } - } - } - return ans; - } -} \ No newline at end of file +public class Solution { + public IList> FourSum(int[] nums, int target) { + int n = nums.Length; + var ans = new List>(); + if (n < 4) { + return ans; + } + Array.Sort(nums); + for (int i = 0; i < n - 3; ++i) { + if (i > 0 && nums[i] == nums[i - 1]) { + continue; + } + for (int j = i + 1; j < n - 2; ++j) { + if (j > i + 1 && nums[j] == nums[j - 1]) { + continue; + } + int k = j + 1, l = n - 1; + while (k < l) { + long x = (long) nums[i] + nums[j] + nums[k] + nums[l]; + if (x < target) { + ++k; + } else if (x > target) { + --l; + } else { + ans.Add(new List {nums[i], nums[j], nums[k++], nums[l--]}); + while (k < l && nums[k] == nums[k - 1]) { + ++k; + } + while (k < l && nums[l] == nums[l + 1]) { + --l; + } + } + } + } + } + return ans; + } +} diff --git a/solution/0000-0099/0018.4Sum/Solution.java b/solution/0000-0099/0018.4Sum/Solution.java index 804a1086ba4d9..e85b959a7753f 100644 --- a/solution/0000-0099/0018.4Sum/Solution.java +++ b/solution/0000-0099/0018.4Sum/Solution.java @@ -1,38 +1,38 @@ -class Solution { - public List> fourSum(int[] nums, int target) { - int n = nums.length; - List> ans = new ArrayList<>(); - if (n < 4) { - return ans; - } - Arrays.sort(nums); - for (int i = 0; i < n - 3; ++i) { - if (i > 0 && nums[i] == nums[i - 1]) { - continue; - } - for (int j = i + 1; j < n - 2; ++j) { - if (j > i + 1 && nums[j] == nums[j - 1]) { - continue; - } - int k = j + 1, l = n - 1; - while (k < l) { - long x = (long) nums[i] + nums[j] + nums[k] + nums[l]; - if (x < target) { - ++k; - } else if (x > target) { - --l; - } else { - ans.add(List.of(nums[i], nums[j], nums[k++], nums[l--])); - while (k < l && nums[k] == nums[k - 1]) { - ++k; - } - while (k < l && nums[l] == nums[l + 1]) { - --l; - } - } - } - } - } - return ans; - } +class Solution { + public List> fourSum(int[] nums, int target) { + int n = nums.length; + List> ans = new ArrayList<>(); + if (n < 4) { + return ans; + } + Arrays.sort(nums); + for (int i = 0; i < n - 3; ++i) { + if (i > 0 && nums[i] == nums[i - 1]) { + continue; + } + for (int j = i + 1; j < n - 2; ++j) { + if (j > i + 1 && nums[j] == nums[j - 1]) { + continue; + } + int k = j + 1, l = n - 1; + while (k < l) { + long x = (long) nums[i] + nums[j] + nums[k] + nums[l]; + if (x < target) { + ++k; + } else if (x > target) { + --l; + } else { + ans.add(List.of(nums[i], nums[j], nums[k++], nums[l--])); + while (k < l && nums[k] == nums[k - 1]) { + ++k; + } + while (k < l && nums[l] == nums[l + 1]) { + --l; + } + } + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0000-0099/0018.4Sum/Solution.py b/solution/0000-0099/0018.4Sum/Solution.py index 1e10966c30dc0..74e02a06336e7 100644 --- a/solution/0000-0099/0018.4Sum/Solution.py +++ b/solution/0000-0099/0018.4Sum/Solution.py @@ -1,28 +1,28 @@ -class Solution: - def fourSum(self, nums: List[int], target: int) -> List[List[int]]: - n = len(nums) - ans = [] - if n < 4: - return ans - nums.sort() - for i in range(n - 3): - if i and nums[i] == nums[i - 1]: - continue - for j in range(i + 1, n - 2): - if j > i + 1 and nums[j] == nums[j - 1]: - continue - k, l = j + 1, n - 1 - while k < l: - x = nums[i] + nums[j] + nums[k] + nums[l] - if x < target: - k += 1 - elif x > target: - l -= 1 - else: - ans.append([nums[i], nums[j], nums[k], nums[l]]) - k, l = k + 1, l - 1 - while k < l and nums[k] == nums[k - 1]: - k += 1 - while k < l and nums[l] == nums[l + 1]: - l -= 1 - return ans +class Solution: + def fourSum(self, nums: List[int], target: int) -> List[List[int]]: + n = len(nums) + ans = [] + if n < 4: + return ans + nums.sort() + for i in range(n - 3): + if i and nums[i] == nums[i - 1]: + continue + for j in range(i + 1, n - 2): + if j > i + 1 and nums[j] == nums[j - 1]: + continue + k, l = j + 1, n - 1 + while k < l: + x = nums[i] + nums[j] + nums[k] + nums[l] + if x < target: + k += 1 + elif x > target: + l -= 1 + else: + ans.append([nums[i], nums[j], nums[k], nums[l]]) + k, l = k + 1, l - 1 + while k < l and nums[k] == nums[k - 1]: + k += 1 + while k < l and nums[l] == nums[l + 1]: + l -= 1 + return ans diff --git a/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.rb b/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.rb index c372468c5e140..71dd3e89b8930 100644 --- a/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.rb +++ b/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.rb @@ -10,16 +10,16 @@ # @param {Integer} n # @return {ListNode} def remove_nth_from_end(head, n) - dummy = ListNode.new(0, head) - fast = slow = dummy - while n > 0 - fast = fast.next - n -= 1 - end - while fast.next - slow = slow.next - fast = fast.next - end - slow.next = slow.next.next - return dummy.next -end \ No newline at end of file + dummy = ListNode.new(0, head) + fast = slow = dummy + while n > 0 + fast = fast.next + n -= 1 + end + while fast.next + slow = slow.next + fast = fast.next + end + slow.next = slow.next.next + return dummy.next +end diff --git a/solution/0000-0099/0020.Valid Parentheses/Solution.cs b/solution/0000-0099/0020.Valid Parentheses/Solution.cs new file mode 100644 index 0000000000000..f0b79f30fbc19 --- /dev/null +++ b/solution/0000-0099/0020.Valid Parentheses/Solution.cs @@ -0,0 +1,17 @@ +public class Solution { + public bool IsValid(string s) { + Stack stk = new Stack(); + foreach (var c in s.ToCharArray()) { + if (c == '(') { + stk.Push(')'); + } else if (c == '[') { + stk.Push(']'); + } else if (c == '{') { + stk.Push('}'); + } else if (stk.Count == 0 || stk.Pop() != c) { + return false; + } + } + return stk.Count == 0; + } +} diff --git a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.cpp b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.cpp index 29bc8c5bf002c..7a51515746e6d 100644 --- a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.cpp +++ b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.cpp @@ -11,19 +11,14 @@ class Solution { public: ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { - ListNode* dummy = new ListNode(); - ListNode* curr = dummy; - while (list1 && list2) { - if (list1->val <= list2->val) { - curr->next = list1; - list1 = list1->next; - } else { - curr->next = list2; - list2 = list2->next; - } - curr = curr->next; + if (!list1) return list2; + if (!list2) return list1; + if (list1->val <= list2->val) { + list1->next = mergeTwoLists(list1->next, list2); + return list1; + } else { + list2->next = mergeTwoLists(list1, list2->next); + return list2; } - curr->next = list1 ? list1 : list2; - return dummy->next; } }; \ No newline at end of file diff --git a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.cs b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.cs index 536a25df58d8a..f51146a70d7d9 100644 --- a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.cs +++ b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.cs @@ -30,4 +30,4 @@ public ListNode MergeTwoLists(ListNode list1, ListNode list2) { cur.next = list1 == null ? list2 : list1; return dummy.next; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.go b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.go index dc5307e0f1a81..fffe7dbbf243d 100644 --- a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.go +++ b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.go @@ -6,22 +6,17 @@ * } */ func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { - dummy := &ListNode{} - curr := dummy - for list1 != nil && list2 != nil { - if list1.Val <= list2.Val { - curr.Next = list1 - list1 = list1.Next - } else { - curr.Next = list2 - list2 = list2.Next - } - curr = curr.Next + if list1 == nil { + return list2 } - if list1 != nil { - curr.Next = list1 + if list2 == nil { + return list1 + } + if list1.Val <= list2.Val { + list1.Next = mergeTwoLists(list1.Next, list2) + return list1 } else { - curr.Next = list2 + list2.Next = mergeTwoLists(list1, list2.Next) + return list2 } - return dummy.Next } \ No newline at end of file diff --git a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.java b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.java index 3c99715d8a068..856ec6c531499 100644 --- a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.java +++ b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.java @@ -10,19 +10,18 @@ */ class Solution { public ListNode mergeTwoLists(ListNode list1, ListNode list2) { - ListNode dummy = new ListNode(); - ListNode curr = dummy; - while (list1 != null && list2 != null) { - if (list1.val <= list2.val) { - curr.next = list1; - list1 = list1.next; - } else { - curr.next = list2; - list2 = list2.next; - } - curr = curr.next; + if (list1 == null) { + return list2; + } + if (list2 == null) { + return list1; + } + if (list1.val <= list2.val) { + list1.next = mergeTwoLists(list1.next, list2); + return list1; + } else { + list2.next = mergeTwoLists(list1, list2.next); + return list2; } - curr.next = list1 == null ? list2 : list1; - return dummy.next; } } \ No newline at end of file diff --git a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.js b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.js index f635532d0d706..67472ed649282 100644 --- a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.js +++ b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.js @@ -11,18 +11,14 @@ * @return {ListNode} */ var mergeTwoLists = function (list1, list2) { - const dummy = new ListNode(); - let curr = dummy; - while (list1 && list2) { - if (list1.val <= list2.val) { - curr.next = list1; - list1 = list1.next; - } else { - curr.next = list2; - list2 = list2.next; - } - curr = curr.next; + if (!list1 || !list2) { + return list1 || list2; + } + if (list1.val <= list2.val) { + list1.next = mergeTwoLists(list1.next, list2); + return list1; + } else { + list2.next = mergeTwoLists(list1, list2.next); + return list2; } - curr.next = list1 || list2; - return dummy.next; }; diff --git a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.py b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.py index a525539522097..c9d9b14a2f43b 100644 --- a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.py +++ b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.py @@ -7,15 +7,11 @@ class Solution: def mergeTwoLists( self, list1: Optional[ListNode], list2: Optional[ListNode] ) -> Optional[ListNode]: - dummy = ListNode() - curr = dummy - while list1 and list2: - if list1.val <= list2.val: - curr.next = list1 - list1 = list1.next - else: - curr.next = list2 - list2 = list2.next - curr = curr.next - curr.next = list1 or list2 - return dummy.next + if list1 is None or list2 is None: + return list1 or list2 + if list1.val <= list2.val: + list1.next = self.mergeTwoLists(list1.next, list2) + return list1 + else: + list2.next = self.mergeTwoLists(list1, list2.next) + return list2 diff --git a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.rb b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.rb index d686136235702..f27273d9fd652 100644 --- a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.rb +++ b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.rb @@ -24,4 +24,4 @@ def merge_two_lists(list1, list2) end cur.next = list1 || list2 dummy.next -end \ No newline at end of file +end diff --git a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.cpp b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.cpp new file mode 100644 index 0000000000000..29bc8c5bf002c --- /dev/null +++ b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.cpp @@ -0,0 +1,29 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { + ListNode* dummy = new ListNode(); + ListNode* curr = dummy; + while (list1 && list2) { + if (list1->val <= list2->val) { + curr->next = list1; + list1 = list1->next; + } else { + curr->next = list2; + list2 = list2->next; + } + curr = curr->next; + } + curr->next = list1 ? list1 : list2; + return dummy->next; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.go b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.go new file mode 100644 index 0000000000000..dc5307e0f1a81 --- /dev/null +++ b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.go @@ -0,0 +1,27 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { + dummy := &ListNode{} + curr := dummy + for list1 != nil && list2 != nil { + if list1.Val <= list2.Val { + curr.Next = list1 + list1 = list1.Next + } else { + curr.Next = list2 + list2 = list2.Next + } + curr = curr.Next + } + if list1 != nil { + curr.Next = list1 + } else { + curr.Next = list2 + } + return dummy.Next +} \ No newline at end of file diff --git a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.java b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.java new file mode 100644 index 0000000000000..3c99715d8a068 --- /dev/null +++ b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.java @@ -0,0 +1,28 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode mergeTwoLists(ListNode list1, ListNode list2) { + ListNode dummy = new ListNode(); + ListNode curr = dummy; + while (list1 != null && list2 != null) { + if (list1.val <= list2.val) { + curr.next = list1; + list1 = list1.next; + } else { + curr.next = list2; + list2 = list2.next; + } + curr = curr.next; + } + curr.next = list1 == null ? list2 : list1; + return dummy.next; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.js b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.js new file mode 100644 index 0000000000000..f635532d0d706 --- /dev/null +++ b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.js @@ -0,0 +1,28 @@ +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} list1 + * @param {ListNode} list2 + * @return {ListNode} + */ +var mergeTwoLists = function (list1, list2) { + const dummy = new ListNode(); + let curr = dummy; + while (list1 && list2) { + if (list1.val <= list2.val) { + curr.next = list1; + list1 = list1.next; + } else { + curr.next = list2; + list2 = list2.next; + } + curr = curr.next; + } + curr.next = list1 || list2; + return dummy.next; +}; diff --git a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.py b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.py new file mode 100644 index 0000000000000..a525539522097 --- /dev/null +++ b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.py @@ -0,0 +1,21 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeTwoLists( + self, list1: Optional[ListNode], list2: Optional[ListNode] + ) -> Optional[ListNode]: + dummy = ListNode() + curr = dummy + while list1 and list2: + if list1.val <= list2.val: + curr.next = list1 + list1 = list1.next + else: + curr.next = list2 + list2 = list2.next + curr = curr.next + curr.next = list1 or list2 + return dummy.next diff --git a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.rs b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.rs new file mode 100644 index 0000000000000..bd31db16f2fff --- /dev/null +++ b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.rs @@ -0,0 +1,40 @@ +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn merge_two_lists( + mut list1: Option>, + mut list2: Option> + ) -> Option> { + let mut new_list = ListNode::new(0); + let mut cur = &mut new_list; + while list1.is_some() && list2.is_some() { + let (l1, l2) = (list1.as_deref_mut().unwrap(), list2.as_deref_mut().unwrap()); + if l1.val < l2.val { + let next = l1.next.take(); + cur.next = list1.take(); + list1 = next; + } else { + let next = l2.next.take(); + cur.next = list2.take(); + list2 = next; + } + cur = cur.next.as_deref_mut().unwrap(); + } + cur.next = list1.or(list2); + new_list.next + } +} diff --git a/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.ts b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.ts new file mode 100644 index 0000000000000..4223abe0346a2 --- /dev/null +++ b/solution/0000-0099/0021.Merge Two Sorted Lists/Solution2.ts @@ -0,0 +1,28 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null { + const dummy = new ListNode(0); + let cur = dummy; + while (list1 != null && list2 != null) { + if (list1.val < list2.val) { + cur.next = list1; + list1 = list1.next; + } else { + cur.next = list2; + list2 = list2.next; + } + cur = cur.next; + } + cur.next = list1 || list2; + return dummy.next; +} diff --git a/solution/0000-0099/0022.Generate Parentheses/Solution2.rs b/solution/0000-0099/0022.Generate Parentheses/Solution2.rs new file mode 100644 index 0000000000000..c5c8acd79026b --- /dev/null +++ b/solution/0000-0099/0022.Generate Parentheses/Solution2.rs @@ -0,0 +1,28 @@ +impl Solution { + pub fn generate_parenthesis(n: i32) -> Vec { + let mut dp: Vec> = vec![vec![]; n as usize + 1]; + + // Initialize the dp vector + dp[0].push(String::from("")); + dp[1].push(String::from("()")); + + // Begin the actual dp process + for i in 2..=n as usize { + for j in 0..i as usize { + let dp_c = dp.clone(); + let first_half = &dp_c[j]; + let second_half = &dp_c[i - j - 1]; + + for f in first_half { + for s in second_half { + let f_c = f.clone(); + let cur_str = f_c + "(" + &*s + ")"; + dp[i].push(cur_str); + } + } + } + } + + dp[n as usize].clone() + } +} diff --git a/solution/0000-0099/0023.Merge k Sorted Lists/Solution.cpp b/solution/0000-0099/0023.Merge k Sorted Lists/Solution.cpp index d09218baa3a72..ea92d9d870e35 100644 --- a/solution/0000-0099/0023.Merge k Sorted Lists/Solution.cpp +++ b/solution/0000-0099/0023.Merge k Sorted Lists/Solution.cpp @@ -1,34 +1,34 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* mergeKLists(vector& lists) { - auto cmp = [](ListNode* a, ListNode* b) { return a->val > b->val; }; - priority_queue, decltype(cmp)> pq; - for (auto head : lists) { - if (head) { - pq.push(head); - } - } - ListNode* dummy = new ListNode(); - ListNode* cur = dummy; - while (!pq.empty()) { - ListNode* node = pq.top(); - pq.pop(); - if (node->next) { - pq.push(node->next); - } - cur->next = node; - cur = cur->next; - } - return dummy->next; - } +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeKLists(vector& lists) { + auto cmp = [](ListNode* a, ListNode* b) { return a->val > b->val; }; + priority_queue, decltype(cmp)> pq; + for (auto head : lists) { + if (head) { + pq.push(head); + } + } + ListNode* dummy = new ListNode(); + ListNode* cur = dummy; + while (!pq.empty()) { + ListNode* node = pq.top(); + pq.pop(); + if (node->next) { + pq.push(node->next); + } + cur->next = node; + cur = cur->next; + } + return dummy->next; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0023.Merge k Sorted Lists/Solution.cs b/solution/0000-0099/0023.Merge k Sorted Lists/Solution.cs index d90f5bde7b6cc..ad5b2da0c5014 100644 --- a/solution/0000-0099/0023.Merge k Sorted Lists/Solution.cs +++ b/solution/0000-0099/0023.Merge k Sorted Lists/Solution.cs @@ -1,32 +1,32 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } - * } - */ -public class Solution { - public ListNode MergeKLists(ListNode[] lists) { - PriorityQueue pq = new PriorityQueue(); - foreach (var head in lists) { - if (head != null) { - pq.Enqueue(head, head.val); - } - } - var dummy = new ListNode(); - var cur = dummy; - while (pq.Count > 0) { - var node = pq.Dequeue(); - cur.next = node; - cur = cur.next; - if (node.next != null) { - pq.Enqueue(node.next, node.next.val); - } - } - return dummy.next; - } -} \ No newline at end of file +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode MergeKLists(ListNode[] lists) { + PriorityQueue pq = new PriorityQueue(); + foreach (var head in lists) { + if (head != null) { + pq.Enqueue(head, head.val); + } + } + var dummy = new ListNode(); + var cur = dummy; + while (pq.Count > 0) { + var node = pq.Dequeue(); + cur.next = node; + cur = cur.next; + if (node.next != null) { + pq.Enqueue(node.next, node.next.val); + } + } + return dummy.next; + } +} diff --git a/solution/0000-0099/0023.Merge k Sorted Lists/Solution.java b/solution/0000-0099/0023.Merge k Sorted Lists/Solution.java index 038e32822fcd5..6f9b5041125ca 100644 --- a/solution/0000-0099/0023.Merge k Sorted Lists/Solution.java +++ b/solution/0000-0099/0023.Merge k Sorted Lists/Solution.java @@ -1,31 +1,31 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode mergeKLists(ListNode[] lists) { - PriorityQueue pq = new PriorityQueue<>((a, b) -> a.val - b.val); - for (ListNode head : lists) { - if (head != null) { - pq.offer(head); - } - } - ListNode dummy = new ListNode(); - ListNode cur = dummy; - while (!pq.isEmpty()) { - ListNode node = pq.poll(); - if (node.next != null) { - pq.offer(node.next); - } - cur.next = node; - cur = cur.next; - } - return dummy.next; - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode mergeKLists(ListNode[] lists) { + PriorityQueue pq = new PriorityQueue<>((a, b) -> a.val - b.val); + for (ListNode head : lists) { + if (head != null) { + pq.offer(head); + } + } + ListNode dummy = new ListNode(); + ListNode cur = dummy; + while (!pq.isEmpty()) { + ListNode node = pq.poll(); + if (node.next != null) { + pq.offer(node.next); + } + cur.next = node; + cur = cur.next; + } + return dummy.next; + } } \ No newline at end of file diff --git a/solution/0000-0099/0023.Merge k Sorted Lists/Solution.py b/solution/0000-0099/0023.Merge k Sorted Lists/Solution.py index 7cc2741281c3b..39d034937250e 100644 --- a/solution/0000-0099/0023.Merge k Sorted Lists/Solution.py +++ b/solution/0000-0099/0023.Merge k Sorted Lists/Solution.py @@ -1,18 +1,18 @@ -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: - setattr(ListNode, "__lt__", lambda a, b: a.val < b.val) - pq = [head for head in lists if head] - heapify(pq) - dummy = cur = ListNode() - while pq: - node = heappop(pq) - if node.next: - heappush(pq, node.next) - cur.next = node - cur = cur.next - return dummy.next +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: + setattr(ListNode, "__lt__", lambda a, b: a.val < b.val) + pq = [head for head in lists if head] + heapify(pq) + dummy = cur = ListNode() + while pq: + node = heappop(pq) + if node.next: + heappush(pq, node.next) + cur.next = node + cur = cur.next + return dummy.next diff --git a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.cpp b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.cpp index 97b80d2973961..0045a05458728 100644 --- a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.cpp +++ b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.cpp @@ -1,27 +1,23 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* swapPairs(ListNode* head) { - ListNode* dummy = new ListNode(0, head); - ListNode* pre = dummy; - ListNode* cur = head; - while (cur && cur->next) { - ListNode* t = cur->next; - cur->next = t->next; - t->next = cur; - pre->next = t; - pre = cur; - cur = cur->next; - } - return dummy->next; - } +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* swapPairs(ListNode* head) { + if (!head || !head->next) { + return head; + } + ListNode* t = swapPairs(head->next->next); + ListNode* p = head->next; + p->next = head; + head->next = t; + return p; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.go b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.go index a382224036bb0..1ad10858aa638 100644 --- a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.go +++ b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.go @@ -6,14 +6,12 @@ * } */ func swapPairs(head *ListNode) *ListNode { - dummy := &ListNode{Next: head} - pre, cur := dummy, head - for cur != nil && cur.Next != nil { - t := cur.Next - cur.Next = t.Next - t.Next = cur - pre.Next = t - pre, cur = cur, cur.Next + if head == nil || head.Next == nil { + return head } - return dummy.Next + t := swapPairs(head.Next.Next) + p := head.Next + p.Next = head + head.Next = t + return p } \ No newline at end of file diff --git a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.java b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.java index b644691e83ab5..fa1db7ac52174 100644 --- a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.java +++ b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.java @@ -1,26 +1,22 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode swapPairs(ListNode head) { - ListNode dummy = new ListNode(0, head); - ListNode pre = dummy; - ListNode cur = head; - while (cur != null && cur.next != null) { - ListNode t = cur.next; - cur.next = t.next; - t.next = cur; - pre.next = t; - pre = cur; - cur = cur.next; - } - return dummy.next; - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode swapPairs(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode t = swapPairs(head.next.next); + ListNode p = head.next; + p.next = head; + head.next = t; + return p; + } } \ No newline at end of file diff --git a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.js b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.js index f1631d353e161..3747c97fd4ef2 100644 --- a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.js +++ b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.js @@ -10,14 +10,12 @@ * @return {ListNode} */ var swapPairs = function (head) { - const dummy = new ListNode(0, head); - let [pre, cur] = [dummy, head]; - while (cur && cur.next) { - const t = cur.next; - cur.next = t.next; - t.next = cur; - pre.next = t; - [pre, cur] = [cur, cur.next]; + if (!head || !head.next) { + return head; } - return dummy.next; + const t = swapPairs(head.next.next); + const p = head.next; + p.next = head; + head.next = t; + return p; }; diff --git a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.py b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.py index 0b592079c7183..a07b803296ff1 100644 --- a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.py +++ b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.py @@ -1,16 +1,14 @@ -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: - dummy = ListNode(next=head) - pre, cur = dummy, head - while cur and cur.next: - t = cur.next - cur.next = t.next - t.next = cur - pre.next = t - pre, cur = cur, cur.next - return dummy.next +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: + if head is None or head.next is None: + return head + t = self.swapPairs(head.next.next) + p = head.next + p.next = head + head.next = t + return p diff --git a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.rb b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.rb index 3b542c52add61..b9d66f5753e3f 100644 --- a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.rb +++ b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.rb @@ -9,16 +9,16 @@ # @param {ListNode} head # @return {ListNode} def swap_pairs(head) - dummy = ListNode.new(0, head) - pre = dummy - cur = head - while !cur.nil? && !cur.next.nil? - t = cur.next - cur.next = t.next - t.next = cur - pre.next = t - pre = cur - cur = cur.next - end - dummy.next -end \ No newline at end of file + dummy = ListNode.new(0, head) + pre = dummy + cur = head + while !cur.nil? && !cur.next.nil? + t = cur.next + cur.next = t.next + t.next = cur + pre.next = t + pre = cur + cur = cur.next + end + dummy.next +end diff --git a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.ts b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.ts index 705c4eac5d770..ac6db6153dfc0 100644 --- a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.ts +++ b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.ts @@ -11,14 +11,12 @@ */ function swapPairs(head: ListNode | null): ListNode | null { - const dummy = new ListNode(0, head); - let [pre, cur] = [dummy, head]; - while (cur && cur.next) { - const t = cur.next; - cur.next = t.next; - t.next = cur; - pre.next = t; - [pre, cur] = [cur, cur.next]; + if (!head || !head.next) { + return head; } - return dummy.next; + const t = swapPairs(head.next.next); + const p = head.next; + p.next = head; + head.next = t; + return p; } diff --git a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution2.cpp b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution2.cpp new file mode 100644 index 0000000000000..3aa31a6efb5fe --- /dev/null +++ b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution2.cpp @@ -0,0 +1,27 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* swapPairs(ListNode* head) { + ListNode* dummy = new ListNode(0, head); + ListNode* pre = dummy; + ListNode* cur = head; + while (cur && cur->next) { + ListNode* t = cur->next; + cur->next = t->next; + t->next = cur; + pre->next = t; + pre = cur; + cur = cur->next; + } + return dummy->next; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution2.go b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution2.go new file mode 100644 index 0000000000000..a382224036bb0 --- /dev/null +++ b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution2.go @@ -0,0 +1,19 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func swapPairs(head *ListNode) *ListNode { + dummy := &ListNode{Next: head} + pre, cur := dummy, head + for cur != nil && cur.Next != nil { + t := cur.Next + cur.Next = t.Next + t.Next = cur + pre.Next = t + pre, cur = cur, cur.Next + } + return dummy.Next +} \ No newline at end of file diff --git a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution2.java b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution2.java new file mode 100644 index 0000000000000..2f263223f9b15 --- /dev/null +++ b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution2.java @@ -0,0 +1,26 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode swapPairs(ListNode head) { + ListNode dummy = new ListNode(0, head); + ListNode pre = dummy; + ListNode cur = head; + while (cur != null && cur.next != null) { + ListNode t = cur.next; + cur.next = t.next; + t.next = cur; + pre.next = t; + pre = cur; + cur = cur.next; + } + return dummy.next; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution2.js b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution2.js new file mode 100644 index 0000000000000..f1631d353e161 --- /dev/null +++ b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution2.js @@ -0,0 +1,23 @@ +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var swapPairs = function (head) { + const dummy = new ListNode(0, head); + let [pre, cur] = [dummy, head]; + while (cur && cur.next) { + const t = cur.next; + cur.next = t.next; + t.next = cur; + pre.next = t; + [pre, cur] = [cur, cur.next]; + } + return dummy.next; +}; diff --git a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution2.py b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution2.py new file mode 100644 index 0000000000000..1eba126d50648 --- /dev/null +++ b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution2.py @@ -0,0 +1,16 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: + dummy = ListNode(next=head) + pre, cur = dummy, head + while cur and cur.next: + t = cur.next + cur.next = t.next + t.next = cur + pre.next = t + pre, cur = cur, cur.next + return dummy.next diff --git a/solution/0000-0099/0024.Swap Nodes in Pairs/Solution2.ts b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution2.ts new file mode 100644 index 0000000000000..705c4eac5d770 --- /dev/null +++ b/solution/0000-0099/0024.Swap Nodes in Pairs/Solution2.ts @@ -0,0 +1,24 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function swapPairs(head: ListNode | null): ListNode | null { + const dummy = new ListNode(0, head); + let [pre, cur] = [dummy, head]; + while (cur && cur.next) { + const t = cur.next; + cur.next = t.next; + t.next = cur; + pre.next = t; + [pre, cur] = [cur, cur.next]; + } + return dummy.next; +} diff --git a/solution/0000-0099/0025.Reverse Nodes in k-Group/Solution.cs b/solution/0000-0099/0025.Reverse Nodes in k-Group/Solution.cs index 60f94ff1c9cce..f99c0cc7b8cb3 100644 --- a/solution/0000-0099/0025.Reverse Nodes in k-Group/Solution.cs +++ b/solution/0000-0099/0025.Reverse Nodes in k-Group/Solution.cs @@ -45,4 +45,4 @@ private ListNode ReverseList(ListNode head) { } return pre; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0025.Reverse Nodes in k-Group/Solution.go b/solution/0000-0099/0025.Reverse Nodes in k-Group/Solution.go index a542ee286c3b1..acde72a916dfb 100644 --- a/solution/0000-0099/0025.Reverse Nodes in k-Group/Solution.go +++ b/solution/0000-0099/0025.Reverse Nodes in k-Group/Solution.go @@ -6,16 +6,20 @@ * } */ func reverseKGroup(head *ListNode, k int) *ListNode { - start, end := head, head - for i := 0; i < k; i++ { - if end == nil { - return head + var dummy *ListNode = &ListNode{} + p, cur := dummy, head + for cur != nil { + start := cur + for i := 0; i < k; i++ { + if cur == nil { + p.Next = start + return dummy.Next + } + cur = cur.Next } - end = end.Next + p.Next, p = reverse(start, cur), start } - res := reverse(start, end) - start.Next = reverseKGroup(end, k) - return res + return dummy.Next } func reverse(start, end *ListNode) *ListNode { diff --git a/solution/0000-0099/0025.Reverse Nodes in k-Group/Solution2.go b/solution/0000-0099/0025.Reverse Nodes in k-Group/Solution2.go new file mode 100644 index 0000000000000..a542ee286c3b1 --- /dev/null +++ b/solution/0000-0099/0025.Reverse Nodes in k-Group/Solution2.go @@ -0,0 +1,29 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func reverseKGroup(head *ListNode, k int) *ListNode { + start, end := head, head + for i := 0; i < k; i++ { + if end == nil { + return head + } + end = end.Next + } + res := reverse(start, end) + start.Next = reverseKGroup(end, k) + return res +} + +func reverse(start, end *ListNode) *ListNode { + var pre *ListNode = nil + for start != end { + tmp := start.Next + start.Next, pre = pre, start + start = tmp + } + return pre +} \ No newline at end of file diff --git a/solution/0000-0099/0025.Reverse Nodes in k-Group/Solution2.ts b/solution/0000-0099/0025.Reverse Nodes in k-Group/Solution2.ts new file mode 100644 index 0000000000000..db9db71869596 --- /dev/null +++ b/solution/0000-0099/0025.Reverse Nodes in k-Group/Solution2.ts @@ -0,0 +1,46 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function reverseKGroup(head: ListNode | null, k: number): ListNode | null { + if (k === 1) { + return head; + } + + const dummy = new ListNode(0, head); + let root = dummy; + while (root != null) { + let pre = root; + let cur = root; + + let count = 0; + while (count !== k) { + count++; + cur = cur.next; + if (cur == null) { + return dummy.next; + } + } + + const nextRoot = pre.next; + pre.next = cur; + + let node = nextRoot; + let next = node.next; + node.next = cur.next; + while (node != cur) { + [next.next, node, next] = [node, next, next.next]; + } + root = nextRoot; + } + + return dummy.next; +} diff --git a/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.cpp b/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.cpp index 905f169e9d64b..991c701e32124 100644 --- a/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.cpp +++ b/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.cpp @@ -1,7 +1,12 @@ class Solution { public: int removeDuplicates(vector& nums) { - nums.erase(unique(nums.begin(), nums.end()), nums.end()); - return nums.size(); + int k = 0; + for (int x : nums) { + if (k == 0 || x != nums[k - 1]) { + nums[k++] = x; + } + } + return k; } -}; +}; \ No newline at end of file diff --git a/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.cs b/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.cs index 96ee0cbdc8717..45ec29fbc84eb 100644 --- a/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.cs +++ b/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.cs @@ -8,4 +8,4 @@ public int RemoveDuplicates(int[] nums) { } return k; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.php b/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.php index 54d060c38455e..93a1244ac4459 100644 --- a/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.php +++ b/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.php @@ -12,4 +12,4 @@ function removeDuplicates(&$nums) { } return $k; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution2.cpp b/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution2.cpp new file mode 100644 index 0000000000000..c1cdf93285b2c --- /dev/null +++ b/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution2.cpp @@ -0,0 +1,7 @@ +class Solution { +public: + int removeDuplicates(vector& nums) { + nums.erase(unique(nums.begin(), nums.end()), nums.end()); + return nums.size(); + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0027.Remove Element/Solution.php b/solution/0000-0099/0027.Remove Element/Solution.php index 2bc1b116e03d5..3ec8334af39bb 100644 --- a/solution/0000-0099/0027.Remove Element/Solution.php +++ b/solution/0000-0099/0027.Remove Element/Solution.php @@ -11,4 +11,4 @@ function removeElement(&$nums, $val) { } } } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution.cpp b/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution.cpp index 493c1e8d6eccf..59bb6c02750f5 100644 --- a/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution.cpp +++ b/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution.cpp @@ -1,4 +1,4 @@ -class Solution { +class Solution { private: vector Next(string str) { vector n(str.length()); diff --git a/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution.cs b/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution.cs index 20539523d0c4a..79c5021db0319 100644 --- a/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution.cs +++ b/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution.cs @@ -11,4 +11,4 @@ public int StrStr(string haystack, string needle) { } return -1; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution.go b/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution.go index 5ed60b2b9f822..0a94888eb3ecb 100644 --- a/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution.go +++ b/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution.go @@ -1,27 +1,9 @@ func strStr(haystack string, needle string) int { n, m := len(haystack), len(needle) - sha, target, left, right, mod := 0, 0, 0, 0, 1<<31-1 - multi := 1 - for i := 0; i < m; i++ { - target = (target*256%mod + int(needle[i])) % mod - } - for i := 1; i < m; i++ { - multi = multi * 256 % mod - } - - for ; right < n; right++ { - sha = (sha*256%mod + int(haystack[right])) % mod - if right-left+1 < m { - continue - } - // 此时 left~right 的长度已经为 needle 的长度 m 了,只需要比对 sha 值与 target 是否一致即可 - // 为避免 hash 冲突,还需要确保 haystack[left:right+1] 与 needle 相同 - if sha == target && haystack[left:right+1] == needle { - return left + for i := 0; i <= n-m; i++ { + if haystack[i:i+m] == needle { + return i } - // 未匹配成功,left 右移一位 - sha = (sha - (int(haystack[left])*multi)%mod + mod) % mod - left++ } return -1 } \ No newline at end of file diff --git a/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution.php b/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution.php index 6d509d0ffef67..fbb89ca1a3810 100644 --- a/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution.php +++ b/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution.php @@ -17,4 +17,4 @@ function strStr($haystack, $needle) { return -1; } } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution2.go b/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution2.go new file mode 100644 index 0000000000000..5ed60b2b9f822 --- /dev/null +++ b/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution2.go @@ -0,0 +1,27 @@ +func strStr(haystack string, needle string) int { + n, m := len(haystack), len(needle) + sha, target, left, right, mod := 0, 0, 0, 0, 1<<31-1 + multi := 1 + for i := 0; i < m; i++ { + target = (target*256%mod + int(needle[i])) % mod + } + for i := 1; i < m; i++ { + multi = multi * 256 % mod + } + + for ; right < n; right++ { + sha = (sha*256%mod + int(haystack[right])) % mod + if right-left+1 < m { + continue + } + // 此时 left~right 的长度已经为 needle 的长度 m 了,只需要比对 sha 值与 target 是否一致即可 + // 为避免 hash 冲突,还需要确保 haystack[left:right+1] 与 needle 相同 + if sha == target && haystack[left:right+1] == needle { + return left + } + // 未匹配成功,left 右移一位 + sha = (sha - (int(haystack[left])*multi)%mod + mod) % mod + left++ + } + return -1 +} \ No newline at end of file diff --git a/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution2.ts b/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution2.ts new file mode 100644 index 0000000000000..6eebf20815812 --- /dev/null +++ b/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/Solution2.ts @@ -0,0 +1,28 @@ +function strStr(haystack: string, needle: string): number { + const m = haystack.length; + const n = needle.length; + const next = new Array(n).fill(0); + let j = 0; + for (let i = 1; i < n; i++) { + while (j > 0 && needle[i] !== needle[j]) { + j = next[j - 1]; + } + if (needle[i] === needle[j]) { + j++; + } + next[i] = j; + } + j = 0; + for (let i = 0; i < m; i++) { + while (j > 0 && haystack[i] !== needle[j]) { + j = next[j - 1]; + } + if (haystack[i] === needle[j]) { + j++; + } + if (j === n) { + return i - n + 1; + } + } + return -1; +} diff --git a/solution/0000-0099/0029.Divide Two Integers/Solution.cpp b/solution/0000-0099/0029.Divide Two Integers/Solution.cpp index e6e59f4a50f44..26d265a0ebb5f 100644 --- a/solution/0000-0099/0029.Divide Two Integers/Solution.cpp +++ b/solution/0000-0099/0029.Divide Two Integers/Solution.cpp @@ -1,26 +1,26 @@ -class Solution { -public: - int divide(int a, int b) { - if (b == 1) { - return a; - } - if (a == INT_MIN && b == -1) { - return INT_MAX; - } - bool sign = (a > 0 && b > 0) || (a < 0 && b < 0); - a = a > 0 ? -a : a; - b = b > 0 ? -b : b; - int ans = 0; - while (a <= b) { - int x = b; - int cnt = 1; - while (x >= (INT_MIN >> 1) && a <= (x << 1)) { - x <<= 1; - cnt <<= 1; - } - ans += cnt; - a -= x; - } - return sign ? ans : -ans; - } +class Solution { +public: + int divide(int a, int b) { + if (b == 1) { + return a; + } + if (a == INT_MIN && b == -1) { + return INT_MAX; + } + bool sign = (a > 0 && b > 0) || (a < 0 && b < 0); + a = a > 0 ? -a : a; + b = b > 0 ? -b : b; + int ans = 0; + while (a <= b) { + int x = b; + int cnt = 1; + while (x >= (INT_MIN >> 1) && a <= (x << 1)) { + x <<= 1; + cnt <<= 1; + } + ans += cnt; + a -= x; + } + return sign ? ans : -ans; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0029.Divide Two Integers/Solution.cs b/solution/0000-0099/0029.Divide Two Integers/Solution.cs index 0eda8847194d9..40369d3d61aa8 100644 --- a/solution/0000-0099/0029.Divide Two Integers/Solution.cs +++ b/solution/0000-0099/0029.Divide Two Integers/Solution.cs @@ -1,25 +1,25 @@ -public class Solution { - public int Divide(int a, int b) { - if (b == 1) { - return a; - } - if (a == int.MinValue && b == -1) { - return int.MaxValue; - } - bool sign = (a > 0 && b > 0) || (a < 0 && b < 0); - a = a > 0 ? -a : a; - b = b > 0 ? -b : b; - int ans = 0; - while (a <= b) { - int x = b; - int cnt = 1; - while (x >= (int.MinValue >> 1) && a <= (x << 1)) { - x <<= 1; - cnt <<= 1; - } - ans += cnt; - a -= x; - } - return sign ? ans : -ans; - } -} \ No newline at end of file +public class Solution { + public int Divide(int a, int b) { + if (b == 1) { + return a; + } + if (a == int.MinValue && b == -1) { + return int.MaxValue; + } + bool sign = (a > 0 && b > 0) || (a < 0 && b < 0); + a = a > 0 ? -a : a; + b = b > 0 ? -b : b; + int ans = 0; + while (a <= b) { + int x = b; + int cnt = 1; + while (x >= (int.MinValue >> 1) && a <= (x << 1)) { + x <<= 1; + cnt <<= 1; + } + ans += cnt; + a -= x; + } + return sign ? ans : -ans; + } +} diff --git a/solution/0000-0099/0029.Divide Two Integers/Solution.java b/solution/0000-0099/0029.Divide Two Integers/Solution.java index 39a3fa4229851..fcdf55eedb442 100644 --- a/solution/0000-0099/0029.Divide Two Integers/Solution.java +++ b/solution/0000-0099/0029.Divide Two Integers/Solution.java @@ -1,25 +1,25 @@ -class Solution { - public int divide(int a, int b) { - if (b == 1) { - return a; - } - if (a == Integer.MIN_VALUE && b == -1) { - return Integer.MAX_VALUE; - } - boolean sign = (a > 0 && b > 0) || (a < 0 && b < 0); - a = a > 0 ? -a : a; - b = b > 0 ? -b : b; - int ans = 0; - while (a <= b) { - int x = b; - int cnt = 1; - while (x >= (Integer.MIN_VALUE >> 1) && a <= (x << 1)) { - x <<= 1; - cnt <<= 1; - } - ans += cnt; - a -= x; - } - return sign ? ans : -ans; - } +class Solution { + public int divide(int a, int b) { + if (b == 1) { + return a; + } + if (a == Integer.MIN_VALUE && b == -1) { + return Integer.MAX_VALUE; + } + boolean sign = (a > 0 && b > 0) || (a < 0 && b < 0); + a = a > 0 ? -a : a; + b = b > 0 ? -b : b; + int ans = 0; + while (a <= b) { + int x = b; + int cnt = 1; + while (x >= (Integer.MIN_VALUE >> 1) && a <= (x << 1)) { + x <<= 1; + cnt <<= 1; + } + ans += cnt; + a -= x; + } + return sign ? ans : -ans; + } } \ No newline at end of file diff --git a/solution/0000-0099/0029.Divide Two Integers/Solution.py b/solution/0000-0099/0029.Divide Two Integers/Solution.py index 8ae7276462454..8870ed193fe42 100644 --- a/solution/0000-0099/0029.Divide Two Integers/Solution.py +++ b/solution/0000-0099/0029.Divide Two Integers/Solution.py @@ -1,19 +1,19 @@ -class Solution: - def divide(self, a: int, b: int) -> int: - if b == 1: - return a - if a == -(2**31) and b == -1: - return 2**31 - 1 - sign = (a > 0 and b > 0) or (a < 0 and b < 0) - a = -a if a > 0 else a - b = -b if b > 0 else b - ans = 0 - while a <= b: - x = b - cnt = 1 - while x >= (-(2**30)) and a <= (x << 1): - x <<= 1 - cnt <<= 1 - a -= x - ans += cnt - return ans if sign else -ans +class Solution: + def divide(self, a: int, b: int) -> int: + if b == 1: + return a + if a == -(2**31) and b == -1: + return 2**31 - 1 + sign = (a > 0 and b > 0) or (a < 0 and b < 0) + a = -a if a > 0 else a + b = -b if b > 0 else b + ans = 0 + while a <= b: + x = b + cnt = 1 + while x >= (-(2**30)) and a <= (x << 1): + x <<= 1 + cnt <<= 1 + a -= x + ans += cnt + return ans if sign else -ans diff --git a/solution/0000-0099/0030.Substring with Concatenation of All Words/Solution.cs b/solution/0000-0099/0030.Substring with Concatenation of All Words/Solution.cs index acb27b9eb7c94..e631e724cf196 100644 --- a/solution/0000-0099/0030.Substring with Concatenation of All Words/Solution.cs +++ b/solution/0000-0099/0030.Substring with Concatenation of All Words/Solution.cs @@ -38,4 +38,4 @@ public IList FindSubstring(string s, string[] words) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0030.Substring with Concatenation of All Words/Solution2.cpp b/solution/0000-0099/0030.Substring with Concatenation of All Words/Solution2.cpp new file mode 100644 index 0000000000000..2e88ae3ac098f --- /dev/null +++ b/solution/0000-0099/0030.Substring with Concatenation of All Words/Solution2.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + vector findSubstring(string s, vector& words) { + unordered_map d; + for (auto& w : words) ++d[w]; + vector ans; + int n = s.size(), m = words.size(), k = words[0].size(); + for (int i = 0; i < k; ++i) { + int cnt = 0; + unordered_map t; + for (int j = i; j <= n; j += k) { + if (j - i >= m * k) { + auto s1 = s.substr(j - m * k, k); + --t[s1]; + cnt -= d[s1] > t[s1]; + } + auto s2 = s.substr(j, k); + ++t[s2]; + cnt += d[s2] >= t[s2]; + if (cnt == m) ans.emplace_back(j - (m - 1) * k); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0031.Next Permutation/Solution.cs b/solution/0000-0099/0031.Next Permutation/Solution.cs index 103f4ccceb112..d0a8f955fe9de 100644 --- a/solution/0000-0099/0031.Next Permutation/Solution.cs +++ b/solution/0000-0099/0031.Next Permutation/Solution.cs @@ -23,4 +23,4 @@ private void swap(int[] nums, int i, int j) { nums[j] = nums[i]; nums[i] = t; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0032.Longest Valid Parentheses/Solution.cpp b/solution/0000-0099/0032.Longest Valid Parentheses/Solution.cpp index dede46f85497a..e67e60f0d92b9 100644 --- a/solution/0000-0099/0032.Longest Valid Parentheses/Solution.cpp +++ b/solution/0000-0099/0032.Longest Valid Parentheses/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - int longestValidParentheses(string s) { - int n = s.size(); - int f[n + 1]; - memset(f, 0, sizeof(f)); - for (int i = 2; i <= n; ++i) { - if (s[i - 1] == ')') { - if (s[i - 2] == '(') { - f[i] = f[i - 2] + 2; - } else { - int j = i - f[i - 1] - 1; - if (j && s[j - 1] == '(') { - f[i] = f[i - 1] + 2 + f[j - 1]; - } - } - } - } - return *max_element(f, f + n + 1); - } +class Solution { +public: + int longestValidParentheses(string s) { + int n = s.size(); + int f[n + 1]; + memset(f, 0, sizeof(f)); + for (int i = 2; i <= n; ++i) { + if (s[i - 1] == ')') { + if (s[i - 2] == '(') { + f[i] = f[i - 2] + 2; + } else { + int j = i - f[i - 1] - 1; + if (j && s[j - 1] == '(') { + f[i] = f[i - 1] + 2 + f[j - 1]; + } + } + } + } + return *max_element(f, f + n + 1); + } }; \ No newline at end of file diff --git a/solution/0000-0099/0032.Longest Valid Parentheses/Solution.cs b/solution/0000-0099/0032.Longest Valid Parentheses/Solution.cs index 80557e20f4135..78ca1e8456839 100644 --- a/solution/0000-0099/0032.Longest Valid Parentheses/Solution.cs +++ b/solution/0000-0099/0032.Longest Valid Parentheses/Solution.cs @@ -1,21 +1,21 @@ -public class Solution { - public int LongestValidParentheses(string s) { - int n = s.Length; - int[] f = new int[n + 1]; - int ans = 0; - for (int i = 2; i <= n; ++i) { - if (s[i - 1] == ')') { - if (s[i - 2] == '(') { - f[i] = f[i - 2] + 2; - } else { - int j = i - f[i - 1] - 1; - if (j > 0 && s[j - 1] == '(') { - f[i] = f[i - 1] + 2 + f[j - 1]; - } - } - ans = Math.Max(ans, f[i]); - } - } - return ans; - } -} \ No newline at end of file +public class Solution { + public int LongestValidParentheses(string s) { + int n = s.Length; + int[] f = new int[n + 1]; + int ans = 0; + for (int i = 2; i <= n; ++i) { + if (s[i - 1] == ')') { + if (s[i - 2] == '(') { + f[i] = f[i - 2] + 2; + } else { + int j = i - f[i - 1] - 1; + if (j > 0 && s[j - 1] == '(') { + f[i] = f[i - 1] + 2 + f[j - 1]; + } + } + ans = Math.Max(ans, f[i]); + } + } + return ans; + } +} diff --git a/solution/0000-0099/0032.Longest Valid Parentheses/Solution.java b/solution/0000-0099/0032.Longest Valid Parentheses/Solution.java index 3713dcb03dbc3..45fe0e8c7daa7 100644 --- a/solution/0000-0099/0032.Longest Valid Parentheses/Solution.java +++ b/solution/0000-0099/0032.Longest Valid Parentheses/Solution.java @@ -1,21 +1,21 @@ -class Solution { - public int longestValidParentheses(String s) { - int n = s.length(); - int[] f = new int[n + 1]; - int ans = 0; - for (int i = 2; i <= n; ++i) { - if (s.charAt(i - 1) == ')') { - if (s.charAt(i - 2) == '(') { - f[i] = f[i - 2] + 2; - } else { - int j = i - f[i - 1] - 1; - if (j > 0 && s.charAt(j - 1) == '(') { - f[i] = f[i - 1] + 2 + f[j - 1]; - } - } - ans = Math.max(ans, f[i]); - } - } - return ans; - } +class Solution { + public int longestValidParentheses(String s) { + int n = s.length(); + int[] f = new int[n + 1]; + int ans = 0; + for (int i = 2; i <= n; ++i) { + if (s.charAt(i - 1) == ')') { + if (s.charAt(i - 2) == '(') { + f[i] = f[i - 2] + 2; + } else { + int j = i - f[i - 1] - 1; + if (j > 0 && s.charAt(j - 1) == '(') { + f[i] = f[i - 1] + 2 + f[j - 1]; + } + } + ans = Math.max(ans, f[i]); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0000-0099/0032.Longest Valid Parentheses/Solution.py b/solution/0000-0099/0032.Longest Valid Parentheses/Solution.py index f6fc9ef77994b..d1a942134cab8 100644 --- a/solution/0000-0099/0032.Longest Valid Parentheses/Solution.py +++ b/solution/0000-0099/0032.Longest Valid Parentheses/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def longestValidParentheses(self, s: str) -> int: - n = len(s) - f = [0] * (n + 1) - for i, c in enumerate(s, 1): - if c == ")": - if i > 1 and s[i - 2] == "(": - f[i] = f[i - 2] + 2 - else: - j = i - f[i - 1] - 1 - if j and s[j - 1] == "(": - f[i] = f[i - 1] + 2 + f[j - 1] - return max(f) +class Solution: + def longestValidParentheses(self, s: str) -> int: + n = len(s) + f = [0] * (n + 1) + for i, c in enumerate(s, 1): + if c == ")": + if i > 1 and s[i - 2] == "(": + f[i] = f[i - 2] + 2 + else: + j = i - f[i - 1] - 1 + if j and s[j - 1] == "(": + f[i] = f[i - 1] + 2 + f[j - 1] + return max(f) diff --git a/solution/0000-0099/0032.Longest Valid Parentheses/Solution2.go b/solution/0000-0099/0032.Longest Valid Parentheses/Solution2.go new file mode 100644 index 0000000000000..9fe6bc3d0e987 --- /dev/null +++ b/solution/0000-0099/0032.Longest Valid Parentheses/Solution2.go @@ -0,0 +1,19 @@ +func longestValidParentheses(s string) int { + ans := 0 + stack := []int{-1} + for i, v := range s { + if v == '(' { + stack = append(stack, i) + } else { + stack = stack[:len(stack)-1] + if len(stack) == 0 { + stack = append(stack, i) + } else { + if ans < i-stack[len(stack)-1] { + ans = i - stack[len(stack)-1] + } + } + } + } + return ans +} \ No newline at end of file diff --git a/solution/0000-0099/0032.Longest Valid Parentheses/Solution2.js b/solution/0000-0099/0032.Longest Valid Parentheses/Solution2.js new file mode 100644 index 0000000000000..033bcf5f1405e --- /dev/null +++ b/solution/0000-0099/0032.Longest Valid Parentheses/Solution2.js @@ -0,0 +1,21 @@ +/** + * @param {string} s + * @return {number} + */ +var longestValidParentheses = function (s) { + let ans = 0; + const stack = [-1]; + for (i = 0; i < s.length; i++) { + if (s.charAt(i) === '(') { + stack.push(i); + } else { + stack.pop(); + if (stack.length === 0) { + stack.push(i); + } else { + ans = Math.max(ans, i - stack[stack.length - 1]); + } + } + } + return ans; +}; diff --git a/solution/0000-0099/0032.Longest Valid Parentheses/Solution2.py b/solution/0000-0099/0032.Longest Valid Parentheses/Solution2.py new file mode 100644 index 0000000000000..5c6d08b0c73af --- /dev/null +++ b/solution/0000-0099/0032.Longest Valid Parentheses/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def longestValidParentheses(self, s: str) -> int: + stack = [-1] + ans = 0 + for i in range(len(s)): + if s[i] == '(': + stack.append(i) + else: + stack.pop() + if not stack: + stack.append(i) + else: + ans = max(ans, i - stack[-1]) + return ans diff --git a/solution/0000-0099/0032.Longest Valid Parentheses/Solution2.rs b/solution/0000-0099/0032.Longest Valid Parentheses/Solution2.rs new file mode 100644 index 0000000000000..07a152aa13510 --- /dev/null +++ b/solution/0000-0099/0032.Longest Valid Parentheses/Solution2.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn longest_valid_parentheses(s: String) -> i32 { + let mut stack = vec![-1]; + let mut res = 0; + for i in 0..s.len() { + if let Some('(') = s.chars().nth(i) { + stack.push(i as i32); + } else { + stack.pop().unwrap(); + if stack.is_empty() { + stack.push(i as i32); + } else { + res = std::cmp::max(res, (i as i32) - stack.last().unwrap()); + } + } + } + res + } +} diff --git a/solution/0000-0099/0032.Longest Valid Parentheses/Solution2.ts b/solution/0000-0099/0032.Longest Valid Parentheses/Solution2.ts new file mode 100644 index 0000000000000..dbcb50a7b820f --- /dev/null +++ b/solution/0000-0099/0032.Longest Valid Parentheses/Solution2.ts @@ -0,0 +1,19 @@ +function longestValidParentheses(s: string): number { + let max_length: number = 0; + const stack: number[] = [-1]; + for (let i = 0; i < s.length; i++) { + if (s.charAt(i) == '(') { + stack.push(i); + } else { + stack.pop(); + + if (stack.length === 0) { + stack.push(i); + } else { + max_length = Math.max(max_length, i - stack[stack.length - 1]); + } + } + } + + return max_length; +} diff --git a/solution/0000-0099/0033.Search in Rotated Sorted Array/Solution.cpp b/solution/0000-0099/0033.Search in Rotated Sorted Array/Solution.cpp index 0e6381f92c526..041326d4f1b03 100644 --- a/solution/0000-0099/0033.Search in Rotated Sorted Array/Solution.cpp +++ b/solution/0000-0099/0033.Search in Rotated Sorted Array/Solution.cpp @@ -1,22 +1,22 @@ -class Solution { -public: - int search(vector& nums, int target) { - int n = nums.size(); - int left = 0, right = n - 1; - while (left < right) { - int mid = (left + right) >> 1; - if (nums[0] <= nums[mid]) { - if (nums[0] <= target && target <= nums[mid]) - right = mid; - else - left = mid + 1; - } else { - if (nums[mid] < target && target <= nums[n - 1]) - left = mid + 1; - else - right = mid; - } - } - return nums[left] == target ? left : -1; - } +class Solution { +public: + int search(vector& nums, int target) { + int n = nums.size(); + int left = 0, right = n - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[0] <= nums[mid]) { + if (nums[0] <= target && target <= nums[mid]) + right = mid; + else + left = mid + 1; + } else { + if (nums[mid] < target && target <= nums[n - 1]) + left = mid + 1; + else + right = mid; + } + } + return nums[left] == target ? left : -1; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0033.Search in Rotated Sorted Array/Solution.java b/solution/0000-0099/0033.Search in Rotated Sorted Array/Solution.java index 01897645dcb75..0f04f4519181a 100644 --- a/solution/0000-0099/0033.Search in Rotated Sorted Array/Solution.java +++ b/solution/0000-0099/0033.Search in Rotated Sorted Array/Solution.java @@ -1,23 +1,23 @@ -class Solution { - public int search(int[] nums, int target) { - int n = nums.length; - int left = 0, right = n - 1; - while (left < right) { - int mid = (left + right) >> 1; - if (nums[0] <= nums[mid]) { - if (nums[0] <= target && target <= nums[mid]) { - right = mid; - } else { - left = mid + 1; - } - } else { - if (nums[mid] < target && target <= nums[n - 1]) { - left = mid + 1; - } else { - right = mid; - } - } - } - return nums[left] == target ? left : -1; - } +class Solution { + public int search(int[] nums, int target) { + int n = nums.length; + int left = 0, right = n - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[0] <= nums[mid]) { + if (nums[0] <= target && target <= nums[mid]) { + right = mid; + } else { + left = mid + 1; + } + } else { + if (nums[mid] < target && target <= nums[n - 1]) { + left = mid + 1; + } else { + right = mid; + } + } + } + return nums[left] == target ? left : -1; + } } \ No newline at end of file diff --git a/solution/0000-0099/0033.Search in Rotated Sorted Array/Solution.py b/solution/0000-0099/0033.Search in Rotated Sorted Array/Solution.py index e4d8f656dfe62..d353518e58e6a 100644 --- a/solution/0000-0099/0033.Search in Rotated Sorted Array/Solution.py +++ b/solution/0000-0099/0033.Search in Rotated Sorted Array/Solution.py @@ -1,17 +1,17 @@ -class Solution: - def search(self, nums: List[int], target: int) -> int: - n = len(nums) - left, right = 0, n - 1 - while left < right: - mid = (left + right) >> 1 - if nums[0] <= nums[mid]: - if nums[0] <= target <= nums[mid]: - right = mid - else: - left = mid + 1 - else: - if nums[mid] < target <= nums[n - 1]: - left = mid + 1 - else: - right = mid - return left if nums[left] == target else -1 +class Solution: + def search(self, nums: List[int], target: int) -> int: + n = len(nums) + left, right = 0, n - 1 + while left < right: + mid = (left + right) >> 1 + if nums[0] <= nums[mid]: + if nums[0] <= target <= nums[mid]: + right = mid + else: + left = mid + 1 + else: + if nums[mid] < target <= nums[n - 1]: + left = mid + 1 + else: + right = mid + return left if nums[left] == target else -1 diff --git a/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/Solution.cpp b/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/Solution.cpp index 0e1f78f3c765b..21673df24de5a 100644 --- a/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/Solution.cpp +++ b/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/Solution.cpp @@ -1,9 +1,9 @@ -class Solution { -public: - vector searchRange(vector& nums, int target) { - int l = lower_bound(nums.begin(), nums.end(), target) - nums.begin(); - int r = lower_bound(nums.begin(), nums.end(), target + 1) - nums.begin(); - if (l == r) return {-1, -1}; - return {l, r - 1}; - } +class Solution { +public: + vector searchRange(vector& nums, int target) { + int l = lower_bound(nums.begin(), nums.end(), target) - nums.begin(); + int r = lower_bound(nums.begin(), nums.end(), target + 1) - nums.begin(); + if (l == r) return {-1, -1}; + return {l, r - 1}; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/Solution.java b/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/Solution.java index 6e8570f93cd43..53a2799a55a2c 100644 --- a/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/Solution.java +++ b/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/Solution.java @@ -1,20 +1,20 @@ -class Solution { - public int[] searchRange(int[] nums, int target) { - int l = search(nums, target); - int r = search(nums, target + 1); - return l == r ? new int[] {-1, -1} : new int[] {l, r - 1}; - } - - private int search(int[] nums, int x) { - int left = 0, right = nums.length; - while (left < right) { - int mid = (left + right) >>> 1; - if (nums[mid] >= x) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - } +class Solution { + public int[] searchRange(int[] nums, int target) { + int l = search(nums, target); + int r = search(nums, target + 1); + return l == r ? new int[] {-1, -1} : new int[] {l, r - 1}; + } + + private int search(int[] nums, int x) { + int left = 0, right = nums.length; + while (left < right) { + int mid = (left + right) >>> 1; + if (nums[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } } \ No newline at end of file diff --git a/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/Solution.py b/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/Solution.py index ea89791660ee9..3ae3a50154afa 100644 --- a/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/Solution.py +++ b/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/Solution.py @@ -1,5 +1,5 @@ -class Solution: - def searchRange(self, nums: List[int], target: int) -> List[int]: - l = bisect_left(nums, target) - r = bisect_left(nums, target + 1) - return [-1, -1] if l == r else [l, r - 1] +class Solution: + def searchRange(self, nums: List[int], target: int) -> List[int]: + l = bisect_left(nums, target) + r = bisect_left(nums, target + 1) + return [-1, -1] if l == r else [l, r - 1] diff --git a/solution/0000-0099/0035.Search Insert Position/Solution2.cpp b/solution/0000-0099/0035.Search Insert Position/Solution2.cpp new file mode 100644 index 0000000000000..f0e7dc9fe7bbf --- /dev/null +++ b/solution/0000-0099/0035.Search Insert Position/Solution2.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + int searchInsert(vector& nums, int target) { + return lower_bound(nums.begin(), nums.end(), target) - nums.begin(); + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0035.Search Insert Position/Solution2.go b/solution/0000-0099/0035.Search Insert Position/Solution2.go new file mode 100644 index 0000000000000..853a18a037769 --- /dev/null +++ b/solution/0000-0099/0035.Search Insert Position/Solution2.go @@ -0,0 +1,3 @@ +func searchInsert(nums []int, target int) int { + return sort.SearchInts(nums, target) +} \ No newline at end of file diff --git a/solution/0000-0099/0035.Search Insert Position/Solution2.py b/solution/0000-0099/0035.Search Insert Position/Solution2.py new file mode 100644 index 0000000000000..bf40f021fd12d --- /dev/null +++ b/solution/0000-0099/0035.Search Insert Position/Solution2.py @@ -0,0 +1,3 @@ +class Solution: + def searchInsert(self, nums: List[int], target: int) -> int: + return bisect_left(nums, target) diff --git a/solution/0000-0099/0038.Count and Say/Solution.cs b/solution/0000-0099/0038.Count and Say/Solution.cs index ff91620e2f282..740af57100538 100644 --- a/solution/0000-0099/0038.Count and Say/Solution.cs +++ b/solution/0000-0099/0038.Count and Say/Solution.cs @@ -34,4 +34,4 @@ public string CountAndSay(int n) { } return s; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0039.Combination Sum/Solution.cpp b/solution/0000-0099/0039.Combination Sum/Solution.cpp index baffdc89aaaa5..c6c9a33863d94 100644 --- a/solution/0000-0099/0039.Combination Sum/Solution.cpp +++ b/solution/0000-0099/0039.Combination Sum/Solution.cpp @@ -9,13 +9,14 @@ class Solution { ans.emplace_back(t); return; } - if (i >= candidates.size() || s < candidates[i]) { + if (s < candidates[i]) { return; } - dfs(i + 1, s); - t.push_back(candidates[i]); - dfs(i, s - candidates[i]); - t.pop_back(); + for (int j = i; j < candidates.size(); ++j) { + t.push_back(candidates[j]); + dfs(j, s - candidates[j]); + t.pop_back(); + } }; dfs(0, target); return ans; diff --git a/solution/0000-0099/0039.Combination Sum/Solution.cs b/solution/0000-0099/0039.Combination Sum/Solution.cs index 33bf9169ec3a9..fde235c42424e 100644 --- a/solution/0000-0099/0039.Combination Sum/Solution.cs +++ b/solution/0000-0099/0039.Combination Sum/Solution.cs @@ -15,12 +15,13 @@ private void dfs(int i, int s) { ans.Add(new List(t)); return; } - if (i >= candidates.Length || s < candidates[i]) { + if (s < candidates[i]) { return; } - dfs(i + 1, s); - t.Add(candidates[i]); - dfs(i, s - candidates[i]); - t.RemoveAt(t.Count - 1); + for (int j = i; j < candidates.Length; ++j) { + t.Add(candidates[j]); + dfs(j, s - candidates[j]); + t.RemoveAt(t.Count - 1); + } } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0039.Combination Sum/Solution.go b/solution/0000-0099/0039.Combination Sum/Solution.go index d290d36a348d9..5304c314d5bcd 100644 --- a/solution/0000-0099/0039.Combination Sum/Solution.go +++ b/solution/0000-0099/0039.Combination Sum/Solution.go @@ -7,13 +7,14 @@ func combinationSum(candidates []int, target int) (ans [][]int) { ans = append(ans, slices.Clone(t)) return } - if i >= len(candidates) || s < candidates[i] { + if s < candidates[i] { return } - dfs(i+1, s) - t = append(t, candidates[i]) - dfs(i, s-candidates[i]) - t = t[:len(t)-1] + for j := i; j < len(candidates); j++ { + t = append(t, candidates[j]) + dfs(j, s-candidates[j]) + t = t[:len(t)-1] + } } dfs(0, target) return diff --git a/solution/0000-0099/0039.Combination Sum/Solution.java b/solution/0000-0099/0039.Combination Sum/Solution.java index 1d07c2b70cfee..09f951a2bba28 100644 --- a/solution/0000-0099/0039.Combination Sum/Solution.java +++ b/solution/0000-0099/0039.Combination Sum/Solution.java @@ -15,12 +15,13 @@ private void dfs(int i, int s) { ans.add(new ArrayList(t)); return; } - if (i >= candidates.length || s < candidates[i]) { + if (s < candidates[i]) { return; } - dfs(i + 1, s); - t.add(candidates[i]); - dfs(i, s - candidates[i]); - t.remove(t.size() - 1); + for (int j = i; j < candidates.length; ++j) { + t.add(candidates[j]); + dfs(j, s - candidates[j]); + t.remove(t.size() - 1); + } } } \ No newline at end of file diff --git a/solution/0000-0099/0039.Combination Sum/Solution.py b/solution/0000-0099/0039.Combination Sum/Solution.py index 8fe7a87a83561..9c29c45888fc3 100644 --- a/solution/0000-0099/0039.Combination Sum/Solution.py +++ b/solution/0000-0099/0039.Combination Sum/Solution.py @@ -4,12 +4,12 @@ def dfs(i: int, s: int): if s == 0: ans.append(t[:]) return - if i >= len(candidates) or s < candidates[i]: + if s < candidates[i]: return - dfs(i + 1, s) - t.append(candidates[i]) - dfs(i, s - candidates[i]) - t.pop() + for j in range(i, len(candidates)): + t.append(candidates[j]) + dfs(j, s - candidates[j]) + t.pop() candidates.sort() t = [] diff --git a/solution/0000-0099/0039.Combination Sum/Solution.rs b/solution/0000-0099/0039.Combination Sum/Solution.rs index e494119d6cf34..4929fcebe35f2 100644 --- a/solution/0000-0099/0039.Combination Sum/Solution.rs +++ b/solution/0000-0099/0039.Combination Sum/Solution.rs @@ -4,13 +4,14 @@ impl Solution { ans.push(t.clone()); return; } - if i >= candidates.len() || s < candidates[i] { + if s < candidates[i] { return; } - Self::dfs(i + 1, s, candidates, t, ans); - t.push(candidates[i]); - Self::dfs(i, s - candidates[i], candidates, t, ans); - t.pop(); + for j in i..candidates.len() { + t.push(candidates[j]); + Self::dfs(j, s - candidates[j], candidates, t, ans); + t.pop(); + } } pub fn combination_sum(mut candidates: Vec, target: i32) -> Vec> { diff --git a/solution/0000-0099/0039.Combination Sum/Solution.ts b/solution/0000-0099/0039.Combination Sum/Solution.ts index 2ef9e34447ac0..46ec7a9d5afc5 100644 --- a/solution/0000-0099/0039.Combination Sum/Solution.ts +++ b/solution/0000-0099/0039.Combination Sum/Solution.ts @@ -7,13 +7,14 @@ function combinationSum(candidates: number[], target: number): number[][] { ans.push(t.slice()); return; } - if (i >= candidates.length || s < candidates[i]) { + if (s < candidates[i]) { return; } - dfs(i + 1, s); - t.push(candidates[i]); - dfs(i, s - candidates[i]); - t.pop(); + for (let j = i; j < candidates.length; ++j) { + t.push(candidates[j]); + dfs(j, s - candidates[j]); + t.pop(); + } }; dfs(0, target); return ans; diff --git a/solution/0000-0099/0039.Combination Sum/Solution2.cpp b/solution/0000-0099/0039.Combination Sum/Solution2.cpp new file mode 100644 index 0000000000000..baffdc89aaaa5 --- /dev/null +++ b/solution/0000-0099/0039.Combination Sum/Solution2.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + vector> combinationSum(vector& candidates, int target) { + sort(candidates.begin(), candidates.end()); + vector> ans; + vector t; + function dfs = [&](int i, int s) { + if (s == 0) { + ans.emplace_back(t); + return; + } + if (i >= candidates.size() || s < candidates[i]) { + return; + } + dfs(i + 1, s); + t.push_back(candidates[i]); + dfs(i, s - candidates[i]); + t.pop_back(); + }; + dfs(0, target); + return ans; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0039.Combination Sum/Solution2.cs b/solution/0000-0099/0039.Combination Sum/Solution2.cs new file mode 100644 index 0000000000000..83f792a374985 --- /dev/null +++ b/solution/0000-0099/0039.Combination Sum/Solution2.cs @@ -0,0 +1,26 @@ +public class Solution { + private List> ans = new List>(); + private List t = new List(); + private int[] candidates; + + public IList> CombinationSum(int[] candidates, int target) { + Array.Sort(candidates); + this.candidates = candidates; + dfs(0, target); + return ans; + } + + private void dfs(int i, int s) { + if (s == 0) { + ans.Add(new List(t)); + return; + } + if (i >= candidates.Length || s < candidates[i]) { + return; + } + dfs(i + 1, s); + t.Add(candidates[i]); + dfs(i, s - candidates[i]); + t.RemoveAt(t.Count - 1); + } +} diff --git a/solution/0000-0099/0039.Combination Sum/Solution2.go b/solution/0000-0099/0039.Combination Sum/Solution2.go new file mode 100644 index 0000000000000..d290d36a348d9 --- /dev/null +++ b/solution/0000-0099/0039.Combination Sum/Solution2.go @@ -0,0 +1,20 @@ +func combinationSum(candidates []int, target int) (ans [][]int) { + sort.Ints(candidates) + t := []int{} + var dfs func(i, s int) + dfs = func(i, s int) { + if s == 0 { + ans = append(ans, slices.Clone(t)) + return + } + if i >= len(candidates) || s < candidates[i] { + return + } + dfs(i+1, s) + t = append(t, candidates[i]) + dfs(i, s-candidates[i]) + t = t[:len(t)-1] + } + dfs(0, target) + return +} \ No newline at end of file diff --git a/solution/0000-0099/0039.Combination Sum/Solution2.java b/solution/0000-0099/0039.Combination Sum/Solution2.java new file mode 100644 index 0000000000000..1d07c2b70cfee --- /dev/null +++ b/solution/0000-0099/0039.Combination Sum/Solution2.java @@ -0,0 +1,26 @@ +class Solution { + private List> ans = new ArrayList<>(); + private List t = new ArrayList<>(); + private int[] candidates; + + public List> combinationSum(int[] candidates, int target) { + Arrays.sort(candidates); + this.candidates = candidates; + dfs(0, target); + return ans; + } + + private void dfs(int i, int s) { + if (s == 0) { + ans.add(new ArrayList(t)); + return; + } + if (i >= candidates.length || s < candidates[i]) { + return; + } + dfs(i + 1, s); + t.add(candidates[i]); + dfs(i, s - candidates[i]); + t.remove(t.size() - 1); + } +} \ No newline at end of file diff --git a/solution/0000-0099/0039.Combination Sum/Solution2.py b/solution/0000-0099/0039.Combination Sum/Solution2.py new file mode 100644 index 0000000000000..8fe7a87a83561 --- /dev/null +++ b/solution/0000-0099/0039.Combination Sum/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + def dfs(i: int, s: int): + if s == 0: + ans.append(t[:]) + return + if i >= len(candidates) or s < candidates[i]: + return + dfs(i + 1, s) + t.append(candidates[i]) + dfs(i, s - candidates[i]) + t.pop() + + candidates.sort() + t = [] + ans = [] + dfs(0, target) + return ans diff --git a/solution/0000-0099/0039.Combination Sum/Solution2.rs b/solution/0000-0099/0039.Combination Sum/Solution2.rs new file mode 100644 index 0000000000000..e494119d6cf34 --- /dev/null +++ b/solution/0000-0099/0039.Combination Sum/Solution2.rs @@ -0,0 +1,22 @@ +impl Solution { + fn dfs(i: usize, s: i32, candidates: &Vec, t: &mut Vec, ans: &mut Vec>) { + if s == 0 { + ans.push(t.clone()); + return; + } + if i >= candidates.len() || s < candidates[i] { + return; + } + Self::dfs(i + 1, s, candidates, t, ans); + t.push(candidates[i]); + Self::dfs(i, s - candidates[i], candidates, t, ans); + t.pop(); + } + + pub fn combination_sum(mut candidates: Vec, target: i32) -> Vec> { + candidates.sort(); + let mut ans = Vec::new(); + Self::dfs(0, target, &candidates, &mut vec![], &mut ans); + ans + } +} diff --git a/solution/0000-0099/0039.Combination Sum/Solution2.ts b/solution/0000-0099/0039.Combination Sum/Solution2.ts new file mode 100644 index 0000000000000..2ef9e34447ac0 --- /dev/null +++ b/solution/0000-0099/0039.Combination Sum/Solution2.ts @@ -0,0 +1,20 @@ +function combinationSum(candidates: number[], target: number): number[][] { + candidates.sort((a, b) => a - b); + const ans: number[][] = []; + const t: number[] = []; + const dfs = (i: number, s: number) => { + if (s === 0) { + ans.push(t.slice()); + return; + } + if (i >= candidates.length || s < candidates[i]) { + return; + } + dfs(i + 1, s); + t.push(candidates[i]); + dfs(i, s - candidates[i]); + t.pop(); + }; + dfs(0, target); + return ans; +} diff --git a/solution/0000-0099/0040.Combination Sum II/Solution.cs b/solution/0000-0099/0040.Combination Sum II/Solution.cs index 7627157bdddc6..f145c64e779c6 100644 --- a/solution/0000-0099/0040.Combination Sum II/Solution.cs +++ b/solution/0000-0099/0040.Combination Sum II/Solution.cs @@ -27,4 +27,4 @@ private void dfs(int i, int s) { t.RemoveAt(t.Count - 1); } } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0040.Combination Sum II/Solution.rs b/solution/0000-0099/0040.Combination Sum II/Solution.rs index 9cc50a99b4719..b668b0a4ae0d2 100644 --- a/solution/0000-0099/0040.Combination Sum II/Solution.rs +++ b/solution/0000-0099/0040.Combination Sum II/Solution.rs @@ -1,12 +1,12 @@ impl Solution { fn dfs(i: usize, s: i32, candidates: &Vec, t: &mut Vec, ans: &mut Vec>) { - if s < 0 { - return; - } if s == 0 { ans.push(t.clone()); return; } + if i >= candidates.len() || s < candidates[i] { + return; + } for j in i..candidates.len() { if j > i && candidates[j] == candidates[j - 1] { continue; diff --git a/solution/0000-0099/0040.Combination Sum II/Solution2.cpp b/solution/0000-0099/0040.Combination Sum II/Solution2.cpp new file mode 100644 index 0000000000000..cbbb545d5bd2f --- /dev/null +++ b/solution/0000-0099/0040.Combination Sum II/Solution2.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector> combinationSum2(vector& candidates, int target) { + sort(candidates.begin(), candidates.end()); + vector> ans; + vector t; + function dfs = [&](int i, int s) { + if (s == 0) { + ans.emplace_back(t); + return; + } + if (i >= candidates.size() || s < candidates[i]) { + return; + } + int x = candidates[i]; + t.emplace_back(x); + dfs(i + 1, s - x); + t.pop_back(); + while (i < candidates.size() && candidates[i] == x) { + ++i; + } + dfs(i, s); + }; + dfs(0, target); + return ans; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0040.Combination Sum II/Solution2.cs b/solution/0000-0099/0040.Combination Sum II/Solution2.cs new file mode 100644 index 0000000000000..9c3d538d27929 --- /dev/null +++ b/solution/0000-0099/0040.Combination Sum II/Solution2.cs @@ -0,0 +1,30 @@ +public class Solution { + private List> ans = new List>(); + private List t = new List(); + private int[] candidates; + + public IList> CombinationSum2(int[] candidates, int target) { + Array.Sort(candidates); + this.candidates = candidates; + dfs(0, target); + return ans; + } + + private void dfs(int i, int s) { + if (s == 0) { + ans.Add(new List(t)); + return; + } + if (i >= candidates.Length || s < candidates[i]) { + return; + } + int x = candidates[i]; + t.Add(x); + dfs(i + 1, s - x); + t.RemoveAt(t.Count - 1); + while (i < candidates.Length && candidates[i] == x) { + ++i; + } + dfs(i, s); + } +} diff --git a/solution/0000-0099/0040.Combination Sum II/Solution2.go b/solution/0000-0099/0040.Combination Sum II/Solution2.go new file mode 100644 index 0000000000000..35a320d0d6913 --- /dev/null +++ b/solution/0000-0099/0040.Combination Sum II/Solution2.go @@ -0,0 +1,24 @@ +func combinationSum2(candidates []int, target int) (ans [][]int) { + sort.Ints(candidates) + t := []int{} + var dfs func(i, s int) + dfs = func(i, s int) { + if s == 0 { + ans = append(ans, slices.Clone(t)) + return + } + if i >= len(candidates) || s < candidates[i] { + return + } + for j := i; j < len(candidates); j++ { + if j > i && candidates[j] == candidates[j-1] { + continue + } + t = append(t, candidates[j]) + dfs(j+1, s-candidates[j]) + t = t[:len(t)-1] + } + } + dfs(0, target) + return +} \ No newline at end of file diff --git a/solution/0000-0099/0040.Combination Sum II/Solution2.java b/solution/0000-0099/0040.Combination Sum II/Solution2.java new file mode 100644 index 0000000000000..c8e14f799368c --- /dev/null +++ b/solution/0000-0099/0040.Combination Sum II/Solution2.java @@ -0,0 +1,30 @@ +class Solution { + private List> ans = new ArrayList<>(); + private List t = new ArrayList<>(); + private int[] candidates; + + public List> combinationSum2(int[] candidates, int target) { + Arrays.sort(candidates); + this.candidates = candidates; + dfs(0, target); + return ans; + } + + private void dfs(int i, int s) { + if (s == 0) { + ans.add(new ArrayList<>(t)); + return; + } + if (i >= candidates.length || s < candidates[i]) { + return; + } + int x = candidates[i]; + t.add(x); + dfs(i + 1, s - x); + t.remove(t.size() - 1); + while (i < candidates.length && candidates[i] == x) { + ++i; + } + dfs(i, s); + } +} \ No newline at end of file diff --git a/solution/0000-0099/0040.Combination Sum II/Solution2.js b/solution/0000-0099/0040.Combination Sum II/Solution2.js new file mode 100644 index 0000000000000..fd4d6b773eff2 --- /dev/null +++ b/solution/0000-0099/0040.Combination Sum II/Solution2.js @@ -0,0 +1,29 @@ +/** + * @param {number[]} candidates + * @param {number} target + * @return {number[][]} + */ +var combinationSum2 = function (candidates, target) { + candidates.sort((a, b) => a - b); + const ans = []; + const t = []; + const dfs = (i, s) => { + if (s === 0) { + ans.push(t.slice()); + return; + } + if (i >= candidates.length || s < candidates[i]) { + return; + } + const x = candidates[i]; + t.push(x); + dfs(i + 1, s - x); + t.pop(); + while (i < candidates.length && candidates[i] === x) { + ++i; + } + dfs(i, s); + }; + dfs(0, target); + return ans; +}; diff --git a/solution/0000-0099/0040.Combination Sum II/Solution2.py b/solution/0000-0099/0040.Combination Sum II/Solution2.py new file mode 100644 index 0000000000000..e070abc55a2b0 --- /dev/null +++ b/solution/0000-0099/0040.Combination Sum II/Solution2.py @@ -0,0 +1,21 @@ +class Solution: + def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: + def dfs(i: int, s: int): + if s == 0: + ans.append(t[:]) + return + if i >= len(candidates) or s < candidates[i]: + return + x = candidates[i] + t.append(x) + dfs(i + 1, s - x) + t.pop() + while i < len(candidates) and candidates[i] == x: + i += 1 + dfs(i, s) + + candidates.sort() + ans = [] + t = [] + dfs(0, target) + return ans diff --git a/solution/0000-0099/0040.Combination Sum II/Solution2.rs b/solution/0000-0099/0040.Combination Sum II/Solution2.rs new file mode 100644 index 0000000000000..5dc5997ce9d6e --- /dev/null +++ b/solution/0000-0099/0040.Combination Sum II/Solution2.rs @@ -0,0 +1,26 @@ +impl Solution { + fn dfs(mut i: usize, s: i32, candidates: &Vec, t: &mut Vec, ans: &mut Vec>) { + if s == 0 { + ans.push(t.clone()); + return; + } + if i >= candidates.len() || s < candidates[i] { + return; + } + let x = candidates[i]; + t.push(x); + Self::dfs(i + 1, s - x, candidates, t, ans); + t.pop(); + while i < candidates.len() && candidates[i] == x { + i += 1; + } + Self::dfs(i, s, candidates, t, ans); + } + + pub fn combination_sum2(mut candidates: Vec, target: i32) -> Vec> { + candidates.sort(); + let mut ans = Vec::new(); + Self::dfs(0, target, &candidates, &mut vec![], &mut ans); + ans + } +} diff --git a/solution/0000-0099/0040.Combination Sum II/Solution2.ts b/solution/0000-0099/0040.Combination Sum II/Solution2.ts new file mode 100644 index 0000000000000..282ed0135e92d --- /dev/null +++ b/solution/0000-0099/0040.Combination Sum II/Solution2.ts @@ -0,0 +1,24 @@ +function combinationSum2(candidates: number[], target: number): number[][] { + candidates.sort((a, b) => a - b); + const ans: number[][] = []; + const t: number[] = []; + const dfs = (i: number, s: number) => { + if (s === 0) { + ans.push(t.slice()); + return; + } + if (i >= candidates.length || s < candidates[i]) { + return; + } + const x = candidates[i]; + t.push(x); + dfs(i + 1, s - x); + t.pop(); + while (i < candidates.length && candidates[i] === x) { + ++i; + } + dfs(i, s); + }; + dfs(0, target); + return ans; +} diff --git a/solution/0000-0099/0041.First Missing Positive/Solution.c b/solution/0000-0099/0041.First Missing Positive/Solution.c index 001bfc6c939cc..9598e2d92262d 100644 --- a/solution/0000-0099/0041.First Missing Positive/Solution.c +++ b/solution/0000-0099/0041.First Missing Positive/Solution.c @@ -19,4 +19,4 @@ int firstMissingPositive(int* nums, int numsSize) { } return i; -} +} \ No newline at end of file diff --git a/solution/0000-0099/0041.First Missing Positive/Solution.cs b/solution/0000-0099/0041.First Missing Positive/Solution.cs index c7122e6bd716a..846c60b8c22e6 100644 --- a/solution/0000-0099/0041.First Missing Positive/Solution.cs +++ b/solution/0000-0099/0041.First Missing Positive/Solution.cs @@ -32,4 +32,4 @@ public int FirstMissingPositive(int[] nums) { } return nums.Length + 1; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0041.First Missing Positive/Solution2.ts b/solution/0000-0099/0041.First Missing Positive/Solution2.ts new file mode 100644 index 0000000000000..3d7c80f3c7519 --- /dev/null +++ b/solution/0000-0099/0041.First Missing Positive/Solution2.ts @@ -0,0 +1,8 @@ +function firstMissingPositive(nums: number[]): number { + const set = new Set(nums); + let ans = 1; + while (true) { + if (!set.has(ans)) return ans; + ans++; + } +} diff --git a/solution/0000-0099/0042.Trapping Rain Water/Solution.cs b/solution/0000-0099/0042.Trapping Rain Water/Solution.cs index b1814b3322537..0bd6e49595d67 100644 --- a/solution/0000-0099/0042.Trapping Rain Water/Solution.cs +++ b/solution/0000-0099/0042.Trapping Rain Water/Solution.cs @@ -15,4 +15,4 @@ public int Trap(int[] height) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0043.Multiply Strings/Solution.cs b/solution/0000-0099/0043.Multiply Strings/Solution.cs index a27c739d22cf5..364f4487e05ab 100644 --- a/solution/0000-0099/0043.Multiply Strings/Solution.cs +++ b/solution/0000-0099/0043.Multiply Strings/Solution.cs @@ -1,36 +1,36 @@ -public class Solution { - public string Multiply(string num1, string num2) { - if (num1 == "0" || num2 == "0") { - return "0"; - } - - int m = num1.Length; - int n = num2.Length; - int[] arr = new int[m + n]; - - for (int i = m - 1; i >= 0; i--) { - int a = num1[i] - '0'; - for (int j = n - 1; j >= 0; j--) { - int b = num2[j] - '0'; - arr[i + j + 1] += a * b; - } - } - - for (int i = arr.Length - 1; i > 0; i--) { - arr[i - 1] += arr[i] / 10; - arr[i] %= 10; - } - - int index = 0; - while (index < arr.Length && arr[index] == 0) { - index++; - } - - StringBuilder ans = new StringBuilder(); - for (; index < arr.Length; index++) { - ans.Append(arr[index]); - } - - return ans.ToString(); - } -} \ No newline at end of file +public class Solution { + public string Multiply(string num1, string num2) { + if (num1 == "0" || num2 == "0") { + return "0"; + } + + int m = num1.Length; + int n = num2.Length; + int[] arr = new int[m + n]; + + for (int i = m - 1; i >= 0; i--) { + int a = num1[i] - '0'; + for (int j = n - 1; j >= 0; j--) { + int b = num2[j] - '0'; + arr[i + j + 1] += a * b; + } + } + + for (int i = arr.Length - 1; i > 0; i--) { + arr[i - 1] += arr[i] / 10; + arr[i] %= 10; + } + + int index = 0; + while (index < arr.Length && arr[index] == 0) { + index++; + } + + StringBuilder ans = new StringBuilder(); + for (; index < arr.Length; index++) { + ans.Append(arr[index]); + } + + return ans.ToString(); + } +} diff --git a/solution/0000-0099/0045.Jump Game II/Solution.cs b/solution/0000-0099/0045.Jump Game II/Solution.cs index c3c20fb0dccf1..a68af31d099d4 100644 --- a/solution/0000-0099/0045.Jump Game II/Solution.cs +++ b/solution/0000-0099/0045.Jump Game II/Solution.cs @@ -10,4 +10,4 @@ public int Jump(int[] nums) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0046.Permutations/Solution.cs b/solution/0000-0099/0046.Permutations/Solution.cs index 1e81c20575627..da7440530aa89 100644 --- a/solution/0000-0099/0046.Permutations/Solution.cs +++ b/solution/0000-0099/0046.Permutations/Solution.cs @@ -22,4 +22,4 @@ private void dfs(int[] nums, int i, IList t, bool[] vis, IList> } } } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0046.Permutations/Solution.py b/solution/0000-0099/0046.Permutations/Solution.py index b5421540a2a90..dbab773b937d7 100644 --- a/solution/0000-0099/0046.Permutations/Solution.py +++ b/solution/0000-0099/0046.Permutations/Solution.py @@ -1,19 +1,3 @@ class Solution: def permute(self, nums: List[int]) -> List[List[int]]: - def dfs(i): - if i == n: - ans.append(t[:]) - return - for j in range(n): - if not vis[j]: - vis[j] = True - t[i] = nums[j] - dfs(i + 1) - vis[j] = False - - n = len(nums) - vis = [False] * n - t = [0] * n - ans = [] - dfs(0) - return ans + return list(permutations(nums)) diff --git a/solution/0000-0099/0046.Permutations/Solution2.py b/solution/0000-0099/0046.Permutations/Solution2.py new file mode 100644 index 0000000000000..b5421540a2a90 --- /dev/null +++ b/solution/0000-0099/0046.Permutations/Solution2.py @@ -0,0 +1,19 @@ +class Solution: + def permute(self, nums: List[int]) -> List[List[int]]: + def dfs(i): + if i == n: + ans.append(t[:]) + return + for j in range(n): + if not vis[j]: + vis[j] = True + t[i] = nums[j] + dfs(i + 1) + vis[j] = False + + n = len(nums) + vis = [False] * n + t = [0] * n + ans = [] + dfs(0) + return ans diff --git a/solution/0000-0099/0046.Permutations/Solution2.rs b/solution/0000-0099/0046.Permutations/Solution2.rs new file mode 100644 index 0000000000000..2f372cb41d400 --- /dev/null +++ b/solution/0000-0099/0046.Permutations/Solution2.rs @@ -0,0 +1,37 @@ +impl Solution { + #[allow(dead_code)] + pub fn permute(nums: Vec) -> Vec> { + let mut ret = Vec::new(); + let mut cur_vec = Vec::new(); + let mut vis = vec![false; nums.len() + 1]; + Self::dfs(&nums, &mut vis, 0, &mut cur_vec, &mut ret); + ret + } + + #[allow(dead_code)] + fn dfs( + nums: &Vec, + vis: &mut Vec, + index: i32, + cur_vec: &mut Vec, + ans: &mut Vec> + ) { + let n = nums.len(); + if (index as usize) == n { + ans.push(cur_vec.clone()); + return; + } + // Otherwise, let's iterate the nums vector + for i in 0..n { + if !vis[i] { + // If this number hasn't been visited, then visit it + vis[i] = true; + cur_vec.push(nums[i]); + Self::dfs(nums, vis, index + 1, cur_vec, ans); + // Reset the changes + cur_vec.pop().unwrap(); + vis[i] = false; + } + } + } +} diff --git a/solution/0000-0099/0046.Permutations/Solution3.py b/solution/0000-0099/0046.Permutations/Solution3.py new file mode 100644 index 0000000000000..e83065b2ce362 --- /dev/null +++ b/solution/0000-0099/0046.Permutations/Solution3.py @@ -0,0 +1,20 @@ +class Solution: + def permute(self, nums: List[int]) -> List[List[int]]: + def dfs(i): + nonlocal mask + if i == n: + ans.append(t[:]) + return + for j in range(n): + if (mask >> j & 1) == 0: + mask |= 1 << j + t[i] = nums[j] + dfs(i + 1) + mask ^= 1 << j + + n = len(nums) + mask = 0 + t = [0] * n + ans = [] + dfs(0) + return ans diff --git a/solution/0000-0099/0047.Permutations II/Solution.cs b/solution/0000-0099/0047.Permutations II/Solution.cs index c17df44ee9bf4..18799b2926882 100644 --- a/solution/0000-0099/0047.Permutations II/Solution.cs +++ b/solution/0000-0099/0047.Permutations II/Solution.cs @@ -29,4 +29,4 @@ private void dfs(int i) { vis[j] = false; } } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0048.Rotate Image/Solution.cs b/solution/0000-0099/0048.Rotate Image/Solution.cs index cf534c5894179..571e30b896365 100644 --- a/solution/0000-0099/0048.Rotate Image/Solution.cs +++ b/solution/0000-0099/0048.Rotate Image/Solution.cs @@ -16,4 +16,4 @@ public void Rotate(int[][] matrix) { } } } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0049.Group Anagrams/Solution.java b/solution/0000-0099/0049.Group Anagrams/Solution.java index 5554c8c059add..e294d577cc6cc 100644 --- a/solution/0000-0099/0049.Group Anagrams/Solution.java +++ b/solution/0000-0099/0049.Group Anagrams/Solution.java @@ -1,12 +1,12 @@ -class Solution { - public List> groupAnagrams(String[] strs) { - Map> d = new HashMap<>(); - for (String s : strs) { - char[] t = s.toCharArray(); - Arrays.sort(t); - String k = String.valueOf(t); - d.computeIfAbsent(k, key -> new ArrayList<>()).add(s); - } - return new ArrayList<>(d.values()); - } +class Solution { + public List> groupAnagrams(String[] strs) { + Map> d = new HashMap<>(); + for (String s : strs) { + char[] t = s.toCharArray(); + Arrays.sort(t); + String k = String.valueOf(t); + d.computeIfAbsent(k, key -> new ArrayList<>()).add(s); + } + return new ArrayList<>(d.values()); + } } \ No newline at end of file diff --git a/solution/0000-0099/0049.Group Anagrams/Solution.py b/solution/0000-0099/0049.Group Anagrams/Solution.py index e5752ece6f703..f98245354208b 100644 --- a/solution/0000-0099/0049.Group Anagrams/Solution.py +++ b/solution/0000-0099/0049.Group Anagrams/Solution.py @@ -2,6 +2,6 @@ class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: d = defaultdict(list) for s in strs: - k = "".join(sorted(s)) + k = ''.join(sorted(s)) d[k].append(s) return list(d.values()) diff --git a/solution/0000-0099/0049.Group Anagrams/Solution2.cpp b/solution/0000-0099/0049.Group Anagrams/Solution2.cpp new file mode 100644 index 0000000000000..f7b808097864a --- /dev/null +++ b/solution/0000-0099/0049.Group Anagrams/Solution2.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + vector> groupAnagrams(vector& strs) { + unordered_map> d; + for (auto& s : strs) { + int cnt[26] = {0}; + for (auto& c : s) ++cnt[c - 'a']; + string k; + for (int i = 0; i < 26; ++i) { + if (cnt[i]) { + k += 'a' + i; + k += to_string(cnt[i]); + } + } + d[k].emplace_back(s); + } + vector> ans; + for (auto& [_, v] : d) ans.emplace_back(v); + return ans; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0049.Group Anagrams/Solution2.go b/solution/0000-0099/0049.Group Anagrams/Solution2.go new file mode 100644 index 0000000000000..9396f0f8edd0b --- /dev/null +++ b/solution/0000-0099/0049.Group Anagrams/Solution2.go @@ -0,0 +1,14 @@ +func groupAnagrams(strs []string) (ans [][]string) { + d := map[[26]int][]string{} + for _, s := range strs { + cnt := [26]int{} + for _, c := range s { + cnt[c-'a']++ + } + d[cnt] = append(d[cnt], s) + } + for _, v := range d { + ans = append(ans, v) + } + return +} \ No newline at end of file diff --git a/solution/0000-0099/0049.Group Anagrams/Solution2.java b/solution/0000-0099/0049.Group Anagrams/Solution2.java new file mode 100644 index 0000000000000..891392c74d008 --- /dev/null +++ b/solution/0000-0099/0049.Group Anagrams/Solution2.java @@ -0,0 +1,20 @@ +class Solution { + public List> groupAnagrams(String[] strs) { + Map> d = new HashMap<>(); + for (String s : strs) { + int[] cnt = new int[26]; + for (int i = 0; i < s.length(); ++i) { + ++cnt[s.charAt(i) - 'a']; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 26; ++i) { + if (cnt[i] > 0) { + sb.append((char) ('a' + i)).append(cnt[i]); + } + } + String k = sb.toString(); + d.computeIfAbsent(k, key -> new ArrayList<>()).add(s); + } + return new ArrayList<>(d.values()); + } +} \ No newline at end of file diff --git a/solution/0000-0099/0049.Group Anagrams/Solution2.py b/solution/0000-0099/0049.Group Anagrams/Solution2.py new file mode 100644 index 0000000000000..9c9ed6a8df8b6 --- /dev/null +++ b/solution/0000-0099/0049.Group Anagrams/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + d = defaultdict(list) + for s in strs: + cnt = [0] * 26 + for c in s: + cnt[ord(c) - ord('a')] += 1 + d[tuple(cnt)].append(s) + return list(d.values()) diff --git a/solution/0000-0099/0049.Group Anagrams/Solution2.ts b/solution/0000-0099/0049.Group Anagrams/Solution2.ts new file mode 100644 index 0000000000000..f2469ceb10559 --- /dev/null +++ b/solution/0000-0099/0049.Group Anagrams/Solution2.ts @@ -0,0 +1,8 @@ +function groupAnagrams(strs: string[]): string[][] { + const map = new Map(); + for (const str of strs) { + const k = str.split('').sort().join(''); + map.set(k, (map.get(k) ?? []).concat([str])); + } + return [...map.values()]; +} diff --git a/solution/0000-0099/0050.Pow(x, n)/Solution.cpp b/solution/0000-0099/0050.Pow(x, n)/Solution.cpp index 352fcf7bea155..4315d748935cd 100644 --- a/solution/0000-0099/0050.Pow(x, n)/Solution.cpp +++ b/solution/0000-0099/0050.Pow(x, n)/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - double myPow(double x, int n) { - auto qpow = [](double a, long long n) { - double ans = 1; - for (; n; n >>= 1) { - if (n & 1) { - ans *= a; - } - a *= a; - } - return ans; - }; - return n >= 0 ? qpow(x, n) : 1 / qpow(x, -(long long) n); - } +class Solution { +public: + double myPow(double x, int n) { + auto qpow = [](double a, long long n) { + double ans = 1; + for (; n; n >>= 1) { + if (n & 1) { + ans *= a; + } + a *= a; + } + return ans; + }; + return n >= 0 ? qpow(x, n) : 1 / qpow(x, -(long long) n); + } }; \ No newline at end of file diff --git a/solution/0000-0099/0050.Pow(x, n)/Solution.cs b/solution/0000-0099/0050.Pow(x, n)/Solution.cs index 93f0cd8681a88..7b4b6a29191dd 100644 --- a/solution/0000-0099/0050.Pow(x, n)/Solution.cs +++ b/solution/0000-0099/0050.Pow(x, n)/Solution.cs @@ -1,16 +1,16 @@ -public class Solution { - public double MyPow(double x, int n) { - return n >= 0 ? qpow(x, n) : 1.0 / qpow(x, -(long)n); - } - - private double qpow(double a, long n) { - double ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans *= a; - } - a *= a; - } - return ans; - } -} \ No newline at end of file +public class Solution { + public double MyPow(double x, int n) { + return n >= 0 ? qpow(x, n) : 1.0 / qpow(x, -(long)n); + } + + private double qpow(double a, long n) { + double ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans *= a; + } + a *= a; + } + return ans; + } +} diff --git a/solution/0000-0099/0050.Pow(x, n)/Solution.java b/solution/0000-0099/0050.Pow(x, n)/Solution.java index efa1dc56dd04d..df591fd553fdf 100644 --- a/solution/0000-0099/0050.Pow(x, n)/Solution.java +++ b/solution/0000-0099/0050.Pow(x, n)/Solution.java @@ -1,16 +1,16 @@ -class Solution { - public double myPow(double x, int n) { - return n >= 0 ? qpow(x, n) : 1 / qpow(x, -(long) n); - } - - private double qpow(double a, long n) { - double ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans = ans * a; - } - a = a * a; - } - return ans; - } +class Solution { + public double myPow(double x, int n) { + return n >= 0 ? qpow(x, n) : 1 / qpow(x, -(long) n); + } + + private double qpow(double a, long n) { + double ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans = ans * a; + } + a = a * a; + } + return ans; + } } \ No newline at end of file diff --git a/solution/0000-0099/0050.Pow(x, n)/Solution.py b/solution/0000-0099/0050.Pow(x, n)/Solution.py index 94981abc703d4..a0d019240926a 100644 --- a/solution/0000-0099/0050.Pow(x, n)/Solution.py +++ b/solution/0000-0099/0050.Pow(x, n)/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def myPow(self, x: float, n: int) -> float: - def qpow(a: float, n: int) -> float: - ans = 1 - while n: - if n & 1: - ans *= a - a *= a - n >>= 1 - return ans - - return qpow(x, n) if n >= 0 else 1 / qpow(x, -n) +class Solution: + def myPow(self, x: float, n: int) -> float: + def qpow(a: float, n: int) -> float: + ans = 1 + while n: + if n & 1: + ans *= a + a *= a + n >>= 1 + return ans + + return qpow(x, n) if n >= 0 else 1 / qpow(x, -n) diff --git a/solution/0000-0099/0051.N-Queens/Solution.cs b/solution/0000-0099/0051.N-Queens/Solution.cs index ddf2d5dd2b019..46deb1980b57b 100644 --- a/solution/0000-0099/0051.N-Queens/Solution.cs +++ b/solution/0000-0099/0051.N-Queens/Solution.cs @@ -5,7 +5,7 @@ public class Solution { private int[] udg; private IList> ans = new List>(); private IList t = new List(); - + public IList> SolveNQueens(int n) { this.n = n; col = new int[n]; @@ -33,4 +33,4 @@ private void dfs(int i) { } } } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0052.N-Queens II/Solution.py b/solution/0000-0099/0052.N-Queens II/Solution.py index 5609f42862b92..8e7619571e81c 100644 --- a/solution/0000-0099/0052.N-Queens II/Solution.py +++ b/solution/0000-0099/0052.N-Queens II/Solution.py @@ -1,21 +1,21 @@ -class Solution: - def totalNQueens(self, n: int) -> int: - def dfs(i: int): - if i == n: - nonlocal ans - ans += 1 - return - for j in range(n): - a, b = i + j, i - j + n - if cols[j] or dg[a] or udg[b]: - continue - cols[j] = dg[a] = udg[b] = True - dfs(i + 1) - cols[j] = dg[a] = udg[b] = False - - cols = [False] * 10 - dg = [False] * 20 - udg = [False] * 20 - ans = 0 - dfs(0) - return ans +class Solution: + def totalNQueens(self, n: int) -> int: + def dfs(i: int): + if i == n: + nonlocal ans + ans += 1 + return + for j in range(n): + a, b = i + j, i - j + n + if cols[j] or dg[a] or udg[b]: + continue + cols[j] = dg[a] = udg[b] = True + dfs(i + 1) + cols[j] = dg[a] = udg[b] = False + + cols = [False] * 10 + dg = [False] * 20 + udg = [False] * 20 + ans = 0 + dfs(0) + return ans diff --git a/solution/0000-0099/0053.Maximum Subarray/Solution.cs b/solution/0000-0099/0053.Maximum Subarray/Solution.cs index 508bf005b00e8..ea16c1b49684d 100644 --- a/solution/0000-0099/0053.Maximum Subarray/Solution.cs +++ b/solution/0000-0099/0053.Maximum Subarray/Solution.cs @@ -7,4 +7,4 @@ public int MaxSubArray(int[] nums) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0053.Maximum Subarray/Solution2.java b/solution/0000-0099/0053.Maximum Subarray/Solution2.java new file mode 100644 index 0000000000000..4bdf6ef6343b2 --- /dev/null +++ b/solution/0000-0099/0053.Maximum Subarray/Solution2.java @@ -0,0 +1,29 @@ +class Solution { + public int maxSubArray(int[] nums) { + return maxSub(nums, 0, nums.length - 1); + } + + private int maxSub(int[] nums, int left, int right) { + if (left == right) { + return nums[left]; + } + int mid = (left + right) >>> 1; + int lsum = maxSub(nums, left, mid); + int rsum = maxSub(nums, mid + 1, right); + return Math.max(Math.max(lsum, rsum), crossMaxSub(nums, left, mid, right)); + } + + private int crossMaxSub(int[] nums, int left, int mid, int right) { + int lsum = 0, rsum = 0; + int lmx = Integer.MIN_VALUE, rmx = Integer.MIN_VALUE; + for (int i = mid; i >= left; --i) { + lsum += nums[i]; + lmx = Math.max(lmx, lsum); + } + for (int i = mid + 1; i <= right; ++i) { + rsum += nums[i]; + rmx = Math.max(rmx, rsum); + } + return lmx + rmx; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0053.Maximum Subarray/Solution2.py b/solution/0000-0099/0053.Maximum Subarray/Solution2.py new file mode 100644 index 0000000000000..704b8c3b0a543 --- /dev/null +++ b/solution/0000-0099/0053.Maximum Subarray/Solution2.py @@ -0,0 +1,24 @@ +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + def crossMaxSub(nums, left, mid, right): + lsum = rsum = 0 + lmx = rmx = -inf + for i in range(mid, left - 1, -1): + lsum += nums[i] + lmx = max(lmx, lsum) + for i in range(mid + 1, right + 1): + rsum += nums[i] + rmx = max(rmx, rsum) + return lmx + rmx + + def maxSub(nums, left, right): + if left == right: + return nums[left] + mid = (left + right) >> 1 + lsum = maxSub(nums, left, mid) + rsum = maxSub(nums, mid + 1, right) + csum = crossMaxSub(nums, left, mid, right) + return max(lsum, rsum, csum) + + left, right = 0, len(nums) - 1 + return maxSub(nums, left, right) diff --git a/solution/0000-0099/0054.Spiral Matrix/Solution.cs b/solution/0000-0099/0054.Spiral Matrix/Solution.cs index 92809db32f7ce..55a881802a84d 100644 --- a/solution/0000-0099/0054.Spiral Matrix/Solution.cs +++ b/solution/0000-0099/0054.Spiral Matrix/Solution.cs @@ -16,4 +16,4 @@ public IList SpiralOrder(int[][] matrix) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0054.Spiral Matrix/Solution2.cpp b/solution/0000-0099/0054.Spiral Matrix/Solution2.cpp new file mode 100644 index 0000000000000..290f98d3eecd0 --- /dev/null +++ b/solution/0000-0099/0054.Spiral Matrix/Solution2.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + vector spiralOrder(vector>& matrix) { + int m = matrix.size(), n = matrix[0].size(); + int dirs[5] = {0, 1, 0, -1, 0}; + vector ans; + for (int h = m * n, i = 0, j = 0, k = 0; h; --h) { + ans.push_back(matrix[i][j]); + matrix[i][j] += 300; + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { + k = (k + 1) % 4; + } + i += dirs[k]; + j += dirs[k + 1]; + } + // for (int i = 0; i < m; ++i) { + // for (int j = 0; j < n; ++j) { + // matrix[i][j] -= 300; + // } + // } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0054.Spiral Matrix/Solution2.cs b/solution/0000-0099/0054.Spiral Matrix/Solution2.cs new file mode 100644 index 0000000000000..1e25df3f57569 --- /dev/null +++ b/solution/0000-0099/0054.Spiral Matrix/Solution2.cs @@ -0,0 +1,23 @@ +public class Solution { + public IList SpiralOrder(int[][] matrix) { + int m = matrix.Length, n = matrix[0].Length; + int[] dirs = new int[] {0, 1, 0, -1, 0}; + IList ans = new List(); + for (int h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { + ans.Add(matrix[i][j]); + matrix[i][j] += 300; + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { + k = (k + 1) % 4; + } + i += dirs[k]; + j += dirs[k + 1]; + } + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + matrix[i][j] -= 300; + } + } + return ans; + } +} diff --git a/solution/0000-0099/0054.Spiral Matrix/Solution2.go b/solution/0000-0099/0054.Spiral Matrix/Solution2.go new file mode 100644 index 0000000000000..433b797679502 --- /dev/null +++ b/solution/0000-0099/0054.Spiral Matrix/Solution2.go @@ -0,0 +1,19 @@ +func spiralOrder(matrix [][]int) (ans []int) { + m, n := len(matrix), len(matrix[0]) + dirs := [5]int{0, 1, 0, -1, 0} + for h, i, j, k := m*n, 0, 0, 0; h > 0; h-- { + ans = append(ans, matrix[i][j]) + matrix[i][j] += 300 + x, y := i+dirs[k], j+dirs[k+1] + if x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100 { + k = (k + 1) % 4 + } + i, j = i+dirs[k], j+dirs[k+1] + } + // for i, row := range matrix { + // for j := range row { + // matrix[i][j] -= 300 + // } + // } + return +} \ No newline at end of file diff --git a/solution/0000-0099/0054.Spiral Matrix/Solution2.java b/solution/0000-0099/0054.Spiral Matrix/Solution2.java new file mode 100644 index 0000000000000..c5d00818b96d5 --- /dev/null +++ b/solution/0000-0099/0054.Spiral Matrix/Solution2.java @@ -0,0 +1,23 @@ +class Solution { + public List spiralOrder(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + int[] dirs = {0, 1, 0, -1, 0}; + List ans = new ArrayList<>(); + for (int h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { + ans.add(matrix[i][j]); + matrix[i][j] += 300; + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { + k = (k + 1) % 4; + } + i += dirs[k]; + j += dirs[k + 1]; + } + // for (int i = 0; i < m; ++i) { + // for (int j = 0; j < n; ++j) { + // matrix[i][j] -= 300; + // } + // } + return ans; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0054.Spiral Matrix/Solution2.js b/solution/0000-0099/0054.Spiral Matrix/Solution2.js new file mode 100644 index 0000000000000..7971309a3e4ac --- /dev/null +++ b/solution/0000-0099/0054.Spiral Matrix/Solution2.js @@ -0,0 +1,27 @@ +/** + * @param {number[][]} matrix + * @return {number[]} + */ +var spiralOrder = function (matrix) { + const m = matrix.length; + const n = matrix[0].length; + const ans = []; + const dirs = [0, 1, 0, -1, 0]; + for (let h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { + ans.push(matrix[i][j]); + matrix[i][j] += 300; + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { + k = (k + 1) % 4; + } + i += dirs[k]; + j += dirs[k + 1]; + } + // for (let i = 0; i < m; ++i) { + // for (let j = 0; j < n; ++j) { + // matrix[i][j] -= 300; + // } + // } + return ans; +}; diff --git a/solution/0000-0099/0054.Spiral Matrix/Solution2.py b/solution/0000-0099/0054.Spiral Matrix/Solution2.py new file mode 100644 index 0000000000000..e4546d84417d1 --- /dev/null +++ b/solution/0000-0099/0054.Spiral Matrix/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + m, n = len(matrix), len(matrix[0]) + dirs = (0, 1, 0, -1, 0) + i = j = k = 0 + ans = [] + for _ in range(m * n): + ans.append(matrix[i][j]) + matrix[i][j] += 300 + x, y = i + dirs[k], j + dirs[k + 1] + if not 0 <= x < m or not 0 <= y < n or matrix[x][y] > 100: + k = (k + 1) % 4 + i = i + dirs[k] + j = j + dirs[k + 1] + # for i in range(m): + # for j in range(n): + # matrix[i][j] -= 300 + return ans diff --git a/solution/0000-0099/0054.Spiral Matrix/Solution2.ts b/solution/0000-0099/0054.Spiral Matrix/Solution2.ts new file mode 100644 index 0000000000000..1a4282624c6e2 --- /dev/null +++ b/solution/0000-0099/0054.Spiral Matrix/Solution2.ts @@ -0,0 +1,23 @@ +function spiralOrder(matrix: number[][]): number[] { + const m = matrix.length; + const n = matrix[0].length; + const ans: number[] = []; + const dirs = [0, 1, 0, -1, 0]; + for (let h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { + ans.push(matrix[i][j]); + matrix[i][j] += 300; + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { + k = (k + 1) % 4; + } + i += dirs[k]; + j += dirs[k + 1]; + } + // for (let i = 0; i < m; ++i) { + // for (let j = 0; j < n; ++j) { + // matrix[i][j] -= 300; + // } + // } + return ans; +} diff --git a/solution/0000-0099/0054.Spiral Matrix/Solution3.cpp b/solution/0000-0099/0054.Spiral Matrix/Solution3.cpp new file mode 100644 index 0000000000000..1aa34c818b26a --- /dev/null +++ b/solution/0000-0099/0054.Spiral Matrix/Solution3.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector spiralOrder(vector>& matrix) { + int m = matrix.size(), n = matrix[0].size(); + int x1 = 0, y1 = 0, x2 = m - 1, y2 = n - 1; + vector ans; + while (x1 <= x2 && y1 <= y2) { + for (int j = y1; j <= y2; ++j) { + ans.push_back(matrix[x1][j]); + } + for (int i = x1 + 1; i <= x2; ++i) { + ans.push_back(matrix[i][y2]); + } + if (x1 < x2 && y1 < y2) { + for (int j = y2 - 1; j >= y1; --j) { + ans.push_back(matrix[x2][j]); + } + for (int i = x2 - 1; i > x1; --i) { + ans.push_back(matrix[i][y1]); + } + } + ++x1, ++y1; + --x2, --y2; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0054.Spiral Matrix/Solution3.cs b/solution/0000-0099/0054.Spiral Matrix/Solution3.cs new file mode 100644 index 0000000000000..7c4e1f17292c6 --- /dev/null +++ b/solution/0000-0099/0054.Spiral Matrix/Solution3.cs @@ -0,0 +1,28 @@ +public class Solution { + public IList SpiralOrder(int[][] matrix) { + int m = matrix.Length, n = matrix[0].Length; + int x1 = 0, y1 = 0, x2 = m - 1, y2 = n - 1; + IList ans = new List(); + while (x1 <= x2 && y1 <= y2) { + for (int j = y1; j <= y2; ++j) { + ans.Add(matrix[x1][j]); + } + for (int i = x1 + 1; i <= x2; ++i) { + ans.Add(matrix[i][y2]); + } + if (x1 < x2 && y1 < y2) { + for (int j = y2 - 1; j >= y1; --j) { + ans.Add(matrix[x2][j]); + } + for (int i = x2 - 1; i > x1; --i) { + ans.Add(matrix[i][y1]); + } + } + ++x1; + ++y1; + --x2; + --y2; + } + return ans; + } +} diff --git a/solution/0000-0099/0054.Spiral Matrix/Solution3.go b/solution/0000-0099/0054.Spiral Matrix/Solution3.go new file mode 100644 index 0000000000000..593da1ab1f358 --- /dev/null +++ b/solution/0000-0099/0054.Spiral Matrix/Solution3.go @@ -0,0 +1,23 @@ +func spiralOrder(matrix [][]int) (ans []int) { + m, n := len(matrix), len(matrix[0]) + x1, y1, x2, y2 := 0, 0, m-1, n-1 + for x1 <= x2 && y1 <= y2 { + for j := y1; j <= y2; j++ { + ans = append(ans, matrix[x1][j]) + } + for i := x1 + 1; i <= x2; i++ { + ans = append(ans, matrix[i][y2]) + } + if x1 < x2 && y1 < y2 { + for j := y2 - 1; j >= y1; j-- { + ans = append(ans, matrix[x2][j]) + } + for i := x2 - 1; i > x1; i-- { + ans = append(ans, matrix[i][y1]) + } + } + x1, y1 = x1+1, y1+1 + x2, y2 = x2-1, y2-1 + } + return +} \ No newline at end of file diff --git a/solution/0000-0099/0054.Spiral Matrix/Solution3.java b/solution/0000-0099/0054.Spiral Matrix/Solution3.java new file mode 100644 index 0000000000000..8fb658b6cfe86 --- /dev/null +++ b/solution/0000-0099/0054.Spiral Matrix/Solution3.java @@ -0,0 +1,28 @@ +class Solution { + public List spiralOrder(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + int x1 = 0, y1 = 0, x2 = m - 1, y2 = n - 1; + List ans = new ArrayList<>(); + while (x1 <= x2 && y1 <= y2) { + for (int j = y1; j <= y2; ++j) { + ans.add(matrix[x1][j]); + } + for (int i = x1 + 1; i <= x2; ++i) { + ans.add(matrix[i][y2]); + } + if (x1 < x2 && y1 < y2) { + for (int j = y2 - 1; j >= y1; --j) { + ans.add(matrix[x2][j]); + } + for (int i = x2 - 1; i > x1; --i) { + ans.add(matrix[i][y1]); + } + } + ++x1; + ++y1; + --x2; + --y2; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0054.Spiral Matrix/Solution3.js b/solution/0000-0099/0054.Spiral Matrix/Solution3.js new file mode 100644 index 0000000000000..19fe4eaa70580 --- /dev/null +++ b/solution/0000-0099/0054.Spiral Matrix/Solution3.js @@ -0,0 +1,34 @@ +/** + * @param {number[][]} matrix + * @return {number[]} + */ +var spiralOrder = function (matrix) { + const m = matrix.length; + const n = matrix[0].length; + let x1 = 0; + let y1 = 0; + let x2 = m - 1; + let y2 = n - 1; + const ans = []; + while (x1 <= x2 && y1 <= y2) { + for (let j = y1; j <= y2; ++j) { + ans.push(matrix[x1][j]); + } + for (let i = x1 + 1; i <= x2; ++i) { + ans.push(matrix[i][y2]); + } + if (x1 < x2 && y1 < y2) { + for (let j = y2 - 1; j >= y1; --j) { + ans.push(matrix[x2][j]); + } + for (let i = x2 - 1; i > x1; --i) { + ans.push(matrix[i][y1]); + } + } + ++x1; + ++y1; + --x2; + --y2; + } + return ans; +}; diff --git a/solution/0000-0099/0054.Spiral Matrix/Solution3.py b/solution/0000-0099/0054.Spiral Matrix/Solution3.py new file mode 100644 index 0000000000000..51102ba2e4b22 --- /dev/null +++ b/solution/0000-0099/0054.Spiral Matrix/Solution3.py @@ -0,0 +1,18 @@ +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + m, n = len(matrix), len(matrix[0]) + x1, y1, x2, y2 = 0, 0, m - 1, n - 1 + ans = [] + while x1 <= x2 and y1 <= y2: + for j in range(y1, y2 + 1): + ans.append(matrix[x1][j]) + for i in range(x1 + 1, x2 + 1): + ans.append(matrix[i][y2]) + if x1 < x2 and y1 < y2: + for j in range(y2 - 1, y1 - 1, -1): + ans.append(matrix[x2][j]) + for i in range(x2 - 1, x1, -1): + ans.append(matrix[i][y1]) + x1, y1 = x1 + 1, y1 + 1 + x2, y2 = x2 - 1, y2 - 1 + return ans diff --git a/solution/0000-0099/0054.Spiral Matrix/Solution3.ts b/solution/0000-0099/0054.Spiral Matrix/Solution3.ts new file mode 100644 index 0000000000000..8438c09a6f7af --- /dev/null +++ b/solution/0000-0099/0054.Spiral Matrix/Solution3.ts @@ -0,0 +1,30 @@ +function spiralOrder(matrix: number[][]): number[] { + const m = matrix.length; + const n = matrix[0].length; + let x1 = 0; + let y1 = 0; + let x2 = m - 1; + let y2 = n - 1; + const ans: number[] = []; + while (x1 <= x2 && y1 <= y2) { + for (let j = y1; j <= y2; ++j) { + ans.push(matrix[x1][j]); + } + for (let i = x1 + 1; i <= x2; ++i) { + ans.push(matrix[i][y2]); + } + if (x1 < x2 && y1 < y2) { + for (let j = y2 - 1; j >= y1; --j) { + ans.push(matrix[x2][j]); + } + for (let i = x2 - 1; i > x1; --i) { + ans.push(matrix[i][y1]); + } + } + ++x1; + ++y1; + --x2; + --y2; + } + return ans; +} diff --git a/solution/0000-0099/0055.Jump Game/Solution.cs b/solution/0000-0099/0055.Jump Game/Solution.cs index d22a7c2f4e64f..3d661ea56984b 100644 --- a/solution/0000-0099/0055.Jump Game/Solution.cs +++ b/solution/0000-0099/0055.Jump Game/Solution.cs @@ -9,4 +9,4 @@ public bool CanJump(int[] nums) { } return true; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0056.Merge Intervals/Solution.cpp b/solution/0000-0099/0056.Merge Intervals/Solution.cpp index d156cfa358ed1..1431cb22dd254 100644 --- a/solution/0000-0099/0056.Merge Intervals/Solution.cpp +++ b/solution/0000-0099/0056.Merge Intervals/Solution.cpp @@ -2,15 +2,18 @@ class Solution { public: vector> merge(vector>& intervals) { sort(intervals.begin(), intervals.end()); + int st = intervals[0][0], ed = intervals[0][1]; vector> ans; - ans.emplace_back(intervals[0]); for (int i = 1; i < intervals.size(); ++i) { - if (ans.back()[1] < intervals[i][0]) { - ans.emplace_back(intervals[i]); + if (ed < intervals[i][0]) { + ans.push_back({st, ed}); + st = intervals[i][0]; + ed = intervals[i][1]; } else { - ans.back()[1] = max(ans.back()[1], intervals[i][1]); + ed = max(ed, intervals[i][1]); } } + ans.push_back({st, ed}); return ans; } }; \ No newline at end of file diff --git a/solution/0000-0099/0056.Merge Intervals/Solution.cs b/solution/0000-0099/0056.Merge Intervals/Solution.cs index 620658fc3467c..0ae3b6dca5a71 100644 --- a/solution/0000-0099/0056.Merge Intervals/Solution.cs +++ b/solution/0000-0099/0056.Merge Intervals/Solution.cs @@ -1,15 +1,18 @@ -public class Solution { - public int[][] Merge(int[][] intervals) { - intervals = intervals.OrderBy(a => a[0]).ToArray(); - var ans = new List(); - ans.Add(intervals[0]); - for (int i = 1; i < intervals.Length; ++i) { - if (ans[ans.Count - 1][1] < intervals[i][0]) { - ans.Add(intervals[i]); - } else { - ans[ans.Count - 1][1] = Math.Max(ans[ans.Count - 1][1], intervals[i][1]); - } - } - return ans.ToArray(); - } -} \ No newline at end of file +public class Solution { + public int[][] Merge(int[][] intervals) { + intervals = intervals.OrderBy(a => a[0]).ToArray(); + int st = intervals[0][0], ed = intervals[0][1]; + var ans = new List(); + for (int i = 1; i < intervals.Length; ++i) { + if (ed < intervals[i][0]) { + ans.Add(new int[] { st, ed }); + st = intervals[i][0]; + ed = intervals[i][1]; + } else { + ed = Math.Max(ed, intervals[i][1]); + } + } + ans.Add(new int[] { st, ed }); + return ans.ToArray(); + } +} diff --git a/solution/0000-0099/0056.Merge Intervals/Solution.go b/solution/0000-0099/0056.Merge Intervals/Solution.go index bbd683ff3f77a..511641bb41854 100644 --- a/solution/0000-0099/0056.Merge Intervals/Solution.go +++ b/solution/0000-0099/0056.Merge Intervals/Solution.go @@ -1,12 +1,16 @@ func merge(intervals [][]int) (ans [][]int) { - sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] }) - ans = append(ans, intervals[0]) + sort.Slice(intervals, func(i, j int) bool { + return intervals[i][0] < intervals[j][0] + }) + st, ed := intervals[0][0], intervals[0][1] for _, e := range intervals[1:] { - if ans[len(ans)-1][1] < e[0] { - ans = append(ans, e) - } else { - ans[len(ans)-1][1] = max(ans[len(ans)-1][1], e[1]) + if ed < e[0] { + ans = append(ans, []int{st, ed}) + st, ed = e[0], e[1] + } else if ed < e[1] { + ed = e[1] } } - return + ans = append(ans, []int{st, ed}) + return ans } \ No newline at end of file diff --git a/solution/0000-0099/0056.Merge Intervals/Solution.java b/solution/0000-0099/0056.Merge Intervals/Solution.java index 7ae5985248b9c..29814a68a552b 100644 --- a/solution/0000-0099/0056.Merge Intervals/Solution.java +++ b/solution/0000-0099/0056.Merge Intervals/Solution.java @@ -1,16 +1,19 @@ -class Solution { - public int[][] merge(int[][] intervals) { - Arrays.sort(intervals, (a, b) -> a[0] - b[0]); - List ans = new ArrayList<>(); - ans.add(intervals[0]); - for (int i = 1; i < intervals.length; ++i) { - int s = intervals[i][0], e = intervals[i][1]; - if (ans.get(ans.size() - 1)[1] < s) { - ans.add(intervals[i]); - } else { - ans.get(ans.size() - 1)[1] = Math.max(ans.get(ans.size() - 1)[1], e); - } - } - return ans.toArray(new int[ans.size()][]); - } +class Solution { + public int[][] merge(int[][] intervals) { + Arrays.sort(intervals, Comparator.comparingInt(a -> a[0])); + int st = intervals[0][0], ed = intervals[0][1]; + List ans = new ArrayList<>(); + for (int i = 1; i < intervals.length; ++i) { + int s = intervals[i][0], e = intervals[i][1]; + if (ed < s) { + ans.add(new int[] {st, ed}); + st = s; + ed = e; + } else { + ed = Math.max(ed, e); + } + } + ans.add(new int[] {st, ed}); + return ans.toArray(new int[ans.size()][]); + } } \ No newline at end of file diff --git a/solution/0000-0099/0056.Merge Intervals/Solution.py b/solution/0000-0099/0056.Merge Intervals/Solution.py index 6689d2d238d83..9042c3fa322bd 100644 --- a/solution/0000-0099/0056.Merge Intervals/Solution.py +++ b/solution/0000-0099/0056.Merge Intervals/Solution.py @@ -1,10 +1,13 @@ class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: intervals.sort() - ans = [intervals[0]] + ans = [] + st, ed = intervals[0] for s, e in intervals[1:]: - if ans[-1][1] < s: - ans.append([s, e]) + if ed < s: + ans.append([st, ed]) + st, ed = s, e else: - ans[-1][1] = max(ans[-1][1], e) + ed = max(ed, e) + ans.append([st, ed]) return ans diff --git a/solution/0000-0099/0056.Merge Intervals/Solution.ts b/solution/0000-0099/0056.Merge Intervals/Solution.ts index 28df270c3d185..c9ff9b9104f0e 100644 --- a/solution/0000-0099/0056.Merge Intervals/Solution.ts +++ b/solution/0000-0099/0056.Merge Intervals/Solution.ts @@ -1,12 +1,15 @@ function merge(intervals: number[][]): number[][] { intervals.sort((a, b) => a[0] - b[0]); - const ans: number[][] = [intervals[0]]; - for (let i = 1; i < intervals.length; ++i) { - if (ans.at(-1)[1] < intervals[i][0]) { - ans.push(intervals[i]); + const ans: number[][] = []; + let [st, ed] = intervals[0]; + for (const [s, e] of intervals.slice(1)) { + if (ed < s) { + ans.push([st, ed]); + [st, ed] = [s, e]; } else { - ans.at(-1)[1] = Math.max(ans.at(-1)[1], intervals[i][1]); + ed = Math.max(ed, e); } } + ans.push([st, ed]); return ans; } diff --git a/solution/0000-0099/0056.Merge Intervals/Solution2.cpp b/solution/0000-0099/0056.Merge Intervals/Solution2.cpp new file mode 100644 index 0000000000000..d156cfa358ed1 --- /dev/null +++ b/solution/0000-0099/0056.Merge Intervals/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector> merge(vector>& intervals) { + sort(intervals.begin(), intervals.end()); + vector> ans; + ans.emplace_back(intervals[0]); + for (int i = 1; i < intervals.size(); ++i) { + if (ans.back()[1] < intervals[i][0]) { + ans.emplace_back(intervals[i]); + } else { + ans.back()[1] = max(ans.back()[1], intervals[i][1]); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0056.Merge Intervals/Solution2.cs b/solution/0000-0099/0056.Merge Intervals/Solution2.cs new file mode 100644 index 0000000000000..f666c4c577bc3 --- /dev/null +++ b/solution/0000-0099/0056.Merge Intervals/Solution2.cs @@ -0,0 +1,15 @@ +public class Solution { + public int[][] Merge(int[][] intervals) { + intervals = intervals.OrderBy(a => a[0]).ToArray(); + var ans = new List(); + ans.Add(intervals[0]); + for (int i = 1; i < intervals.Length; ++i) { + if (ans[ans.Count - 1][1] < intervals[i][0]) { + ans.Add(intervals[i]); + } else { + ans[ans.Count - 1][1] = Math.Max(ans[ans.Count - 1][1], intervals[i][1]); + } + } + return ans.ToArray(); + } +} diff --git a/solution/0000-0099/0056.Merge Intervals/Solution2.go b/solution/0000-0099/0056.Merge Intervals/Solution2.go new file mode 100644 index 0000000000000..bbd683ff3f77a --- /dev/null +++ b/solution/0000-0099/0056.Merge Intervals/Solution2.go @@ -0,0 +1,12 @@ +func merge(intervals [][]int) (ans [][]int) { + sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] }) + ans = append(ans, intervals[0]) + for _, e := range intervals[1:] { + if ans[len(ans)-1][1] < e[0] { + ans = append(ans, e) + } else { + ans[len(ans)-1][1] = max(ans[len(ans)-1][1], e[1]) + } + } + return +} \ No newline at end of file diff --git a/solution/0000-0099/0056.Merge Intervals/Solution2.java b/solution/0000-0099/0056.Merge Intervals/Solution2.java new file mode 100644 index 0000000000000..a88780f14f7e1 --- /dev/null +++ b/solution/0000-0099/0056.Merge Intervals/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public int[][] merge(int[][] intervals) { + Arrays.sort(intervals, (a, b) -> a[0] - b[0]); + List ans = new ArrayList<>(); + ans.add(intervals[0]); + for (int i = 1; i < intervals.length; ++i) { + int s = intervals[i][0], e = intervals[i][1]; + if (ans.get(ans.size() - 1)[1] < s) { + ans.add(intervals[i]); + } else { + ans.get(ans.size() - 1)[1] = Math.max(ans.get(ans.size() - 1)[1], e); + } + } + return ans.toArray(new int[ans.size()][]); + } +} \ No newline at end of file diff --git a/solution/0000-0099/0056.Merge Intervals/Solution2.py b/solution/0000-0099/0056.Merge Intervals/Solution2.py new file mode 100644 index 0000000000000..6689d2d238d83 --- /dev/null +++ b/solution/0000-0099/0056.Merge Intervals/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def merge(self, intervals: List[List[int]]) -> List[List[int]]: + intervals.sort() + ans = [intervals[0]] + for s, e in intervals[1:]: + if ans[-1][1] < s: + ans.append([s, e]) + else: + ans[-1][1] = max(ans[-1][1], e) + return ans diff --git a/solution/0000-0099/0056.Merge Intervals/Solution2.ts b/solution/0000-0099/0056.Merge Intervals/Solution2.ts new file mode 100644 index 0000000000000..28df270c3d185 --- /dev/null +++ b/solution/0000-0099/0056.Merge Intervals/Solution2.ts @@ -0,0 +1,12 @@ +function merge(intervals: number[][]): number[][] { + intervals.sort((a, b) => a[0] - b[0]); + const ans: number[][] = [intervals[0]]; + for (let i = 1; i < intervals.length; ++i) { + if (ans.at(-1)[1] < intervals[i][0]) { + ans.push(intervals[i]); + } else { + ans.at(-1)[1] = Math.max(ans.at(-1)[1], intervals[i][1]); + } + } + return ans; +} diff --git a/solution/0000-0099/0056.Merge Intervals/Solution3.ts b/solution/0000-0099/0056.Merge Intervals/Solution3.ts new file mode 100644 index 0000000000000..ae33aa01534b8 --- /dev/null +++ b/solution/0000-0099/0056.Merge Intervals/Solution3.ts @@ -0,0 +1,16 @@ +function merge(intervals: number[][]): number[][] { + intervals.sort((a, b) => a[0] - b[0]); + const n = intervals.length; + const res = []; + let i = 0; + while (i < n) { + let [l, r] = intervals[i]; + i++; + while (i < n && r >= intervals[i][0]) { + r = Math.max(r, intervals[i][1]); + i++; + } + res.push([l, r]); + } + return res; +} diff --git a/solution/0000-0099/0057.Insert Interval/Solution.cpp b/solution/0000-0099/0057.Insert Interval/Solution.cpp index f427547fca346..81b4bbe366c51 100644 --- a/solution/0000-0099/0057.Insert Interval/Solution.cpp +++ b/solution/0000-0099/0057.Insert Interval/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - vector> insert(vector>& intervals, vector& newInterval) { - intervals.emplace_back(newInterval); - return merge(intervals); - } - - vector> merge(vector>& intervals) { - sort(intervals.begin(), intervals.end()); - vector> ans; - ans.emplace_back(intervals[0]); - for (int i = 1; i < intervals.size(); ++i) { - if (ans.back()[1] < intervals[i][0]) { - ans.emplace_back(intervals[i]); - } else { - ans.back()[1] = max(ans.back()[1], intervals[i][1]); - } - } - return ans; - } +class Solution { +public: + vector> insert(vector>& intervals, vector& newInterval) { + intervals.emplace_back(newInterval); + return merge(intervals); + } + + vector> merge(vector>& intervals) { + sort(intervals.begin(), intervals.end()); + vector> ans; + ans.emplace_back(intervals[0]); + for (int i = 1; i < intervals.size(); ++i) { + if (ans.back()[1] < intervals[i][0]) { + ans.emplace_back(intervals[i]); + } else { + ans.back()[1] = max(ans.back()[1], intervals[i][1]); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0057.Insert Interval/Solution.cs b/solution/0000-0099/0057.Insert Interval/Solution.cs index 5516e808b8710..c45f9040c9a68 100644 --- a/solution/0000-0099/0057.Insert Interval/Solution.cs +++ b/solution/0000-0099/0057.Insert Interval/Solution.cs @@ -1,26 +1,24 @@ public class Solution { public int[][] Insert(int[][] intervals, int[] newInterval) { + int[][] newIntervals = new int[intervals.Length + 1][]; + for (int i = 0; i < intervals.Length; ++i) { + newIntervals[i] = intervals[i]; + } + newIntervals[intervals.Length] = newInterval; + return Merge(newIntervals); + } + + public int[][] Merge(int[][] intervals) { + intervals = intervals.OrderBy(a => a[0]).ToArray(); var ans = new List(); - int st = newInterval[0], ed = newInterval[1]; - bool insert = false; - foreach (var interval in intervals) { - int s = interval[0], e = interval[1]; - if (ed < s) { - if (!insert) { - ans.Add(new int[]{st, ed}); - insert = true; - } - ans.Add(interval); - } else if (st > e) { - ans.Add(interval); + ans.Add(intervals[0]); + for (int i = 1; i < intervals.Length; ++i) { + if (ans[ans.Count - 1][1] < intervals[i][0]) { + ans.Add(intervals[i]); } else { - st = Math.Min(st, s); - ed = Math.Max(ed, e); + ans[ans.Count - 1][1] = Math.Max(ans[ans.Count - 1][1], intervals[i][1]); } } - if (!insert) { - ans.Add(new int[]{st, ed}); - } return ans.ToArray(); } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0057.Insert Interval/Solution.java b/solution/0000-0099/0057.Insert Interval/Solution.java index 0f897cc861229..4f7dca6e117fd 100644 --- a/solution/0000-0099/0057.Insert Interval/Solution.java +++ b/solution/0000-0099/0057.Insert Interval/Solution.java @@ -1,25 +1,25 @@ -class Solution { - public int[][] insert(int[][] intervals, int[] newInterval) { - int[][] newIntervals = new int[intervals.length + 1][2]; - for (int i = 0; i < intervals.length; ++i) { - newIntervals[i] = intervals[i]; - } - newIntervals[intervals.length] = newInterval; - return merge(newIntervals); - } - - private int[][] merge(int[][] intervals) { - Arrays.sort(intervals, (a, b) -> a[0] - b[0]); - List ans = new ArrayList<>(); - ans.add(intervals[0]); - for (int i = 1; i < intervals.length; ++i) { - int s = intervals[i][0], e = intervals[i][1]; - if (ans.get(ans.size() - 1)[1] < s) { - ans.add(intervals[i]); - } else { - ans.get(ans.size() - 1)[1] = Math.max(ans.get(ans.size() - 1)[1], e); - } - } - return ans.toArray(new int[ans.size()][]); - } +class Solution { + public int[][] insert(int[][] intervals, int[] newInterval) { + int[][] newIntervals = new int[intervals.length + 1][2]; + for (int i = 0; i < intervals.length; ++i) { + newIntervals[i] = intervals[i]; + } + newIntervals[intervals.length] = newInterval; + return merge(newIntervals); + } + + private int[][] merge(int[][] intervals) { + Arrays.sort(intervals, (a, b) -> a[0] - b[0]); + List ans = new ArrayList<>(); + ans.add(intervals[0]); + for (int i = 1; i < intervals.length; ++i) { + int s = intervals[i][0], e = intervals[i][1]; + if (ans.get(ans.size() - 1)[1] < s) { + ans.add(intervals[i]); + } else { + ans.get(ans.size() - 1)[1] = Math.max(ans.get(ans.size() - 1)[1], e); + } + } + return ans.toArray(new int[ans.size()][]); + } } \ No newline at end of file diff --git a/solution/0000-0099/0057.Insert Interval/Solution.rs b/solution/0000-0099/0057.Insert Interval/Solution.rs index 49be224f5754b..4565fbf8b85ec 100644 --- a/solution/0000-0099/0057.Insert Interval/Solution.rs +++ b/solution/0000-0099/0057.Insert Interval/Solution.rs @@ -1,27 +1,24 @@ impl Solution { pub fn insert(intervals: Vec>, new_interval: Vec) -> Vec> { - let mut inserted = false; + let mut merged_intervals = intervals.clone(); + merged_intervals.push(vec![new_interval[0], new_interval[1]]); + // sort by elem[0] + merged_intervals.sort_by_key(|elem| elem[0]); + // merge interval let mut result = vec![]; - let (mut start, mut end) = (new_interval[0], new_interval[1]); - for iter in intervals.iter() { - let (cur_st, cur_ed) = (iter[0], iter[1]); - if cur_ed < start { - result.push(vec![cur_st, cur_ed]); - } else if cur_st > end { - if !inserted { - inserted = true; - result.push(vec![start, end]); - } - result.push(vec![cur_st, cur_ed]); - } else { - start = std::cmp::min(start, cur_st); - end = std::cmp::max(end, cur_ed); + for interval in merged_intervals { + if result.is_empty() { + result.push(interval); + continue; } - } - if !inserted { - result.push(vec![start, end]); + let last_elem = result.last_mut().unwrap(); + if interval[0] > last_elem[1] { + result.push(interval); + } else { + last_elem[1] = last_elem[1].max(interval[1]); + } } result } diff --git a/solution/0000-0099/0057.Insert Interval/Solution.ts b/solution/0000-0099/0057.Insert Interval/Solution.ts index 173f05f39a238..b77db4d4a8102 100644 --- a/solution/0000-0099/0057.Insert Interval/Solution.ts +++ b/solution/0000-0099/0057.Insert Interval/Solution.ts @@ -1,23 +1,17 @@ function insert(intervals: number[][], newInterval: number[]): number[][] { - let [st, ed] = newInterval; - const ans: number[][] = []; - let insert = false; - for (const [s, e] of intervals) { - if (ed < s) { - if (!insert) { - ans.push([st, ed]); - insert = true; + const merge = (intervals: number[][]): number[][] => { + intervals.sort((a, b) => a[0] - b[0]); + const ans: number[][] = [intervals[0]]; + for (let i = 1; i < intervals.length; ++i) { + if (ans.at(-1)[1] < intervals[i][0]) { + ans.push(intervals[i]); + } else { + ans.at(-1)[1] = Math.max(ans.at(-1)[1], intervals[i][1]); } - ans.push([s, e]); - } else if (e < st) { - ans.push([s, e]); - } else { - st = Math.min(st, s); - ed = Math.max(ed, e); } - } - if (!insert) { - ans.push([st, ed]); - } - return ans; + return ans; + }; + + intervals.push(newInterval); + return merge(intervals); } diff --git a/solution/0000-0099/0057.Insert Interval/Solution2.cpp b/solution/0000-0099/0057.Insert Interval/Solution2.cpp new file mode 100644 index 0000000000000..2f840685d1cd1 --- /dev/null +++ b/solution/0000-0099/0057.Insert Interval/Solution2.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector> insert(vector>& intervals, vector& newInterval) { + vector> ans; + int st = newInterval[0], ed = newInterval[1]; + bool insert = false; + for (auto& interval : intervals) { + int s = interval[0], e = interval[1]; + if (ed < s) { + if (!insert) { + ans.push_back({st, ed}); + insert = true; + } + ans.push_back(interval); + } else if (e < st) { + ans.push_back(interval); + } else { + st = min(st, s); + ed = max(ed, e); + } + } + if (!insert) { + ans.push_back({st, ed}); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0057.Insert Interval/Solution2.cs b/solution/0000-0099/0057.Insert Interval/Solution2.cs new file mode 100644 index 0000000000000..9e9e5ef267740 --- /dev/null +++ b/solution/0000-0099/0057.Insert Interval/Solution2.cs @@ -0,0 +1,26 @@ +public class Solution { + public int[][] Insert(int[][] intervals, int[] newInterval) { + var ans = new List(); + int st = newInterval[0], ed = newInterval[1]; + bool insert = false; + foreach (var interval in intervals) { + int s = interval[0], e = interval[1]; + if (ed < s) { + if (!insert) { + ans.Add(new int[]{st, ed}); + insert = true; + } + ans.Add(interval); + } else if (st > e) { + ans.Add(interval); + } else { + st = Math.Min(st, s); + ed = Math.Max(ed, e); + } + } + if (!insert) { + ans.Add(new int[]{st, ed}); + } + return ans.ToArray(); + } +} diff --git a/solution/0000-0099/0057.Insert Interval/Solution2.go b/solution/0000-0099/0057.Insert Interval/Solution2.go new file mode 100644 index 0000000000000..0951f49851916 --- /dev/null +++ b/solution/0000-0099/0057.Insert Interval/Solution2.go @@ -0,0 +1,23 @@ +func insert(intervals [][]int, newInterval []int) (ans [][]int) { + st, ed := newInterval[0], newInterval[1] + insert := false + for _, interval := range intervals { + s, e := interval[0], interval[1] + if ed < s { + if !insert { + ans = append(ans, []int{st, ed}) + insert = true + } + ans = append(ans, interval) + } else if e < st { + ans = append(ans, interval) + } else { + st = min(st, s) + ed = max(ed, e) + } + } + if !insert { + ans = append(ans, []int{st, ed}) + } + return +} \ No newline at end of file diff --git a/solution/0000-0099/0057.Insert Interval/Solution2.java b/solution/0000-0099/0057.Insert Interval/Solution2.java new file mode 100644 index 0000000000000..9b6a7a01724fb --- /dev/null +++ b/solution/0000-0099/0057.Insert Interval/Solution2.java @@ -0,0 +1,26 @@ +class Solution { + public int[][] insert(int[][] intervals, int[] newInterval) { + List ans = new ArrayList<>(); + int st = newInterval[0], ed = newInterval[1]; + boolean insert = false; + for (int[] interval : intervals) { + int s = interval[0], e = interval[1]; + if (ed < s) { + if (!insert) { + ans.add(new int[] {st, ed}); + insert = true; + } + ans.add(interval); + } else if (e < st) { + ans.add(interval); + } else { + st = Math.min(st, s); + ed = Math.max(ed, e); + } + } + if (!insert) { + ans.add(new int[] {st, ed}); + } + return ans.toArray(new int[ans.size()][]); + } +} \ No newline at end of file diff --git a/solution/0000-0099/0057.Insert Interval/Solution2.py b/solution/0000-0099/0057.Insert Interval/Solution2.py new file mode 100644 index 0000000000000..042d525156cf5 --- /dev/null +++ b/solution/0000-0099/0057.Insert Interval/Solution2.py @@ -0,0 +1,21 @@ +class Solution: + def insert( + self, intervals: List[List[int]], newInterval: List[int] + ) -> List[List[int]]: + st, ed = newInterval + ans = [] + insert = False + for s, e in intervals: + if ed < s: + if not insert: + ans.append([st, ed]) + insert = True + ans.append([s, e]) + elif e < st: + ans.append([s, e]) + else: + st = min(st, s) + ed = max(ed, e) + if not insert: + ans.append([st, ed]) + return ans diff --git a/solution/0000-0099/0057.Insert Interval/Solution2.rs b/solution/0000-0099/0057.Insert Interval/Solution2.rs new file mode 100644 index 0000000000000..49be224f5754b --- /dev/null +++ b/solution/0000-0099/0057.Insert Interval/Solution2.rs @@ -0,0 +1,28 @@ +impl Solution { + pub fn insert(intervals: Vec>, new_interval: Vec) -> Vec> { + let mut inserted = false; + let mut result = vec![]; + + let (mut start, mut end) = (new_interval[0], new_interval[1]); + for iter in intervals.iter() { + let (cur_st, cur_ed) = (iter[0], iter[1]); + if cur_ed < start { + result.push(vec![cur_st, cur_ed]); + } else if cur_st > end { + if !inserted { + inserted = true; + result.push(vec![start, end]); + } + result.push(vec![cur_st, cur_ed]); + } else { + start = std::cmp::min(start, cur_st); + end = std::cmp::max(end, cur_ed); + } + } + + if !inserted { + result.push(vec![start, end]); + } + result + } +} diff --git a/solution/0000-0099/0057.Insert Interval/Solution2.ts b/solution/0000-0099/0057.Insert Interval/Solution2.ts new file mode 100644 index 0000000000000..173f05f39a238 --- /dev/null +++ b/solution/0000-0099/0057.Insert Interval/Solution2.ts @@ -0,0 +1,23 @@ +function insert(intervals: number[][], newInterval: number[]): number[][] { + let [st, ed] = newInterval; + const ans: number[][] = []; + let insert = false; + for (const [s, e] of intervals) { + if (ed < s) { + if (!insert) { + ans.push([st, ed]); + insert = true; + } + ans.push([s, e]); + } else if (e < st) { + ans.push([s, e]); + } else { + st = Math.min(st, s); + ed = Math.max(ed, e); + } + } + if (!insert) { + ans.push([st, ed]); + } + return ans; +} diff --git a/solution/0000-0099/0058.Length of Last Word/Solution.cs b/solution/0000-0099/0058.Length of Last Word/Solution.cs index 7ede5b368d81c..25a2b5f1cd2fb 100644 --- a/solution/0000-0099/0058.Length of Last Word/Solution.cs +++ b/solution/0000-0099/0058.Length of Last Word/Solution.cs @@ -10,4 +10,4 @@ public int LengthOfLastWord(string s) { } return i - j; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0058.Length of Last Word/Solution.php b/solution/0000-0099/0058.Length of Last Word/Solution.php index 7ffd7b6c85dc5..140e2b11c7c25 100644 --- a/solution/0000-0099/0058.Length of Last Word/Solution.php +++ b/solution/0000-0099/0058.Length of Last Word/Solution.php @@ -14,4 +14,4 @@ function lengthOfLastWord($s) { } return $count; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0059.Spiral Matrix II/Solution2.ts b/solution/0000-0099/0059.Spiral Matrix II/Solution2.ts new file mode 100644 index 0000000000000..bcb830215b6bb --- /dev/null +++ b/solution/0000-0099/0059.Spiral Matrix II/Solution2.ts @@ -0,0 +1,22 @@ +function generateMatrix(n: number): number[][] { + const res = new Array(n).fill(0).map(() => new Array(n).fill(0)); + let num = 1; + for (let i = 0; i < Math.floor(n / 2); i++) { + for (let j = i; j < n - i - 1; j++) { + res[i][j] = num++; + } + for (let j = i; j < n - i - 1; j++) { + res[j][n - i - 1] = num++; + } + for (let j = i; j < n - i - 1; j++) { + res[n - i - 1][n - j - 1] = num++; + } + for (let j = i; j < n - i - 1; j++) { + res[n - j - 1][i] = num++; + } + } + if (n % 2 === 1) { + res[n >> 1][n >> 1] = num; + } + return res; +} diff --git a/solution/0000-0099/0060.Permutation Sequence/Solution.cs b/solution/0000-0099/0060.Permutation Sequence/Solution.cs index b6c19f90dcbb4..d1688ea27789c 100644 --- a/solution/0000-0099/0060.Permutation Sequence/Solution.cs +++ b/solution/0000-0099/0060.Permutation Sequence/Solution.cs @@ -21,4 +21,4 @@ public string GetPermutation(int n, int k) { } return ans.ToString(); } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0061.Rotate List/Solution.cpp b/solution/0000-0099/0061.Rotate List/Solution.cpp index 22d814ba5c695..d4922df4ce63a 100644 --- a/solution/0000-0099/0061.Rotate List/Solution.cpp +++ b/solution/0000-0099/0061.Rotate List/Solution.cpp @@ -1,41 +1,41 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* rotateRight(ListNode* head, int k) { - if (!head || !head->next) { - return head; - } - ListNode* cur = head; - int n = 0; - while (cur) { - ++n; - cur = cur->next; - } - k %= n; - if (k == 0) { - return head; - } - ListNode* fast = head; - ListNode* slow = head; - while (k--) { - fast = fast->next; - } - while (fast->next) { - fast = fast->next; - slow = slow->next; - } - ListNode* ans = slow->next; - slow->next = nullptr; - fast->next = head; - return ans; - } +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* rotateRight(ListNode* head, int k) { + if (!head || !head->next) { + return head; + } + ListNode* cur = head; + int n = 0; + while (cur) { + ++n; + cur = cur->next; + } + k %= n; + if (k == 0) { + return head; + } + ListNode* fast = head; + ListNode* slow = head; + while (k--) { + fast = fast->next; + } + while (fast->next) { + fast = fast->next; + slow = slow->next; + } + ListNode* ans = slow->next; + slow->next = nullptr; + fast->next = head; + return ans; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0061.Rotate List/Solution.cs b/solution/0000-0099/0061.Rotate List/Solution.cs index 070d58f1631b9..6be3a43572393 100644 --- a/solution/0000-0099/0061.Rotate List/Solution.cs +++ b/solution/0000-0099/0061.Rotate List/Solution.cs @@ -1,41 +1,41 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } - * } - */ -public class Solution { - public ListNode RotateRight(ListNode head, int k) { - if (head == null || head.next == null) { - return head; - } - var cur = head; - int n = 0; - while (cur != null) { - cur = cur.next; - ++n; - } - k %= n; - if (k == 0) { - return head; - } - var fast = head; - var slow = head; - while (k-- > 0) { - fast = fast.next; - } - while (fast.next != null) { - fast = fast.next; - slow = slow.next; - } - var ans = slow.next; - slow.next = null; - fast.next = head; - return ans; - } -} \ No newline at end of file +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode RotateRight(ListNode head, int k) { + if (head == null || head.next == null) { + return head; + } + var cur = head; + int n = 0; + while (cur != null) { + cur = cur.next; + ++n; + } + k %= n; + if (k == 0) { + return head; + } + var fast = head; + var slow = head; + while (k-- > 0) { + fast = fast.next; + } + while (fast.next != null) { + fast = fast.next; + slow = slow.next; + } + var ans = slow.next; + slow.next = null; + fast.next = head; + return ans; + } +} diff --git a/solution/0000-0099/0061.Rotate List/Solution.java b/solution/0000-0099/0061.Rotate List/Solution.java index c2d35255b0a83..64818d4d38da3 100644 --- a/solution/0000-0099/0061.Rotate List/Solution.java +++ b/solution/0000-0099/0061.Rotate List/Solution.java @@ -1,39 +1,39 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode rotateRight(ListNode head, int k) { - if (head == null || head.next == null) { - return head; - } - ListNode cur = head; - int n = 0; - for (; cur != null; cur = cur.next) { - n++; - } - k %= n; - if (k == 0) { - return head; - } - ListNode fast = head; - ListNode slow = head; - while (k-- > 0) { - fast = fast.next; - } - while (fast.next != null) { - fast = fast.next; - slow = slow.next; - } - ListNode ans = slow.next; - slow.next = null; - fast.next = head; - return ans; - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode rotateRight(ListNode head, int k) { + if (head == null || head.next == null) { + return head; + } + ListNode cur = head; + int n = 0; + for (; cur != null; cur = cur.next) { + n++; + } + k %= n; + if (k == 0) { + return head; + } + ListNode fast = head; + ListNode slow = head; + while (k-- > 0) { + fast = fast.next; + } + while (fast.next != null) { + fast = fast.next; + slow = slow.next; + } + ListNode ans = slow.next; + slow.next = null; + fast.next = head; + return ans; + } } \ No newline at end of file diff --git a/solution/0000-0099/0061.Rotate List/Solution.py b/solution/0000-0099/0061.Rotate List/Solution.py index 6c3b61956c457..dc33fe23b4441 100644 --- a/solution/0000-0099/0061.Rotate List/Solution.py +++ b/solution/0000-0099/0061.Rotate List/Solution.py @@ -1,26 +1,26 @@ -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: - if head is None or head.next is None: - return head - cur, n = head, 0 - while cur: - n += 1 - cur = cur.next - k %= n - if k == 0: - return head - fast = slow = head - for _ in range(k): - fast = fast.next - while fast.next: - fast, slow = fast.next, slow.next - - ans = slow.next - slow.next = None - fast.next = head - return ans +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: + if head is None or head.next is None: + return head + cur, n = head, 0 + while cur: + n += 1 + cur = cur.next + k %= n + if k == 0: + return head + fast = slow = head + for _ in range(k): + fast = fast.next + while fast.next: + fast, slow = fast.next, slow.next + + ans = slow.next + slow.next = None + fast.next = head + return ans diff --git a/solution/0000-0099/0061.Rotate List/Solution.rs b/solution/0000-0099/0061.Rotate List/Solution.rs new file mode 100644 index 0000000000000..5c750cfdee2cb --- /dev/null +++ b/solution/0000-0099/0061.Rotate List/Solution.rs @@ -0,0 +1,48 @@ +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn rotate_right(mut head: Option>, mut k: i32) -> Option> { + if head.is_none() || k == 0 { + return head; + } + let n = { + let mut cur = &head; + let mut res = 0; + while cur.is_some() { + cur = &cur.as_ref().unwrap().next; + res += 1; + } + res + }; + k = k % n; + if k == 0 { + return head; + } + + let mut cur = &mut head; + for _ in 0..n - k - 1 { + cur = &mut cur.as_mut().unwrap().next; + } + let mut res = cur.as_mut().unwrap().next.take(); + cur = &mut res; + while cur.is_some() { + cur = &mut cur.as_mut().unwrap().next; + } + *cur = head.take(); + res + } +} diff --git a/solution/0000-0099/0061.Rotate List/Solution.ts b/solution/0000-0099/0061.Rotate List/Solution.ts new file mode 100644 index 0000000000000..5d828dcd18a17 --- /dev/null +++ b/solution/0000-0099/0061.Rotate List/Solution.ts @@ -0,0 +1,40 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function rotateRight(head: ListNode | null, k: number): ListNode | null { + if (!head || !head.next) { + return head; + } + let cur = head; + let n = 0; + while (cur) { + cur = cur.next; + ++n; + } + k %= n; + if (k === 0) { + return head; + } + let fast = head; + let slow = head; + while (k--) { + fast = fast.next; + } + while (fast.next) { + fast = fast.next; + slow = slow.next; + } + const ans = slow.next; + slow.next = null; + fast.next = head; + return ans; +} diff --git a/solution/0000-0099/0062.Unique Paths/Solution.cpp b/solution/0000-0099/0062.Unique Paths/Solution.cpp index 44adfd0b04fac..97ab7c9f30376 100644 --- a/solution/0000-0099/0062.Unique Paths/Solution.cpp +++ b/solution/0000-0099/0062.Unique Paths/Solution.cpp @@ -1,12 +1,18 @@ -class Solution { -public: - int uniquePaths(int m, int n) { - vector f(n, 1); - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - f[j] += f[j - 1]; - } - } - return f[n - 1]; - } +class Solution { +public: + int uniquePaths(int m, int n) { + vector> f(m, vector(n)); + f[0][0] = 1; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (i) { + f[i][j] += f[i - 1][j]; + } + if (j) { + f[i][j] += f[i][j - 1]; + } + } + } + return f[m - 1][n - 1]; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0062.Unique Paths/Solution.go b/solution/0000-0099/0062.Unique Paths/Solution.go index d8be9bf206fba..a24ae81946451 100644 --- a/solution/0000-0099/0062.Unique Paths/Solution.go +++ b/solution/0000-0099/0062.Unique Paths/Solution.go @@ -1,12 +1,18 @@ func uniquePaths(m int, n int) int { - f := make([]int, n+1) + f := make([][]int, m) for i := range f { - f[i] = 1 + f[i] = make([]int, n) } - for i := 1; i < m; i++ { - for j := 1; j < n; j++ { - f[j] += f[j-1] + f[0][0] = 1 + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if i > 0 { + f[i][j] += f[i-1][j] + } + if j > 0 { + f[i][j] += f[i][j-1] + } } } - return f[n-1] + return f[m-1][n-1] } \ No newline at end of file diff --git a/solution/0000-0099/0062.Unique Paths/Solution.java b/solution/0000-0099/0062.Unique Paths/Solution.java index 8200544e6b54a..e498a681dedd7 100644 --- a/solution/0000-0099/0062.Unique Paths/Solution.java +++ b/solution/0000-0099/0062.Unique Paths/Solution.java @@ -1,12 +1,17 @@ -class Solution { - public int uniquePaths(int m, int n) { - int[] f = new int[n]; - Arrays.fill(f, 1); - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - f[j] += f[j - 1]; - } - } - return f[n - 1]; - } +class Solution { + public int uniquePaths(int m, int n) { + var f = new int[m][n]; + f[0][0] = 1; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (i > 0) { + f[i][j] += f[i - 1][j]; + } + if (j > 0) { + f[i][j] += f[i][j - 1]; + } + } + } + return f[m - 1][n - 1]; + } } \ No newline at end of file diff --git a/solution/0000-0099/0062.Unique Paths/Solution.js b/solution/0000-0099/0062.Unique Paths/Solution.js index 8853e8f24afc5..12576e257380a 100644 --- a/solution/0000-0099/0062.Unique Paths/Solution.js +++ b/solution/0000-0099/0062.Unique Paths/Solution.js @@ -4,11 +4,19 @@ * @return {number} */ var uniquePaths = function (m, n) { - const f = Array(n).fill(1); - for (let i = 1; i < m; ++i) { - for (let j = 1; j < n; ++j) { - f[j] += f[j - 1]; + const f = Array(m) + .fill(0) + .map(() => Array(n).fill(0)); + f[0][0] = 1; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (i > 0) { + f[i][j] += f[i - 1][j]; + } + if (j > 0) { + f[i][j] += f[i][j - 1]; + } } } - return f[n - 1]; + return f[m - 1][n - 1]; }; diff --git a/solution/0000-0099/0062.Unique Paths/Solution.py b/solution/0000-0099/0062.Unique Paths/Solution.py index 125d910221d98..cbeed6832f606 100644 --- a/solution/0000-0099/0062.Unique Paths/Solution.py +++ b/solution/0000-0099/0062.Unique Paths/Solution.py @@ -1,7 +1,11 @@ -class Solution: - def uniquePaths(self, m: int, n: int) -> int: - f = [1] * n - for _ in range(1, m): - for j in range(1, n): - f[j] += f[j - 1] - return f[-1] +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + f = [[0] * n for _ in range(m)] + f[0][0] = 1 + for i in range(m): + for j in range(n): + if i: + f[i][j] += f[i - 1][j] + if j: + f[i][j] += f[i][j - 1] + return f[-1][-1] diff --git a/solution/0000-0099/0062.Unique Paths/Solution.ts b/solution/0000-0099/0062.Unique Paths/Solution.ts index 6dae713f485bd..4b55fcf8dcddf 100644 --- a/solution/0000-0099/0062.Unique Paths/Solution.ts +++ b/solution/0000-0099/0062.Unique Paths/Solution.ts @@ -1,9 +1,17 @@ function uniquePaths(m: number, n: number): number { - const f: number[] = Array(n).fill(1); - for (let i = 1; i < m; ++i) { - for (let j = 1; j < n; ++j) { - f[j] += f[j - 1]; + const f: number[][] = Array(m) + .fill(0) + .map(() => Array(n).fill(0)); + f[0][0] = 1; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (i > 0) { + f[i][j] += f[i - 1][j]; + } + if (j > 0) { + f[i][j] += f[i][j - 1]; + } } } - return f[n - 1]; + return f[m - 1][n - 1]; } diff --git a/solution/0000-0099/0062.Unique Paths/Solution2.cpp b/solution/0000-0099/0062.Unique Paths/Solution2.cpp new file mode 100644 index 0000000000000..2c8161b2ac5f2 --- /dev/null +++ b/solution/0000-0099/0062.Unique Paths/Solution2.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int uniquePaths(int m, int n) { + vector> f(m, vector(n, 1)); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + f[i][j] = f[i - 1][j] + f[i][j - 1]; + } + } + return f[m - 1][n - 1]; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0062.Unique Paths/Solution2.go b/solution/0000-0099/0062.Unique Paths/Solution2.go new file mode 100644 index 0000000000000..62eb31203dfa4 --- /dev/null +++ b/solution/0000-0099/0062.Unique Paths/Solution2.go @@ -0,0 +1,15 @@ +func uniquePaths(m int, n int) int { + f := make([][]int, m) + for i := range f { + f[i] = make([]int, n) + for j := range f[i] { + f[i][j] = 1 + } + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + f[i][j] = f[i-1][j] + f[i][j-1] + } + } + return f[m-1][n-1] +} \ No newline at end of file diff --git a/solution/0000-0099/0062.Unique Paths/Solution2.java b/solution/0000-0099/0062.Unique Paths/Solution2.java new file mode 100644 index 0000000000000..1d5c65794d8e1 --- /dev/null +++ b/solution/0000-0099/0062.Unique Paths/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public int uniquePaths(int m, int n) { + var f = new int[m][n]; + for (var g : f) { + Arrays.fill(g, 1); + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; j++) { + f[i][j] = f[i - 1][j] + f[i][j - 1]; + } + } + return f[m - 1][n - 1]; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0062.Unique Paths/Solution2.js b/solution/0000-0099/0062.Unique Paths/Solution2.js new file mode 100644 index 0000000000000..ffc8b03570664 --- /dev/null +++ b/solution/0000-0099/0062.Unique Paths/Solution2.js @@ -0,0 +1,16 @@ +/** + * @param {number} m + * @param {number} n + * @return {number} + */ +var uniquePaths = function (m, n) { + const f = Array(m) + .fill(0) + .map(() => Array(n).fill(1)); + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + f[i][j] = f[i - 1][j] + f[i][j - 1]; + } + } + return f[m - 1][n - 1]; +}; diff --git a/solution/0000-0099/0062.Unique Paths/Solution2.py b/solution/0000-0099/0062.Unique Paths/Solution2.py new file mode 100644 index 0000000000000..68b287d621cc9 --- /dev/null +++ b/solution/0000-0099/0062.Unique Paths/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + f = [[1] * n for _ in range(m)] + for i in range(1, m): + for j in range(1, n): + f[i][j] = f[i - 1][j] + f[i][j - 1] + return f[-1][-1] diff --git a/solution/0000-0099/0062.Unique Paths/Solution2.ts b/solution/0000-0099/0062.Unique Paths/Solution2.ts new file mode 100644 index 0000000000000..ec1856c09b50f --- /dev/null +++ b/solution/0000-0099/0062.Unique Paths/Solution2.ts @@ -0,0 +1,11 @@ +function uniquePaths(m: number, n: number): number { + const f: number[][] = Array(m) + .fill(0) + .map(() => Array(n).fill(1)); + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + f[i][j] = f[i - 1][j] + f[i][j - 1]; + } + } + return f[m - 1][n - 1]; +} diff --git a/solution/0000-0099/0062.Unique Paths/Solution3.cpp b/solution/0000-0099/0062.Unique Paths/Solution3.cpp new file mode 100644 index 0000000000000..a935d4ba6895a --- /dev/null +++ b/solution/0000-0099/0062.Unique Paths/Solution3.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int uniquePaths(int m, int n) { + vector f(n, 1); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + f[j] += f[j - 1]; + } + } + return f[n - 1]; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0062.Unique Paths/Solution3.go b/solution/0000-0099/0062.Unique Paths/Solution3.go new file mode 100644 index 0000000000000..d8be9bf206fba --- /dev/null +++ b/solution/0000-0099/0062.Unique Paths/Solution3.go @@ -0,0 +1,12 @@ +func uniquePaths(m int, n int) int { + f := make([]int, n+1) + for i := range f { + f[i] = 1 + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + f[j] += f[j-1] + } + } + return f[n-1] +} \ No newline at end of file diff --git a/solution/0000-0099/0062.Unique Paths/Solution3.java b/solution/0000-0099/0062.Unique Paths/Solution3.java new file mode 100644 index 0000000000000..162c3b4ad34c4 --- /dev/null +++ b/solution/0000-0099/0062.Unique Paths/Solution3.java @@ -0,0 +1,12 @@ +class Solution { + public int uniquePaths(int m, int n) { + int[] f = new int[n]; + Arrays.fill(f, 1); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + f[j] += f[j - 1]; + } + } + return f[n - 1]; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0062.Unique Paths/Solution3.js b/solution/0000-0099/0062.Unique Paths/Solution3.js new file mode 100644 index 0000000000000..8853e8f24afc5 --- /dev/null +++ b/solution/0000-0099/0062.Unique Paths/Solution3.js @@ -0,0 +1,14 @@ +/** + * @param {number} m + * @param {number} n + * @return {number} + */ +var uniquePaths = function (m, n) { + const f = Array(n).fill(1); + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + f[j] += f[j - 1]; + } + } + return f[n - 1]; +}; diff --git a/solution/0000-0099/0062.Unique Paths/Solution3.py b/solution/0000-0099/0062.Unique Paths/Solution3.py new file mode 100644 index 0000000000000..98fb5ac1af0c6 --- /dev/null +++ b/solution/0000-0099/0062.Unique Paths/Solution3.py @@ -0,0 +1,7 @@ +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + f = [1] * n + for _ in range(1, m): + for j in range(1, n): + f[j] += f[j - 1] + return f[-1] diff --git a/solution/0000-0099/0062.Unique Paths/Solution3.ts b/solution/0000-0099/0062.Unique Paths/Solution3.ts new file mode 100644 index 0000000000000..6dae713f485bd --- /dev/null +++ b/solution/0000-0099/0062.Unique Paths/Solution3.ts @@ -0,0 +1,9 @@ +function uniquePaths(m: number, n: number): number { + const f: number[] = Array(n).fill(1); + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + f[j] += f[j - 1]; + } + } + return f[n - 1]; +} diff --git a/solution/0000-0099/0064.Minimum Path Sum/Solution.cpp b/solution/0000-0099/0064.Minimum Path Sum/Solution.cpp index 4ec3e7bc3bafa..1a7034ed078e2 100644 --- a/solution/0000-0099/0064.Minimum Path Sum/Solution.cpp +++ b/solution/0000-0099/0064.Minimum Path Sum/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - int minPathSum(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - int f[m][n]; - f[0][0] = grid[0][0]; - for (int i = 1; i < m; ++i) { - f[i][0] = f[i - 1][0] + grid[i][0]; - } - for (int j = 1; j < n; ++j) { - f[0][j] = f[0][j - 1] + grid[0][j]; - } - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - f[i][j] = min(f[i - 1][j], f[i][j - 1]) + grid[i][j]; - } - } - return f[m - 1][n - 1]; - } +class Solution { +public: + int minPathSum(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int f[m][n]; + f[0][0] = grid[0][0]; + for (int i = 1; i < m; ++i) { + f[i][0] = f[i - 1][0] + grid[i][0]; + } + for (int j = 1; j < n; ++j) { + f[0][j] = f[0][j - 1] + grid[0][j]; + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + f[i][j] = min(f[i - 1][j], f[i][j - 1]) + grid[i][j]; + } + } + return f[m - 1][n - 1]; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0064.Minimum Path Sum/Solution.cs b/solution/0000-0099/0064.Minimum Path Sum/Solution.cs index b1a09562be969..b7931ff465354 100644 --- a/solution/0000-0099/0064.Minimum Path Sum/Solution.cs +++ b/solution/0000-0099/0064.Minimum Path Sum/Solution.cs @@ -1,19 +1,19 @@ -public class Solution { - public int MinPathSum(int[][] grid) { - int m = grid.Length, n = grid[0].Length; - int[,] f = new int[m, n]; - f[0, 0] = grid[0][0]; - for (int i = 1; i < m; ++i) { - f[i, 0] = f[i - 1, 0] + grid[i][0]; - } - for (int j = 1; j < n; ++j) { - f[0, j] = f[0, j - 1] + grid[0][j]; - } - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - f[i, j] = Math.Min(f[i - 1, j], f[i, j - 1]) + grid[i][j]; - } - } - return f[m - 1, n - 1]; - } -} \ No newline at end of file +public class Solution { + public int MinPathSum(int[][] grid) { + int m = grid.Length, n = grid[0].Length; + int[,] f = new int[m, n]; + f[0, 0] = grid[0][0]; + for (int i = 1; i < m; ++i) { + f[i, 0] = f[i - 1, 0] + grid[i][0]; + } + for (int j = 1; j < n; ++j) { + f[0, j] = f[0, j - 1] + grid[0][j]; + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + f[i, j] = Math.Min(f[i - 1, j], f[i, j - 1]) + grid[i][j]; + } + } + return f[m - 1, n - 1]; + } +} diff --git a/solution/0000-0099/0064.Minimum Path Sum/Solution.java b/solution/0000-0099/0064.Minimum Path Sum/Solution.java index 33b5db9cff846..21b9fea035adf 100644 --- a/solution/0000-0099/0064.Minimum Path Sum/Solution.java +++ b/solution/0000-0099/0064.Minimum Path Sum/Solution.java @@ -1,19 +1,19 @@ -class Solution { - public int minPathSum(int[][] grid) { - int m = grid.length, n = grid[0].length; - int[][] f = new int[m][n]; - f[0][0] = grid[0][0]; - for (int i = 1; i < m; ++i) { - f[i][0] = f[i - 1][0] + grid[i][0]; - } - for (int j = 1; j < n; ++j) { - f[0][j] = f[0][j - 1] + grid[0][j]; - } - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - f[i][j] = Math.min(f[i - 1][j], f[i][j - 1]) + grid[i][j]; - } - } - return f[m - 1][n - 1]; - } +class Solution { + public int minPathSum(int[][] grid) { + int m = grid.length, n = grid[0].length; + int[][] f = new int[m][n]; + f[0][0] = grid[0][0]; + for (int i = 1; i < m; ++i) { + f[i][0] = f[i - 1][0] + grid[i][0]; + } + for (int j = 1; j < n; ++j) { + f[0][j] = f[0][j - 1] + grid[0][j]; + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + f[i][j] = Math.min(f[i - 1][j], f[i][j - 1]) + grid[i][j]; + } + } + return f[m - 1][n - 1]; + } } \ No newline at end of file diff --git a/solution/0000-0099/0064.Minimum Path Sum/Solution.py b/solution/0000-0099/0064.Minimum Path Sum/Solution.py index 9ef1ffe2bc347..dc2ce685c22bd 100644 --- a/solution/0000-0099/0064.Minimum Path Sum/Solution.py +++ b/solution/0000-0099/0064.Minimum Path Sum/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def minPathSum(self, grid: List[List[int]]) -> int: - m, n = len(grid), len(grid[0]) - f = [[0] * n for _ in range(m)] - f[0][0] = grid[0][0] - for i in range(1, m): - f[i][0] = f[i - 1][0] + grid[i][0] - for j in range(1, n): - f[0][j] = f[0][j - 1] + grid[0][j] - for i in range(1, m): - for j in range(1, n): - f[i][j] = min(f[i - 1][j], f[i][j - 1]) + grid[i][j] - return f[-1][-1] +class Solution: + def minPathSum(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + f = [[0] * n for _ in range(m)] + f[0][0] = grid[0][0] + for i in range(1, m): + f[i][0] = f[i - 1][0] + grid[i][0] + for j in range(1, n): + f[0][j] = f[0][j - 1] + grid[0][j] + for i in range(1, m): + for j in range(1, n): + f[i][j] = min(f[i - 1][j], f[i][j - 1]) + grid[i][j] + return f[-1][-1] diff --git a/solution/0000-0099/0065.Valid Number/Solution.cs b/solution/0000-0099/0065.Valid Number/Solution.cs index 57e7bf9672dcd..bf1b9428f9477 100644 --- a/solution/0000-0099/0065.Valid Number/Solution.cs +++ b/solution/0000-0099/0065.Valid Number/Solution.cs @@ -1,4 +1,4 @@ -using System.Text.RegularExpressions; +using System.Text.RegularExpressions; public class Solution { private readonly Regex _isNumber_Regex = new Regex(@"^\s*[+-]?(\d+(\.\d*)?|\.\d+)([Ee][+-]?\d+)?\s*$"); @@ -6,4 +6,4 @@ public class Solution { public bool IsNumber(string s) { return _isNumber_Regex.IsMatch(s); } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0067.Add Binary/Solution.cpp b/solution/0000-0099/0067.Add Binary/Solution.cpp index 486f0a13a8af2..74686204d3f17 100644 --- a/solution/0000-0099/0067.Add Binary/Solution.cpp +++ b/solution/0000-0099/0067.Add Binary/Solution.cpp @@ -1,14 +1,14 @@ -class Solution { -public: - string addBinary(string a, string b) { - string ans; - int i = a.size() - 1, j = b.size() - 1; - for (int carry = 0; i >= 0 || j >= 0 || carry; --i, --j) { - carry += (i >= 0 ? a[i] - '0' : 0) + (j >= 0 ? b[j] - '0' : 0); - ans.push_back((carry % 2) + '0'); - carry /= 2; - } - reverse(ans.begin(), ans.end()); - return ans; - } +class Solution { +public: + string addBinary(string a, string b) { + string ans; + int i = a.size() - 1, j = b.size() - 1; + for (int carry = 0; i >= 0 || j >= 0 || carry; --i, --j) { + carry += (i >= 0 ? a[i] - '0' : 0) + (j >= 0 ? b[j] - '0' : 0); + ans.push_back((carry % 2) + '0'); + carry /= 2; + } + reverse(ans.begin(), ans.end()); + return ans; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0067.Add Binary/Solution.java b/solution/0000-0099/0067.Add Binary/Solution.java index 66ae1c5ee2f93..74dba05511318 100644 --- a/solution/0000-0099/0067.Add Binary/Solution.java +++ b/solution/0000-0099/0067.Add Binary/Solution.java @@ -1,12 +1,12 @@ -class Solution { - public String addBinary(String a, String b) { - var sb = new StringBuilder(); - int i = a.length() - 1, j = b.length() - 1; - for (int carry = 0; i >= 0 || j >= 0 || carry > 0; --i, --j) { - carry += (i >= 0 ? a.charAt(i) - '0' : 0) + (j >= 0 ? b.charAt(j) - '0' : 0); - sb.append(carry % 2); - carry /= 2; - } - return sb.reverse().toString(); - } +class Solution { + public String addBinary(String a, String b) { + var sb = new StringBuilder(); + int i = a.length() - 1, j = b.length() - 1; + for (int carry = 0; i >= 0 || j >= 0 || carry > 0; --i, --j) { + carry += (i >= 0 ? a.charAt(i) - '0' : 0) + (j >= 0 ? b.charAt(j) - '0' : 0); + sb.append(carry % 2); + carry /= 2; + } + return sb.reverse().toString(); + } } \ No newline at end of file diff --git a/solution/0000-0099/0067.Add Binary/Solution.py b/solution/0000-0099/0067.Add Binary/Solution.py index 324ddf82389b5..d451827d22b99 100644 --- a/solution/0000-0099/0067.Add Binary/Solution.py +++ b/solution/0000-0099/0067.Add Binary/Solution.py @@ -1,10 +1,3 @@ -class Solution: - def addBinary(self, a: str, b: str) -> str: - ans = [] - i, j, carry = len(a) - 1, len(b) - 1, 0 - while i >= 0 or j >= 0 or carry: - carry += (0 if i < 0 else int(a[i])) + (0 if j < 0 else int(b[j])) - carry, v = divmod(carry, 2) - ans.append(str(v)) - i, j = i - 1, j - 1 - return "".join(ans[::-1]) +class Solution: + def addBinary(self, a: str, b: str) -> str: + return bin(int(a, 2) + int(b, 2))[2:] diff --git a/solution/0000-0099/0067.Add Binary/Solution.ts b/solution/0000-0099/0067.Add Binary/Solution.ts index 41271cda5b144..9287735eb29eb 100644 --- a/solution/0000-0099/0067.Add Binary/Solution.ts +++ b/solution/0000-0099/0067.Add Binary/Solution.ts @@ -1,12 +1,3 @@ function addBinary(a: string, b: string): string { - let i = a.length - 1; - let j = b.length - 1; - let ans: number[] = []; - for (let carry = 0; i >= 0 || j >= 0 || carry; --i, --j) { - carry += (i >= 0 ? a[i] : '0').charCodeAt(0) - '0'.charCodeAt(0); - carry += (j >= 0 ? b[j] : '0').charCodeAt(0) - '0'.charCodeAt(0); - ans.push(carry % 2); - carry >>= 1; - } - return ans.reverse().join(''); + return (BigInt('0b' + a) + BigInt('0b' + b)).toString(2); } diff --git a/solution/0000-0099/0067.Add Binary/Solution2.py b/solution/0000-0099/0067.Add Binary/Solution2.py new file mode 100644 index 0000000000000..8f15c0c8d670d --- /dev/null +++ b/solution/0000-0099/0067.Add Binary/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def addBinary(self, a: str, b: str) -> str: + ans = [] + i, j, carry = len(a) - 1, len(b) - 1, 0 + while i >= 0 or j >= 0 or carry: + carry += (0 if i < 0 else int(a[i])) + (0 if j < 0 else int(b[j])) + carry, v = divmod(carry, 2) + ans.append(str(v)) + i, j = i - 1, j - 1 + return ''.join(ans[::-1]) diff --git a/solution/0000-0099/0067.Add Binary/Solution2.ts b/solution/0000-0099/0067.Add Binary/Solution2.ts new file mode 100644 index 0000000000000..41271cda5b144 --- /dev/null +++ b/solution/0000-0099/0067.Add Binary/Solution2.ts @@ -0,0 +1,12 @@ +function addBinary(a: string, b: string): string { + let i = a.length - 1; + let j = b.length - 1; + let ans: number[] = []; + for (let carry = 0; i >= 0 || j >= 0 || carry; --i, --j) { + carry += (i >= 0 ? a[i] : '0').charCodeAt(0) - '0'.charCodeAt(0); + carry += (j >= 0 ? b[j] : '0').charCodeAt(0) - '0'.charCodeAt(0); + ans.push(carry % 2); + carry >>= 1; + } + return ans.reverse().join(''); +} diff --git a/solution/0000-0099/0068.Text Justification/Solution.cs b/solution/0000-0099/0068.Text Justification/Solution.cs index 6bd12668b7882..50c84de56c32a 100644 --- a/solution/0000-0099/0068.Text Justification/Solution.cs +++ b/solution/0000-0099/0068.Text Justification/Solution.cs @@ -30,4 +30,4 @@ public IList FullJustify(string[] words, int maxWidth) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0069.Sqrt(x)/Solution.cpp b/solution/0000-0099/0069.Sqrt(x)/Solution.cpp index 549861575efe3..772e4901b8b2a 100644 --- a/solution/0000-0099/0069.Sqrt(x)/Solution.cpp +++ b/solution/0000-0099/0069.Sqrt(x)/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - int mySqrt(int x) { - int l = 0, r = x; - while (l < r) { - int mid = (l + r + 1ll) >> 1; - if (mid > x / mid) { - r = mid - 1; - } else { - l = mid; - } - } - return l; - } +class Solution { +public: + int mySqrt(int x) { + int l = 0, r = x; + while (l < r) { + int mid = (l + r + 1ll) >> 1; + if (mid > x / mid) { + r = mid - 1; + } else { + l = mid; + } + } + return l; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0069.Sqrt(x)/Solution.cs b/solution/0000-0099/0069.Sqrt(x)/Solution.cs index d25afa99b044e..07885059e9b90 100644 --- a/solution/0000-0099/0069.Sqrt(x)/Solution.cs +++ b/solution/0000-0099/0069.Sqrt(x)/Solution.cs @@ -1,14 +1,14 @@ -public class Solution { - public int MySqrt(int x) { - int l = 0, r = x; - while (l < r) { - int mid = (l + r + 1) >>> 1; - if (mid > x / mid) { - r = mid - 1; - } else { - l = mid; - } - } - return l; - } -} \ No newline at end of file +public class Solution { + public int MySqrt(int x) { + int l = 0, r = x; + while (l < r) { + int mid = (l + r + 1) >>> 1; + if (mid > x / mid) { + r = mid - 1; + } else { + l = mid; + } + } + return l; + } +} diff --git a/solution/0000-0099/0069.Sqrt(x)/Solution.java b/solution/0000-0099/0069.Sqrt(x)/Solution.java index 560733a31219a..f67cf9f6656e6 100644 --- a/solution/0000-0099/0069.Sqrt(x)/Solution.java +++ b/solution/0000-0099/0069.Sqrt(x)/Solution.java @@ -1,14 +1,14 @@ -class Solution { - public int mySqrt(int x) { - int l = 0, r = x; - while (l < r) { - int mid = (l + r + 1) >>> 1; - if (mid > x / mid) { - r = mid - 1; - } else { - l = mid; - } - } - return l; - } +class Solution { + public int mySqrt(int x) { + int l = 0, r = x; + while (l < r) { + int mid = (l + r + 1) >>> 1; + if (mid > x / mid) { + r = mid - 1; + } else { + l = mid; + } + } + return l; + } } \ No newline at end of file diff --git a/solution/0000-0099/0069.Sqrt(x)/Solution.py b/solution/0000-0099/0069.Sqrt(x)/Solution.py index fca95d48efe35..eabc26e8af2fc 100644 --- a/solution/0000-0099/0069.Sqrt(x)/Solution.py +++ b/solution/0000-0099/0069.Sqrt(x)/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def mySqrt(self, x: int) -> int: - l, r = 0, x - while l < r: - mid = (l + r + 1) >> 1 - if mid > x // mid: - r = mid - 1 - else: - l = mid - return l +class Solution: + def mySqrt(self, x: int) -> int: + l, r = 0, x + while l < r: + mid = (l + r + 1) >> 1 + if mid > x // mid: + r = mid - 1 + else: + l = mid + return l diff --git a/solution/0000-0099/0070.Climbing Stairs/README.md b/solution/0000-0099/0070.Climbing Stairs/README.md index 97d4fe60d79db..93f787291567d 100644 --- a/solution/0000-0099/0070.Climbing Stairs/README.md +++ b/solution/0000-0099/0070.Climbing Stairs/README.md @@ -177,8 +177,9 @@ class Solution { ```java class Solution { + private final int[][] a = {{1, 1}, {1, 0}}; + public int climbStairs(int n) { - int[][] a = {{1, 1,}, {1, 0}}; return pow(a, n - 1)[0][0]; } diff --git a/solution/0000-0099/0070.Climbing Stairs/README_EN.md b/solution/0000-0099/0070.Climbing Stairs/README_EN.md index c96205caca3b5..35e6fd3f7598c 100644 --- a/solution/0000-0099/0070.Climbing Stairs/README_EN.md +++ b/solution/0000-0099/0070.Climbing Stairs/README_EN.md @@ -168,8 +168,9 @@ class Solution { ```java class Solution { + private final int[][] a = {{1, 1}, {1, 0}}; + public int climbStairs(int n) { - int[][] a = {{1, 1,}, {1, 0}}; return pow(a, n - 1)[0][0]; } diff --git a/solution/0000-0099/0070.Climbing Stairs/Solution.php b/solution/0000-0099/0070.Climbing Stairs/Solution.php index 0217e41120c2c..3346f2e83eb64 100644 --- a/solution/0000-0099/0070.Climbing Stairs/Solution.php +++ b/solution/0000-0099/0070.Climbing Stairs/Solution.php @@ -13,4 +13,4 @@ function climbStairs($n) { } return $dp[$n]; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0070.Climbing Stairs/Solution2.cpp b/solution/0000-0099/0070.Climbing Stairs/Solution2.cpp new file mode 100644 index 0000000000000..9789ce4a13442 --- /dev/null +++ b/solution/0000-0099/0070.Climbing Stairs/Solution2.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int climbStairs(int n) { + vector> a = {{1, 1}, {1, 0}}; + return pow(a, n - 1)[0][0]; + } + +private: + vector> mul(vector>& a, vector>& b) { + int m = a.size(), n = b[0].size(); + vector> res(m, vector(n)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k < a[0].size(); ++k) { + res[i][j] += a[i][k] * b[k][j]; + } + } + } + return res; + } + + vector> pow(vector>& a, int n) { + vector> res = {{1, 1}, {0, 0}}; + while (n) { + if (n & 1) { + res = mul(res, a); + } + a = mul(a, a); + n >>= 1; + } + return res; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0070.Climbing Stairs/Solution2.go b/solution/0000-0099/0070.Climbing Stairs/Solution2.go new file mode 100644 index 0000000000000..0b511253af7cd --- /dev/null +++ b/solution/0000-0099/0070.Climbing Stairs/Solution2.go @@ -0,0 +1,30 @@ +type matrix [2][2]int + +func climbStairs(n int) int { + a := matrix{{1, 1}, {1, 0}} + return pow(a, n-1)[0][0] +} + +func mul(a, b matrix) (c matrix) { + m, n := len(a), len(b[0]) + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + for k := 0; k < len(a[0]); k++ { + c[i][j] += a[i][k] * b[k][j] + } + } + } + return +} + +func pow(a matrix, n int) matrix { + res := matrix{{1, 1}, {0, 0}} + for n > 0 { + if n&1 == 1 { + res = mul(res, a) + } + a = mul(a, a) + n >>= 1 + } + return res +} \ No newline at end of file diff --git a/solution/0000-0099/0070.Climbing Stairs/Solution2.java b/solution/0000-0099/0070.Climbing Stairs/Solution2.java new file mode 100644 index 0000000000000..e5d7fc78911c0 --- /dev/null +++ b/solution/0000-0099/0070.Climbing Stairs/Solution2.java @@ -0,0 +1,32 @@ +class Solution { + private final int[][] a = {{1, 1}, {1, 0}}; + + public int climbStairs(int n) { + return pow(a, n - 1)[0][0]; + } + + private int[][] mul(int[][] a, int[][] b) { + int m = a.length, n = b[0].length; + int[][] c = new int[m][n]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k < a[0].length; ++k) { + c[i][j] += a[i][k] * b[k][j]; + } + } + } + return c; + } + + private int[][] pow(int[][] a, int n) { + int[][] res = {{1, 1}, {0, 0}}; + while (n > 0) { + if ((n & 1) == 1) { + res = mul(res, a); + } + n >>= 1; + a = mul(a, a); + } + return res; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0070.Climbing Stairs/Solution2.js b/solution/0000-0099/0070.Climbing Stairs/Solution2.js new file mode 100644 index 0000000000000..ea6b3fd471cdb --- /dev/null +++ b/solution/0000-0099/0070.Climbing Stairs/Solution2.js @@ -0,0 +1,41 @@ +/** + * @param {number} n + * @return {number} + */ +var climbStairs = function (n) { + const a = [ + [1, 1], + [1, 0], + ]; + return pow(a, n - 1)[0][0]; +}; + +function mul(a, b) { + const [m, n] = [a.length, b[0].length]; + const c = Array(m) + .fill(0) + .map(() => Array(n).fill(0)); + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + for (let k = 0; k < a[0].length; ++k) { + c[i][j] += a[i][k] * b[k][j]; + } + } + } + return c; +} + +function pow(a, n) { + let res = [ + [1, 1], + [0, 0], + ]; + while (n) { + if (n & 1) { + res = mul(res, a); + } + a = mul(a, a); + n >>= 1; + } + return res; +} diff --git a/solution/0000-0099/0070.Climbing Stairs/Solution2.py b/solution/0000-0099/0070.Climbing Stairs/Solution2.py new file mode 100644 index 0000000000000..f38127ff7aee1 --- /dev/null +++ b/solution/0000-0099/0070.Climbing Stairs/Solution2.py @@ -0,0 +1,22 @@ +class Solution: + def climbStairs(self, n: int) -> int: + def mul(a: List[List[int]], b: List[List[int]]) -> List[List[int]]: + m, n = len(a), len(b[0]) + c = [[0] * n for _ in range(m)] + for i in range(m): + for j in range(n): + for k in range(len(a[0])): + c[i][j] = c[i][j] + a[i][k] * b[k][j] + return c + + def pow(a: List[List[int]], n: int) -> List[List[int]]: + res = [[1, 1]] + while n: + if n & 1: + res = mul(res, a) + n >>= 1 + a = mul(a, a) + return res + + a = [[1, 1], [1, 0]] + return pow(a, n - 1)[0][0] diff --git a/solution/0000-0099/0070.Climbing Stairs/Solution2.ts b/solution/0000-0099/0070.Climbing Stairs/Solution2.ts new file mode 100644 index 0000000000000..d34754b4121a2 --- /dev/null +++ b/solution/0000-0099/0070.Climbing Stairs/Solution2.ts @@ -0,0 +1,37 @@ +function climbStairs(n: number): number { + const a = [ + [1, 1], + [1, 0], + ]; + return pow(a, n - 1)[0][0]; +} + +function mul(a: number[][], b: number[][]): number[][] { + const [m, n] = [a.length, b[0].length]; + const c = Array(m) + .fill(0) + .map(() => Array(n).fill(0)); + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + for (let k = 0; k < a[0].length; ++k) { + c[i][j] += a[i][k] * b[k][j]; + } + } + } + return c; +} + +function pow(a: number[][], n: number): number[][] { + let res = [ + [1, 1], + [0, 0], + ]; + while (n) { + if (n & 1) { + res = mul(res, a); + } + a = mul(a, a); + n >>= 1; + } + return res; +} diff --git a/solution/0000-0099/0070.Climbing Stairs/Solution3.py b/solution/0000-0099/0070.Climbing Stairs/Solution3.py new file mode 100644 index 0000000000000..073a590c5bccd --- /dev/null +++ b/solution/0000-0099/0070.Climbing Stairs/Solution3.py @@ -0,0 +1,14 @@ +import numpy as np + + +class Solution: + def climbStairs(self, n: int) -> int: + res = np.mat([(1, 1)], np.dtype("O")) + factor = np.mat([(1, 1), (1, 0)], np.dtype("O")) + n -= 1 + while n: + if n & 1: + res *= factor + factor *= factor + n >>= 1 + return res[0, 0] diff --git a/solution/0000-0099/0071.Simplify Path/Solution.cs b/solution/0000-0099/0071.Simplify Path/Solution.cs index cd7836af702be..bc9f4b743a91d 100644 --- a/solution/0000-0099/0071.Simplify Path/Solution.cs +++ b/solution/0000-0099/0071.Simplify Path/Solution.cs @@ -19,4 +19,4 @@ public string SimplifyPath(string path) { } return sb.Length == 0 ? "/" : sb.ToString(); } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0071.Simplify Path/Solution2.go b/solution/0000-0099/0071.Simplify Path/Solution2.go new file mode 100644 index 0000000000000..b92442adbc561 --- /dev/null +++ b/solution/0000-0099/0071.Simplify Path/Solution2.go @@ -0,0 +1,3 @@ +func simplifyPath(path string) string { + return filepath.Clean(path) +} \ No newline at end of file diff --git a/solution/0000-0099/0072.Edit Distance/Solution.cpp b/solution/0000-0099/0072.Edit Distance/Solution.cpp index c848fc4f50efd..9022b40f439b7 100644 --- a/solution/0000-0099/0072.Edit Distance/Solution.cpp +++ b/solution/0000-0099/0072.Edit Distance/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - int minDistance(string word1, string word2) { - int m = word1.size(), n = word2.size(); - int f[m + 1][n + 1]; - for (int j = 0; j <= n; ++j) { - f[0][j] = j; - } - for (int i = 1; i <= m; ++i) { - f[i][0] = i; - for (int j = 1; j <= n; ++j) { - if (word1[i - 1] == word2[j - 1]) { - f[i][j] = f[i - 1][j - 1]; - } else { - f[i][j] = min({f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]}) + 1; - } - } - } - return f[m][n]; - } +class Solution { +public: + int minDistance(string word1, string word2) { + int m = word1.size(), n = word2.size(); + int f[m + 1][n + 1]; + for (int j = 0; j <= n; ++j) { + f[0][j] = j; + } + for (int i = 1; i <= m; ++i) { + f[i][0] = i; + for (int j = 1; j <= n; ++j) { + if (word1[i - 1] == word2[j - 1]) { + f[i][j] = f[i - 1][j - 1]; + } else { + f[i][j] = min({f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]}) + 1; + } + } + } + return f[m][n]; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0072.Edit Distance/Solution.java b/solution/0000-0099/0072.Edit Distance/Solution.java index 9fa98fcfdba89..73cb1e6563b4c 100644 --- a/solution/0000-0099/0072.Edit Distance/Solution.java +++ b/solution/0000-0099/0072.Edit Distance/Solution.java @@ -1,20 +1,20 @@ -class Solution { - public int minDistance(String word1, String word2) { - int m = word1.length(), n = word2.length(); - int[][] f = new int[m + 1][n + 1]; - for (int j = 1; j <= n; ++j) { - f[0][j] = j; - } - for (int i = 1; i <= m; ++i) { - f[i][0] = i; - for (int j = 1; j <= n; ++j) { - if (word1.charAt(i - 1) == word2.charAt(j - 1)) { - f[i][j] = f[i - 1][j - 1]; - } else { - f[i][j] = Math.min(f[i - 1][j], Math.min(f[i][j - 1], f[i - 1][j - 1])) + 1; - } - } - } - return f[m][n]; - } +class Solution { + public int minDistance(String word1, String word2) { + int m = word1.length(), n = word2.length(); + int[][] f = new int[m + 1][n + 1]; + for (int j = 1; j <= n; ++j) { + f[0][j] = j; + } + for (int i = 1; i <= m; ++i) { + f[i][0] = i; + for (int j = 1; j <= n; ++j) { + if (word1.charAt(i - 1) == word2.charAt(j - 1)) { + f[i][j] = f[i - 1][j - 1]; + } else { + f[i][j] = Math.min(f[i - 1][j], Math.min(f[i][j - 1], f[i - 1][j - 1])) + 1; + } + } + } + return f[m][n]; + } } \ No newline at end of file diff --git a/solution/0000-0099/0072.Edit Distance/Solution.py b/solution/0000-0099/0072.Edit Distance/Solution.py index 6dbf63cfdf4a2..70c870f9b2901 100644 --- a/solution/0000-0099/0072.Edit Distance/Solution.py +++ b/solution/0000-0099/0072.Edit Distance/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def minDistance(self, word1: str, word2: str) -> int: - m, n = len(word1), len(word2) - f = [[0] * (n + 1) for _ in range(m + 1)] - for j in range(1, n + 1): - f[0][j] = j - for i, a in enumerate(word1, 1): - f[i][0] = i - for j, b in enumerate(word2, 1): - if a == b: - f[i][j] = f[i - 1][j - 1] - else: - f[i][j] = min(f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]) + 1 - return f[m][n] +class Solution: + def minDistance(self, word1: str, word2: str) -> int: + m, n = len(word1), len(word2) + f = [[0] * (n + 1) for _ in range(m + 1)] + for j in range(1, n + 1): + f[0][j] = j + for i, a in enumerate(word1, 1): + f[i][0] = i + for j, b in enumerate(word2, 1): + if a == b: + f[i][j] = f[i - 1][j - 1] + else: + f[i][j] = min(f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]) + 1 + return f[m][n] diff --git a/solution/0000-0099/0073.Set Matrix Zeroes/Solution.cpp b/solution/0000-0099/0073.Set Matrix Zeroes/Solution.cpp index 35fb03beee932..16cc4dec3010c 100644 --- a/solution/0000-0099/0073.Set Matrix Zeroes/Solution.cpp +++ b/solution/0000-0099/0073.Set Matrix Zeroes/Solution.cpp @@ -2,43 +2,22 @@ class Solution { public: void setZeroes(vector>& matrix) { int m = matrix.size(), n = matrix[0].size(); - bool i0 = false, j0 = false; - for (int j = 0; j < n; ++j) { - if (matrix[0][j] == 0) { - i0 = true; - break; - } - } + vector rows(m); + vector cols(n); for (int i = 0; i < m; ++i) { - if (matrix[i][0] == 0) { - j0 = true; - break; - } - } - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - if (matrix[i][j] == 0) { - matrix[i][0] = 0; - matrix[0][j] = 0; + for (int j = 0; j < n; ++j) { + if (!matrix[i][j]) { + rows[i] = 1; + cols[j] = 1; } } } - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - if (matrix[i][0] == 0 || matrix[0][j] == 0) { + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (rows[i] || cols[j]) { matrix[i][j] = 0; } } } - if (i0) { - for (int j = 0; j < n; ++j) { - matrix[0][j] = 0; - } - } - if (j0) { - for (int i = 0; i < m; ++i) { - matrix[i][0] = 0; - } - } } }; \ No newline at end of file diff --git a/solution/0000-0099/0073.Set Matrix Zeroes/Solution.cs b/solution/0000-0099/0073.Set Matrix Zeroes/Solution.cs index 69f3eeb76d686..128351f61b70a 100644 --- a/solution/0000-0099/0073.Set Matrix Zeroes/Solution.cs +++ b/solution/0000-0099/0073.Set Matrix Zeroes/Solution.cs @@ -1,37 +1,21 @@ public class Solution { public void SetZeroes(int[][] matrix) { int m = matrix.Length, n = matrix[0].Length; - bool i0 = matrix[0].Contains(0), j0 = false; + bool[] rows = new bool[m], cols = new bool[n]; for (int i = 0; i < m; ++i) { - if (matrix[i][0] == 0) { - j0 = true; - break; - } - } - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { + for (int j = 0; j < n; ++j) { if (matrix[i][j] == 0) { - matrix[i][0] = 0; - matrix[0][j] = 0; + rows[i] = true; + cols[j] = true; } } } - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - if (matrix[i][0] == 0 || matrix[0][j] == 0) { + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (rows[i] || cols[j]) { matrix[i][j] = 0; } } } - if (i0) { - for (int j = 0; j < n; ++j) { - matrix[0][j] = 0; - } - } - if (j0) { - for (int i = 0; i < m; ++i) { - matrix[i][0] = 0; - } - } } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0073.Set Matrix Zeroes/Solution.go b/solution/0000-0099/0073.Set Matrix Zeroes/Solution.go index 563745744194b..05f7e65c331fb 100644 --- a/solution/0000-0099/0073.Set Matrix Zeroes/Solution.go +++ b/solution/0000-0099/0073.Set Matrix Zeroes/Solution.go @@ -1,40 +1,20 @@ func setZeroes(matrix [][]int) { m, n := len(matrix), len(matrix[0]) - i0, j0 := false, false - for j := 0; j < n; j++ { - if matrix[0][j] == 0 { - i0 = true - break - } - } - for i := 0; i < m; i++ { - if matrix[i][0] == 0 { - j0 = true - break - } - } - for i := 1; i < m; i++ { - for j := 1; j < n; j++ { - if matrix[i][j] == 0 { - matrix[i][0], matrix[0][j] = 0, 0 + rows := make([]bool, m) + cols := make([]bool, n) + for i, row := range matrix { + for j, v := range row { + if v == 0 { + rows[i] = true + cols[j] = true } } } - for i := 1; i < m; i++ { - for j := 1; j < n; j++ { - if matrix[i][0] == 0 || matrix[0][j] == 0 { + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if rows[i] || cols[j] { matrix[i][j] = 0 } } } - if i0 { - for j := 0; j < n; j++ { - matrix[0][j] = 0 - } - } - if j0 { - for i := 0; i < m; i++ { - matrix[i][0] = 0 - } - } } \ No newline at end of file diff --git a/solution/0000-0099/0073.Set Matrix Zeroes/Solution.java b/solution/0000-0099/0073.Set Matrix Zeroes/Solution.java index dc71ae3359d35..0735d0e50a0a0 100644 --- a/solution/0000-0099/0073.Set Matrix Zeroes/Solution.java +++ b/solution/0000-0099/0073.Set Matrix Zeroes/Solution.java @@ -1,43 +1,22 @@ class Solution { public void setZeroes(int[][] matrix) { int m = matrix.length, n = matrix[0].length; - boolean i0 = false, j0 = false; - for (int j = 0; j < n; ++j) { - if (matrix[0][j] == 0) { - i0 = true; - break; - } - } + boolean[] rows = new boolean[m]; + boolean[] cols = new boolean[n]; for (int i = 0; i < m; ++i) { - if (matrix[i][0] == 0) { - j0 = true; - break; - } - } - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { + for (int j = 0; j < n; ++j) { if (matrix[i][j] == 0) { - matrix[i][0] = 0; - matrix[0][j] = 0; + rows[i] = true; + cols[j] = true; } } } - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - if (matrix[i][0] == 0 || matrix[0][j] == 0) { + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (rows[i] || cols[j]) { matrix[i][j] = 0; } } } - if (i0) { - for (int j = 0; j < n; ++j) { - matrix[0][j] = 0; - } - } - if (j0) { - for (int i = 0; i < m; ++i) { - matrix[i][0] = 0; - } - } } } \ No newline at end of file diff --git a/solution/0000-0099/0073.Set Matrix Zeroes/Solution.js b/solution/0000-0099/0073.Set Matrix Zeroes/Solution.js index 88961eaf80b75..8a46036d11e59 100644 --- a/solution/0000-0099/0073.Set Matrix Zeroes/Solution.js +++ b/solution/0000-0099/0073.Set Matrix Zeroes/Solution.js @@ -5,37 +5,21 @@ var setZeroes = function (matrix) { const m = matrix.length; const n = matrix[0].length; - let i0 = matrix[0].some(v => v == 0); - let j0 = false; + const rows = new Array(m).fill(false); + const cols = new Array(n).fill(false); for (let i = 0; i < m; ++i) { - if (matrix[i][0] == 0) { - j0 = true; - break; - } - } - for (let i = 1; i < m; ++i) { - for (let j = 1; j < n; ++j) { + for (let j = 0; j < n; ++j) { if (matrix[i][j] == 0) { - matrix[i][0] = 0; - matrix[0][j] = 0; + rows[i] = true; + cols[j] = true; } } } - for (let i = 1; i < m; ++i) { - for (let j = 1; j < n; ++j) { - if (matrix[i][0] == 0 || matrix[0][j] == 0) { + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (rows[i] || cols[j]) { matrix[i][j] = 0; } } } - if (i0) { - for (let j = 0; j < n; ++j) { - matrix[0][j] = 0; - } - } - if (j0) { - for (let i = 0; i < m; ++i) { - matrix[i][0] = 0; - } - } }; diff --git a/solution/0000-0099/0073.Set Matrix Zeroes/Solution.py b/solution/0000-0099/0073.Set Matrix Zeroes/Solution.py index ec6ae77626f2a..d486145d0db8a 100644 --- a/solution/0000-0099/0073.Set Matrix Zeroes/Solution.py +++ b/solution/0000-0099/0073.Set Matrix Zeroes/Solution.py @@ -1,19 +1,13 @@ class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: m, n = len(matrix), len(matrix[0]) - i0 = any(v == 0 for v in matrix[0]) - j0 = any(matrix[i][0] == 0 for i in range(m)) - for i in range(1, m): - for j in range(1, n): - if matrix[i][j] == 0: - matrix[i][0] = matrix[0][j] = 0 - for i in range(1, m): - for j in range(1, n): - if matrix[i][0] == 0 or matrix[0][j] == 0: - matrix[i][j] = 0 - if i0: + rows = [0] * m + cols = [0] * n + for i, row in enumerate(matrix): + for j, v in enumerate(row): + if v == 0: + rows[i] = cols[j] = 1 + for i in range(m): for j in range(n): - matrix[0][j] = 0 - if j0: - for i in range(m): - matrix[i][0] = 0 + if rows[i] or cols[j]: + matrix[i][j] = 0 diff --git a/solution/0000-0099/0073.Set Matrix Zeroes/Solution.ts b/solution/0000-0099/0073.Set Matrix Zeroes/Solution.ts index e735d38628446..7042732d5af20 100644 --- a/solution/0000-0099/0073.Set Matrix Zeroes/Solution.ts +++ b/solution/0000-0099/0073.Set Matrix Zeroes/Solution.ts @@ -4,29 +4,21 @@ function setZeroes(matrix: number[][]): void { const m = matrix.length; const n = matrix[0].length; - const i0 = matrix[0].includes(0); - const j0 = matrix.map(row => row[0]).includes(0); - for (let i = 1; i < m; ++i) { - for (let j = 1; j < n; ++j) { + const rows: boolean[] = new Array(m).fill(false); + const cols: boolean[] = new Array(n).fill(false); + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { if (matrix[i][j] === 0) { - matrix[i][0] = 0; - matrix[0][j] = 0; + rows[i] = true; + cols[j] = true; } } } - for (let i = 1; i < m; ++i) { - for (let j = 1; j < n; ++j) { - if (matrix[i][0] === 0 || matrix[0][j] === 0) { + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (rows[i] || cols[j]) { matrix[i][j] = 0; } } } - if (i0) { - matrix[0].fill(0); - } - if (j0) { - for (let i = 0; i < m; ++i) { - matrix[i][0] = 0; - } - } } diff --git a/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.cpp b/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.cpp new file mode 100644 index 0000000000000..35fb03beee932 --- /dev/null +++ b/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + void setZeroes(vector>& matrix) { + int m = matrix.size(), n = matrix[0].size(); + bool i0 = false, j0 = false; + for (int j = 0; j < n; ++j) { + if (matrix[0][j] == 0) { + i0 = true; + break; + } + } + for (int i = 0; i < m; ++i) { + if (matrix[i][0] == 0) { + j0 = true; + break; + } + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (matrix[i][j] == 0) { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + } + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (matrix[i][0] == 0 || matrix[0][j] == 0) { + matrix[i][j] = 0; + } + } + } + if (i0) { + for (int j = 0; j < n; ++j) { + matrix[0][j] = 0; + } + } + if (j0) { + for (int i = 0; i < m; ++i) { + matrix[i][0] = 0; + } + } + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.cs b/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.cs new file mode 100644 index 0000000000000..7c20677f654c4 --- /dev/null +++ b/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.cs @@ -0,0 +1,37 @@ +public class Solution { + public void SetZeroes(int[][] matrix) { + int m = matrix.Length, n = matrix[0].Length; + bool i0 = matrix[0].Contains(0), j0 = false; + for (int i = 0; i < m; ++i) { + if (matrix[i][0] == 0) { + j0 = true; + break; + } + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (matrix[i][j] == 0) { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + } + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (matrix[i][0] == 0 || matrix[0][j] == 0) { + matrix[i][j] = 0; + } + } + } + if (i0) { + for (int j = 0; j < n; ++j) { + matrix[0][j] = 0; + } + } + if (j0) { + for (int i = 0; i < m; ++i) { + matrix[i][0] = 0; + } + } + } +} diff --git a/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.go b/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.go new file mode 100644 index 0000000000000..563745744194b --- /dev/null +++ b/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.go @@ -0,0 +1,40 @@ +func setZeroes(matrix [][]int) { + m, n := len(matrix), len(matrix[0]) + i0, j0 := false, false + for j := 0; j < n; j++ { + if matrix[0][j] == 0 { + i0 = true + break + } + } + for i := 0; i < m; i++ { + if matrix[i][0] == 0 { + j0 = true + break + } + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + if matrix[i][j] == 0 { + matrix[i][0], matrix[0][j] = 0, 0 + } + } + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + if matrix[i][0] == 0 || matrix[0][j] == 0 { + matrix[i][j] = 0 + } + } + } + if i0 { + for j := 0; j < n; j++ { + matrix[0][j] = 0 + } + } + if j0 { + for i := 0; i < m; i++ { + matrix[i][0] = 0 + } + } +} \ No newline at end of file diff --git a/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.java b/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.java new file mode 100644 index 0000000000000..dc71ae3359d35 --- /dev/null +++ b/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.java @@ -0,0 +1,43 @@ +class Solution { + public void setZeroes(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + boolean i0 = false, j0 = false; + for (int j = 0; j < n; ++j) { + if (matrix[0][j] == 0) { + i0 = true; + break; + } + } + for (int i = 0; i < m; ++i) { + if (matrix[i][0] == 0) { + j0 = true; + break; + } + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (matrix[i][j] == 0) { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + } + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (matrix[i][0] == 0 || matrix[0][j] == 0) { + matrix[i][j] = 0; + } + } + } + if (i0) { + for (int j = 0; j < n; ++j) { + matrix[0][j] = 0; + } + } + if (j0) { + for (int i = 0; i < m; ++i) { + matrix[i][0] = 0; + } + } + } +} \ No newline at end of file diff --git a/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.js b/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.js new file mode 100644 index 0000000000000..88961eaf80b75 --- /dev/null +++ b/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.js @@ -0,0 +1,41 @@ +/** + * @param {number[][]} matrix + * @return {void} Do not return anything, modify matrix in-place instead. + */ +var setZeroes = function (matrix) { + const m = matrix.length; + const n = matrix[0].length; + let i0 = matrix[0].some(v => v == 0); + let j0 = false; + for (let i = 0; i < m; ++i) { + if (matrix[i][0] == 0) { + j0 = true; + break; + } + } + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + if (matrix[i][j] == 0) { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + } + } + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + if (matrix[i][0] == 0 || matrix[0][j] == 0) { + matrix[i][j] = 0; + } + } + } + if (i0) { + for (let j = 0; j < n; ++j) { + matrix[0][j] = 0; + } + } + if (j0) { + for (let i = 0; i < m; ++i) { + matrix[i][0] = 0; + } + } +}; diff --git a/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.py b/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.py new file mode 100644 index 0000000000000..ec6ae77626f2a --- /dev/null +++ b/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.py @@ -0,0 +1,19 @@ +class Solution: + def setZeroes(self, matrix: List[List[int]]) -> None: + m, n = len(matrix), len(matrix[0]) + i0 = any(v == 0 for v in matrix[0]) + j0 = any(matrix[i][0] == 0 for i in range(m)) + for i in range(1, m): + for j in range(1, n): + if matrix[i][j] == 0: + matrix[i][0] = matrix[0][j] = 0 + for i in range(1, m): + for j in range(1, n): + if matrix[i][0] == 0 or matrix[0][j] == 0: + matrix[i][j] = 0 + if i0: + for j in range(n): + matrix[0][j] = 0 + if j0: + for i in range(m): + matrix[i][0] = 0 diff --git a/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.ts b/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.ts new file mode 100644 index 0000000000000..e735d38628446 --- /dev/null +++ b/solution/0000-0099/0073.Set Matrix Zeroes/Solution2.ts @@ -0,0 +1,32 @@ +/** + Do not return anything, modify matrix in-place instead. + */ +function setZeroes(matrix: number[][]): void { + const m = matrix.length; + const n = matrix[0].length; + const i0 = matrix[0].includes(0); + const j0 = matrix.map(row => row[0]).includes(0); + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + if (matrix[i][j] === 0) { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + } + } + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + if (matrix[i][0] === 0 || matrix[0][j] === 0) { + matrix[i][j] = 0; + } + } + } + if (i0) { + matrix[0].fill(0); + } + if (j0) { + for (let i = 0; i < m; ++i) { + matrix[i][0] = 0; + } + } +} diff --git a/solution/0000-0099/0074.Search a 2D Matrix/Solution2.cpp b/solution/0000-0099/0074.Search a 2D Matrix/Solution2.cpp new file mode 100644 index 0000000000000..767ddb7b45fff --- /dev/null +++ b/solution/0000-0099/0074.Search a 2D Matrix/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + int m = matrix.size(), n = matrix[0].size(); + for (int i = m - 1, j = 0; i >= 0 && j < n;) { + if (matrix[i][j] == target) return true; + if (matrix[i][j] > target) + --i; + else + ++j; + } + return false; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0074.Search a 2D Matrix/Solution2.go b/solution/0000-0099/0074.Search a 2D Matrix/Solution2.go new file mode 100644 index 0000000000000..4b5cb0c4c3193 --- /dev/null +++ b/solution/0000-0099/0074.Search a 2D Matrix/Solution2.go @@ -0,0 +1,14 @@ +func searchMatrix(matrix [][]int, target int) bool { + m, n := len(matrix), len(matrix[0]) + for i, j := m-1, 0; i >= 0 && j < n; { + if matrix[i][j] == target { + return true + } + if matrix[i][j] > target { + i-- + } else { + j++ + } + } + return false +} \ No newline at end of file diff --git a/solution/0000-0099/0074.Search a 2D Matrix/Solution2.java b/solution/0000-0099/0074.Search a 2D Matrix/Solution2.java new file mode 100644 index 0000000000000..aa9533f5b6382 --- /dev/null +++ b/solution/0000-0099/0074.Search a 2D Matrix/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + int m = matrix.length, n = matrix[0].length; + for (int i = m - 1, j = 0; i >= 0 && j < n;) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0074.Search a 2D Matrix/Solution2.js b/solution/0000-0099/0074.Search a 2D Matrix/Solution2.js new file mode 100644 index 0000000000000..6eb533b938b9b --- /dev/null +++ b/solution/0000-0099/0074.Search a 2D Matrix/Solution2.js @@ -0,0 +1,20 @@ +/** + * @param {number[][]} matrix + * @param {number} target + * @return {boolean} + */ +var searchMatrix = function (matrix, target) { + const m = matrix.length, + n = matrix[0].length; + for (let i = m - 1, j = 0; i >= 0 && j < n; ) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; +}; diff --git a/solution/0000-0099/0074.Search a 2D Matrix/Solution2.py b/solution/0000-0099/0074.Search a 2D Matrix/Solution2.py new file mode 100644 index 0000000000000..08bd1ef8378c3 --- /dev/null +++ b/solution/0000-0099/0074.Search a 2D Matrix/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + m, n = len(matrix), len(matrix[0]) + i, j = m - 1, 0 + while i >= 0 and j < n: + if matrix[i][j] == target: + return True + if matrix[i][j] > target: + i -= 1 + else: + j += 1 + return False diff --git a/solution/0000-0099/0074.Search a 2D Matrix/Solution2.rs b/solution/0000-0099/0074.Search a 2D Matrix/Solution2.rs new file mode 100644 index 0000000000000..440ea96c1f9c6 --- /dev/null +++ b/solution/0000-0099/0074.Search a 2D Matrix/Solution2.rs @@ -0,0 +1,26 @@ +use std::cmp::Ordering; +impl Solution { + pub fn search_matrix(matrix: Vec>, target: i32) -> bool { + let m = matrix.len(); + let n = matrix[0].len(); + let mut left = 0; + let mut right = m * n; + while left < right { + let mid = left + (right - left) / 2; + let i = mid / n; + let j = mid % n; + match matrix[i][j].cmp(&target) { + Ordering::Equal => { + return true; + } + Ordering::Less => { + left = mid + 1; + } + Ordering::Greater => { + right = mid; + } + } + } + false + } +} diff --git a/solution/0000-0099/0075.Sort Colors/Solution.cpp b/solution/0000-0099/0075.Sort Colors/Solution.cpp index 701a6e4866f54..6fe2242670f9d 100644 --- a/solution/0000-0099/0075.Sort Colors/Solution.cpp +++ b/solution/0000-0099/0075.Sort Colors/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - void sortColors(vector& nums) { - int i = -1, j = nums.size(), k = 0; - while (k < j) { - if (nums[k] == 0) { - swap(nums[++i], nums[k++]); - } else if (nums[k] == 2) { - swap(nums[--j], nums[k]); - } else { - ++k; - } - } - } +class Solution { +public: + void sortColors(vector& nums) { + int i = -1, j = nums.size(), k = 0; + while (k < j) { + if (nums[k] == 0) { + swap(nums[++i], nums[k++]); + } else if (nums[k] == 2) { + swap(nums[--j], nums[k]); + } else { + ++k; + } + } + } }; \ No newline at end of file diff --git a/solution/0000-0099/0075.Sort Colors/Solution.cs b/solution/0000-0099/0075.Sort Colors/Solution.cs index f209e55c0c47d..0f269abf8c8d0 100644 --- a/solution/0000-0099/0075.Sort Colors/Solution.cs +++ b/solution/0000-0099/0075.Sort Colors/Solution.cs @@ -1,20 +1,20 @@ -public class Solution { - public void SortColors(int[] nums) { - int i = -1, j = nums.Length, k = 0; - while (k < j) { - if (nums[k] == 0) { - swap(nums, ++i, k++); - } else if (nums[k] == 2) { - swap(nums, --j, k); - } else { - ++k; - } - } - } - - private void swap(int[] nums, int i, int j) { - int t = nums[i]; - nums[i] = nums[j]; - nums[j] = t; - } -} \ No newline at end of file +public class Solution { + public void SortColors(int[] nums) { + int i = -1, j = nums.Length, k = 0; + while (k < j) { + if (nums[k] == 0) { + swap(nums, ++i, k++); + } else if (nums[k] == 2) { + swap(nums, --j, k); + } else { + ++k; + } + } + } + + private void swap(int[] nums, int i, int j) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } +} diff --git a/solution/0000-0099/0075.Sort Colors/Solution.java b/solution/0000-0099/0075.Sort Colors/Solution.java index 23f6899b2c3af..3f9672a17510c 100644 --- a/solution/0000-0099/0075.Sort Colors/Solution.java +++ b/solution/0000-0099/0075.Sort Colors/Solution.java @@ -1,20 +1,20 @@ -class Solution { - public void sortColors(int[] nums) { - int i = -1, j = nums.length, k = 0; - while (k < j) { - if (nums[k] == 0) { - swap(nums, ++i, k++); - } else if (nums[k] == 2) { - swap(nums, --j, k); - } else { - ++k; - } - } - } - - private void swap(int[] nums, int i, int j) { - int t = nums[i]; - nums[i] = nums[j]; - nums[j] = t; - } +class Solution { + public void sortColors(int[] nums) { + int i = -1, j = nums.length, k = 0; + while (k < j) { + if (nums[k] == 0) { + swap(nums, ++i, k++); + } else if (nums[k] == 2) { + swap(nums, --j, k); + } else { + ++k; + } + } + } + + private void swap(int[] nums, int i, int j) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } } \ No newline at end of file diff --git a/solution/0000-0099/0075.Sort Colors/Solution.py b/solution/0000-0099/0075.Sort Colors/Solution.py index 81dd68eca52d8..f1fb5a8f91fa1 100644 --- a/solution/0000-0099/0075.Sort Colors/Solution.py +++ b/solution/0000-0099/0075.Sort Colors/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def sortColors(self, nums: List[int]) -> None: - i, j, k = -1, len(nums), 0 - while k < j: - if nums[k] == 0: - i += 1 - nums[i], nums[k] = nums[k], nums[i] - k += 1 - elif nums[k] == 2: - j -= 1 - nums[j], nums[k] = nums[k], nums[j] - else: - k += 1 +class Solution: + def sortColors(self, nums: List[int]) -> None: + i, j, k = -1, len(nums), 0 + while k < j: + if nums[k] == 0: + i += 1 + nums[i], nums[k] = nums[k], nums[i] + k += 1 + elif nums[k] == 2: + j -= 1 + nums[j], nums[k] = nums[k], nums[j] + else: + k += 1 diff --git a/solution/0000-0099/0076.Minimum Window Substring/Solution.cs b/solution/0000-0099/0076.Minimum Window Substring/Solution.cs index d55026b735256..7e52c6100c0dc 100644 --- a/solution/0000-0099/0076.Minimum Window Substring/Solution.cs +++ b/solution/0000-0099/0076.Minimum Window Substring/Solution.cs @@ -24,4 +24,4 @@ public string MinWindow(string s, string t) { } return k < 0 ? "" : s.Substring(k, mi); } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0076.Minimum Window Substring/Solution.py b/solution/0000-0099/0076.Minimum Window Substring/Solution.py index 90c603952d565..ee70c9eadb436 100644 --- a/solution/0000-0099/0076.Minimum Window Substring/Solution.py +++ b/solution/0000-0099/0076.Minimum Window Substring/Solution.py @@ -1,18 +1,18 @@ -class Solution: - def minWindow(self, s: str, t: str) -> str: - need = Counter(t) - window = Counter() - cnt, j, k, mi = 0, 0, -1, inf - for i, c in enumerate(s): - window[c] += 1 - if need[c] >= window[c]: - cnt += 1 - while cnt == len(t): - if i - j + 1 < mi: - mi = i - j + 1 - k = j - if need[s[j]] >= window[s[j]]: - cnt -= 1 - window[s[j]] -= 1 - j += 1 - return '' if k < 0 else s[k : k + mi] +class Solution: + def minWindow(self, s: str, t: str) -> str: + need = Counter(t) + window = Counter() + cnt, j, k, mi = 0, 0, -1, inf + for i, c in enumerate(s): + window[c] += 1 + if need[c] >= window[c]: + cnt += 1 + while cnt == len(t): + if i - j + 1 < mi: + mi = i - j + 1 + k = j + if need[s[j]] >= window[s[j]]: + cnt -= 1 + window[s[j]] -= 1 + j += 1 + return '' if k < 0 else s[k : k + mi] diff --git a/solution/0000-0099/0077.Combinations/Solution.cs b/solution/0000-0099/0077.Combinations/Solution.cs index 0b05a6f8bbb02..1b4e6afc42dde 100644 --- a/solution/0000-0099/0077.Combinations/Solution.cs +++ b/solution/0000-0099/0077.Combinations/Solution.cs @@ -3,7 +3,7 @@ public class Solution { private List t = new List(); private int n; private int k; - + public IList> Combine(int n, int k) { this.n = n; this.k = k; @@ -19,10 +19,9 @@ private void dfs(int i) { if (i > n) { return; } - for (int j = i; j <= n; ++j) { - t.Add(j); - dfs(j + 1); - t.RemoveAt(t.Count - 1); - } + t.Add(i); + dfs(i + 1); + t.RemoveAt(t.Count - 1); + dfs(i + 1); } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0077.Combinations/Solution2.cpp b/solution/0000-0099/0077.Combinations/Solution2.cpp new file mode 100644 index 0000000000000..bf7e6e080db57 --- /dev/null +++ b/solution/0000-0099/0077.Combinations/Solution2.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + vector> combine(int n, int k) { + vector> ans; + vector t; + function dfs = [&](int i) { + if (t.size() == k) { + ans.emplace_back(t); + return; + } + if (i > n) { + return; + } + for (int j = i; j <= n; ++j) { + t.emplace_back(j); + dfs(j + 1); + t.pop_back(); + } + }; + dfs(1); + return ans; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0077.Combinations/Solution2.cs b/solution/0000-0099/0077.Combinations/Solution2.cs new file mode 100644 index 0000000000000..787169118fa0f --- /dev/null +++ b/solution/0000-0099/0077.Combinations/Solution2.cs @@ -0,0 +1,28 @@ +public class Solution { + private List> ans = new List>(); + private List t = new List(); + private int n; + private int k; + + public IList> Combine(int n, int k) { + this.n = n; + this.k = k; + dfs(1); + return ans; + } + + private void dfs(int i) { + if (t.Count == k) { + ans.Add(new List(t)); + return; + } + if (i > n) { + return; + } + for (int j = i; j <= n; ++j) { + t.Add(j); + dfs(j + 1); + t.RemoveAt(t.Count - 1); + } + } +} diff --git a/solution/0000-0099/0077.Combinations/Solution2.go b/solution/0000-0099/0077.Combinations/Solution2.go new file mode 100644 index 0000000000000..457f5ae4f67e1 --- /dev/null +++ b/solution/0000-0099/0077.Combinations/Solution2.go @@ -0,0 +1,20 @@ +func combine(n int, k int) (ans [][]int) { + t := []int{} + var dfs func(int) + dfs = func(i int) { + if len(t) == k { + ans = append(ans, slices.Clone(t)) + return + } + if i > n { + return + } + for j := i; j <= n; j++ { + t = append(t, j) + dfs(j + 1) + t = t[:len(t)-1] + } + } + dfs(1) + return +} \ No newline at end of file diff --git a/solution/0000-0099/0077.Combinations/Solution2.java b/solution/0000-0099/0077.Combinations/Solution2.java new file mode 100644 index 0000000000000..8751bf5cec058 --- /dev/null +++ b/solution/0000-0099/0077.Combinations/Solution2.java @@ -0,0 +1,28 @@ +class Solution { + private List> ans = new ArrayList<>(); + private List t = new ArrayList<>(); + private int n; + private int k; + + public List> combine(int n, int k) { + this.n = n; + this.k = k; + dfs(1); + return ans; + } + + private void dfs(int i) { + if (t.size() == k) { + ans.add(new ArrayList<>(t)); + return; + } + if (i > n) { + return; + } + for (int j = i; j <= n; ++j) { + t.add(j); + dfs(j + 1); + t.remove(t.size() - 1); + } + } +} \ No newline at end of file diff --git a/solution/0000-0099/0077.Combinations/Solution2.py b/solution/0000-0099/0077.Combinations/Solution2.py new file mode 100644 index 0000000000000..27f0e8f545ce5 --- /dev/null +++ b/solution/0000-0099/0077.Combinations/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def combine(self, n: int, k: int) -> List[List[int]]: + def dfs(i: int): + if len(t) == k: + ans.append(t[:]) + return + if i > n: + return + for j in range(i, n + 1): + t.append(j) + dfs(j + 1) + t.pop() + + ans = [] + t = [] + dfs(1) + return ans diff --git a/solution/0000-0099/0077.Combinations/Solution2.rs b/solution/0000-0099/0077.Combinations/Solution2.rs new file mode 100644 index 0000000000000..b0844d4e28448 --- /dev/null +++ b/solution/0000-0099/0077.Combinations/Solution2.rs @@ -0,0 +1,22 @@ +impl Solution { + fn dfs(i: i32, n: i32, k: i32, t: &mut Vec, ans: &mut Vec>) { + if t.len() == (k as usize) { + ans.push(t.clone()); + return; + } + if i > n { + return; + } + for j in i..=n { + t.push(j); + Self::dfs(j + 1, n, k, t, ans); + t.pop(); + } + } + + pub fn combine(n: i32, k: i32) -> Vec> { + let mut ans = vec![]; + Self::dfs(1, n, k, &mut vec![], &mut ans); + ans + } +} diff --git a/solution/0000-0099/0077.Combinations/Solution2.ts b/solution/0000-0099/0077.Combinations/Solution2.ts new file mode 100644 index 0000000000000..e00ad6dee99b7 --- /dev/null +++ b/solution/0000-0099/0077.Combinations/Solution2.ts @@ -0,0 +1,20 @@ +function combine(n: number, k: number): number[][] { + const ans: number[][] = []; + const t: number[] = []; + const dfs = (i: number) => { + if (t.length === k) { + ans.push(t.slice()); + return; + } + if (i > n) { + return; + } + for (let j = i; j <= n; ++j) { + t.push(j); + dfs(j + 1); + t.pop(); + } + }; + dfs(1); + return ans; +} diff --git a/solution/0000-0099/0078.Subsets/Solution2.cpp b/solution/0000-0099/0078.Subsets/Solution2.cpp new file mode 100644 index 0000000000000..62bd9d59cfe9c --- /dev/null +++ b/solution/0000-0099/0078.Subsets/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector> subsets(vector& nums) { + int n = nums.size(); + vector> ans; + for (int mask = 0; mask < 1 << n; ++mask) { + vector t; + for (int i = 0; i < n; ++i) { + if (mask >> i & 1) { + t.emplace_back(nums[i]); + } + } + ans.emplace_back(t); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0078.Subsets/Solution2.go b/solution/0000-0099/0078.Subsets/Solution2.go new file mode 100644 index 0000000000000..4116109de543b --- /dev/null +++ b/solution/0000-0099/0078.Subsets/Solution2.go @@ -0,0 +1,13 @@ +func subsets(nums []int) (ans [][]int) { + n := len(nums) + for mask := 0; mask < 1<>i&1 == 1 { + t = append(t, x) + } + } + ans = append(ans, t) + } + return +} \ No newline at end of file diff --git a/solution/0000-0099/0078.Subsets/Solution2.java b/solution/0000-0099/0078.Subsets/Solution2.java new file mode 100644 index 0000000000000..8a20bcc9d3fb7 --- /dev/null +++ b/solution/0000-0099/0078.Subsets/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public List> subsets(int[] nums) { + int n = nums.length; + List> ans = new ArrayList<>(); + for (int mask = 0; mask < 1 << n; ++mask) { + List t = new ArrayList<>(); + for (int i = 0; i < n; ++i) { + if (((mask >> i) & 1) == 1) { + t.add(nums[i]); + } + } + ans.add(t); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0078.Subsets/Solution2.py b/solution/0000-0099/0078.Subsets/Solution2.py new file mode 100644 index 0000000000000..8ef95fa9da3e1 --- /dev/null +++ b/solution/0000-0099/0078.Subsets/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: + ans = [] + for mask in range(1 << len(nums)): + t = [x for i, x in enumerate(nums) if mask >> i & 1] + ans.append(t) + return ans diff --git a/solution/0000-0099/0078.Subsets/Solution2.ts b/solution/0000-0099/0078.Subsets/Solution2.ts new file mode 100644 index 0000000000000..a9c2851e3ab0b --- /dev/null +++ b/solution/0000-0099/0078.Subsets/Solution2.ts @@ -0,0 +1,14 @@ +function subsets(nums: number[]): number[][] { + const n = nums.length; + const ans: number[][] = []; + for (let mask = 0; mask < 1 << n; ++mask) { + const t: number[] = []; + for (let i = 0; i < n; ++i) { + if (((mask >> i) & 1) === 1) { + t.push(nums[i]); + } + } + ans.push(t); + } + return ans; +} diff --git a/solution/0000-0099/0079.Word Search/Solution.cs b/solution/0000-0099/0079.Word Search/Solution.cs index 5dfd85bf50acb..60a210385b81a 100644 --- a/solution/0000-0099/0079.Word Search/Solution.cs +++ b/solution/0000-0099/0079.Word Search/Solution.cs @@ -39,4 +39,4 @@ private bool dfs(int i, int j, int k) { board[i][j] = c; return false; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0079.Word Search/Solution.rs b/solution/0000-0099/0079.Word Search/Solution.rs index 59e4bbed2dfa7..38d4cc5f3c39a 100644 --- a/solution/0000-0099/0079.Word Search/Solution.rs +++ b/solution/0000-0099/0079.Word Search/Solution.rs @@ -21,7 +21,6 @@ impl Solution { [0, 1], ]; for [x, y] in dirs.into_iter() { - // 索引合法性审核 let i = x + (i as i32); let j = y + (j as i32); if i < 0 || i == (board.len() as i32) || j < 0 || j == (board[0].len() as i32) { diff --git a/solution/0000-0099/0080.Remove Duplicates from Sorted Array II/Solution.cs b/solution/0000-0099/0080.Remove Duplicates from Sorted Array II/Solution.cs index fc4b9caf1670f..83c3523b8eb65 100644 --- a/solution/0000-0099/0080.Remove Duplicates from Sorted Array II/Solution.cs +++ b/solution/0000-0099/0080.Remove Duplicates from Sorted Array II/Solution.cs @@ -8,4 +8,4 @@ public int RemoveDuplicates(int[] nums) { } return k; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0081.Search in Rotated Sorted Array II/Solution.cpp b/solution/0000-0099/0081.Search in Rotated Sorted Array II/Solution.cpp index 17f555845eb49..55053b0bc5466 100644 --- a/solution/0000-0099/0081.Search in Rotated Sorted Array II/Solution.cpp +++ b/solution/0000-0099/0081.Search in Rotated Sorted Array II/Solution.cpp @@ -1,25 +1,25 @@ -class Solution { -public: - bool search(vector& nums, int target) { - int l = 0, r = nums.size() - 1; - while (l < r) { - int mid = (l + r) >> 1; - if (nums[mid] > nums[r]) { - if (nums[l] <= target && target <= nums[mid]) { - r = mid; - } else { - l = mid + 1; - } - } else if (nums[mid] < nums[r]) { - if (nums[mid] < target && target <= nums[r]) { - l = mid + 1; - } else { - r = mid; - } - } else { - --r; - } - } - return nums[l] == target; - } +class Solution { +public: + bool search(vector& nums, int target) { + int l = 0, r = nums.size() - 1; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid] > nums[r]) { + if (nums[l] <= target && target <= nums[mid]) { + r = mid; + } else { + l = mid + 1; + } + } else if (nums[mid] < nums[r]) { + if (nums[mid] < target && target <= nums[r]) { + l = mid + 1; + } else { + r = mid; + } + } else { + --r; + } + } + return nums[l] == target; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0081.Search in Rotated Sorted Array II/Solution.java b/solution/0000-0099/0081.Search in Rotated Sorted Array II/Solution.java index c95536a02e9c0..23c97e7edf913 100644 --- a/solution/0000-0099/0081.Search in Rotated Sorted Array II/Solution.java +++ b/solution/0000-0099/0081.Search in Rotated Sorted Array II/Solution.java @@ -1,24 +1,24 @@ -class Solution { - public boolean search(int[] nums, int target) { - int l = 0, r = nums.length - 1; - while (l < r) { - int mid = (l + r) >> 1; - if (nums[mid] > nums[r]) { - if (nums[l] <= target && target <= nums[mid]) { - r = mid; - } else { - l = mid + 1; - } - } else if (nums[mid] < nums[r]) { - if (nums[mid] < target && target <= nums[r]) { - l = mid + 1; - } else { - r = mid; - } - } else { - --r; - } - } - return nums[l] == target; - } +class Solution { + public boolean search(int[] nums, int target) { + int l = 0, r = nums.length - 1; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid] > nums[r]) { + if (nums[l] <= target && target <= nums[mid]) { + r = mid; + } else { + l = mid + 1; + } + } else if (nums[mid] < nums[r]) { + if (nums[mid] < target && target <= nums[r]) { + l = mid + 1; + } else { + r = mid; + } + } else { + --r; + } + } + return nums[l] == target; + } } \ No newline at end of file diff --git a/solution/0000-0099/0081.Search in Rotated Sorted Array II/Solution.py b/solution/0000-0099/0081.Search in Rotated Sorted Array II/Solution.py index 972d774f6c38c..e14537438645f 100644 --- a/solution/0000-0099/0081.Search in Rotated Sorted Array II/Solution.py +++ b/solution/0000-0099/0081.Search in Rotated Sorted Array II/Solution.py @@ -1,19 +1,19 @@ -class Solution: - def search(self, nums: List[int], target: int) -> bool: - n = len(nums) - l, r = 0, n - 1 - while l < r: - mid = (l + r) >> 1 - if nums[mid] > nums[r]: - if nums[l] <= target <= nums[mid]: - r = mid - else: - l = mid + 1 - elif nums[mid] < nums[r]: - if nums[mid] < target <= nums[r]: - l = mid + 1 - else: - r = mid - else: - r -= 1 - return nums[l] == target +class Solution: + def search(self, nums: List[int], target: int) -> bool: + n = len(nums) + l, r = 0, n - 1 + while l < r: + mid = (l + r) >> 1 + if nums[mid] > nums[r]: + if nums[l] <= target <= nums[mid]: + r = mid + else: + l = mid + 1 + elif nums[mid] < nums[r]: + if nums[mid] < target <= nums[r]: + l = mid + 1 + else: + r = mid + else: + r -= 1 + return nums[l] == target diff --git a/solution/0000-0099/0082.Remove Duplicates from Sorted List II/Solution.cs b/solution/0000-0099/0082.Remove Duplicates from Sorted List II/Solution.cs index 3b9f6e942315e..173ee9fff179c 100644 --- a/solution/0000-0099/0082.Remove Duplicates from Sorted List II/Solution.cs +++ b/solution/0000-0099/0082.Remove Duplicates from Sorted List II/Solution.cs @@ -27,4 +27,4 @@ public ListNode DeleteDuplicates(ListNode head) { } return dummy.next; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0083.Remove Duplicates from Sorted List/Solution.cs b/solution/0000-0099/0083.Remove Duplicates from Sorted List/Solution.cs index 45e7529f37c69..4f940b8ae743d 100644 --- a/solution/0000-0099/0083.Remove Duplicates from Sorted List/Solution.cs +++ b/solution/0000-0099/0083.Remove Duplicates from Sorted List/Solution.cs @@ -1,24 +1,24 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } - * } - */ -public class Solution { - public ListNode DeleteDuplicates(ListNode head) { - ListNode cur = head; - while (cur != null && cur.next != null) { - if (cur.val == cur.next.val) { - cur.next = cur.next.next; - } else { - cur = cur.next; - } - } - return head; - } -} \ No newline at end of file +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode DeleteDuplicates(ListNode head) { + ListNode cur = head; + while (cur != null && cur.next != null) { + if (cur.val == cur.next.val) { + cur.next = cur.next.next; + } else { + cur = cur.next; + } + } + return head; + } +} diff --git a/solution/0000-0099/0083.Remove Duplicates from Sorted List/Solution.py b/solution/0000-0099/0083.Remove Duplicates from Sorted List/Solution.py index 25c52cd0afe39..4e5b1aabe6e13 100644 --- a/solution/0000-0099/0083.Remove Duplicates from Sorted List/Solution.py +++ b/solution/0000-0099/0083.Remove Duplicates from Sorted List/Solution.py @@ -1,14 +1,14 @@ -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: - cur = head - while cur and cur.next: - if cur.val == cur.next.val: - cur.next = cur.next.next - else: - cur = cur.next - return head +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: + cur = head + while cur and cur.next: + if cur.val == cur.next.val: + cur.next = cur.next.next + else: + cur = cur.next + return head diff --git a/solution/0000-0099/0084.Largest Rectangle in Histogram/Solution2.py b/solution/0000-0099/0084.Largest Rectangle in Histogram/Solution2.py new file mode 100644 index 0000000000000..72d228f03d7dd --- /dev/null +++ b/solution/0000-0099/0084.Largest Rectangle in Histogram/Solution2.py @@ -0,0 +1,21 @@ +class Solution: + def largestRectangleArea(self, heights: List[int]) -> int: + n = len(heights) + stk = [] + left = [-1] * n + right = [n] * n + for i, h in enumerate(heights): + while stk and heights[stk[-1]] >= h: + stk.pop() + if stk: + left[i] = stk[-1] + stk.append(i) + stk = [] + for i in range(n - 1, -1, -1): + h = heights[i] + while stk and heights[stk[-1]] >= h: + stk.pop() + if stk: + right[i] = stk[-1] + stk.append(i) + return max(h * (right[i] - left[i] - 1) for i, h in enumerate(heights)) diff --git a/solution/0000-0099/0087.Scramble String/Solution.cs b/solution/0000-0099/0087.Scramble String/Solution.cs index d9221293c3cb2..9ca9c4cc94eb8 100644 --- a/solution/0000-0099/0087.Scramble String/Solution.cs +++ b/solution/0000-0099/0087.Scramble String/Solution.cs @@ -31,4 +31,4 @@ private bool dfs(int i, int j, int k) { f[i, j, k] = -1; return false; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0087.Scramble String/Solution2.cpp b/solution/0000-0099/0087.Scramble String/Solution2.cpp new file mode 100644 index 0000000000000..c3251005e4ea6 --- /dev/null +++ b/solution/0000-0099/0087.Scramble String/Solution2.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + bool isScramble(string s1, string s2) { + int n = s1.length(); + bool f[n][n][n + 1]; + memset(f, false, sizeof(f)); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + f[i][j][1] = s1[i] == s2[j]; + } + } + for (int k = 2; k <= n; ++k) { + for (int i = 0; i <= n - k; ++i) { + for (int j = 0; j <= n - k; ++j) { + for (int h = 1; h < k; ++h) { + if () { + f[i][j][k] = true; + break; + } + if (f[i + h][j][k - h] && f[i][j + k - h][h]) { + f[i][j][k] = true; + break; + } + } + } + } + } + return f[0][0][n]; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0087.Scramble String/Solution2.cs b/solution/0000-0099/0087.Scramble String/Solution2.cs new file mode 100644 index 0000000000000..3cc059a9cc6c1 --- /dev/null +++ b/solution/0000-0099/0087.Scramble String/Solution2.cs @@ -0,0 +1,28 @@ +public class Solution { + public bool IsScramble(string s1, string s2) { + int n = s1.Length; + bool[,,] f = new bool[n, n, n + 1]; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++ j) { + f[i, j, 1] = s1[i] == s2[j]; + } + } + for (int k = 2; k <= n; ++k) { + for (int i = 0; i <= n - k; ++i) { + for (int j = 0; j <= n - k; ++j) { + for (int h = 1; h < k; ++h) { + if (f[i, j, h] && f[i + h, j + h, k - h]) { + f[i, j, k] = true; + break; + } + if (f[i, j + k - h, h] && f[i + h, j, k - h]) { + f[i, j, k] = true; + break; + } + } + } + } + } + return f[0, 0, n]; + } +} diff --git a/solution/0000-0099/0087.Scramble String/Solution2.go b/solution/0000-0099/0087.Scramble String/Solution2.go new file mode 100644 index 0000000000000..b3e9dfed6996c --- /dev/null +++ b/solution/0000-0099/0087.Scramble String/Solution2.go @@ -0,0 +1,24 @@ +func isScramble(s1 string, s2 string) bool { + n := len(s1) + f := make([][][]bool, n) + for i := range f { + f[i] = make([][]bool, n) + for j := 0; j < n; j++ { + f[i][j] = make([]bool, n+1) + f[i][j][1] = s1[i] == s2[j] + } + } + for k := 2; k <= n; k++ { + for i := 0; i <= n-k; i++ { + for j := 0; j <= n-k; j++ { + for h := 1; h < k; h++ { + if (f[i][j][h] && f[i+h][j+h][k-h]) || (f[i+h][j][k-h] && f[i][j+k-h][h]) { + f[i][j][k] = true + break + } + } + } + } + } + return f[0][0][n] +} \ No newline at end of file diff --git a/solution/0000-0099/0087.Scramble String/Solution2.java b/solution/0000-0099/0087.Scramble String/Solution2.java new file mode 100644 index 0000000000000..992ef9b872d1f --- /dev/null +++ b/solution/0000-0099/0087.Scramble String/Solution2.java @@ -0,0 +1,28 @@ +class Solution { + public boolean isScramble(String s1, String s2) { + int n = s1.length(); + boolean[][][] f = new boolean[n][n][n + 1]; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + f[i][j][1] = s1.charAt(i) == s2.charAt(j); + } + } + for (int k = 2; k <= n; ++k) { + for (int i = 0; i <= n - k; ++i) { + for (int j = 0; j <= n - k; ++j) { + for (int h = 1; h < k; ++h) { + if (f[i][j][h] && f[i + h][j + h][k - h]) { + f[i][j][k] = true; + break; + } + if (f[i + h][j][k - h] && f[i][j + k - h][h]) { + f[i][j][k] = true; + break; + } + } + } + } + } + return f[0][0][n]; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0087.Scramble String/Solution2.py b/solution/0000-0099/0087.Scramble String/Solution2.py new file mode 100644 index 0000000000000..787b320717bc6 --- /dev/null +++ b/solution/0000-0099/0087.Scramble String/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def isScramble(self, s1: str, s2: str) -> bool: + n = len(s1) + f = [[[False] * (n + 1) for _ in range(n)] for _ in range(n)] + for i in range(n): + for j in range(n): + f[i][j][1] = s1[i] == s2[j] + for k in range(2, n + 1): + for i in range(n - k + 1): + for j in range(n - k + 1): + for h in range(1, k): + if f[i][j][h] and f[i + h][j + h][k - h]: + f[i][j][k] = True + break + if f[i + h][j][k - h] and f[i][j + k - h][h]: + f[i][j][k] = True + break + return f[0][0][n] diff --git a/solution/0000-0099/0087.Scramble String/Solution2.ts b/solution/0000-0099/0087.Scramble String/Solution2.ts new file mode 100644 index 0000000000000..fd9d472efcd2f --- /dev/null +++ b/solution/0000-0099/0087.Scramble String/Solution2.ts @@ -0,0 +1,28 @@ +function isScramble(s1: string, s2: string): boolean { + const n = s1.length; + const f = new Array(n) + .fill(0) + .map(() => new Array(n).fill(0).map(() => new Array(n + 1).fill(false))); + for (let i = 0; i < n; ++i) { + for (let j = 0; j < n; ++j) { + f[i][j][1] = s1[i] === s2[j]; + } + } + for (let k = 2; k <= n; ++k) { + for (let i = 0; i <= n - k; ++i) { + for (let j = 0; j <= n - k; ++j) { + for (let h = 1; h < k; ++h) { + if (f[i][j][h] && f[i + h][j + h][k - h]) { + f[i][j][k] = true; + break; + } + if (f[i + h][j][k - h] && f[i][j + k - h][h]) { + f[i][j][k] = true; + break; + } + } + } + } + } + return f[0][0][n]; +} diff --git a/solution/0000-0099/0088.Merge Sorted Array/Solution.php b/solution/0000-0099/0088.Merge Sorted Array/Solution.php index b8d34826f1c27..419349afa6460 100644 --- a/solution/0000-0099/0088.Merge Sorted Array/Solution.php +++ b/solution/0000-0099/0088.Merge Sorted Array/Solution.php @@ -15,4 +15,4 @@ function merge(&$nums1, $m, $nums2, $n) { } asort($nums1); } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0088.Merge Sorted Array/Solution2.ts b/solution/0000-0099/0088.Merge Sorted Array/Solution2.ts new file mode 100644 index 0000000000000..b39e6527d0dd5 --- /dev/null +++ b/solution/0000-0099/0088.Merge Sorted Array/Solution2.ts @@ -0,0 +1,9 @@ +/** + Do not return anything, modify nums1 in-place instead. + */ +function merge(nums1: number[], m: number, nums2: number[], n: number): void { + nums1.length = m; + nums2.length = n; + nums1.push(...nums2); + nums1.sort((a, b) => a - b); +} diff --git a/solution/0000-0099/0090.Subsets II/Solution.cpp b/solution/0000-0099/0090.Subsets II/Solution.cpp index 58c1ad52fb29a..49b08baab6a7d 100644 --- a/solution/0000-0099/0090.Subsets II/Solution.cpp +++ b/solution/0000-0099/0090.Subsets II/Solution.cpp @@ -1,25 +1,24 @@ -class Solution { -public: - vector> subsetsWithDup(vector& nums) { - sort(nums.begin(), nums.end()); - int n = nums.size(); - vector> ans; - for (int mask = 0; mask < 1 << n; ++mask) { - vector t; - bool ok = true; - for (int i = 0; i < n; ++i) { - if ((mask >> i & 1) == 1) { - if (i > 0 && (mask >> (i - 1) & 1) == 0 && nums[i] == nums[i - 1]) { - ok = false; - break; - } - t.push_back(nums[i]); - } - } - if (ok) { - ans.push_back(t); - } - } - return ans; - } +class Solution { +public: + vector> subsetsWithDup(vector& nums) { + sort(nums.begin(), nums.end()); + vector> ans; + vector t; + int n = nums.size(); + function dfs = [&](int i) { + if (i >= n) { + ans.push_back(t); + return; + } + t.push_back(nums[i]); + dfs(i + 1); + t.pop_back(); + while (i + 1 < n && nums[i + 1] == nums[i]) { + ++i; + } + dfs(i + 1); + }; + dfs(0); + return ans; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0090.Subsets II/Solution.go b/solution/0000-0099/0090.Subsets II/Solution.go index cec1dc4a9d090..70194ede97453 100644 --- a/solution/0000-0099/0090.Subsets II/Solution.go +++ b/solution/0000-0099/0090.Subsets II/Solution.go @@ -1,21 +1,21 @@ func subsetsWithDup(nums []int) (ans [][]int) { sort.Ints(nums) n := len(nums) - for mask := 0; mask < 1<>i&1 == 1 { - if i > 0 && mask>>(i-1)&1 == 0 && nums[i] == nums[i-1] { - ok = false - break - } - t = append(t, nums[i]) - } + t := []int{} + var dfs func(int) + dfs = func(i int) { + if i >= n { + ans = append(ans, slices.Clone(t)) + return } - if ok { - ans = append(ans, t) + t = append(t, nums[i]) + dfs(i + 1) + t = t[:len(t)-1] + for i+1 < n && nums[i+1] == nums[i] { + i++ } + dfs(i + 1) } + dfs(0) return } \ No newline at end of file diff --git a/solution/0000-0099/0090.Subsets II/Solution.java b/solution/0000-0099/0090.Subsets II/Solution.java index 53c9c7d4c7194..d9bea8a9b1f4c 100644 --- a/solution/0000-0099/0090.Subsets II/Solution.java +++ b/solution/0000-0099/0090.Subsets II/Solution.java @@ -1,24 +1,26 @@ -class Solution { - public List> subsetsWithDup(int[] nums) { - Arrays.sort(nums); - int n = nums.length; - List> ans = new ArrayList<>(); - for (int mask = 0; mask < 1 << n; ++mask) { - List t = new ArrayList<>(); - boolean ok = true; - for (int i = 0; i < n; ++i) { - if ((mask >> i & 1) == 1) { - if (i > 0 && (mask >> (i - 1) & 1) == 0 && nums[i] == nums[i - 1]) { - ok = false; - break; - } - t.add(nums[i]); - } - } - if (ok) { - ans.add(t); - } - } - return ans; - } +class Solution { + private List> ans = new ArrayList<>(); + private List t = new ArrayList<>(); + private int[] nums; + + public List> subsetsWithDup(int[] nums) { + Arrays.sort(nums); + this.nums = nums; + dfs(0); + return ans; + } + + private void dfs(int i) { + if (i >= nums.length) { + ans.add(new ArrayList<>(t)); + return; + } + t.add(nums[i]); + dfs(i + 1); + int x = t.remove(t.size() - 1); + while (i + 1 < nums.length && nums[i + 1] == x) { + ++i; + } + dfs(i + 1); + } } \ No newline at end of file diff --git a/solution/0000-0099/0090.Subsets II/Solution.py b/solution/0000-0099/0090.Subsets II/Solution.py index c0aa8d12289f2..199c837f9147c 100644 --- a/solution/0000-0099/0090.Subsets II/Solution.py +++ b/solution/0000-0099/0090.Subsets II/Solution.py @@ -1,17 +1,18 @@ -class Solution: - def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: - nums.sort() - n = len(nums) - ans = [] - for mask in range(1 << n): - ok = True - t = [] - for i in range(n): - if mask >> i & 1: - if i and (mask >> (i - 1) & 1) == 0 and nums[i] == nums[i - 1]: - ok = False - break - t.append(nums[i]) - if ok: - ans.append(t) - return ans +class Solution: + def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: + def dfs(i: int): + if i == len(nums): + ans.append(t[:]) + return + t.append(nums[i]) + dfs(i + 1) + x = t.pop() + while i + 1 < len(nums) and nums[i + 1] == x: + i += 1 + dfs(i + 1) + + nums.sort() + ans = [] + t = [] + dfs(0) + return ans diff --git a/solution/0000-0099/0090.Subsets II/Solution.rs b/solution/0000-0099/0090.Subsets II/Solution.rs index 6f272559d3d46..54827d9273eb3 100644 --- a/solution/0000-0099/0090.Subsets II/Solution.rs +++ b/solution/0000-0099/0090.Subsets II/Solution.rs @@ -2,24 +2,25 @@ impl Solution { pub fn subsets_with_dup(nums: Vec) -> Vec> { let mut nums = nums; nums.sort(); - let n = nums.len(); let mut ans = Vec::new(); - for mask in 0..1 << n { - let mut t = Vec::new(); - let mut ok = true; - for i in 0..n { - if ((mask >> i) & 1) == 1 { - if i > 0 && ((mask >> (i - 1)) & 1) == 0 && nums[i] == nums[i - 1] { - ok = false; - break; - } - t.push(nums[i]); - } + let mut t = Vec::new(); + + fn dfs(i: usize, nums: &Vec, t: &mut Vec, ans: &mut Vec>) { + if i >= nums.len() { + ans.push(t.clone()); + return; } - if ok { - ans.push(t); + t.push(nums[i]); + dfs(i + 1, nums, t, ans); + t.pop(); + let mut i = i; + while i + 1 < nums.len() && nums[i + 1] == nums[i] { + i += 1; } + dfs(i + 1, nums, t, ans); } + + dfs(0, &nums, &mut t, &mut ans); ans } } diff --git a/solution/0000-0099/0090.Subsets II/Solution.ts b/solution/0000-0099/0090.Subsets II/Solution.ts index 9ac9ba3681a87..7cc715e0d0a68 100644 --- a/solution/0000-0099/0090.Subsets II/Solution.ts +++ b/solution/0000-0099/0090.Subsets II/Solution.ts @@ -1,22 +1,21 @@ function subsetsWithDup(nums: number[]): number[][] { nums.sort((a, b) => a - b); const n = nums.length; + const t: number[] = []; const ans: number[][] = []; - for (let mask = 0; mask < 1 << n; ++mask) { - const t: number[] = []; - let ok: boolean = true; - for (let i = 0; i < n; ++i) { - if (((mask >> i) & 1) === 1) { - if (i && ((mask >> (i - 1)) & 1) === 0 && nums[i] === nums[i - 1]) { - ok = false; - break; - } - t.push(nums[i]); - } + const dfs = (i: number): void => { + if (i >= n) { + ans.push([...t]); + return; } - if (ok) { - ans.push(t); + t.push(nums[i]); + dfs(i + 1); + t.pop(); + while (i + 1 < n && nums[i] === nums[i + 1]) { + i++; } - } + dfs(i + 1); + }; + dfs(0); return ans; } diff --git a/solution/0000-0099/0090.Subsets II/Solution2.cpp b/solution/0000-0099/0090.Subsets II/Solution2.cpp new file mode 100644 index 0000000000000..2d5b88450b3e1 --- /dev/null +++ b/solution/0000-0099/0090.Subsets II/Solution2.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + vector> subsetsWithDup(vector& nums) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + vector> ans; + for (int mask = 0; mask < 1 << n; ++mask) { + vector t; + bool ok = true; + for (int i = 0; i < n; ++i) { + if ((mask >> i & 1) == 1) { + if (i > 0 && (mask >> (i - 1) & 1) == 0 && nums[i] == nums[i - 1]) { + ok = false; + break; + } + t.push_back(nums[i]); + } + } + if (ok) { + ans.push_back(t); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0090.Subsets II/Solution2.go b/solution/0000-0099/0090.Subsets II/Solution2.go new file mode 100644 index 0000000000000..cec1dc4a9d090 --- /dev/null +++ b/solution/0000-0099/0090.Subsets II/Solution2.go @@ -0,0 +1,21 @@ +func subsetsWithDup(nums []int) (ans [][]int) { + sort.Ints(nums) + n := len(nums) + for mask := 0; mask < 1<>i&1 == 1 { + if i > 0 && mask>>(i-1)&1 == 0 && nums[i] == nums[i-1] { + ok = false + break + } + t = append(t, nums[i]) + } + } + if ok { + ans = append(ans, t) + } + } + return +} \ No newline at end of file diff --git a/solution/0000-0099/0090.Subsets II/Solution2.java b/solution/0000-0099/0090.Subsets II/Solution2.java new file mode 100644 index 0000000000000..2b88015fdaa2a --- /dev/null +++ b/solution/0000-0099/0090.Subsets II/Solution2.java @@ -0,0 +1,24 @@ +class Solution { + public List> subsetsWithDup(int[] nums) { + Arrays.sort(nums); + int n = nums.length; + List> ans = new ArrayList<>(); + for (int mask = 0; mask < 1 << n; ++mask) { + List t = new ArrayList<>(); + boolean ok = true; + for (int i = 0; i < n; ++i) { + if ((mask >> i & 1) == 1) { + if (i > 0 && (mask >> (i - 1) & 1) == 0 && nums[i] == nums[i - 1]) { + ok = false; + break; + } + t.add(nums[i]); + } + } + if (ok) { + ans.add(t); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0090.Subsets II/Solution2.py b/solution/0000-0099/0090.Subsets II/Solution2.py new file mode 100644 index 0000000000000..4a41926d40e44 --- /dev/null +++ b/solution/0000-0099/0090.Subsets II/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: + nums.sort() + n = len(nums) + ans = [] + for mask in range(1 << n): + ok = True + t = [] + for i in range(n): + if mask >> i & 1: + if i and (mask >> (i - 1) & 1) == 0 and nums[i] == nums[i - 1]: + ok = False + break + t.append(nums[i]) + if ok: + ans.append(t) + return ans diff --git a/solution/0000-0099/0090.Subsets II/Solution2.rs b/solution/0000-0099/0090.Subsets II/Solution2.rs new file mode 100644 index 0000000000000..6f272559d3d46 --- /dev/null +++ b/solution/0000-0099/0090.Subsets II/Solution2.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn subsets_with_dup(nums: Vec) -> Vec> { + let mut nums = nums; + nums.sort(); + let n = nums.len(); + let mut ans = Vec::new(); + for mask in 0..1 << n { + let mut t = Vec::new(); + let mut ok = true; + for i in 0..n { + if ((mask >> i) & 1) == 1 { + if i > 0 && ((mask >> (i - 1)) & 1) == 0 && nums[i] == nums[i - 1] { + ok = false; + break; + } + t.push(nums[i]); + } + } + if ok { + ans.push(t); + } + } + ans + } +} diff --git a/solution/0000-0099/0090.Subsets II/Solution2.ts b/solution/0000-0099/0090.Subsets II/Solution2.ts new file mode 100644 index 0000000000000..9ac9ba3681a87 --- /dev/null +++ b/solution/0000-0099/0090.Subsets II/Solution2.ts @@ -0,0 +1,22 @@ +function subsetsWithDup(nums: number[]): number[][] { + nums.sort((a, b) => a - b); + const n = nums.length; + const ans: number[][] = []; + for (let mask = 0; mask < 1 << n; ++mask) { + const t: number[] = []; + let ok: boolean = true; + for (let i = 0; i < n; ++i) { + if (((mask >> i) & 1) === 1) { + if (i && ((mask >> (i - 1)) & 1) === 0 && nums[i] === nums[i - 1]) { + ok = false; + break; + } + t.push(nums[i]); + } + } + if (ok) { + ans.push(t); + } + } + return ans; +} diff --git a/solution/0000-0099/0091.Decode Ways/Solution.cpp b/solution/0000-0099/0091.Decode Ways/Solution.cpp index 95d1ccb3c69c1..a87f3a75fa669 100644 --- a/solution/0000-0099/0091.Decode Ways/Solution.cpp +++ b/solution/0000-0099/0091.Decode Ways/Solution.cpp @@ -1,16 +1,18 @@ -class Solution { -public: - int numDecodings(string s) { - int n = s.size(); - int f = 0, g = 1; - for (int i = 1; i <= n; ++i) { - int h = s[i - 1] != '0' ? g : 0; - if (i > 1 && (s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6'))) { - h += f; - } - f = g; - g = h; - } - return g; - } +class Solution { +public: + int numDecodings(string s) { + int n = s.size(); + int f[n + 1]; + memset(f, 0, sizeof(f)); + f[0] = 1; + for (int i = 1; i <= n; ++i) { + if (s[i - 1] != '0') { + f[i] = f[i - 1]; + } + if (i > 1 && (s[i - 2] == '1' || s[i - 2] == '2' && s[i - 1] <= '6')) { + f[i] += f[i - 2]; + } + } + return f[n]; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0091.Decode Ways/Solution.cs b/solution/0000-0099/0091.Decode Ways/Solution.cs index 1d1b739436473..e57b189cd0a79 100644 --- a/solution/0000-0099/0091.Decode Ways/Solution.cs +++ b/solution/0000-0099/0091.Decode Ways/Solution.cs @@ -1,15 +1,16 @@ -public class Solution { - public int NumDecodings(string s) { - int n = s.Length; - int f = 0, g = 1; - for (int i = 1; i <= n; ++i) { - int h = s[i - 1] != '0' ? g : 0; - if (i > 1 && (s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6'))) { - h += f; - } - f = g; - g = h; - } - return g; - } -} \ No newline at end of file +public class Solution { + public int NumDecodings(string s) { + int n = s.Length; + int[] f = new int[n + 1]; + f[0] = 1; + for (int i = 1; i <= n; ++i) { + if (s[i - 1] != '0') { + f[i] = f[i - 1]; + } + if (i > 1 && (s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6'))) { + f[i] += f[i - 2]; + } + } + return f[n]; + } +} diff --git a/solution/0000-0099/0091.Decode Ways/Solution.go b/solution/0000-0099/0091.Decode Ways/Solution.go index 3369efe1a9bba..59d82b775c54e 100644 --- a/solution/0000-0099/0091.Decode Ways/Solution.go +++ b/solution/0000-0099/0091.Decode Ways/Solution.go @@ -1,15 +1,14 @@ func numDecodings(s string) int { n := len(s) - f, g := 0, 1 + f := make([]int, n+1) + f[0] = 1 for i := 1; i <= n; i++ { - h := 0 if s[i-1] != '0' { - h = g + f[i] = f[i-1] } if i > 1 && (s[i-2] == '1' || (s[i-2] == '2' && s[i-1] <= '6')) { - h += f + f[i] += f[i-2] } - f, g = g, h } - return g + return f[n] } \ No newline at end of file diff --git a/solution/0000-0099/0091.Decode Ways/Solution.java b/solution/0000-0099/0091.Decode Ways/Solution.java index 51045383bdca6..2eaf1e1ef6dd1 100644 --- a/solution/0000-0099/0091.Decode Ways/Solution.java +++ b/solution/0000-0099/0091.Decode Ways/Solution.java @@ -1,15 +1,16 @@ -class Solution { - public int numDecodings(String s) { - int n = s.length(); - int f = 0, g = 1; - for (int i = 1; i <= n; ++i) { - int h = s.charAt(i - 1) != '0' ? g : 0; - if (i > 1 && s.charAt(i - 2) != '0' && Integer.valueOf(s.substring(i - 2, i)) <= 26) { - h += f; - } - f = g; - g = h; - } - return g; - } +class Solution { + public int numDecodings(String s) { + int n = s.length(); + int[] f = new int[n + 1]; + f[0] = 1; + for (int i = 1; i <= n; ++i) { + if (s.charAt(i - 1) != '0') { + f[i] = f[i - 1]; + } + if (i > 1 && s.charAt(i - 2) != '0' && Integer.valueOf(s.substring(i - 2, i)) <= 26) { + f[i] += f[i - 2]; + } + } + return f[n]; + } } \ No newline at end of file diff --git a/solution/0000-0099/0091.Decode Ways/Solution.py b/solution/0000-0099/0091.Decode Ways/Solution.py index e57d570cab52e..52fa0eecf7ed2 100644 --- a/solution/0000-0099/0091.Decode Ways/Solution.py +++ b/solution/0000-0099/0091.Decode Ways/Solution.py @@ -1,9 +1,10 @@ -class Solution: - def numDecodings(self, s: str) -> int: - f, g = 0, 1 - for i, c in enumerate(s, 1): - h = g if c != "0" else 0 - if i > 1 and s[i - 2] != "0" and int(s[i - 2 : i]) <= 26: - h += f - f, g = g, h - return g +class Solution: + def numDecodings(self, s: str) -> int: + n = len(s) + f = [1] + [0] * n + for i, c in enumerate(s, 1): + if c != "0": + f[i] = f[i - 1] + if i > 1 and s[i - 2] != "0" and int(s[i - 2 : i]) <= 26: + f[i] += f[i - 2] + return f[n] diff --git a/solution/0000-0099/0091.Decode Ways/Solution.ts b/solution/0000-0099/0091.Decode Ways/Solution.ts index 95745a148ca6a..5846d6e9ddc08 100644 --- a/solution/0000-0099/0091.Decode Ways/Solution.ts +++ b/solution/0000-0099/0091.Decode Ways/Solution.ts @@ -1,12 +1,14 @@ function numDecodings(s: string): number { const n = s.length; - let [f, g] = [0, 1]; + const f: number[] = new Array(n + 1).fill(0); + f[0] = 1; for (let i = 1; i <= n; ++i) { - let h = s[i - 1] !== '0' ? g : 0; + if (s[i - 1] !== '0') { + f[i] = f[i - 1]; + } if (i > 1 && (s[i - 2] === '1' || (s[i - 2] === '2' && s[i - 1] <= '6'))) { - h += f; + f[i] += f[i - 2]; } - [f, g] = [g, h]; } - return g; + return f[n]; } diff --git a/solution/0000-0099/0091.Decode Ways/Solution2.cpp b/solution/0000-0099/0091.Decode Ways/Solution2.cpp new file mode 100644 index 0000000000000..a8405e33ca648 --- /dev/null +++ b/solution/0000-0099/0091.Decode Ways/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int numDecodings(string s) { + int n = s.size(); + int f = 0, g = 1; + for (int i = 1; i <= n; ++i) { + int h = s[i - 1] != '0' ? g : 0; + if (i > 1 && (s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6'))) { + h += f; + } + f = g; + g = h; + } + return g; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0091.Decode Ways/Solution2.cs b/solution/0000-0099/0091.Decode Ways/Solution2.cs new file mode 100644 index 0000000000000..faf30eb5e56cb --- /dev/null +++ b/solution/0000-0099/0091.Decode Ways/Solution2.cs @@ -0,0 +1,15 @@ +public class Solution { + public int NumDecodings(string s) { + int n = s.Length; + int f = 0, g = 1; + for (int i = 1; i <= n; ++i) { + int h = s[i - 1] != '0' ? g : 0; + if (i > 1 && (s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6'))) { + h += f; + } + f = g; + g = h; + } + return g; + } +} diff --git a/solution/0000-0099/0091.Decode Ways/Solution2.go b/solution/0000-0099/0091.Decode Ways/Solution2.go new file mode 100644 index 0000000000000..3369efe1a9bba --- /dev/null +++ b/solution/0000-0099/0091.Decode Ways/Solution2.go @@ -0,0 +1,15 @@ +func numDecodings(s string) int { + n := len(s) + f, g := 0, 1 + for i := 1; i <= n; i++ { + h := 0 + if s[i-1] != '0' { + h = g + } + if i > 1 && (s[i-2] == '1' || (s[i-2] == '2' && s[i-1] <= '6')) { + h += f + } + f, g = g, h + } + return g +} \ No newline at end of file diff --git a/solution/0000-0099/0091.Decode Ways/Solution2.java b/solution/0000-0099/0091.Decode Ways/Solution2.java new file mode 100644 index 0000000000000..a78f5debb7e33 --- /dev/null +++ b/solution/0000-0099/0091.Decode Ways/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public int numDecodings(String s) { + int n = s.length(); + int f = 0, g = 1; + for (int i = 1; i <= n; ++i) { + int h = s.charAt(i - 1) != '0' ? g : 0; + if (i > 1 && s.charAt(i - 2) != '0' && Integer.valueOf(s.substring(i - 2, i)) <= 26) { + h += f; + } + f = g; + g = h; + } + return g; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0091.Decode Ways/Solution2.py b/solution/0000-0099/0091.Decode Ways/Solution2.py new file mode 100644 index 0000000000000..38e3f2d249bb5 --- /dev/null +++ b/solution/0000-0099/0091.Decode Ways/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def numDecodings(self, s: str) -> int: + f, g = 0, 1 + for i, c in enumerate(s, 1): + h = g if c != "0" else 0 + if i > 1 and s[i - 2] != "0" and int(s[i - 2 : i]) <= 26: + h += f + f, g = g, h + return g diff --git a/solution/0000-0099/0091.Decode Ways/Solution2.ts b/solution/0000-0099/0091.Decode Ways/Solution2.ts new file mode 100644 index 0000000000000..95745a148ca6a --- /dev/null +++ b/solution/0000-0099/0091.Decode Ways/Solution2.ts @@ -0,0 +1,12 @@ +function numDecodings(s: string): number { + const n = s.length; + let [f, g] = [0, 1]; + for (let i = 1; i <= n; ++i) { + let h = s[i - 1] !== '0' ? g : 0; + if (i > 1 && (s[i - 2] === '1' || (s[i - 2] === '2' && s[i - 1] <= '6'))) { + h += f; + } + [f, g] = [g, h]; + } + return g; +} diff --git a/solution/0000-0099/0092.Reverse Linked List II/Solution.cs b/solution/0000-0099/0092.Reverse Linked List II/Solution.cs index 2802441215d82..019d7392e0e49 100644 --- a/solution/0000-0099/0092.Reverse Linked List II/Solution.cs +++ b/solution/0000-0099/0092.Reverse Linked List II/Solution.cs @@ -32,4 +32,4 @@ public ListNode ReverseBetween(ListNode head, int left, int right) { q.next = cur; return dummy.next; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0093.Restore IP Addresses/Solution.cpp b/solution/0000-0099/0093.Restore IP Addresses/Solution.cpp index bd30bf8a1d575..dc9ff6773f0b3 100644 --- a/solution/0000-0099/0093.Restore IP Addresses/Solution.cpp +++ b/solution/0000-0099/0093.Restore IP Addresses/Solution.cpp @@ -1,29 +1,29 @@ -class Solution { -public: - vector restoreIpAddresses(string s) { - int n = s.size(); - vector ans; - vector t; - function dfs = [&](int i) { - if (i >= n && t.size() == 4) { - ans.push_back(t[0] + "." + t[1] + "." + t[2] + "." + t[3]); - return; - } - if (i >= n || t.size() >= 4) { - return; - } - int x = 0; - for (int j = i; j < min(n, i + 3); ++j) { - x = x * 10 + s[j] - '0'; - if (x > 255 || (j > i && s[i] == '0')) { - break; - } - t.push_back(s.substr(i, j - i + 1)); - dfs(j + 1); - t.pop_back(); - } - }; - dfs(0); - return ans; - } +class Solution { +public: + vector restoreIpAddresses(string s) { + int n = s.size(); + vector ans; + vector t; + function dfs = [&](int i) { + if (i >= n && t.size() == 4) { + ans.push_back(t[0] + "." + t[1] + "." + t[2] + "." + t[3]); + return; + } + if (i >= n || t.size() >= 4) { + return; + } + int x = 0; + for (int j = i; j < min(n, i + 3); ++j) { + x = x * 10 + s[j] - '0'; + if (x > 255 || (j > i && s[i] == '0')) { + break; + } + t.push_back(s.substr(i, j - i + 1)); + dfs(j + 1); + t.pop_back(); + } + }; + dfs(0); + return ans; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0093.Restore IP Addresses/Solution.cs b/solution/0000-0099/0093.Restore IP Addresses/Solution.cs index 366b6d8e64f5a..cad6031422c2b 100644 --- a/solution/0000-0099/0093.Restore IP Addresses/Solution.cs +++ b/solution/0000-0099/0093.Restore IP Addresses/Solution.cs @@ -1,33 +1,33 @@ -public class Solution { - private IList ans = new List(); - private IList t = new List(); - private int n; - private string s; - - public IList RestoreIpAddresses(string s) { - n = s.Length; - this.s = s; - dfs(0); - return ans; - } - - private void dfs(int i) { - if (i >= n && t.Count == 4) { - ans.Add(string.Join(".", t)); - return; - } - if (i >= n || t.Count == 4) { - return; - } - int x = 0; - for (int j = i; j < i + 3 && j < n; ++j) { - x = x * 10 + (s[j] - '0'); - if (x > 255 || (j > i && s[i] == '0')) { - break; - } - t.Add(x.ToString()); - dfs(j + 1); - t.RemoveAt(t.Count - 1); - } - } -} \ No newline at end of file +public class Solution { + private IList ans = new List(); + private IList t = new List(); + private int n; + private string s; + + public IList RestoreIpAddresses(string s) { + n = s.Length; + this.s = s; + dfs(0); + return ans; + } + + private void dfs(int i) { + if (i >= n && t.Count == 4) { + ans.Add(string.Join(".", t)); + return; + } + if (i >= n || t.Count == 4) { + return; + } + int x = 0; + for (int j = i; j < i + 3 && j < n; ++j) { + x = x * 10 + (s[j] - '0'); + if (x > 255 || (j > i && s[i] == '0')) { + break; + } + t.Add(x.ToString()); + dfs(j + 1); + t.RemoveAt(t.Count - 1); + } + } +} diff --git a/solution/0000-0099/0093.Restore IP Addresses/Solution.java b/solution/0000-0099/0093.Restore IP Addresses/Solution.java index 84bd9b8888e9e..1d2033031c387 100644 --- a/solution/0000-0099/0093.Restore IP Addresses/Solution.java +++ b/solution/0000-0099/0093.Restore IP Addresses/Solution.java @@ -1,33 +1,33 @@ -class Solution { - private int n; - private String s; - private List ans = new ArrayList<>(); - private List t = new ArrayList<>(); - - public List restoreIpAddresses(String s) { - n = s.length(); - this.s = s; - dfs(0); - return ans; - } - - private void dfs(int i) { - if (i >= n && t.size() == 4) { - ans.add(String.join(".", t)); - return; - } - if (i >= n || t.size() >= 4) { - return; - } - int x = 0; - for (int j = i; j < Math.min(i + 3, n); ++j) { - x = x * 10 + s.charAt(j) - '0'; - if (x > 255 || (s.charAt(i) == '0' && i != j)) { - break; - } - t.add(s.substring(i, j + 1)); - dfs(j + 1); - t.remove(t.size() - 1); - } - } +class Solution { + private int n; + private String s; + private List ans = new ArrayList<>(); + private List t = new ArrayList<>(); + + public List restoreIpAddresses(String s) { + n = s.length(); + this.s = s; + dfs(0); + return ans; + } + + private void dfs(int i) { + if (i >= n && t.size() == 4) { + ans.add(String.join(".", t)); + return; + } + if (i >= n || t.size() >= 4) { + return; + } + int x = 0; + for (int j = i; j < Math.min(i + 3, n); ++j) { + x = x * 10 + s.charAt(j) - '0'; + if (x > 255 || (s.charAt(i) == '0' && i != j)) { + break; + } + t.add(s.substring(i, j + 1)); + dfs(j + 1); + t.remove(t.size() - 1); + } + } } \ No newline at end of file diff --git a/solution/0000-0099/0093.Restore IP Addresses/Solution.py b/solution/0000-0099/0093.Restore IP Addresses/Solution.py index c7150e6003caa..ec040afb985af 100644 --- a/solution/0000-0099/0093.Restore IP Addresses/Solution.py +++ b/solution/0000-0099/0093.Restore IP Addresses/Solution.py @@ -1,24 +1,24 @@ -class Solution: - def restoreIpAddresses(self, s: str) -> List[str]: - def check(i: int, j: int) -> int: - if s[i] == "0" and i != j: - return False - return 0 <= int(s[i : j + 1]) <= 255 - - def dfs(i: int): - if i >= n and len(t) == 4: - ans.append(".".join(t)) - return - if i >= n or len(t) >= 4: - return - for j in range(i, min(i + 3, n)): - if check(i, j): - t.append(s[i : j + 1]) - dfs(j + 1) - t.pop() - - n = len(s) - ans = [] - t = [] - dfs(0) - return ans +class Solution: + def restoreIpAddresses(self, s: str) -> List[str]: + def check(i: int, j: int) -> int: + if s[i] == "0" and i != j: + return False + return 0 <= int(s[i : j + 1]) <= 255 + + def dfs(i: int): + if i >= n and len(t) == 4: + ans.append(".".join(t)) + return + if i >= n or len(t) >= 4: + return + for j in range(i, min(i + 3, n)): + if check(i, j): + t.append(s[i : j + 1]) + dfs(j + 1) + t.pop() + + n = len(s) + ans = [] + t = [] + dfs(0) + return ans diff --git a/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution.java b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution.java index e8972579d133e..3573745ee1fb5 100644 --- a/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution.java +++ b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution.java @@ -14,27 +14,20 @@ * } */ class Solution { + private List ans; + public List inorderTraversal(TreeNode root) { - List ans = new ArrayList<>(); - while (root != null) { - if (root.left == null) { - ans.add(root.val); - root = root.right; - } else { - TreeNode prev = root.left; - while (prev.right != null && prev.right != root) { - prev = prev.right; - } - if (prev.right == null) { - prev.right = root; - root = root.left; - } else { - ans.add(root.val); - prev.right = null; - root = root.right; - } - } - } + ans = new ArrayList<>(); + dfs(root); return ans; } + + private void dfs(TreeNode root) { + if (root == null) { + return; + } + dfs(root.left); + ans.add(root.val); + dfs(root.right); + } } \ No newline at end of file diff --git a/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution.js b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution.js index 63270cb4b8fb6..5389a6d16b151 100644 --- a/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution.js +++ b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution.js @@ -12,24 +12,12 @@ */ var inorderTraversal = function (root) { let ans = []; - while (root) { - if (!root.left) { - ans.push(root.val); - root = root.right; - } else { - let prev = root.left; - while (prev.right && prev.right != root) { - prev = prev.right; - } - if (!prev.right) { - prev.right = root; - root = root.left; - } else { - ans.push(root.val); - prev.right = null; - root = root.right; - } - } + function dfs(root) { + if (!root) return; + dfs(root.left); + ans.push(root.val); + dfs(root.right); } + dfs(root); return ans; }; diff --git a/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution.py b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution.py index 27a7a55ff7104..7a383bea3c861 100644 --- a/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution.py +++ b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution.py @@ -6,20 +6,14 @@ # self.right = right class Solution: def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + def dfs(root): + if root is None: + return + dfs(root.left) + nonlocal ans + ans.append(root.val) + dfs(root.right) + ans = [] - while root: - if root.left is None: - ans.append(root.val) - root = root.right - else: - prev = root.left - while prev.right and prev.right != root: - prev = prev.right - if prev.right is None: - prev.right = root - root = root.left - else: - ans.append(root.val) - prev.right = None - root = root.right + dfs(root) return ans diff --git a/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution2.java b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution2.java new file mode 100644 index 0000000000000..90bf28ece5e3d --- /dev/null +++ b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution2.java @@ -0,0 +1,32 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List inorderTraversal(TreeNode root) { + List ans = new ArrayList<>(); + Deque stk = new ArrayDeque<>(); + while (root != null || !stk.isEmpty()) { + if (root != null) { + stk.push(root); + root = root.left; + } else { + root = stk.pop(); + ans.add(root.val); + root = root.right; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution2.js b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution2.js new file mode 100644 index 0000000000000..d8361d88e5d33 --- /dev/null +++ b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution2.js @@ -0,0 +1,27 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var inorderTraversal = function (root) { + let ans = [], + stk = []; + while (root || stk.length > 0) { + if (root) { + stk.push(root); + root = root.left; + } else { + root = stk.pop(); + ans.push(root.val); + root = root.right; + } + } + return ans; +}; diff --git a/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution2.py b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution2.py new file mode 100644 index 0000000000000..c2d013b673480 --- /dev/null +++ b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution2.py @@ -0,0 +1,18 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans, stk = [], [] + while root or stk: + if root: + stk.append(root) + root = root.left + else: + root = stk.pop() + ans.append(root.val) + root = root.right + return ans diff --git a/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution2.rs b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution2.rs new file mode 100644 index 0000000000000..4c34874305b14 --- /dev/null +++ b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution2.rs @@ -0,0 +1,39 @@ +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn inorder_traversal(mut root: Option>>) -> Vec { + let mut res = vec![]; + let mut stack = vec![]; + while root.is_some() || !stack.is_empty() { + if root.is_some() { + let next = root.as_mut().unwrap().borrow_mut().left.take(); + stack.push(root); + root = next; + } else { + let mut node = stack.pop().unwrap(); + let mut node = node.as_mut().unwrap().borrow_mut(); + res.push(node.val); + root = node.right.take(); + } + } + res + } +} diff --git a/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution2.ts b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution2.ts new file mode 100644 index 0000000000000..d32be441be54b --- /dev/null +++ b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution2.ts @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function inorderTraversal(root: TreeNode | null): number[] { + const res = []; + const stack = []; + while (root != null || stack.length != 0) { + if (root != null) { + stack.push(root); + root = root.left; + } else { + const { val, right } = stack.pop(); + res.push(val); + root = right; + } + } + return res; +} diff --git a/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution3.java b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution3.java new file mode 100644 index 0000000000000..e8972579d133e --- /dev/null +++ b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution3.java @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List inorderTraversal(TreeNode root) { + List ans = new ArrayList<>(); + while (root != null) { + if (root.left == null) { + ans.add(root.val); + root = root.right; + } else { + TreeNode prev = root.left; + while (prev.right != null && prev.right != root) { + prev = prev.right; + } + if (prev.right == null) { + prev.right = root; + root = root.left; + } else { + ans.add(root.val); + prev.right = null; + root = root.right; + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution3.js b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution3.js new file mode 100644 index 0000000000000..63270cb4b8fb6 --- /dev/null +++ b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution3.js @@ -0,0 +1,35 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var inorderTraversal = function (root) { + let ans = []; + while (root) { + if (!root.left) { + ans.push(root.val); + root = root.right; + } else { + let prev = root.left; + while (prev.right && prev.right != root) { + prev = prev.right; + } + if (!prev.right) { + prev.right = root; + root = root.left; + } else { + ans.push(root.val); + prev.right = null; + root = root.right; + } + } + } + return ans; +}; diff --git a/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution3.py b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution3.py new file mode 100644 index 0000000000000..27a7a55ff7104 --- /dev/null +++ b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution3.py @@ -0,0 +1,25 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + while root: + if root.left is None: + ans.append(root.val) + root = root.right + else: + prev = root.left + while prev.right and prev.right != root: + prev = prev.right + if prev.right is None: + prev.right = root + root = root.left + else: + ans.append(root.val) + prev.right = None + root = root.right + return ans diff --git a/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution3.ts b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution3.ts new file mode 100644 index 0000000000000..db7e6ac32228d --- /dev/null +++ b/solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution3.ts @@ -0,0 +1,38 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function inorderTraversal(root: TreeNode | null): number[] { + const res = []; + while (root != null) { + const { val, left, right } = root; + if (left == null) { + res.push(val); + root = right; + } else { + let mostRight = left; + while (mostRight.right != null && mostRight.right != root) { + mostRight = mostRight.right; + } + if (mostRight.right == root) { + res.push(val); + mostRight.right = null; + root = right; + } else { + mostRight.right = root; + root = left; + } + } + } + return res; +} diff --git a/solution/0000-0099/0095.Unique Binary Search Trees II/Solution.cpp b/solution/0000-0099/0095.Unique Binary Search Trees II/Solution.cpp index 4f362fd516f63..c501214ce6c05 100644 --- a/solution/0000-0099/0095.Unique Binary Search Trees II/Solution.cpp +++ b/solution/0000-0099/0095.Unique Binary Search Trees II/Solution.cpp @@ -1,33 +1,33 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - vector generateTrees(int n) { - function(int, int)> dfs = [&](int i, int j) { - if (i > j) { - return vector{nullptr}; - } - vector ans; - for (int v = i; v <= j; ++v) { - auto left = dfs(i, v - 1); - auto right = dfs(v + 1, j); - for (auto l : left) { - for (auto r : right) { - ans.push_back(new TreeNode(v, l, r)); - } - } - } - return ans; - }; - return dfs(1, n); - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector generateTrees(int n) { + function(int, int)> dfs = [&](int i, int j) { + if (i > j) { + return vector{nullptr}; + } + vector ans; + for (int v = i; v <= j; ++v) { + auto left = dfs(i, v - 1); + auto right = dfs(v + 1, j); + for (auto l : left) { + for (auto r : right) { + ans.push_back(new TreeNode(v, l, r)); + } + } + } + return ans; + }; + return dfs(1, n); + } }; \ No newline at end of file diff --git a/solution/0000-0099/0095.Unique Binary Search Trees II/Solution.java b/solution/0000-0099/0095.Unique Binary Search Trees II/Solution.java index 94c1c81e49f58..50ecb184b0f0c 100644 --- a/solution/0000-0099/0095.Unique Binary Search Trees II/Solution.java +++ b/solution/0000-0099/0095.Unique Binary Search Trees II/Solution.java @@ -1,38 +1,38 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public List generateTrees(int n) { - return dfs(1, n); - } - - private List dfs(int i, int j) { - List ans = new ArrayList<>(); - if (i > j) { - ans.add(null); - return ans; - } - for (int v = i; v <= j; ++v) { - var left = dfs(i, v - 1); - var right = dfs(v + 1, j); - for (var l : left) { - for (var r : right) { - ans.add(new TreeNode(v, l, r)); - } - } - } - return ans; - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List generateTrees(int n) { + return dfs(1, n); + } + + private List dfs(int i, int j) { + List ans = new ArrayList<>(); + if (i > j) { + ans.add(null); + return ans; + } + for (int v = i; v <= j; ++v) { + var left = dfs(i, v - 1); + var right = dfs(v + 1, j); + for (var l : left) { + for (var r : right) { + ans.add(new TreeNode(v, l, r)); + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0000-0099/0095.Unique Binary Search Trees II/Solution.py b/solution/0000-0099/0095.Unique Binary Search Trees II/Solution.py index 19f94c8c32f62..4b85a3980041e 100644 --- a/solution/0000-0099/0095.Unique Binary Search Trees II/Solution.py +++ b/solution/0000-0099/0095.Unique Binary Search Trees II/Solution.py @@ -1,21 +1,21 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def generateTrees(self, n: int) -> List[Optional[TreeNode]]: - def dfs(i: int, j: int) -> List[Optional[TreeNode]]: - if i > j: - return [None] - ans = [] - for v in range(i, j + 1): - left = dfs(i, v - 1) - right = dfs(v + 1, j) - for l in left: - for r in right: - ans.append(TreeNode(v, l, r)) - return ans - - return dfs(1, n) +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def generateTrees(self, n: int) -> List[Optional[TreeNode]]: + def dfs(i: int, j: int) -> List[Optional[TreeNode]]: + if i > j: + return [None] + ans = [] + for v in range(i, j + 1): + left = dfs(i, v - 1) + right = dfs(v + 1, j) + for l in left: + for r in right: + ans.append(TreeNode(v, l, r)) + return ans + + return dfs(1, n) diff --git a/solution/0000-0099/0096.Unique Binary Search Trees/Solution.cpp b/solution/0000-0099/0096.Unique Binary Search Trees/Solution.cpp index ea316145a9ce5..dc2f8de159c8c 100644 --- a/solution/0000-0099/0096.Unique Binary Search Trees/Solution.cpp +++ b/solution/0000-0099/0096.Unique Binary Search Trees/Solution.cpp @@ -1,13 +1,13 @@ -class Solution { -public: - int numTrees(int n) { - vector f(n + 1); - f[0] = 1; - for (int i = 1; i <= n; ++i) { - for (int j = 0; j < i; ++j) { - f[i] += f[j] * f[i - j - 1]; - } - } - return f[n]; - } +class Solution { +public: + int numTrees(int n) { + vector f(n + 1); + f[0] = 1; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < i; ++j) { + f[i] += f[j] * f[i - j - 1]; + } + } + return f[n]; + } }; \ No newline at end of file diff --git a/solution/0000-0099/0096.Unique Binary Search Trees/Solution.cs b/solution/0000-0099/0096.Unique Binary Search Trees/Solution.cs index 4e9a6eea897f6..f4192e1497c6c 100644 --- a/solution/0000-0099/0096.Unique Binary Search Trees/Solution.cs +++ b/solution/0000-0099/0096.Unique Binary Search Trees/Solution.cs @@ -1,12 +1,12 @@ -public class Solution { - public int NumTrees(int n) { - int[] f = new int[n + 1]; - f[0] = 1; - for (int i = 1; i <= n; ++i) { - for (int j = 0; j < i; ++j) { - f[i] += f[j] * f[i - j - 1]; - } - } - return f[n]; - } -} \ No newline at end of file +public class Solution { + public int NumTrees(int n) { + int[] f = new int[n + 1]; + f[0] = 1; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < i; ++j) { + f[i] += f[j] * f[i - j - 1]; + } + } + return f[n]; + } +} diff --git a/solution/0000-0099/0096.Unique Binary Search Trees/Solution.java b/solution/0000-0099/0096.Unique Binary Search Trees/Solution.java index 3a7a196f25540..f31ec96a9babf 100644 --- a/solution/0000-0099/0096.Unique Binary Search Trees/Solution.java +++ b/solution/0000-0099/0096.Unique Binary Search Trees/Solution.java @@ -1,12 +1,12 @@ -class Solution { - public int numTrees(int n) { - int[] f = new int[n + 1]; - f[0] = 1; - for (int i = 1; i <= n; ++i) { - for (int j = 0; j < i; ++j) { - f[i] += f[j] * f[i - j - 1]; - } - } - return f[n]; - } +class Solution { + public int numTrees(int n) { + int[] f = new int[n + 1]; + f[0] = 1; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < i; ++j) { + f[i] += f[j] * f[i - j - 1]; + } + } + return f[n]; + } } \ No newline at end of file diff --git a/solution/0000-0099/0096.Unique Binary Search Trees/Solution.py b/solution/0000-0099/0096.Unique Binary Search Trees/Solution.py index 16dd7e1a5391d..f839152df3fc7 100644 --- a/solution/0000-0099/0096.Unique Binary Search Trees/Solution.py +++ b/solution/0000-0099/0096.Unique Binary Search Trees/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def numTrees(self, n: int) -> int: - f = [1] + [0] * n - for i in range(n + 1): - for j in range(i): - f[i] += f[j] * f[i - j - 1] - return f[n] +class Solution: + def numTrees(self, n: int) -> int: + f = [1] + [0] * n + for i in range(n + 1): + for j in range(i): + f[i] += f[j] * f[i - j - 1] + return f[n] diff --git a/solution/0000-0099/0097.Interleaving String/Solution.cpp b/solution/0000-0099/0097.Interleaving String/Solution.cpp index 352af91c98b82..8847e9660235c 100644 --- a/solution/0000-0099/0097.Interleaving String/Solution.cpp +++ b/solution/0000-0099/0097.Interleaving String/Solution.cpp @@ -5,20 +5,24 @@ class Solution { if (m + n != s3.size()) { return false; } - bool f[n + 1]; - memset(f, false, sizeof(f)); - f[0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - int k = i + j - 1; - if (i) { - f[j] &= s1[i - 1] == s3[k]; - } - if (j) { - f[j] |= (s2[j - 1] == s3[k] && f[j - 1]); - } + vector> f(m + 1, vector(n + 1, -1)); + function dfs = [&](int i, int j) { + if (i >= m && j >= n) { + return true; } - } - return f[n]; + if (f[i][j] != -1) { + return f[i][j] == 1; + } + f[i][j] = 0; + int k = i + j; + if (i < m && s1[i] == s3[k] && dfs(i + 1, j)) { + f[i][j] = 1; + } + if (!f[i][j] && j < n && s2[j] == s3[k] && dfs(i, j + 1)) { + f[i][j] = 1; + } + return f[i][j] == 1; + }; + return dfs(0, 0); } }; \ No newline at end of file diff --git a/solution/0000-0099/0097.Interleaving String/Solution.cs b/solution/0000-0099/0097.Interleaving String/Solution.cs index b930965b32f7d..32a77cdd6bbf4 100644 --- a/solution/0000-0099/0097.Interleaving String/Solution.cs +++ b/solution/0000-0099/0097.Interleaving String/Solution.cs @@ -1,22 +1,38 @@ public class Solution { + private int m; + private int n; + private string s1; + private string s2; + private string s3; + private int[,] f; + public bool IsInterleave(string s1, string s2, string s3) { - int m = s1.Length, n = s2.Length; + m = s1.Length; + n = s2.Length; if (m + n != s3.Length) { return false; } - bool[] f = new bool[n + 1]; - f[0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - int k = i + j - 1; - if (i > 0) { - f[j] &= s1[i - 1] == s3[k]; - } - if (j > 0) { - f[j] |= (f[j - 1] & s2[j - 1] == s3[k]); - } - } + this.s1 = s1; + this.s2 = s2; + this.s3 = s3; + f = new int[m + 1, n + 1]; + return dfs(0, 0); + } + + private bool dfs(int i, int j) { + if (i >= m && j >= n) { + return true; + } + if (f[i, j] != 0) { + return f[i, j] == 1; + } + f[i, j] = -1; + if (i < m && s1[i] == s3[i + j] && dfs(i + 1, j)) { + f[i, j] = 1; + } + if (f[i, j] == -1 && j < n && s2[j] == s3[i + j] && dfs(i, j + 1)) { + f[i, j] = 1; } - return f[n]; + return f[i, j] == 1; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0097.Interleaving String/Solution.go b/solution/0000-0099/0097.Interleaving String/Solution.go index 6edbffd1c3cbf..a244bee4934da 100644 --- a/solution/0000-0099/0097.Interleaving String/Solution.go +++ b/solution/0000-0099/0097.Interleaving String/Solution.go @@ -3,18 +3,19 @@ func isInterleave(s1 string, s2 string, s3 string) bool { if m+n != len(s3) { return false } - f := make([]bool, n+1) - f[0] = true - for i := 0; i <= m; i++ { - for j := 0; j <= n; j++ { - k := i + j - 1 - if i > 0 { - f[j] = (f[j] && s1[i-1] == s3[k]) - } - if j > 0 { - f[j] = (f[j] || (s2[j-1] == s3[k] && f[j-1])) - } + + f := map[int]bool{} + var dfs func(int, int) bool + dfs = func(i, j int) bool { + if i >= m && j >= n { + return true } + if v, ok := f[i*200+j]; ok { + return v + } + k := i + j + f[i*200+j] = (i < m && s1[i] == s3[k] && dfs(i+1, j)) || (j < n && s2[j] == s3[k] && dfs(i, j+1)) + return f[i*200+j] } - return f[n] + return dfs(0, 0) } \ No newline at end of file diff --git a/solution/0000-0099/0097.Interleaving String/Solution.java b/solution/0000-0099/0097.Interleaving String/Solution.java index f60c0122b4e95..f831ee066ef61 100644 --- a/solution/0000-0099/0097.Interleaving String/Solution.java +++ b/solution/0000-0099/0097.Interleaving String/Solution.java @@ -1,22 +1,40 @@ class Solution { + private Map, Boolean> f = new HashMap<>(); + private String s1; + private String s2; + private String s3; + private int m; + private int n; + public boolean isInterleave(String s1, String s2, String s3) { - int m = s1.length(), n = s2.length(); + m = s1.length(); + n = s2.length(); if (m + n != s3.length()) { return false; } - boolean[] f = new boolean[n + 1]; - f[0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - int k = i + j - 1; - if (i > 0) { - f[j] &= s1.charAt(i - 1) == s3.charAt(k); - } - if (j > 0) { - f[j] |= (f[j - 1] & s2.charAt(j - 1) == s3.charAt(k)); - } - } + this.s1 = s1; + this.s2 = s2; + this.s3 = s3; + return dfs(0, 0); + } + + private boolean dfs(int i, int j) { + if (i >= m && j >= n) { + return true; + } + var key = List.of(i, j); + if (f.containsKey(key)) { + return f.get(key); + } + int k = i + j; + boolean ans = false; + if (i < m && s1.charAt(i) == s3.charAt(k) && dfs(i + 1, j)) { + ans = true; + } + if (!ans && j < n && s2.charAt(j) == s3.charAt(k) && dfs(i, j + 1)) { + ans = true; } - return f[n]; + f.put(key, ans); + return ans; } } \ No newline at end of file diff --git a/solution/0000-0099/0097.Interleaving String/Solution.py b/solution/0000-0099/0097.Interleaving String/Solution.py index 1f17ed5709878..b79604f1ea770 100644 --- a/solution/0000-0099/0097.Interleaving String/Solution.py +++ b/solution/0000-0099/0097.Interleaving String/Solution.py @@ -1,14 +1,17 @@ class Solution: def isInterleave(self, s1: str, s2: str, s3: str) -> bool: + @cache + def dfs(i: int, j: int) -> bool: + if i >= m and j >= n: + return True + k = i + j + if i < m and s1[i] == s3[k] and dfs(i + 1, j): + return True + if j < n and s2[j] == s3[k] and dfs(i, j + 1): + return True + return False + m, n = len(s1), len(s2) if m + n != len(s3): return False - f = [True] + [False] * n - for i in range(m + 1): - for j in range(n + 1): - k = i + j - 1 - if i: - f[j] &= s1[i - 1] == s3[k] - if j: - f[j] |= f[j - 1] and s2[j - 1] == s3[k] - return f[n] + return dfs(0, 0) diff --git a/solution/0000-0099/0097.Interleaving String/Solution.ts b/solution/0000-0099/0097.Interleaving String/Solution.ts index 04b168eedfda8..3469ba561a219 100644 --- a/solution/0000-0099/0097.Interleaving String/Solution.ts +++ b/solution/0000-0099/0097.Interleaving String/Solution.ts @@ -4,18 +4,22 @@ function isInterleave(s1: string, s2: string, s3: string): boolean { if (m + n !== s3.length) { return false; } - const f: boolean[] = new Array(n + 1).fill(false); - f[0] = true; - for (let i = 0; i <= m; ++i) { - for (let j = 0; j <= n; ++j) { - const k = i + j - 1; - if (i) { - f[j] = f[j] && s1[i - 1] === s3[k]; - } - if (j) { - f[j] = f[j] || (f[j - 1] && s2[j - 1] === s3[k]); - } + const f: number[][] = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); + const dfs = (i: number, j: number): boolean => { + if (i >= m && j >= n) { + return true; } - } - return f[n]; + if (f[i][j]) { + return f[i][j] === 1; + } + f[i][j] = -1; + if (i < m && s1[i] === s3[i + j] && dfs(i + 1, j)) { + f[i][j] = 1; + } + if (f[i][j] === -1 && j < n && s2[j] === s3[i + j] && dfs(i, j + 1)) { + f[i][j] = 1; + } + return f[i][j] === 1; + }; + return dfs(0, 0); } diff --git a/solution/0000-0099/0097.Interleaving String/Solution2.cpp b/solution/0000-0099/0097.Interleaving String/Solution2.cpp new file mode 100644 index 0000000000000..a88428e3b1f3d --- /dev/null +++ b/solution/0000-0099/0097.Interleaving String/Solution2.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + bool isInterleave(string s1, string s2, string s3) { + int m = s1.size(), n = s2.size(); + if (m + n != s3.size()) { + return false; + } + bool f[m + 1][n + 1]; + memset(f, false, sizeof(f)); + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0 && s1[i - 1] == s3[k]) { + f[i][j] = f[i - 1][j]; + } + if (j > 0 && s2[j - 1] == s3[k]) { + f[i][j] |= f[i][j - 1]; + } + } + } + return f[m][n]; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0097.Interleaving String/Solution2.cs b/solution/0000-0099/0097.Interleaving String/Solution2.cs new file mode 100644 index 0000000000000..04ab33e811624 --- /dev/null +++ b/solution/0000-0099/0097.Interleaving String/Solution2.cs @@ -0,0 +1,22 @@ +public class Solution { + public bool IsInterleave(string s1, string s2, string s3) { + int m = s1.Length, n = s2.Length; + if (m + n != s3.Length) { + return false; + } + bool[,] f = new bool[m + 1, n + 1]; + f[0, 0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0 && s1[i - 1] == s3[k]) { + f[i, j] = f[i - 1, j]; + } + if (j > 0 && s2[j - 1] == s3[k]) { + f[i, j] |= f[i, j - 1]; + } + } + } + return f[m, n]; + } +} diff --git a/solution/0000-0099/0097.Interleaving String/Solution2.go b/solution/0000-0099/0097.Interleaving String/Solution2.go new file mode 100644 index 0000000000000..183596d1ba535 --- /dev/null +++ b/solution/0000-0099/0097.Interleaving String/Solution2.go @@ -0,0 +1,23 @@ +func isInterleave(s1 string, s2 string, s3 string) bool { + m, n := len(s1), len(s2) + if m+n != len(s3) { + return false + } + f := make([][]bool, m+1) + for i := range f { + f[i] = make([]bool, n+1) + } + f[0][0] = true + for i := 0; i <= m; i++ { + for j := 0; j <= n; j++ { + k := i + j - 1 + if i > 0 && s1[i-1] == s3[k] { + f[i][j] = f[i-1][j] + } + if j > 0 && s2[j-1] == s3[k] { + f[i][j] = (f[i][j] || f[i][j-1]) + } + } + } + return f[m][n] +} \ No newline at end of file diff --git a/solution/0000-0099/0097.Interleaving String/Solution2.java b/solution/0000-0099/0097.Interleaving String/Solution2.java new file mode 100644 index 0000000000000..5808f488cfaab --- /dev/null +++ b/solution/0000-0099/0097.Interleaving String/Solution2.java @@ -0,0 +1,22 @@ +class Solution { + public boolean isInterleave(String s1, String s2, String s3) { + int m = s1.length(), n = s2.length(); + if (m + n != s3.length()) { + return false; + } + boolean[][] f = new boolean[m + 1][n + 1]; + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0 && s1.charAt(i - 1) == s3.charAt(k)) { + f[i][j] = f[i - 1][j]; + } + if (j > 0 && s2.charAt(j - 1) == s3.charAt(k)) { + f[i][j] |= f[i][j - 1]; + } + } + } + return f[m][n]; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0097.Interleaving String/Solution2.py b/solution/0000-0099/0097.Interleaving String/Solution2.py new file mode 100644 index 0000000000000..8e164d25cb14f --- /dev/null +++ b/solution/0000-0099/0097.Interleaving String/Solution2.py @@ -0,0 +1,15 @@ +class Solution: + def isInterleave(self, s1: str, s2: str, s3: str) -> bool: + m, n = len(s1), len(s2) + if m + n != len(s3): + return False + f = [[False] * (n + 1) for _ in range(m + 1)] + f[0][0] = True + for i in range(m + 1): + for j in range(n + 1): + k = i + j - 1 + if i and s1[i - 1] == s3[k]: + f[i][j] = f[i - 1][j] + if j and s2[j - 1] == s3[k]: + f[i][j] |= f[i][j - 1] + return f[m][n] diff --git a/solution/0000-0099/0097.Interleaving String/Solution2.ts b/solution/0000-0099/0097.Interleaving String/Solution2.ts new file mode 100644 index 0000000000000..5c1cb78bf8ec1 --- /dev/null +++ b/solution/0000-0099/0097.Interleaving String/Solution2.ts @@ -0,0 +1,21 @@ +function isInterleave(s1: string, s2: string, s3: string): boolean { + const m = s1.length; + const n = s2.length; + if (m + n !== s3.length) { + return false; + } + const f: boolean[][] = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(false)); + f[0][0] = true; + for (let i = 0; i <= m; ++i) { + for (let j = 0; j <= n; ++j) { + const k = i + j - 1; + if (i > 0 && s1[i - 1] === s3[k]) { + f[i][j] = f[i - 1][j]; + } + if (j > 0 && s2[j - 1] === s3[k]) { + f[i][j] = f[i][j] || f[i][j - 1]; + } + } + } + return f[m][n]; +} diff --git a/solution/0000-0099/0097.Interleaving String/Solution3.cpp b/solution/0000-0099/0097.Interleaving String/Solution3.cpp new file mode 100644 index 0000000000000..352af91c98b82 --- /dev/null +++ b/solution/0000-0099/0097.Interleaving String/Solution3.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + bool isInterleave(string s1, string s2, string s3) { + int m = s1.size(), n = s2.size(); + if (m + n != s3.size()) { + return false; + } + bool f[n + 1]; + memset(f, false, sizeof(f)); + f[0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i) { + f[j] &= s1[i - 1] == s3[k]; + } + if (j) { + f[j] |= (s2[j - 1] == s3[k] && f[j - 1]); + } + } + } + return f[n]; + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0097.Interleaving String/Solution3.cs b/solution/0000-0099/0097.Interleaving String/Solution3.cs new file mode 100644 index 0000000000000..1dba3cca4cdce --- /dev/null +++ b/solution/0000-0099/0097.Interleaving String/Solution3.cs @@ -0,0 +1,22 @@ +public class Solution { + public bool IsInterleave(string s1, string s2, string s3) { + int m = s1.Length, n = s2.Length; + if (m + n != s3.Length) { + return false; + } + bool[] f = new bool[n + 1]; + f[0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0) { + f[j] &= s1[i - 1] == s3[k]; + } + if (j > 0) { + f[j] |= (f[j - 1] & s2[j - 1] == s3[k]); + } + } + } + return f[n]; + } +} diff --git a/solution/0000-0099/0097.Interleaving String/Solution3.go b/solution/0000-0099/0097.Interleaving String/Solution3.go new file mode 100644 index 0000000000000..6edbffd1c3cbf --- /dev/null +++ b/solution/0000-0099/0097.Interleaving String/Solution3.go @@ -0,0 +1,20 @@ +func isInterleave(s1 string, s2 string, s3 string) bool { + m, n := len(s1), len(s2) + if m+n != len(s3) { + return false + } + f := make([]bool, n+1) + f[0] = true + for i := 0; i <= m; i++ { + for j := 0; j <= n; j++ { + k := i + j - 1 + if i > 0 { + f[j] = (f[j] && s1[i-1] == s3[k]) + } + if j > 0 { + f[j] = (f[j] || (s2[j-1] == s3[k] && f[j-1])) + } + } + } + return f[n] +} \ No newline at end of file diff --git a/solution/0000-0099/0097.Interleaving String/Solution3.java b/solution/0000-0099/0097.Interleaving String/Solution3.java new file mode 100644 index 0000000000000..f60c0122b4e95 --- /dev/null +++ b/solution/0000-0099/0097.Interleaving String/Solution3.java @@ -0,0 +1,22 @@ +class Solution { + public boolean isInterleave(String s1, String s2, String s3) { + int m = s1.length(), n = s2.length(); + if (m + n != s3.length()) { + return false; + } + boolean[] f = new boolean[n + 1]; + f[0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0) { + f[j] &= s1.charAt(i - 1) == s3.charAt(k); + } + if (j > 0) { + f[j] |= (f[j - 1] & s2.charAt(j - 1) == s3.charAt(k)); + } + } + } + return f[n]; + } +} \ No newline at end of file diff --git a/solution/0000-0099/0097.Interleaving String/Solution3.py b/solution/0000-0099/0097.Interleaving String/Solution3.py new file mode 100644 index 0000000000000..1f17ed5709878 --- /dev/null +++ b/solution/0000-0099/0097.Interleaving String/Solution3.py @@ -0,0 +1,14 @@ +class Solution: + def isInterleave(self, s1: str, s2: str, s3: str) -> bool: + m, n = len(s1), len(s2) + if m + n != len(s3): + return False + f = [True] + [False] * n + for i in range(m + 1): + for j in range(n + 1): + k = i + j - 1 + if i: + f[j] &= s1[i - 1] == s3[k] + if j: + f[j] |= f[j - 1] and s2[j - 1] == s3[k] + return f[n] diff --git a/solution/0000-0099/0097.Interleaving String/Solution3.ts b/solution/0000-0099/0097.Interleaving String/Solution3.ts new file mode 100644 index 0000000000000..04b168eedfda8 --- /dev/null +++ b/solution/0000-0099/0097.Interleaving String/Solution3.ts @@ -0,0 +1,21 @@ +function isInterleave(s1: string, s2: string, s3: string): boolean { + const m = s1.length; + const n = s2.length; + if (m + n !== s3.length) { + return false; + } + const f: boolean[] = new Array(n + 1).fill(false); + f[0] = true; + for (let i = 0; i <= m; ++i) { + for (let j = 0; j <= n; ++j) { + const k = i + j - 1; + if (i) { + f[j] = f[j] && s1[i - 1] === s3[k]; + } + if (j) { + f[j] = f[j] || (f[j - 1] && s2[j - 1] === s3[k]); + } + } + } + return f[n]; +} diff --git a/solution/0000-0099/0098.Validate Binary Search Tree/Solution.cs b/solution/0000-0099/0098.Validate Binary Search Tree/Solution.cs index 37537168a3a97..1a45e1b8f2648 100644 --- a/solution/0000-0099/0098.Validate Binary Search Tree/Solution.cs +++ b/solution/0000-0099/0098.Validate Binary Search Tree/Solution.cs @@ -39,4 +39,4 @@ private bool dfs(TreeNode root) { } return true; } -} \ No newline at end of file +} diff --git a/solution/0000-0099/0098.Validate Binary Search Tree/Solution.py b/solution/0000-0099/0098.Validate Binary Search Tree/Solution.py index 0c600a0acf62a..a31d683436812 100644 --- a/solution/0000-0099/0098.Validate Binary Search Tree/Solution.py +++ b/solution/0000-0099/0098.Validate Binary Search Tree/Solution.py @@ -5,7 +5,7 @@ # self.left = left # self.right = right class Solution: - def isValidBST(self, root: TreeNode) -> bool: + def isValidBST(self, root: Optional[TreeNode]) -> bool: def dfs(root): nonlocal prev if root is None: diff --git a/solution/0000-0099/0098.Validate Binary Search Tree/Solution2.cpp b/solution/0000-0099/0098.Validate Binary Search Tree/Solution2.cpp new file mode 100644 index 0000000000000..f8576b4d71d23 --- /dev/null +++ b/solution/0000-0099/0098.Validate Binary Search Tree/Solution2.cpp @@ -0,0 +1,23 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isValidBST(TreeNode* root) { + return dfs(root, LONG_MIN, LONG_MAX); + } + + bool dfs(TreeNode* root, long long l, long long r) { + if (!root) return true; + if (root->val <= l || root->val >= r) return false; + return dfs(root->left, l, root->val) && dfs(root->right, root->val, r); + } +}; \ No newline at end of file diff --git a/solution/0000-0099/0098.Validate Binary Search Tree/Solution2.cs b/solution/0000-0099/0098.Validate Binary Search Tree/Solution2.cs new file mode 100644 index 0000000000000..53723ebe79c07 --- /dev/null +++ b/solution/0000-0099/0098.Validate Binary Search Tree/Solution2.cs @@ -0,0 +1,28 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + public bool IsValidBST(TreeNode root) { + return dfs(root, long.MinValue, long.MaxValue); + } + + public bool dfs(TreeNode root, long l, long r) { + if (root == null) { + return true; + } + if (root.val <= l || root.val >= r) { + return false; + } + return dfs(root.left, l, root.val) && dfs(root.right, root.val, r); + } +} diff --git a/solution/0000-0099/0098.Validate Binary Search Tree/Solution2.go b/solution/0000-0099/0098.Validate Binary Search Tree/Solution2.go new file mode 100644 index 0000000000000..a7cc3f17529bb --- /dev/null +++ b/solution/0000-0099/0098.Validate Binary Search Tree/Solution2.go @@ -0,0 +1,22 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func isValidBST(root *TreeNode) bool { + return dfs(root, math.MinInt64, math.MaxInt64) +} + +func dfs(root *TreeNode, l, r int64) bool { + if root == nil { + return true + } + v := int64(root.Val) + if v <= l || v >= r { + return false + } + return dfs(root.Left, l, v) && dfs(root.Right, v, r) +} \ No newline at end of file diff --git a/solution/0000-0099/0098.Validate Binary Search Tree/Solution2.java b/solution/0000-0099/0098.Validate Binary Search Tree/Solution2.java new file mode 100644 index 0000000000000..c4e27728bb0e6 --- /dev/null +++ b/solution/0000-0099/0098.Validate Binary Search Tree/Solution2.java @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean isValidBST(TreeNode root) { + return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE); + } + + private boolean dfs(TreeNode root, long l, long r) { + if (root == null) { + return true; + } + if (root.val <= l || root.val >= r) { + return false; + } + return dfs(root.left, l, root.val) && dfs(root.right, root.val, r); + } +} \ No newline at end of file diff --git a/solution/0000-0099/0098.Validate Binary Search Tree/Solution2.js b/solution/0000-0099/0098.Validate Binary Search Tree/Solution2.js new file mode 100644 index 0000000000000..5ba987359a6f0 --- /dev/null +++ b/solution/0000-0099/0098.Validate Binary Search Tree/Solution2.js @@ -0,0 +1,24 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ +var isValidBST = function (root) { + function dfs(root, l, r) { + if (!root) { + return true; + } + if (root.val <= l || root.val >= r) { + return false; + } + return dfs(root.left, l, root.val) && dfs(root.right, root.val, r); + } + return dfs(root, -Infinity, Infinity); +}; diff --git a/solution/0000-0099/0098.Validate Binary Search Tree/Solution2.py b/solution/0000-0099/0098.Validate Binary Search Tree/Solution2.py new file mode 100644 index 0000000000000..057d2f023c018 --- /dev/null +++ b/solution/0000-0099/0098.Validate Binary Search Tree/Solution2.py @@ -0,0 +1,16 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isValidBST(self, root: Optional[TreeNode]) -> bool: + def dfs(root, l, r): + if root is None: + return True + if root.val <= l or root.val >= r: + return False + return dfs(root.left, l, root.val) and dfs(root.right, root.val, r) + + return dfs(root, -inf, inf) diff --git a/solution/0000-0099/0099.Recover Binary Search Tree/Solution.cs b/solution/0000-0099/0099.Recover Binary Search Tree/Solution.cs index 0f2432985ae8b..4b1d572557b9f 100644 --- a/solution/0000-0099/0099.Recover Binary Search Tree/Solution.cs +++ b/solution/0000-0099/0099.Recover Binary Search Tree/Solution.cs @@ -35,4 +35,4 @@ private void dfs(TreeNode root) { prev = root; dfs(root.right); } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0100.Same Tree/Solution.php b/solution/0100-0199/0100.Same Tree/Solution.php index 73c9418c7f388..ef802ed843986 100644 --- a/solution/0100-0199/0100.Same Tree/Solution.php +++ b/solution/0100-0199/0100.Same Tree/Solution.php @@ -29,4 +29,4 @@ function isSameTree($p, $q) { } return $this->isSameTree($p->left, $q->left) && $this->isSameTree($p->right, $q->right); } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0100.Same Tree/Solution2.cpp b/solution/0100-0199/0100.Same Tree/Solution2.cpp new file mode 100644 index 0000000000000..10e5f102a9bc2 --- /dev/null +++ b/solution/0100-0199/0100.Same Tree/Solution2.cpp @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isSameTree(TreeNode* p, TreeNode* q) { + if (p == q) return true; + if (!p || !q) return false; + queue q1{{p}}; + queue q2{{q}}; + while (!q1.empty() && !q2.empty()) { + p = q1.front(); + q = q2.front(); + if (p->val != q->val) return false; + q1.pop(); + q2.pop(); + TreeNode *la = p->left, *ra = p->right; + TreeNode *lb = q->left, *rb = q->right; + if ((la && !lb) || (lb && !la)) return false; + if ((ra && !rb) || (rb && !ra)) return false; + if (la) { + q1.push(la); + q2.push(lb); + } + if (ra) { + q1.push(ra); + q2.push(rb); + } + } + return true; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0100.Same Tree/Solution2.go b/solution/0100-0199/0100.Same Tree/Solution2.go new file mode 100644 index 0000000000000..6692cb2c78090 --- /dev/null +++ b/solution/0100-0199/0100.Same Tree/Solution2.go @@ -0,0 +1,42 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func isSameTree(p *TreeNode, q *TreeNode) bool { + if p == q { + return true + } + if p == nil || q == nil { + return false + } + q1 := []*TreeNode{p} + q2 := []*TreeNode{q} + for len(q1) > 0 && len(q2) > 0 { + p, q = q1[0], q2[0] + if p.Val != q.Val { + return false + } + q1, q2 = q1[1:], q2[1:] + la, ra := p.Left, p.Right + lb, rb := q.Left, q.Right + if (la != nil && lb == nil) || (lb != nil && la == nil) { + return false + } + if (ra != nil && rb == nil) || (rb != nil && ra == nil) { + return false + } + if la != nil { + q1 = append(q1, la) + q2 = append(q2, lb) + } + if ra != nil { + q1 = append(q1, ra) + q2 = append(q2, rb) + } + } + return true +} \ No newline at end of file diff --git a/solution/0100-0199/0100.Same Tree/Solution2.java b/solution/0100-0199/0100.Same Tree/Solution2.java new file mode 100644 index 0000000000000..3fa6347bf994f --- /dev/null +++ b/solution/0100-0199/0100.Same Tree/Solution2.java @@ -0,0 +1,53 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean isSameTree(TreeNode p, TreeNode q) { + if (p == q) { + return true; + } + if (p == null || q == null) { + return false; + } + Deque q1 = new ArrayDeque<>(); + Deque q2 = new ArrayDeque<>(); + q1.offer(p); + q2.offer(q); + while (!q1.isEmpty() && !q2.isEmpty()) { + p = q1.poll(); + q = q2.poll(); + if (p.val != q.val) { + return false; + } + TreeNode la = p.left, ra = p.right; + TreeNode lb = q.left, rb = q.right; + if ((la != null && lb == null) || (lb != null && la == null)) { + return false; + } + if ((ra != null && rb == null) || (rb != null && ra == null)) { + return false; + } + if (la != null) { + q1.offer(la); + q2.offer(lb); + } + if (ra != null) { + q1.offer(ra); + q2.offer(rb); + } + } + return true; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0100.Same Tree/Solution2.py b/solution/0100-0199/0100.Same Tree/Solution2.py new file mode 100644 index 0000000000000..ba2bb424afae0 --- /dev/null +++ b/solution/0100-0199/0100.Same Tree/Solution2.py @@ -0,0 +1,30 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: + if p == q: + return True + if p is None or q is None: + return False + q1, q2 = deque([p]), deque([q]) + while q1 and q2: + a, b = q1.popleft(), q2.popleft() + if a.val != b.val: + return False + la, ra = a.left, a.right + lb, rb = b.left, b.right + if (la and not lb) or (lb and not la): + return False + if (ra and not rb) or (rb and not ra): + return False + if la: + q1.append(la) + q2.append(lb) + if ra: + q1.append(ra) + q2.append(rb) + return True diff --git a/solution/0100-0199/0100.Same Tree/Solution2.rs b/solution/0100-0199/0100.Same Tree/Solution2.rs new file mode 100644 index 0000000000000..992b3b21e84cf --- /dev/null +++ b/solution/0100-0199/0100.Same Tree/Solution2.rs @@ -0,0 +1,68 @@ +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +use std::collections::VecDeque; +impl Solution { + pub fn is_same_tree( + mut p: Option>>, + mut q: Option>> + ) -> bool { + let mut queue = VecDeque::new(); + if p.is_some() { + queue.push_back(p.take()); + } + if q.is_some() { + queue.push_back(q.take()); + } + if queue.len() == 1 { + return false; + } + while queue.len() != 0 { + if let (Some(mut node1), Some(mut node2)) = (queue.pop_front(), queue.pop_front()) { + let mut node1 = node1.as_mut().unwrap().borrow_mut(); + let mut node2 = node2.as_mut().unwrap().borrow_mut(); + if node1.val != node2.val { + return false; + } + match (node1.left.is_some(), node2.left.is_some()) { + (false, false) => {} + (true, true) => { + queue.push_back(node1.left.take()); + queue.push_back(node2.left.take()); + } + (_, _) => { + return false; + } + } + match (node1.right.is_some(), node2.right.is_some()) { + (false, false) => {} + (true, true) => { + queue.push_back(node1.right.take()); + queue.push_back(node2.right.take()); + } + (_, _) => { + return false; + } + } + } + } + true + } +} diff --git a/solution/0100-0199/0100.Same Tree/Solution2.ts b/solution/0100-0199/0100.Same Tree/Solution2.ts new file mode 100644 index 0000000000000..02695dfc05c14 --- /dev/null +++ b/solution/0100-0199/0100.Same Tree/Solution2.ts @@ -0,0 +1,51 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean { + const queue = []; + p && queue.push(p); + q && queue.push(q); + if (queue.length === 1) { + return false; + } + while (queue.length !== 0) { + const node1 = queue.shift(); + const node2 = queue.shift(); + if (node1.val !== node2.val) { + return false; + } + if ( + (node1.left == null && node2.left != null) || + (node1.left != null && node2.left == null) + ) { + return false; + } + if ( + (node1.right == null && node2.right != null) || + (node1.right != null && node2.right == null) + ) { + return false; + } + + if (node1.left != null) { + queue.push(node1.left); + queue.push(node2.left); + } + if (node1.right != null) { + queue.push(node1.right); + queue.push(node2.right); + } + } + return true; +} diff --git a/solution/0100-0199/0101.Symmetric Tree/Solution2.rs b/solution/0100-0199/0101.Symmetric Tree/Solution2.rs new file mode 100644 index 0000000000000..3bdcaffe5ae13 --- /dev/null +++ b/solution/0100-0199/0101.Symmetric Tree/Solution2.rs @@ -0,0 +1,47 @@ +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +use std::collections::VecDeque; +impl Solution { + pub fn is_symmetric(root: Option>>) -> bool { + let root = root.unwrap(); + let mut node = root.as_ref().borrow_mut(); + let mut queue = VecDeque::new(); + queue.push_back([node.left.take(), node.right.take()]); + while let Some([root1, root2]) = queue.pop_front() { + if root1.is_none() && root2.is_none() { + continue; + } + if root1.is_none() || root2.is_none() { + return false; + } + if let (Some(node1), Some(node2)) = (root1, root2) { + let mut node1 = node1.as_ref().borrow_mut(); + let mut node2 = node2.as_ref().borrow_mut(); + if node1.val != node2.val { + return false; + } + queue.push_back([node1.left.take(), node2.right.take()]); + queue.push_back([node1.right.take(), node2.left.take()]); + } + } + true + } +} diff --git a/solution/0100-0199/0104.Maximum Depth of Binary Tree/Solution.c b/solution/0100-0199/0104.Maximum Depth of Binary Tree/Solution.c index 849b9b4a73ca3..2c291d3c3316c 100644 --- a/solution/0100-0199/0104.Maximum Depth of Binary Tree/Solution.c +++ b/solution/0100-0199/0104.Maximum Depth of Binary Tree/Solution.c @@ -16,4 +16,4 @@ int maxDepth(struct TreeNode* root) { int left = maxDepth(root->left); int right = maxDepth(root->right); return 1 + max(left, right); -} +} \ No newline at end of file diff --git a/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution.cpp b/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution.cpp index baf5e5219c0c4..2b22c98ece5aa 100644 --- a/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution.cpp +++ b/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution.cpp @@ -1,32 +1,32 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* buildTree(vector& preorder, vector& inorder) { - int n = preorder.size(); - unordered_map d; - for (int i = 0; i < n; ++i) { - d[inorder[i]] = i; - } - function dfs = [&](int i, int j, int n) -> TreeNode* { - if (n <= 0) { - return nullptr; - } - int v = preorder[i]; - int k = d[v]; - TreeNode* l = dfs(i + 1, j, k - j); - TreeNode* r = dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)); - return new TreeNode(v, l, r); - }; - return dfs(0, 0, n); - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* buildTree(vector& preorder, vector& inorder) { + int n = preorder.size(); + unordered_map d; + for (int i = 0; i < n; ++i) { + d[inorder[i]] = i; + } + function dfs = [&](int i, int j, int n) -> TreeNode* { + if (n <= 0) { + return nullptr; + } + int v = preorder[i]; + int k = d[v]; + TreeNode* l = dfs(i + 1, j, k - j); + TreeNode* r = dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)); + return new TreeNode(v, l, r); + }; + return dfs(0, 0, n); + } }; \ No newline at end of file diff --git a/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution.java b/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution.java index 55a79c30b0d13..bc175b21f3df5 100644 --- a/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution.java +++ b/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution.java @@ -1,39 +1,41 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private int[] preorder; - private Map d = new HashMap<>(); - - public TreeNode buildTree(int[] preorder, int[] inorder) { - int n = preorder.length; - this.preorder = preorder; - for (int i = 0; i < n; ++i) { - d.put(inorder[i], i); - } - return dfs(0, 0, n); - } - - private TreeNode dfs(int i, int j, int n) { - if (n <= 0) { - return null; - } - int v = preorder[i]; - int k = d.get(v); - TreeNode l = dfs(i + 1, j, k - j); - TreeNode r = dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)); - return new TreeNode(v, l, r); - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int[] preorder; + private int[] inorder; + private Map d = new HashMap<>(); + + public TreeNode buildTree(int[] preorder, int[] inorder) { + int n = preorder.length; + this.preorder = preorder; + this.inorder = inorder; + for (int i = 0; i < n; ++i) { + d.put(inorder[i], i); + } + return dfs(0, 0, n); + } + + private TreeNode dfs(int i, int j, int n) { + if (n <= 0) { + return null; + } + int v = preorder[i]; + int k = d.get(v); + TreeNode l = dfs(i + 1, j, k - j); + TreeNode r = dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)); + return new TreeNode(v, l, r); + } } \ No newline at end of file diff --git a/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution.py b/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution.py index e0946ea996489..3cd2c6d228e58 100644 --- a/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution.py +++ b/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution.py @@ -1,19 +1,19 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: - def dfs(i: int, j: int, n: int): - if n <= 0: - return None - v = preorder[i] - k = d[v] - l = dfs(i + 1, j, k - j) - r = dfs(i + 1 + k - j, k + 1, n - k + j - 1) - return TreeNode(v, l, r) - - d = {v: i for i, v in enumerate(inorder)} - return dfs(0, 0, len(preorder)) +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: + def dfs(i: int, j: int, n: int): + if n <= 0: + return None + v = preorder[i] + k = d[v] + l = dfs(i + 1, j, k - j) + r = dfs(i + 1 + k - j, k + 1, n - k + j - 1) + return TreeNode(v, l, r) + + d = {v: i for i, v in enumerate(inorder)} + return dfs(0, 0, len(preorder)) diff --git a/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution2.cpp b/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution2.cpp new file mode 100644 index 0000000000000..03576f34c28ff --- /dev/null +++ b/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution2.cpp @@ -0,0 +1,42 @@ +/** + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * }; + */ +class Solution { +public: + vector getBinaryTrees(vector& preOrder, vector& inOrder) { + int n = inOrder.size(); + unordered_map> d; + for (int i = 0; i < n; ++i) { + d[inOrder[i]].push_back(i); + } + function(int, int, int)> dfs = [&](int i, int j, int n) -> vector { + vector ans; + if (n <= 0) { + ans.push_back(nullptr); + return ans; + } + int v = preOrder[i]; + for (int k : d[v]) { + if (k >= j && k < j + n) { + auto lefts = dfs(i + 1, j, k - j); + auto rights = dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)); + for (TreeNode* l : lefts) { + for (TreeNode* r : rights) { + TreeNode* node = new TreeNode(v); + node->left = l; + node->right = r; + ans.push_back(node); + } + } + } + } + return ans; + }; + return dfs(0, 0, n); + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution2.go b/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution2.go new file mode 100644 index 0000000000000..5dbe03672b7cf --- /dev/null +++ b/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution2.go @@ -0,0 +1,29 @@ +func getBinaryTrees(preOrder []int, inOrder []int) []*TreeNode { + n := len(preOrder) + d := map[int][]int{} + for i, x := range inOrder { + d[x] = append(d[x], i) + } + var dfs func(i, j, n int) []*TreeNode + dfs = func(i, j, n int) []*TreeNode { + ans := []*TreeNode{} + if n <= 0 { + ans = append(ans, nil) + return ans + } + v := preOrder[i] + for _, k := range d[v] { + if k >= j && k < j+n { + lefts := dfs(i+1, j, k-j) + rights := dfs(i+1+k-j, k+1, n-1-(k-j)) + for _, left := range lefts { + for _, right := range rights { + ans = append(ans, &TreeNode{v, left, right}) + } + } + } + } + return ans + } + return dfs(0, 0, n) +} \ No newline at end of file diff --git a/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution2.java b/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution2.java new file mode 100644 index 0000000000000..de6b5c7b0c156 --- /dev/null +++ b/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution2.java @@ -0,0 +1,39 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int[] preorder; + private Map d = new HashMap<>(); + + public TreeNode buildTree(int[] preorder, int[] inorder) { + int n = preorder.length; + this.preorder = preorder; + for (int i = 0; i < n; ++i) { + d.put(inorder[i], i); + } + return dfs(0, 0, n); + } + + private TreeNode dfs(int i, int j, int n) { + if (n <= 0) { + return null; + } + int v = preorder[i]; + int k = d.get(v); + TreeNode l = dfs(i + 1, j, k - j); + TreeNode r = dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)); + return new TreeNode(v, l, r); + } +} \ No newline at end of file diff --git a/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution2.py b/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution2.py new file mode 100644 index 0000000000000..feec802876bc8 --- /dev/null +++ b/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def getBinaryTrees(self, preOrder: List[int], inOrder: List[int]) -> List[TreeNode]: + def dfs(i: int, j: int, n: int) -> List[TreeNode]: + if n <= 0: + return [None] + v = preOrder[i] + ans = [] + for k in d[v]: + if j <= k < j + n: + for l in dfs(i + 1, j, k - j): + for r in dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)): + ans.append(TreeNode(v, l, r)) + return ans + + d = defaultdict(list) + for i, x in enumerate(inOrder): + d[x].append(i) + return dfs(0, 0, len(preOrder)) diff --git a/solution/0100-0199/0109.Convert Sorted List to Binary Search Tree/Solution.c b/solution/0100-0199/0109.Convert Sorted List to Binary Search Tree/Solution.c index 224ccb2a3ff9d..f32e42d04329e 100644 --- a/solution/0100-0199/0109.Convert Sorted List to Binary Search Tree/Solution.c +++ b/solution/0100-0199/0109.Convert Sorted List to Binary Search Tree/Solution.c @@ -37,4 +37,4 @@ struct TreeNode* bulid(struct ListNode* start, struct ListNode* end) { struct TreeNode* sortedListToBST(struct ListNode* head) { return bulid(head, NULL); -} +} \ No newline at end of file diff --git a/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution.c b/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution.c index 738148e0fac55..f7db27f562631 100644 --- a/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution.c +++ b/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution.c @@ -22,4 +22,4 @@ int minDepth(struct TreeNode* root) { int left = minDepth(root->left); int right = minDepth(root->right); return 1 + min(left, right); -} +} \ No newline at end of file diff --git a/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution2.cpp b/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution2.cpp new file mode 100644 index 0000000000000..b937f4c428650 --- /dev/null +++ b/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution2.cpp @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int minDepth(TreeNode* root) { + if (!root) { + return 0; + } + queue q{{root}}; + int ans = 0; + while (1) { + ++ans; + for (int n = q.size(); n; --n) { + auto node = q.front(); + q.pop(); + if (!node->left && !node->right) { + return ans; + } + if (node->left) { + q.push(node->left); + } + if (node->right) { + q.push(node->right); + } + } + } + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution2.go b/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution2.go new file mode 100644 index 0000000000000..bbc6da20f71b5 --- /dev/null +++ b/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution2.go @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func minDepth(root *TreeNode) (ans int) { + if root == nil { + return 0 + } + q := []*TreeNode{root} + for { + ans++ + for n := len(q); n > 0; n-- { + node := q[0] + q = q[1:] + if node.Left == nil && node.Right == nil { + return + } + if node.Left != nil { + q = append(q, node.Left) + } + if node.Right != nil { + q = append(q, node.Right) + } + } + } +} \ No newline at end of file diff --git a/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution2.java b/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution2.java new file mode 100644 index 0000000000000..3ed2222ec9aa1 --- /dev/null +++ b/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution2.java @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int minDepth(TreeNode root) { + if (root == null) { + return 0; + } + Deque q = new ArrayDeque<>(); + q.offer(root); + int ans = 0; + while (true) { + ++ans; + for (int n = q.size(); n > 0; n--) { + TreeNode node = q.poll(); + if (node.left == null && node.right == null) { + return ans; + } + if (node.left != null) { + q.offer(node.left); + } + if (node.right != null) { + q.offer(node.right); + } + } + } + } +} \ No newline at end of file diff --git a/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution2.js b/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution2.js new file mode 100644 index 0000000000000..7e8408f101fdb --- /dev/null +++ b/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution2.js @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var minDepth = function (root) { + if (!root) { + return 0; + } + const q = [root]; + let ans = 0; + while (1) { + ++ans; + for (let n = q.length; n; --n) { + const node = q.shift(); + if (!node.left && !node.right) { + return ans; + } + if (node.left) { + q.push(node.left); + } + if (node.right) { + q.push(node.right); + } + } + } +}; diff --git a/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution2.py b/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution2.py new file mode 100644 index 0000000000000..da99399abee51 --- /dev/null +++ b/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution2.py @@ -0,0 +1,22 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def minDepth(self, root: Optional[TreeNode]) -> int: + if root is None: + return 0 + q = deque([root]) + ans = 0 + while 1: + ans += 1 + for _ in range(len(q)): + node = q.popleft() + if node.left is None and node.right is None: + return ans + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) diff --git a/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution2.ts b/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution2.ts new file mode 100644 index 0000000000000..7728748ffab0a --- /dev/null +++ b/solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution2.ts @@ -0,0 +1,36 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function minDepth(root: TreeNode | null): number { + if (!root) { + return 0; + } + const q = [root]; + let ans = 0; + while (1) { + ++ans; + for (let n = q.length; n; --n) { + const node = q.shift(); + if (!node.left && !node.right) { + return ans; + } + if (node.left) { + q.push(node.left); + } + if (node.right) { + q.push(node.right); + } + } + } +} diff --git a/solution/0100-0199/0114.Flatten Binary Tree to Linked List/Solution.go b/solution/0100-0199/0114.Flatten Binary Tree to Linked List/Solution.go index df0eb53068166..6de5805b5f6ef 100644 --- a/solution/0100-0199/0114.Flatten Binary Tree to Linked List/Solution.go +++ b/solution/0100-0199/0114.Flatten Binary Tree to Linked List/Solution.go @@ -8,14 +8,14 @@ */ func flatten(root *TreeNode) { for root != nil { - left, right := root.Left, root.Right - root.Left = nil - if left != nil { - root.Right = left - for left.Right != nil { - left = left.Right + if root.Left != nil { + pre := root.Left + for pre.Right != nil { + pre = pre.Right } - left.Right = right + pre.Right = root.Right + root.Right = root.Left + root.Left = nil } root = root.Right } diff --git a/solution/0100-0199/0114.Flatten Binary Tree to Linked List/Solution.java b/solution/0100-0199/0114.Flatten Binary Tree to Linked List/Solution.java index e616a7f033962..eca02e2aa1f0d 100644 --- a/solution/0100-0199/0114.Flatten Binary Tree to Linked List/Solution.java +++ b/solution/0100-0199/0114.Flatten Binary Tree to Linked List/Solution.java @@ -17,11 +17,16 @@ class Solution { public void flatten(TreeNode root) { while (root != null) { if (root.left != null) { + // 找到当前节点左子树的最右节点 TreeNode pre = root.left; while (pre.right != null) { pre = pre.right; } + + // 将左子树的最右节点指向原来的右子树 pre.right = root.right; + + // 将当前节点指向左子树 root.right = root.left; root.left = null; } diff --git a/solution/0100-0199/0114.Flatten Binary Tree to Linked List/Solution2.go b/solution/0100-0199/0114.Flatten Binary Tree to Linked List/Solution2.go new file mode 100644 index 0000000000000..df0eb53068166 --- /dev/null +++ b/solution/0100-0199/0114.Flatten Binary Tree to Linked List/Solution2.go @@ -0,0 +1,22 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func flatten(root *TreeNode) { + for root != nil { + left, right := root.Left, root.Right + root.Left = nil + if left != nil { + root.Right = left + for left.Right != nil { + left = left.Right + } + left.Right = right + } + root = root.Right + } +} \ No newline at end of file diff --git a/solution/0100-0199/0115.Distinct Subsequences/Solution.cpp b/solution/0100-0199/0115.Distinct Subsequences/Solution.cpp index eff3166f6e6e6..06a52cbcc8c5e 100644 --- a/solution/0100-0199/0115.Distinct Subsequences/Solution.cpp +++ b/solution/0100-0199/0115.Distinct Subsequences/Solution.cpp @@ -1,18 +1,20 @@ -class Solution { -public: - int numDistinct(string s, string t) { - int n = t.size(); - unsigned long long f[n + 1]; - memset(f, 0, sizeof(f)); - f[0] = 1; - for (char& a : s) { - for (int j = n; j; --j) { - char b = t[j - 1]; - if (a == b) { - f[j] += f[j - 1]; - } - } - } - return f[n]; - } +class Solution { +public: + int numDistinct(string s, string t) { + int m = s.size(), n = t.size(); + unsigned long long f[m + 1][n + 1]; + memset(f, 0, sizeof(f)); + for (int i = 0; i < m + 1; ++i) { + f[i][0] = 1; + } + for (int i = 1; i < m + 1; ++i) { + for (int j = 1; j < n + 1; ++j) { + f[i][j] = f[i - 1][j]; + if (s[i - 1] == t[j - 1]) { + f[i][j] += f[i - 1][j - 1]; + } + } + } + return f[m][n]; + } }; \ No newline at end of file diff --git a/solution/0100-0199/0115.Distinct Subsequences/Solution.go b/solution/0100-0199/0115.Distinct Subsequences/Solution.go index 3b1eed97f2db4..47af7378388af 100644 --- a/solution/0100-0199/0115.Distinct Subsequences/Solution.go +++ b/solution/0100-0199/0115.Distinct Subsequences/Solution.go @@ -1,13 +1,19 @@ func numDistinct(s string, t string) int { - n := len(t) - f := make([]int, n+1) - f[0] = 1 - for _, a := range s { - for j := n; j > 0; j-- { - if b := t[j-1]; byte(a) == b { - f[j] += f[j-1] + m, n := len(s), len(t) + f := make([][]int, m+1) + for i := range f { + f[i] = make([]int, n+1) + } + for i := 0; i <= m; i++ { + f[i][0] = 1 + } + for i := 1; i <= m; i++ { + for j := 1; j <= n; j++ { + f[i][j] = f[i-1][j] + if s[i-1] == t[j-1] { + f[i][j] += f[i-1][j-1] } } } - return f[n] + return f[m][n] } \ No newline at end of file diff --git a/solution/0100-0199/0115.Distinct Subsequences/Solution.java b/solution/0100-0199/0115.Distinct Subsequences/Solution.java index 0c90de4f2d637..7f169917fc1dd 100644 --- a/solution/0100-0199/0115.Distinct Subsequences/Solution.java +++ b/solution/0100-0199/0115.Distinct Subsequences/Solution.java @@ -1,16 +1,18 @@ -class Solution { - public int numDistinct(String s, String t) { - int n = t.length(); - int[] f = new int[n + 1]; - f[0] = 1; - for (char a : s.toCharArray()) { - for (int j = n; j > 0; --j) { - char b = t.charAt(j - 1); - if (a == b) { - f[j] += f[j - 1]; - } - } - } - return f[n]; - } +class Solution { + public int numDistinct(String s, String t) { + int m = s.length(), n = t.length(); + int[][] f = new int[m + 1][n + 1]; + for (int i = 0; i < m + 1; ++i) { + f[i][0] = 1; + } + for (int i = 1; i < m + 1; ++i) { + for (int j = 1; j < n + 1; ++j) { + f[i][j] = f[i - 1][j]; + if (s.charAt(i - 1) == t.charAt(j - 1)) { + f[i][j] += f[i - 1][j - 1]; + } + } + } + return f[m][n]; + } } \ No newline at end of file diff --git a/solution/0100-0199/0115.Distinct Subsequences/Solution.py b/solution/0100-0199/0115.Distinct Subsequences/Solution.py index 9e7e02af1363e..e569169624c83 100644 --- a/solution/0100-0199/0115.Distinct Subsequences/Solution.py +++ b/solution/0100-0199/0115.Distinct Subsequences/Solution.py @@ -1,9 +1,12 @@ -class Solution: - def numDistinct(self, s: str, t: str) -> int: - n = len(t) - f = [1] + [0] * n - for a in s: - for j in range(n, 0, -1): - if a == t[j - 1]: - f[j] += f[j - 1] - return f[n] +class Solution: + def numDistinct(self, s: str, t: str) -> int: + m, n = len(s), len(t) + f = [[0] * (n + 1) for _ in range(m + 1)] + for i in range(m + 1): + f[i][0] = 1 + for i, a in enumerate(s, 1): + for j, b in enumerate(t, 1): + f[i][j] = f[i - 1][j] + if a == b: + f[i][j] += f[i - 1][j - 1] + return f[m][n] diff --git a/solution/0100-0199/0115.Distinct Subsequences/Solution.ts b/solution/0100-0199/0115.Distinct Subsequences/Solution.ts index f254f30e9f3f8..792189f8e6954 100644 --- a/solution/0100-0199/0115.Distinct Subsequences/Solution.ts +++ b/solution/0100-0199/0115.Distinct Subsequences/Solution.ts @@ -1,14 +1,17 @@ function numDistinct(s: string, t: string): number { + const m = s.length; const n = t.length; - const f: number[] = new Array(n + 1).fill(0); - f[0] = 1; - for (const a of s) { - for (let j = n; j; --j) { - const b = t[j - 1]; - if (a === b) { - f[j] += f[j - 1]; + const f: number[][] = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); + for (let i = 0; i <= m; ++i) { + f[i][0] = 1; + } + for (let i = 1; i <= m; ++i) { + for (let j = 1; j <= n; ++j) { + f[i][j] = f[i - 1][j]; + if (s[i - 1] === t[j - 1]) { + f[i][j] += f[i - 1][j - 1]; } } } - return f[n]; + return f[m][n]; } diff --git a/solution/0100-0199/0115.Distinct Subsequences/Solution2.cpp b/solution/0100-0199/0115.Distinct Subsequences/Solution2.cpp new file mode 100644 index 0000000000000..30d8d498fcb96 --- /dev/null +++ b/solution/0100-0199/0115.Distinct Subsequences/Solution2.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int numDistinct(string s, string t) { + int n = t.size(); + unsigned long long f[n + 1]; + memset(f, 0, sizeof(f)); + f[0] = 1; + for (char& a : s) { + for (int j = n; j; --j) { + char b = t[j - 1]; + if (a == b) { + f[j] += f[j - 1]; + } + } + } + return f[n]; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0115.Distinct Subsequences/Solution2.go b/solution/0100-0199/0115.Distinct Subsequences/Solution2.go new file mode 100644 index 0000000000000..3b1eed97f2db4 --- /dev/null +++ b/solution/0100-0199/0115.Distinct Subsequences/Solution2.go @@ -0,0 +1,13 @@ +func numDistinct(s string, t string) int { + n := len(t) + f := make([]int, n+1) + f[0] = 1 + for _, a := range s { + for j := n; j > 0; j-- { + if b := t[j-1]; byte(a) == b { + f[j] += f[j-1] + } + } + } + return f[n] +} \ No newline at end of file diff --git a/solution/0100-0199/0115.Distinct Subsequences/Solution2.java b/solution/0100-0199/0115.Distinct Subsequences/Solution2.java new file mode 100644 index 0000000000000..c8d2d4c51c681 --- /dev/null +++ b/solution/0100-0199/0115.Distinct Subsequences/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public int numDistinct(String s, String t) { + int n = t.length(); + int[] f = new int[n + 1]; + f[0] = 1; + for (char a : s.toCharArray()) { + for (int j = n; j > 0; --j) { + char b = t.charAt(j - 1); + if (a == b) { + f[j] += f[j - 1]; + } + } + } + return f[n]; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0115.Distinct Subsequences/Solution2.py b/solution/0100-0199/0115.Distinct Subsequences/Solution2.py new file mode 100644 index 0000000000000..b6dad9021840e --- /dev/null +++ b/solution/0100-0199/0115.Distinct Subsequences/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def numDistinct(self, s: str, t: str) -> int: + n = len(t) + f = [1] + [0] * n + for a in s: + for j in range(n, 0, -1): + if a == t[j - 1]: + f[j] += f[j - 1] + return f[n] diff --git a/solution/0100-0199/0115.Distinct Subsequences/Solution2.ts b/solution/0100-0199/0115.Distinct Subsequences/Solution2.ts new file mode 100644 index 0000000000000..f254f30e9f3f8 --- /dev/null +++ b/solution/0100-0199/0115.Distinct Subsequences/Solution2.ts @@ -0,0 +1,14 @@ +function numDistinct(s: string, t: string): number { + const n = t.length; + const f: number[] = new Array(n + 1).fill(0); + f[0] = 1; + for (const a of s) { + for (let j = n; j; --j) { + const b = t[j - 1]; + if (a === b) { + f[j] += f[j - 1]; + } + } + } + return f[n]; +} diff --git a/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/Solution2.cpp b/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/Solution2.cpp new file mode 100644 index 0000000000000..702920532c041 --- /dev/null +++ b/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/Solution2.cpp @@ -0,0 +1,36 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(NULL), right(NULL), next(NULL) {} + + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} + + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; +*/ + +class Solution { +public: + Node* connect(Node* root) { + function dfs = [&](Node* left, Node* right) { + if (!left || !right) { + return; + } + left->next = right; + dfs(left->left, left->right); + dfs(left->right, right->left); + dfs(right->left, right->right); + }; + if (root) { + dfs(root->left, root->right); + } + return root; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/Solution2.go b/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/Solution2.go new file mode 100644 index 0000000000000..8611196ee79a9 --- /dev/null +++ b/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/Solution2.go @@ -0,0 +1,26 @@ +/** + * Definition for a Node. + * type Node struct { + * Val int + * Left *Node + * Right *Node + * Next *Node + * } + */ + +func connect(root *Node) *Node { + var dfs func(*Node, *Node) + dfs = func(left, right *Node) { + if left == nil || right == nil { + return + } + left.Next = right + dfs(left.Left, left.Right) + dfs(left.Right, right.Left) + dfs(right.Left, right.Right) + } + if root != nil { + dfs(root.Left, root.Right) + } + return root +} \ No newline at end of file diff --git a/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/Solution2.java b/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/Solution2.java new file mode 100644 index 0000000000000..5b4f8e2ee471e --- /dev/null +++ b/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/Solution2.java @@ -0,0 +1,41 @@ +/* +// Definition for a Node. +class Node { + public int val; + public Node left; + public Node right; + public Node next; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, Node _left, Node _right, Node _next) { + val = _val; + left = _left; + right = _right; + next = _next; + } +}; +*/ + +class Solution { + public Node connect(Node root) { + if (root != null) { + dfs(root.left, root.right); + } + return root; + } + + private void dfs(Node left, Node right) { + if (left == null || right == null) { + return; + } + left.next = right; + dfs(left.left, left.right); + dfs(left.right, right.left); + dfs(right.left, right.right); + } +} \ No newline at end of file diff --git a/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/Solution2.py b/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/Solution2.py new file mode 100644 index 0000000000000..c20e0f2c9f373 --- /dev/null +++ b/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/Solution2.py @@ -0,0 +1,24 @@ +""" +# Definition for a Node. +class Node: + def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): + self.val = val + self.left = left + self.right = right + self.next = next +""" + + +class Solution: + def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': + def dfs(left, right): + if left is None or right is None: + return + left.next = right + dfs(left.left, left.right) + dfs(left.right, right.left) + dfs(right.left, right.right) + + if root: + dfs(root.left, root.right) + return root diff --git a/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/Solution2.ts b/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/Solution2.ts new file mode 100644 index 0000000000000..e27ad01c15840 --- /dev/null +++ b/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/Solution2.ts @@ -0,0 +1,34 @@ +/** + * Definition for Node. + * class Node { + * val: number + * left: Node | null + * right: Node | null + * next: Node | null + * constructor(val?: number, left?: Node, right?: Node, next?: Node) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function connect(root: Node | null): Node | null { + if (root == null) { + return root; + } + const queue = [root]; + while (queue.length !== 0) { + const n = queue.length; + let pre = null; + for (let i = 0; i < n; i++) { + const node = queue.shift(); + node.next = pre; + pre = node; + const { left, right } = node; + left && queue.push(right, left); + } + } + return root; +} diff --git a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.cpp b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.cpp index 30feb7f597bb3..7098ad5d3d431 100644 --- a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.cpp +++ b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.cpp @@ -19,29 +19,26 @@ class Node { class Solution { public: Node* connect(Node* root) { - Node* node = root; - Node* prev = nullptr; - Node* next = nullptr; - auto modify = [&](Node* curr) { - if (!curr) { - return; - } - if (!next) { - next = curr; - } - if (prev) { - prev->next = curr; - } - prev = curr; - }; - while (node) { - prev = next = nullptr; - while (node) { - modify(node->left); - modify(node->right); - node = node->next; + if (!root) { + return root; + } + queue q{{root}}; + while (!q.empty()) { + Node* p = nullptr; + for (int n = q.size(); n; --n) { + Node* node = q.front(); + q.pop(); + if (p) { + p->next = node; + } + p = node; + if (node->left) { + q.push(node->left); + } + if (node->right) { + q.push(node->right); + } } - node = next; } return root; } diff --git a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.cs b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.cs index ccd7d67648a02..edef25778186e 100644 --- a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.cs +++ b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.cs @@ -1,54 +1,49 @@ -/* -// Definition for a Node. -public class Node { - public int val; - public Node left; - public Node right; - public Node next; - - public Node() {} - - public Node(int _val) { - val = _val; - } - - public Node(int _val, Node _left, Node _right, Node _next) { - val = _val; - left = _left; - right = _right; - next = _next; - } -} -*/ - -public class Solution { - private Node prev, next; - - public Node Connect(Node root) { - Node node = root; - while (node != null) { - prev = null; - next = null; - while (node != null) { - modify(node.left); - modify(node.right); - node = node.next; - } - node = next; - } - return root; - } - - private void modify(Node curr) { - if (curr == null) { - return; - } - if (next == null) { - next = curr; - } - if (prev != null) { - prev.next = curr; - } - prev = curr; - } -} \ No newline at end of file +/* +// Definition for a Node. +public class Node { + public int val; + public Node left; + public Node right; + public Node next; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, Node _left, Node _right, Node _next) { + val = _val; + left = _left; + right = _right; + next = _next; + } +} +*/ + +public class Solution { + public Node Connect(Node root) { + if (root == null) { + return null; + } + var q = new Queue(); + q.Enqueue(root); + while (q.Count > 0) { + Node p = null; + for (int i = q.Count; i > 0; --i) { + var node = q.Dequeue(); + if (p != null) { + p.next = node; + } + p = node; + if (node.left != null) { + q.Enqueue(node.left); + } + if (node.right != null) { + q.Enqueue(node.right); + } + } + } + return root; + } +} diff --git a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.go b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.go index 670b3b8060505..191fed05c93b1 100644 --- a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.go +++ b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.go @@ -9,28 +9,26 @@ */ func connect(root *Node) *Node { - node := root - var prev, next *Node - modify := func(curr *Node) { - if curr == nil { - return - } - if next == nil { - next = curr - } - if prev != nil { - prev.Next = curr - } - prev = curr + if root == nil { + return root } - for node != nil { - prev, next = nil, nil - for node != nil { - modify(node.Left) - modify(node.Right) - node = node.Next + q := []*Node{root} + for len(q) > 0 { + var p *Node + for n := len(q); n > 0; n-- { + node := q[0] + q = q[1:] + if p != nil { + p.Next = node + } + p = node + if node.Left != nil { + q = append(q, node.Left) + } + if node.Right != nil { + q = append(q, node.Right) + } } - node = next } return root } \ No newline at end of file diff --git a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.java b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.java index 48c49364617d1..1bbd53c899395 100644 --- a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.java +++ b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.java @@ -22,33 +22,28 @@ public Node(int _val, Node _left, Node _right, Node _next) { */ class Solution { - private Node prev, next; - public Node connect(Node root) { - Node node = root; - while (node != null) { - prev = null; - next = null; - while (node != null) { - modify(node.left); - modify(node.right); - node = node.next; + if (root == null) { + return root; + } + Deque q = new ArrayDeque<>(); + q.offer(root); + while (!q.isEmpty()) { + Node p = null; + for (int n = q.size(); n > 0; --n) { + Node node = q.poll(); + if (p != null) { + p.next = node; + } + p = node; + if (node.left != null) { + q.offer(node.left); + } + if (node.right != null) { + q.offer(node.right); + } } - node = next; } return root; } - - private void modify(Node curr) { - if (curr == null) { - return; - } - if (next == null) { - next = curr; - } - if (prev != null) { - prev.next = curr; - } - prev = curr; - } } \ No newline at end of file diff --git a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.py b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.py index 1eff737d14f05..bbb7e27da7109 100644 --- a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.py +++ b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.py @@ -11,21 +11,18 @@ def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next class Solution: def connect(self, root: "Node") -> "Node": - def modify(curr): - nonlocal prev, next - if curr is None: - return - next = next or curr - if prev: - prev.next = curr - prev = curr - - node = root - while node: - prev = next = None - while node: - modify(node.left) - modify(node.right) - node = node.next - node = next + if root is None: + return root + q = deque([root]) + while q: + p = None + for _ in range(len(q)): + node = q.popleft() + if p: + p.next = node + p = node + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) return root diff --git a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.ts b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.ts index d3187790686e2..ba358a4c13d4d 100644 --- a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.ts +++ b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution.ts @@ -15,26 +15,23 @@ */ function connect(root: Node | null): Node | null { - const modify = (curr: Node | null): void => { - if (!curr) { - return; - } - next = next || curr; - if (prev) { - prev.next = curr; - } - prev = curr; - }; - let node = root; - let [prev, next] = [null, null]; - while (node) { - while (node) { - modify(node.left); - modify(node.right); - node = node.next; + if (!root) { + return null; + } + const q: Node[] = [root]; + while (q.length) { + const nq: Node[] = []; + let p: Node | null = null; + for (const node of q) { + if (p) { + p.next = node; + } + p = node; + const { left, right } = node; + left && nq.push(left); + right && nq.push(right); } - node = next; - [prev, next] = [null, null]; + q.splice(0, q.length, ...nq); } return root; } diff --git a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution2.cpp b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution2.cpp new file mode 100644 index 0000000000000..30feb7f597bb3 --- /dev/null +++ b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution2.cpp @@ -0,0 +1,48 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(NULL), right(NULL), next(NULL) {} + + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} + + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; +*/ + +class Solution { +public: + Node* connect(Node* root) { + Node* node = root; + Node* prev = nullptr; + Node* next = nullptr; + auto modify = [&](Node* curr) { + if (!curr) { + return; + } + if (!next) { + next = curr; + } + if (prev) { + prev->next = curr; + } + prev = curr; + }; + while (node) { + prev = next = nullptr; + while (node) { + modify(node->left); + modify(node->right); + node = node->next; + } + node = next; + } + return root; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution2.cs b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution2.cs new file mode 100644 index 0000000000000..d1b946604fafa --- /dev/null +++ b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution2.cs @@ -0,0 +1,54 @@ +/* +// Definition for a Node. +public class Node { + public int val; + public Node left; + public Node right; + public Node next; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, Node _left, Node _right, Node _next) { + val = _val; + left = _left; + right = _right; + next = _next; + } +} +*/ + +public class Solution { + private Node prev, next; + + public Node Connect(Node root) { + Node node = root; + while (node != null) { + prev = null; + next = null; + while (node != null) { + modify(node.left); + modify(node.right); + node = node.next; + } + node = next; + } + return root; + } + + private void modify(Node curr) { + if (curr == null) { + return; + } + if (next == null) { + next = curr; + } + if (prev != null) { + prev.next = curr; + } + prev = curr; + } +} diff --git a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution2.go b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution2.go new file mode 100644 index 0000000000000..670b3b8060505 --- /dev/null +++ b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution2.go @@ -0,0 +1,36 @@ +/** + * Definition for a Node. + * type Node struct { + * Val int + * Left *Node + * Right *Node + * Next *Node + * } + */ + +func connect(root *Node) *Node { + node := root + var prev, next *Node + modify := func(curr *Node) { + if curr == nil { + return + } + if next == nil { + next = curr + } + if prev != nil { + prev.Next = curr + } + prev = curr + } + for node != nil { + prev, next = nil, nil + for node != nil { + modify(node.Left) + modify(node.Right) + node = node.Next + } + node = next + } + return root +} \ No newline at end of file diff --git a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution2.java b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution2.java new file mode 100644 index 0000000000000..48c49364617d1 --- /dev/null +++ b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution2.java @@ -0,0 +1,54 @@ +/* +// Definition for a Node. +class Node { + public int val; + public Node left; + public Node right; + public Node next; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, Node _left, Node _right, Node _next) { + val = _val; + left = _left; + right = _right; + next = _next; + } +}; +*/ + +class Solution { + private Node prev, next; + + public Node connect(Node root) { + Node node = root; + while (node != null) { + prev = null; + next = null; + while (node != null) { + modify(node.left); + modify(node.right); + node = node.next; + } + node = next; + } + return root; + } + + private void modify(Node curr) { + if (curr == null) { + return; + } + if (next == null) { + next = curr; + } + if (prev != null) { + prev.next = curr; + } + prev = curr; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution2.py b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution2.py new file mode 100644 index 0000000000000..52d282103ab8e --- /dev/null +++ b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution2.py @@ -0,0 +1,31 @@ +""" +# Definition for a Node. +class Node: + def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): + self.val = val + self.left = left + self.right = right + self.next = next +""" + + +class Solution: + def connect(self, root: 'Node') -> 'Node': + def modify(curr): + nonlocal prev, next + if curr is None: + return + next = next or curr + if prev: + prev.next = curr + prev = curr + + node = root + while node: + prev = next = None + while node: + modify(node.left) + modify(node.right) + node = node.next + node = next + return root diff --git a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution2.ts b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution2.ts new file mode 100644 index 0000000000000..d3187790686e2 --- /dev/null +++ b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/Solution2.ts @@ -0,0 +1,40 @@ +/** + * Definition for Node. + * class Node { + * val: number + * left: Node | null + * right: Node | null + * next: Node | null + * constructor(val?: number, left?: Node, right?: Node, next?: Node) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function connect(root: Node | null): Node | null { + const modify = (curr: Node | null): void => { + if (!curr) { + return; + } + next = next || curr; + if (prev) { + prev.next = curr; + } + prev = curr; + }; + let node = root; + let [prev, next] = [null, null]; + while (node) { + while (node) { + modify(node.left); + modify(node.right); + node = node.next; + } + node = next; + [prev, next] = [null, null]; + } + return root; +} diff --git a/solution/0100-0199/0118.Pascal's Triangle/Solution.cpp b/solution/0100-0199/0118.Pascal's Triangle/Solution.cpp index 1f963e0a9dab7..62f2014da6b74 100644 --- a/solution/0100-0199/0118.Pascal's Triangle/Solution.cpp +++ b/solution/0100-0199/0118.Pascal's Triangle/Solution.cpp @@ -1,17 +1,17 @@ -class Solution { -public: - vector> generate(int numRows) { - vector> f; - f.push_back(vector(1, 1)); - for (int i = 0; i < numRows - 1; ++i) { - vector g; - g.push_back(1); - for (int j = 0; j < f[i].size() - 1; ++j) { - g.push_back(f[i][j] + f[i][j + 1]); - } - g.push_back(1); - f.push_back(g); - } - return f; - } +class Solution { +public: + vector> generate(int numRows) { + vector> f; + f.push_back(vector(1, 1)); + for (int i = 0; i < numRows - 1; ++i) { + vector g; + g.push_back(1); + for (int j = 0; j < f[i].size() - 1; ++j) { + g.push_back(f[i][j] + f[i][j + 1]); + } + g.push_back(1); + f.push_back(g); + } + return f; + } }; \ No newline at end of file diff --git a/solution/0100-0199/0118.Pascal's Triangle/Solution.java b/solution/0100-0199/0118.Pascal's Triangle/Solution.java index c149e8b52d498..550edb73b4d18 100644 --- a/solution/0100-0199/0118.Pascal's Triangle/Solution.java +++ b/solution/0100-0199/0118.Pascal's Triangle/Solution.java @@ -1,16 +1,16 @@ -class Solution { - public List> generate(int numRows) { - List> f = new ArrayList<>(); - f.add(List.of(1)); - for (int i = 0; i < numRows - 1; ++i) { - List g = new ArrayList<>(); - g.add(1); - for (int j = 0; j < f.get(i).size() - 1; ++j) { - g.add(f.get(i).get(j) + f.get(i).get(j + 1)); - } - g.add(1); - f.add(g); - } - return f; - } +class Solution { + public List> generate(int numRows) { + List> f = new ArrayList<>(); + f.add(List.of(1)); + for (int i = 0; i < numRows - 1; ++i) { + List g = new ArrayList<>(); + g.add(1); + for (int j = 0; j < f.get(i).size() - 1; ++j) { + g.add(f.get(i).get(j) + f.get(i).get(j + 1)); + } + g.add(1); + f.add(g); + } + return f; + } } \ No newline at end of file diff --git a/solution/0100-0199/0118.Pascal's Triangle/Solution.py b/solution/0100-0199/0118.Pascal's Triangle/Solution.py index 7162c4b5dcda1..e7f0ae85242c0 100644 --- a/solution/0100-0199/0118.Pascal's Triangle/Solution.py +++ b/solution/0100-0199/0118.Pascal's Triangle/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def generate(self, numRows: int) -> List[List[int]]: - f = [[1]] - for i in range(numRows - 1): - g = [1] + [a + b for a, b in pairwise(f[-1])] + [1] - f.append(g) - return f +class Solution: + def generate(self, numRows: int) -> List[List[int]]: + f = [[1]] + for i in range(numRows - 1): + g = [1] + [a + b for a, b in pairwise(f[-1])] + [1] + f.append(g) + return f diff --git a/solution/0100-0199/0119.Pascal's Triangle II/Solution.cpp b/solution/0100-0199/0119.Pascal's Triangle II/Solution.cpp index 39bc0342631ef..a073aa6e5d718 100644 --- a/solution/0100-0199/0119.Pascal's Triangle II/Solution.cpp +++ b/solution/0100-0199/0119.Pascal's Triangle II/Solution.cpp @@ -1,12 +1,12 @@ -class Solution { -public: - vector getRow(int rowIndex) { - vector f(rowIndex + 1, 1); - for (int i = 2; i < rowIndex + 1; ++i) { - for (int j = i - 1; j; --j) { - f[j] += f[j - 1]; - } - } - return f; - } +class Solution { +public: + vector getRow(int rowIndex) { + vector f(rowIndex + 1, 1); + for (int i = 2; i < rowIndex + 1; ++i) { + for (int j = i - 1; j; --j) { + f[j] += f[j - 1]; + } + } + return f; + } }; \ No newline at end of file diff --git a/solution/0100-0199/0119.Pascal's Triangle II/Solution.java b/solution/0100-0199/0119.Pascal's Triangle II/Solution.java index 14b49ba0c1779..bd47b26cd3235 100644 --- a/solution/0100-0199/0119.Pascal's Triangle II/Solution.java +++ b/solution/0100-0199/0119.Pascal's Triangle II/Solution.java @@ -1,14 +1,14 @@ -class Solution { - public List getRow(int rowIndex) { - List f = new ArrayList<>(); - for (int i = 0; i < rowIndex + 1; ++i) { - f.add(1); - } - for (int i = 2; i < rowIndex + 1; ++i) { - for (int j = i - 1; j > 0; --j) { - f.set(j, f.get(j) + f.get(j - 1)); - } - } - return f; - } +class Solution { + public List getRow(int rowIndex) { + List f = new ArrayList<>(); + for (int i = 0; i < rowIndex + 1; ++i) { + f.add(1); + } + for (int i = 2; i < rowIndex + 1; ++i) { + for (int j = i - 1; j > 0; --j) { + f.set(j, f.get(j) + f.get(j - 1)); + } + } + return f; + } } \ No newline at end of file diff --git a/solution/0100-0199/0119.Pascal's Triangle II/Solution.py b/solution/0100-0199/0119.Pascal's Triangle II/Solution.py index b1a9263646064..1f503d7f0a089 100644 --- a/solution/0100-0199/0119.Pascal's Triangle II/Solution.py +++ b/solution/0100-0199/0119.Pascal's Triangle II/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def getRow(self, rowIndex: int) -> List[int]: - f = [1] * (rowIndex + 1) - for i in range(2, rowIndex + 1): - for j in range(i - 1, 0, -1): - f[j] += f[j - 1] - return f +class Solution: + def getRow(self, rowIndex: int) -> List[int]: + f = [1] * (rowIndex + 1) + for i in range(2, rowIndex + 1): + for j in range(i - 1, 0, -1): + f[j] += f[j - 1] + return f diff --git a/solution/0100-0199/0120.Triangle/Solution.cpp b/solution/0100-0199/0120.Triangle/Solution.cpp index ee98c105031ce..8324e1432b429 100644 --- a/solution/0100-0199/0120.Triangle/Solution.cpp +++ b/solution/0100-0199/0120.Triangle/Solution.cpp @@ -1,11 +1,14 @@ -class Solution { -public: - int minimumTotal(vector>& triangle) { - for (int i = triangle.size() - 2; ~i; --i) { - for (int j = 0; j <= i; ++j) { - triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]); - } - } - return triangle[0][0]; - } +class Solution { +public: + int minimumTotal(vector>& triangle) { + int n = triangle.size(); + int f[n + 1]; + memset(f, 0, sizeof(f)); + for (int i = n - 1; ~i; --i) { + for (int j = 0; j <= i; ++j) { + f[j] = min(f[j], f[j + 1]) + triangle[i][j]; + } + } + return f[0]; + } }; \ No newline at end of file diff --git a/solution/0100-0199/0120.Triangle/Solution.go b/solution/0100-0199/0120.Triangle/Solution.go index 252de43cf0acf..3c6a55ad9a78d 100644 --- a/solution/0100-0199/0120.Triangle/Solution.go +++ b/solution/0100-0199/0120.Triangle/Solution.go @@ -1,8 +1,10 @@ func minimumTotal(triangle [][]int) int { - for i := len(triangle) - 2; i >= 0; i-- { + n := len(triangle) + f := make([]int, n+1) + for i := n - 1; i >= 0; i-- { for j := 0; j <= i; j++ { - triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]) + f[j] = min(f[j], f[j+1]) + triangle[i][j] } } - return triangle[0][0] + return f[0] } \ No newline at end of file diff --git a/solution/0100-0199/0120.Triangle/Solution.java b/solution/0100-0199/0120.Triangle/Solution.java index efad279e8b46b..7bf72bf2c0d5d 100644 --- a/solution/0100-0199/0120.Triangle/Solution.java +++ b/solution/0100-0199/0120.Triangle/Solution.java @@ -1,12 +1,12 @@ -class Solution { - public int minimumTotal(List> triangle) { - for (int i = triangle.size() - 2; i >= 0; --i) { - for (int j = 0; j <= i; ++j) { - int x = triangle.get(i).get(j); - int y = Math.min(triangle.get(i + 1).get(j), triangle.get(i + 1).get(j + 1)); - triangle.get(i).set(j, x + y); - } - } - return triangle.get(0).get(0); - } +class Solution { + public int minimumTotal(List> triangle) { + int n = triangle.size(); + int[] f = new int[n + 1]; + for (int i = n - 1; i >= 0; --i) { + for (int j = 0; j <= i; ++j) { + f[j] = Math.min(f[j], f[j + 1]) + triangle.get(i).get(j); + } + } + return f[0]; + } } \ No newline at end of file diff --git a/solution/0100-0199/0120.Triangle/Solution.py b/solution/0100-0199/0120.Triangle/Solution.py index b979b1a32047f..b4aed7da37fde 100644 --- a/solution/0100-0199/0120.Triangle/Solution.py +++ b/solution/0100-0199/0120.Triangle/Solution.py @@ -1,9 +1,8 @@ -class Solution: - def minimumTotal(self, triangle: List[List[int]]) -> int: - n = len(triangle) - for i in range(n - 2, -1, -1): - for j in range(i + 1): - triangle[i][j] = ( - min(triangle[i + 1][j], triangle[i + 1][j + 1]) + triangle[i][j] - ) - return triangle[0][0] +class Solution: + def minimumTotal(self, triangle: List[List[int]]) -> int: + n = len(triangle) + f = [[0] * (n + 1) for _ in range(n + 1)] + for i in range(n - 1, -1, -1): + for j in range(i + 1): + f[i][j] = min(f[i + 1][j], f[i + 1][j + 1]) + triangle[i][j] + return f[0][0] diff --git a/solution/0100-0199/0120.Triangle/Solution.rs b/solution/0100-0199/0120.Triangle/Solution.rs index dee8ef3772966..446e48438da5b 100644 --- a/solution/0100-0199/0120.Triangle/Solution.rs +++ b/solution/0100-0199/0120.Triangle/Solution.rs @@ -1,11 +1,12 @@ impl Solution { pub fn minimum_total(triangle: Vec>) -> i32 { - let mut triangle = triangle; - for i in (0..triangle.len() - 1).rev() { + let n = triangle.len(); + let mut f = vec![0; n + 1]; + for i in (0..n).rev() { for j in 0..=i { - triangle[i][j] += triangle[i + 1][j].min(triangle[i + 1][j + 1]); + f[j] = f[j].min(f[j + 1]) + triangle[i][j]; } } - triangle[0][0] + f[0] } } diff --git a/solution/0100-0199/0120.Triangle/Solution.ts b/solution/0100-0199/0120.Triangle/Solution.ts index f448dbb021d9b..93969b6180aec 100644 --- a/solution/0100-0199/0120.Triangle/Solution.ts +++ b/solution/0100-0199/0120.Triangle/Solution.ts @@ -1,8 +1,10 @@ function minimumTotal(triangle: number[][]): number { - for (let i = triangle.length - 2; ~i; --i) { + const n = triangle.length; + const f: number[] = Array(n + 1).fill(0); + for (let i = n - 1; ~i; --i) { for (let j = 0; j <= i; ++j) { - triangle[i][j] += Math.min(triangle[i + 1][j], triangle[i + 1][j + 1]); + f[j] = Math.min(f[j], f[j + 1]) + triangle[i][j]; } } - return triangle[0][0]; + return f[0]; } diff --git a/solution/0100-0199/0120.Triangle/Solution2.cpp b/solution/0100-0199/0120.Triangle/Solution2.cpp new file mode 100644 index 0000000000000..a73b51182ee2f --- /dev/null +++ b/solution/0100-0199/0120.Triangle/Solution2.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int minimumTotal(vector>& triangle) { + for (int i = triangle.size() - 2; ~i; --i) { + for (int j = 0; j <= i; ++j) { + triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]); + } + } + return triangle[0][0]; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0120.Triangle/Solution2.go b/solution/0100-0199/0120.Triangle/Solution2.go new file mode 100644 index 0000000000000..252de43cf0acf --- /dev/null +++ b/solution/0100-0199/0120.Triangle/Solution2.go @@ -0,0 +1,8 @@ +func minimumTotal(triangle [][]int) int { + for i := len(triangle) - 2; i >= 0; i-- { + for j := 0; j <= i; j++ { + triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]) + } + } + return triangle[0][0] +} \ No newline at end of file diff --git a/solution/0100-0199/0120.Triangle/Solution2.java b/solution/0100-0199/0120.Triangle/Solution2.java new file mode 100644 index 0000000000000..3f3fd591132b8 --- /dev/null +++ b/solution/0100-0199/0120.Triangle/Solution2.java @@ -0,0 +1,12 @@ +class Solution { + public int minimumTotal(List> triangle) { + for (int i = triangle.size() - 2; i >= 0; --i) { + for (int j = 0; j <= i; ++j) { + int x = triangle.get(i).get(j); + int y = Math.min(triangle.get(i + 1).get(j), triangle.get(i + 1).get(j + 1)); + triangle.get(i).set(j, x + y); + } + } + return triangle.get(0).get(0); + } +} \ No newline at end of file diff --git a/solution/0100-0199/0120.Triangle/Solution2.py b/solution/0100-0199/0120.Triangle/Solution2.py new file mode 100644 index 0000000000000..d36d809b94286 --- /dev/null +++ b/solution/0100-0199/0120.Triangle/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def minimumTotal(self, triangle: List[List[int]]) -> int: + n = len(triangle) + f = [0] * (n + 1) + for i in range(n - 1, -1, -1): + for j in range(i + 1): + f[j] = min(f[j], f[j + 1]) + triangle[i][j] + return f[0] diff --git a/solution/0100-0199/0120.Triangle/Solution2.rs b/solution/0100-0199/0120.Triangle/Solution2.rs new file mode 100644 index 0000000000000..dee8ef3772966 --- /dev/null +++ b/solution/0100-0199/0120.Triangle/Solution2.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn minimum_total(triangle: Vec>) -> i32 { + let mut triangle = triangle; + for i in (0..triangle.len() - 1).rev() { + for j in 0..=i { + triangle[i][j] += triangle[i + 1][j].min(triangle[i + 1][j + 1]); + } + } + triangle[0][0] + } +} diff --git a/solution/0100-0199/0120.Triangle/Solution2.ts b/solution/0100-0199/0120.Triangle/Solution2.ts new file mode 100644 index 0000000000000..f448dbb021d9b --- /dev/null +++ b/solution/0100-0199/0120.Triangle/Solution2.ts @@ -0,0 +1,8 @@ +function minimumTotal(triangle: number[][]): number { + for (let i = triangle.length - 2; ~i; --i) { + for (let j = 0; j <= i; ++j) { + triangle[i][j] += Math.min(triangle[i + 1][j], triangle[i + 1][j + 1]); + } + } + return triangle[0][0]; +} diff --git a/solution/0100-0199/0120.Triangle/Solution3.py b/solution/0100-0199/0120.Triangle/Solution3.py new file mode 100644 index 0000000000000..e7b530df106ba --- /dev/null +++ b/solution/0100-0199/0120.Triangle/Solution3.py @@ -0,0 +1,9 @@ +class Solution: + def minimumTotal(self, triangle: List[List[int]]) -> int: + n = len(triangle) + for i in range(n - 2, -1, -1): + for j in range(i + 1): + triangle[i][j] = ( + min(triangle[i + 1][j], triangle[i + 1][j + 1]) + triangle[i][j] + ) + return triangle[0][0] diff --git a/solution/0100-0199/0121.Best Time to Buy and Sell Stock/Solution.cs b/solution/0100-0199/0121.Best Time to Buy and Sell Stock/Solution.cs index 3099f09d3b622..e5a28ae2c7d42 100644 --- a/solution/0100-0199/0121.Best Time to Buy and Sell Stock/Solution.cs +++ b/solution/0100-0199/0121.Best Time to Buy and Sell Stock/Solution.cs @@ -7,4 +7,4 @@ public int MaxProfit(int[] prices) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0121.Best Time to Buy and Sell Stock/Solution.php b/solution/0100-0199/0121.Best Time to Buy and Sell Stock/Solution.php index 9f0d8961724a7..4b93ac4847599 100644 --- a/solution/0100-0199/0121.Best Time to Buy and Sell Stock/Solution.php +++ b/solution/0100-0199/0121.Best Time to Buy and Sell Stock/Solution.php @@ -13,4 +13,4 @@ function maxProfit($prices) { } return $win; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution.cpp b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution.cpp index 766e573552733..971bbd08d5936 100644 --- a/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution.cpp +++ b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution.cpp @@ -1,4 +1,4 @@ -class Solution { +class Solution { public: int maxProfit(vector& prices) { int ans = 0; diff --git a/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution.cs b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution.cs index 9c1b0a5984883..6faff49de4984 100644 --- a/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution.cs +++ b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution.cs @@ -6,4 +6,4 @@ public int MaxProfit(int[] prices) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution2.cpp b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution2.cpp new file mode 100644 index 0000000000000..e5d7829744973 --- /dev/null +++ b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int maxProfit(vector& prices) { + int n = prices.size(); + int f[n][2]; + f[0][0] = -prices[0]; + f[0][1] = 0; + for (int i = 1; i < n; ++i) { + f[i][0] = max(f[i - 1][0], f[i - 1][1] - prices[i]); + f[i][1] = max(f[i - 1][1], f[i - 1][0] + prices[i]); + } + return f[n - 1][1]; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution2.cs b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution2.cs new file mode 100644 index 0000000000000..d1b388d44d5d4 --- /dev/null +++ b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution2.cs @@ -0,0 +1,11 @@ +public class Solution { + public int MaxProfit(int[] prices) { + int f1 = -prices[0], f2 = 0; + for (int i = 1; i < prices.Length; ++i) + { + f1 = Math.Max(f1, f2 - prices[i]); + f2 = Math.Max(f2, f1 + prices[i]); + } + return f2; + } +} diff --git a/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution2.go b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution2.go new file mode 100644 index 0000000000000..f8df70fecffc2 --- /dev/null +++ b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution2.go @@ -0,0 +1,10 @@ +func maxProfit(prices []int) int { + n := len(prices) + f := make([][2]int, n) + f[0][0] = -prices[0] + for i := 1; i < n; i++ { + f[i][0] = max(f[i-1][0], f[i-1][1]-prices[i]) + f[i][1] = max(f[i-1][1], f[i-1][0]+prices[i]) + } + return f[n-1][1] +} \ No newline at end of file diff --git a/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution2.java b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution2.java new file mode 100644 index 0000000000000..30f977f942f15 --- /dev/null +++ b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution2.java @@ -0,0 +1,12 @@ +class Solution { + public int maxProfit(int[] prices) { + int n = prices.length; + int[][] f = new int[n][2]; + f[0][0] = -prices[0]; + for (int i = 1; i < n; ++i) { + f[i][0] = Math.max(f[i - 1][0], f[i - 1][1] - prices[i]); + f[i][1] = Math.max(f[i - 1][1], f[i - 1][0] + prices[i]); + } + return f[n - 1][1]; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution2.py b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution2.py new file mode 100644 index 0000000000000..244d52383f26f --- /dev/null +++ b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + n = len(prices) + f = [[0] * 2 for _ in range(n)] + f[0][0] = -prices[0] + for i in range(1, n): + f[i][0] = max(f[i - 1][0], f[i - 1][1] - prices[i]) + f[i][1] = max(f[i - 1][1], f[i - 1][0] + prices[i]) + return f[n - 1][1] diff --git a/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution3.cpp b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution3.cpp new file mode 100644 index 0000000000000..f48ba2cf7c839 --- /dev/null +++ b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution3.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int maxProfit(vector& prices) { + int n = prices.size(); + int f[2] = {-prices[0], 0}; + for (int i = 1; i < n; ++i) { + int g[2]; + g[0] = max(f[0], f[1] - prices[i]); + g[1] = max(f[1], f[0] + prices[i]); + f[0] = g[0], f[1] = g[1]; + } + return f[1]; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution3.go b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution3.go new file mode 100644 index 0000000000000..505cb162cde34 --- /dev/null +++ b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution3.go @@ -0,0 +1,11 @@ +func maxProfit(prices []int) int { + n := len(prices) + f := [2]int{-prices[0], 0} + for i := 1; i < n; i++ { + g := [2]int{} + g[0] = max(f[0], f[1]-prices[i]) + g[1] = max(f[1], f[0]+prices[i]) + f = g + } + return f[1] +} \ No newline at end of file diff --git a/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution3.java b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution3.java new file mode 100644 index 0000000000000..efddfe6c273f3 --- /dev/null +++ b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution3.java @@ -0,0 +1,13 @@ +class Solution { + public int maxProfit(int[] prices) { + int n = prices.length; + int[] f = new int[] {-prices[0], 0}; + for (int i = 1; i < n; ++i) { + int[] g = new int[2]; + g[0] = Math.max(f[0], f[1] - prices[i]); + g[1] = Math.max(f[1], f[0] + prices[i]); + f = g; + } + return f[1]; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution3.py b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution3.py new file mode 100644 index 0000000000000..a1a1ac98bca05 --- /dev/null +++ b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution3.py @@ -0,0 +1,10 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + n = len(prices) + f = [-prices[0], 0] + for i in range(1, n): + g = [0] * 2 + g[0] = max(f[0], f[1] - prices[i]) + g[1] = max(f[1], f[0] + prices[i]) + f = g + return f[1] diff --git a/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/Solution.cs b/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/Solution.cs index 9ccd3bbfaf963..485ba2cfd4e15 100644 --- a/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/Solution.cs +++ b/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/Solution.cs @@ -9,4 +9,4 @@ public int MaxProfit(int[] prices) { } return f4; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/Solution.java b/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/Solution.java index 9ccd3bbfaf963..e3977e193d146 100644 --- a/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/Solution.java +++ b/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/Solution.java @@ -1,11 +1,12 @@ -public class Solution { - public int MaxProfit(int[] prices) { +class Solution { + public int maxProfit(int[] prices) { + // 第一次买入,第一次卖出,第二次买入,第二次卖出 int f1 = -prices[0], f2 = 0, f3 = -prices[0], f4 = 0; - for (int i = 1; i < prices.Length; ++i) { - f1 = Math.Max(f1, -prices[i]); - f2 = Math.Max(f2, f1 + prices[i]); - f3 = Math.Max(f3, f2 - prices[i]); - f4 = Math.Max(f4, f3 + prices[i]); + for (int i = 1; i < prices.length; ++i) { + f1 = Math.max(f1, -prices[i]); + f2 = Math.max(f2, f1 + prices[i]); + f3 = Math.max(f3, f2 - prices[i]); + f4 = Math.max(f4, f3 + prices[i]); } return f4; } diff --git a/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/Solution.py b/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/Solution.py index 5f8c5ac655bc6..d7bda56ed3959 100644 --- a/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/Solution.py +++ b/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/Solution.py @@ -1,5 +1,6 @@ class Solution: def maxProfit(self, prices: List[int]) -> int: + # 第一次买入,第一次卖出,第二次买入,第二次卖出 f1, f2, f3, f4 = -prices[0], 0, -prices[0], 0 for price in prices[1:]: f1 = max(f1, -price) diff --git a/solution/0100-0199/0124.Binary Tree Maximum Path Sum/Solution.cpp b/solution/0100-0199/0124.Binary Tree Maximum Path Sum/Solution.cpp index 466357a6006e3..c11b28c7d5cea 100644 --- a/solution/0100-0199/0124.Binary Tree Maximum Path Sum/Solution.cpp +++ b/solution/0100-0199/0124.Binary Tree Maximum Path Sum/Solution.cpp @@ -1,28 +1,28 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int maxPathSum(TreeNode* root) { - int ans = -1001; - function dfs = [&](TreeNode* root) { - if (!root) { - return 0; - } - int left = max(0, dfs(root->left)); - int right = max(0, dfs(root->right)); - ans = max(ans, left + right + root->val); - return root->val + max(left, right); - }; - dfs(root); - return ans; - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int maxPathSum(TreeNode* root) { + int ans = -1001; + function dfs = [&](TreeNode* root) { + if (!root) { + return 0; + } + int left = max(0, dfs(root->left)); + int right = max(0, dfs(root->right)); + ans = max(ans, left + right + root->val); + return root->val + max(left, right); + }; + dfs(root); + return ans; + } }; \ No newline at end of file diff --git a/solution/0100-0199/0124.Binary Tree Maximum Path Sum/Solution.cs b/solution/0100-0199/0124.Binary Tree Maximum Path Sum/Solution.cs index 40b0d3dc2bc60..0d6436df998ad 100644 --- a/solution/0100-0199/0124.Binary Tree Maximum Path Sum/Solution.cs +++ b/solution/0100-0199/0124.Binary Tree Maximum Path Sum/Solution.cs @@ -1,31 +1,31 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -public class Solution { - private int ans = -1001; - - public int MaxPathSum(TreeNode root) { - dfs(root); - return ans; - } - - private int dfs(TreeNode root) { - if (root == null) { - return 0; - } - int left = Math.Max(0, dfs(root.left)); - int right = Math.Max(0, dfs(root.right)); - ans = Math.Max(ans, left + right + root.val); - return root.val + Math.Max(left, right); - } -} \ No newline at end of file +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + private int ans = -1001; + + public int MaxPathSum(TreeNode root) { + dfs(root); + return ans; + } + + private int dfs(TreeNode root) { + if (root == null) { + return 0; + } + int left = Math.Max(0, dfs(root.left)); + int right = Math.Max(0, dfs(root.right)); + ans = Math.Max(ans, left + right + root.val); + return root.val + Math.Max(left, right); + } +} diff --git a/solution/0100-0199/0124.Binary Tree Maximum Path Sum/Solution.java b/solution/0100-0199/0124.Binary Tree Maximum Path Sum/Solution.java index 608ec5183e72f..c211867929b68 100644 --- a/solution/0100-0199/0124.Binary Tree Maximum Path Sum/Solution.java +++ b/solution/0100-0199/0124.Binary Tree Maximum Path Sum/Solution.java @@ -1,33 +1,33 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private int ans = -1001; - - public int maxPathSum(TreeNode root) { - dfs(root); - return ans; - } - - private int dfs(TreeNode root) { - if (root == null) { - return 0; - } - int left = Math.max(0, dfs(root.left)); - int right = Math.max(0, dfs(root.right)); - ans = Math.max(ans, root.val + left + right); - return root.val + Math.max(left, right); - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int ans = -1001; + + public int maxPathSum(TreeNode root) { + dfs(root); + return ans; + } + + private int dfs(TreeNode root) { + if (root == null) { + return 0; + } + int left = Math.max(0, dfs(root.left)); + int right = Math.max(0, dfs(root.right)); + ans = Math.max(ans, root.val + left + right); + return root.val + Math.max(left, right); + } } \ No newline at end of file diff --git a/solution/0100-0199/0124.Binary Tree Maximum Path Sum/Solution.py b/solution/0100-0199/0124.Binary Tree Maximum Path Sum/Solution.py index 2d718b215b91f..6f909001c4cc3 100644 --- a/solution/0100-0199/0124.Binary Tree Maximum Path Sum/Solution.py +++ b/solution/0100-0199/0124.Binary Tree Maximum Path Sum/Solution.py @@ -1,20 +1,20 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def maxPathSum(self, root: Optional[TreeNode]) -> int: - def dfs(root: Optional[TreeNode]) -> int: - if root is None: - return 0 - left = max(0, dfs(root.left)) - right = max(0, dfs(root.right)) - nonlocal ans - ans = max(ans, root.val + left + right) - return root.val + max(left, right) - - ans = -inf - dfs(root) - return ans +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def maxPathSum(self, root: Optional[TreeNode]) -> int: + def dfs(root: Optional[TreeNode]) -> int: + if root is None: + return 0 + left = max(0, dfs(root.left)) + right = max(0, dfs(root.right)) + nonlocal ans + ans = max(ans, root.val + left + right) + return root.val + max(left, right) + + ans = -inf + dfs(root) + return ans diff --git a/solution/0100-0199/0125.Valid Palindrome/Solution.cs b/solution/0100-0199/0125.Valid Palindrome/Solution.cs index 594b7e02f1f13..63110b48d069c 100644 --- a/solution/0100-0199/0125.Valid Palindrome/Solution.cs +++ b/solution/0100-0199/0125.Valid Palindrome/Solution.cs @@ -12,4 +12,4 @@ public bool IsPalindrome(string s) { } return true; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0125.Valid Palindrome/Solution.php b/solution/0100-0199/0125.Valid Palindrome/Solution.php index dc4aec3dc5ead..7f7ce2a40192e 100644 --- a/solution/0100-0199/0125.Valid Palindrome/Solution.php +++ b/solution/0100-0199/0125.Valid Palindrome/Solution.php @@ -18,4 +18,4 @@ function isPalindrome($s) { } return true; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0127.Word Ladder/Solution.cpp b/solution/0100-0199/0127.Word Ladder/Solution.cpp index a3aeb9ed860f4..796779ca50d81 100644 --- a/solution/0100-0199/0127.Word Ladder/Solution.cpp +++ b/solution/0100-0199/0127.Word Ladder/Solution.cpp @@ -2,37 +2,26 @@ class Solution { public: int ladderLength(string beginWord, string endWord, vector& wordList) { unordered_set words(wordList.begin(), wordList.end()); - if (!words.count(endWord)) return 0; - queue q1{{beginWord}}; - queue q2{{endWord}}; - unordered_map m1; - unordered_map m2; - m1[beginWord] = 0; - m2[endWord] = 0; - while (!q1.empty() && !q2.empty()) { - int t = q1.size() <= q2.size() ? extend(m1, m2, q1, words) : extend(m2, m1, q2, words); - if (t != -1) return t + 1; - } - return 0; - } - - int extend(unordered_map& m1, unordered_map& m2, queue& q, unordered_set& words) { - for (int i = q.size(); i > 0; --i) { - string s = q.front(); - int step = m1[s]; - q.pop(); - for (int j = 0; j < s.size(); ++j) { - char ch = s[j]; - for (char k = 'a'; k <= 'z'; ++k) { - s[j] = k; - if (!words.count(s) || m1.count(s)) continue; - if (m2.count(s)) return step + 1 + m2[s]; - m1[s] = step + 1; - q.push(s); + queue q{{beginWord}}; + int ans = 1; + while (!q.empty()) { + ++ans; + for (int i = q.size(); i > 0; --i) { + string s = q.front(); + q.pop(); + for (int j = 0; j < s.size(); ++j) { + char ch = s[j]; + for (char k = 'a'; k <= 'z'; ++k) { + s[j] = k; + if (!words.count(s)) continue; + if (s == endWord) return ans; + q.push(s); + words.erase(s); + } + s[j] = ch; } - s[j] = ch; } } - return -1; + return 0; } }; \ No newline at end of file diff --git a/solution/0100-0199/0127.Word Ladder/Solution.go b/solution/0100-0199/0127.Word Ladder/Solution.go index 7922ed2a98439..ec9a668749064 100644 --- a/solution/0100-0199/0127.Word Ladder/Solution.go +++ b/solution/0100-0199/0127.Word Ladder/Solution.go @@ -3,17 +3,13 @@ func ladderLength(beginWord string, endWord string, wordList []string) int { for _, word := range wordList { words[word] = true } - if !words[endWord] { - return 0 - } - - q1, q2 := []string{beginWord}, []string{endWord} - m1, m2 := map[string]int{beginWord: 0}, map[string]int{endWord: 0} - extend := func() int { - for i := len(q1); i > 0; i-- { - s := q1[0] - step, _ := m1[s] - q1 = q1[1:] + q := []string{beginWord} + ans := 1 + for len(q) > 0 { + ans++ + for i := len(q); i > 0; i-- { + s := q[0] + q = q[1:] chars := []byte(s) for j := 0; j < len(chars); j++ { ch := chars[j] @@ -23,29 +19,15 @@ func ladderLength(beginWord string, endWord string, wordList []string) int { if !words[t] { continue } - if _, ok := m1[t]; ok { - continue - } - if v, ok := m2[t]; ok { - return step + 1 + v + if t == endWord { + return ans } - q1 = append(q1, t) - m1[t] = step + 1 + q = append(q, t) + words[t] = false } chars[j] = ch } } - return -1 - } - for len(q1) > 0 && len(q2) > 0 { - if len(q1) > len(q2) { - m1, m2 = m2, m1 - q1, q2 = q2, q1 - } - t := extend() - if t != -1 { - return t + 1 - } } return 0 } \ No newline at end of file diff --git a/solution/0100-0199/0127.Word Ladder/Solution.java b/solution/0100-0199/0127.Word Ladder/Solution.java index f83ca50d19747..9df3fe94d77f6 100644 --- a/solution/0100-0199/0127.Word Ladder/Solution.java +++ b/solution/0100-0199/0127.Word Ladder/Solution.java @@ -1,50 +1,32 @@ class Solution { - private Set words; - public int ladderLength(String beginWord, String endWord, List wordList) { - words = new HashSet<>(wordList); - if (!words.contains(endWord)) { - return 0; - } - Queue q1 = new ArrayDeque<>(); - Queue q2 = new ArrayDeque<>(); - Map m1 = new HashMap<>(); - Map m2 = new HashMap<>(); - q1.offer(beginWord); - q2.offer(endWord); - m1.put(beginWord, 0); - m2.put(endWord, 0); - while (!q1.isEmpty() && !q2.isEmpty()) { - int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); - if (t != -1) { - return t + 1; - } - } - return 0; - } - - private int extend(Map m1, Map m2, Queue q) { - for (int i = q.size(); i > 0; --i) { - String s = q.poll(); - int step = m1.get(s); - char[] chars = s.toCharArray(); - for (int j = 0; j < chars.length; ++j) { - char ch = chars[j]; - for (char k = 'a'; k <= 'z'; ++k) { - chars[j] = k; - String t = new String(chars); - if (!words.contains(t) || m1.containsKey(t)) { - continue; - } - if (m2.containsKey(t)) { - return step + 1 + m2.get(t); + Set words = new HashSet<>(wordList); + Queue q = new ArrayDeque<>(); + q.offer(beginWord); + int ans = 1; + while (!q.isEmpty()) { + ++ans; + for (int i = q.size(); i > 0; --i) { + String s = q.poll(); + char[] chars = s.toCharArray(); + for (int j = 0; j < chars.length; ++j) { + char ch = chars[j]; + for (char k = 'a'; k <= 'z'; ++k) { + chars[j] = k; + String t = new String(chars); + if (!words.contains(t)) { + continue; + } + if (endWord.equals(t)) { + return ans; + } + q.offer(t); + words.remove(t); } - q.offer(t); - m1.put(t, step + 1); + chars[j] = ch; } - chars[j] = ch; } } - return -1; + return 0; } } \ No newline at end of file diff --git a/solution/0100-0199/0127.Word Ladder/Solution.py b/solution/0100-0199/0127.Word Ladder/Solution.py index a353f6f45e68f..c209fe09ed0fa 100644 --- a/solution/0100-0199/0127.Word Ladder/Solution.py +++ b/solution/0100-0199/0127.Word Ladder/Solution.py @@ -1,31 +1,23 @@ -class Solution: - def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: - def extend(m1, m2, q): - for _ in range(len(q)): - s = q.popleft() - step = m1[s] - s = list(s) - for i in range(len(s)): - ch = s[i] - for j in range(26): - s[i] = chr(ord('a') + j) - t = ''.join(s) - if t in m1 or t not in words: - continue - if t in m2: - return step + 1 + m2[t] - m1[t] = step + 1 - q.append(t) - s[i] = ch - return -1 - - words = set(wordList) - if endWord not in words: - return 0 - q1, q2 = deque([beginWord]), deque([endWord]) - m1, m2 = {beginWord: 0}, {endWord: 0} - while q1 and q2: - t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) - if t != -1: - return t + 1 - return 0 +class Solution: + def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: + words = set(wordList) + q = deque([beginWord]) + ans = 1 + while q: + ans += 1 + for _ in range(len(q)): + s = q.popleft() + s = list(s) + for i in range(len(s)): + ch = s[i] + for j in range(26): + s[i] = chr(ord('a') + j) + t = ''.join(s) + if t not in words: + continue + if t == endWord: + return ans + q.append(t) + words.remove(t) + s[i] = ch + return 0 diff --git a/solution/0100-0199/0127.Word Ladder/Solution2.cpp b/solution/0100-0199/0127.Word Ladder/Solution2.cpp new file mode 100644 index 0000000000000..a3aeb9ed860f4 --- /dev/null +++ b/solution/0100-0199/0127.Word Ladder/Solution2.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + int ladderLength(string beginWord, string endWord, vector& wordList) { + unordered_set words(wordList.begin(), wordList.end()); + if (!words.count(endWord)) return 0; + queue q1{{beginWord}}; + queue q2{{endWord}}; + unordered_map m1; + unordered_map m2; + m1[beginWord] = 0; + m2[endWord] = 0; + while (!q1.empty() && !q2.empty()) { + int t = q1.size() <= q2.size() ? extend(m1, m2, q1, words) : extend(m2, m1, q2, words); + if (t != -1) return t + 1; + } + return 0; + } + + int extend(unordered_map& m1, unordered_map& m2, queue& q, unordered_set& words) { + for (int i = q.size(); i > 0; --i) { + string s = q.front(); + int step = m1[s]; + q.pop(); + for (int j = 0; j < s.size(); ++j) { + char ch = s[j]; + for (char k = 'a'; k <= 'z'; ++k) { + s[j] = k; + if (!words.count(s) || m1.count(s)) continue; + if (m2.count(s)) return step + 1 + m2[s]; + m1[s] = step + 1; + q.push(s); + } + s[j] = ch; + } + } + return -1; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0127.Word Ladder/Solution2.go b/solution/0100-0199/0127.Word Ladder/Solution2.go new file mode 100644 index 0000000000000..7922ed2a98439 --- /dev/null +++ b/solution/0100-0199/0127.Word Ladder/Solution2.go @@ -0,0 +1,51 @@ +func ladderLength(beginWord string, endWord string, wordList []string) int { + words := make(map[string]bool) + for _, word := range wordList { + words[word] = true + } + if !words[endWord] { + return 0 + } + + q1, q2 := []string{beginWord}, []string{endWord} + m1, m2 := map[string]int{beginWord: 0}, map[string]int{endWord: 0} + extend := func() int { + for i := len(q1); i > 0; i-- { + s := q1[0] + step, _ := m1[s] + q1 = q1[1:] + chars := []byte(s) + for j := 0; j < len(chars); j++ { + ch := chars[j] + for k := 'a'; k <= 'z'; k++ { + chars[j] = byte(k) + t := string(chars) + if !words[t] { + continue + } + if _, ok := m1[t]; ok { + continue + } + if v, ok := m2[t]; ok { + return step + 1 + v + } + q1 = append(q1, t) + m1[t] = step + 1 + } + chars[j] = ch + } + } + return -1 + } + for len(q1) > 0 && len(q2) > 0 { + if len(q1) > len(q2) { + m1, m2 = m2, m1 + q1, q2 = q2, q1 + } + t := extend() + if t != -1 { + return t + 1 + } + } + return 0 +} \ No newline at end of file diff --git a/solution/0100-0199/0127.Word Ladder/Solution2.java b/solution/0100-0199/0127.Word Ladder/Solution2.java new file mode 100644 index 0000000000000..f83ca50d19747 --- /dev/null +++ b/solution/0100-0199/0127.Word Ladder/Solution2.java @@ -0,0 +1,50 @@ +class Solution { + private Set words; + + public int ladderLength(String beginWord, String endWord, List wordList) { + words = new HashSet<>(wordList); + if (!words.contains(endWord)) { + return 0; + } + Queue q1 = new ArrayDeque<>(); + Queue q2 = new ArrayDeque<>(); + Map m1 = new HashMap<>(); + Map m2 = new HashMap<>(); + q1.offer(beginWord); + q2.offer(endWord); + m1.put(beginWord, 0); + m2.put(endWord, 0); + while (!q1.isEmpty() && !q2.isEmpty()) { + int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); + if (t != -1) { + return t + 1; + } + } + return 0; + } + + private int extend(Map m1, Map m2, Queue q) { + for (int i = q.size(); i > 0; --i) { + String s = q.poll(); + int step = m1.get(s); + char[] chars = s.toCharArray(); + for (int j = 0; j < chars.length; ++j) { + char ch = chars[j]; + for (char k = 'a'; k <= 'z'; ++k) { + chars[j] = k; + String t = new String(chars); + if (!words.contains(t) || m1.containsKey(t)) { + continue; + } + if (m2.containsKey(t)) { + return step + 1 + m2.get(t); + } + q.offer(t); + m1.put(t, step + 1); + } + chars[j] = ch; + } + } + return -1; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0127.Word Ladder/Solution2.py b/solution/0100-0199/0127.Word Ladder/Solution2.py new file mode 100644 index 0000000000000..1bd38a2ca039f --- /dev/null +++ b/solution/0100-0199/0127.Word Ladder/Solution2.py @@ -0,0 +1,31 @@ +class Solution: + def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: + def extend(m1, m2, q): + for _ in range(len(q)): + s = q.popleft() + step = m1[s] + s = list(s) + for i in range(len(s)): + ch = s[i] + for j in range(26): + s[i] = chr(ord('a') + j) + t = ''.join(s) + if t in m1 or t not in words: + continue + if t in m2: + return step + 1 + m2[t] + m1[t] = step + 1 + q.append(t) + s[i] = ch + return -1 + + words = set(wordList) + if endWord not in words: + return 0 + q1, q2 = deque([beginWord]), deque([endWord]) + m1, m2 = {beginWord: 0}, {endWord: 0} + while q1 and q2: + t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) + if t != -1: + return t + 1 + return 0 diff --git a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.cpp b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.cpp index 63963f9f4512b..a3c9a84ec208c 100644 --- a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.cpp +++ b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.cpp @@ -1,15 +1,20 @@ class Solution { public: int longestConsecutive(vector& nums) { - unordered_set s(nums.begin(), nums.end()); - int ans = 0; - for (int x : nums) { - if (!s.count(x - 1)) { - int y = x + 1; - while (s.count(y)) { - y++; - } - ans = max(ans, y - x); + int n = nums.size(); + if (n < 2) { + return n; + } + sort(nums.begin(), nums.end()); + int ans = 1, t = 1; + for (int i = 1; i < n; ++i) { + if (nums[i] == nums[i - 1]) { + continue; + } + if (nums[i] == nums[i - 1] + 1) { + ans = max(ans, ++t); + } else { + t = 1; } } return ans; diff --git a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.go b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.go index 1a38e03b11467..272692b96d9ad 100644 --- a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.go +++ b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.go @@ -1,16 +1,20 @@ -func longestConsecutive(nums []int) (ans int) { - s := map[int]bool{} - for _, x := range nums { - s[x] = true +func longestConsecutive(nums []int) int { + n := len(nums) + if n < 2 { + return n } - for _, x := range nums { - if !s[x-1] { - y := x + 1 - for s[y] { - y++ - } - ans = max(ans, y-x) + sort.Ints(nums) + ans, t := 1, 1 + for i, x := range nums[1:] { + if x == nums[i] { + continue + } + if x == nums[i]+1 { + t++ + ans = max(ans, t) + } else { + t = 1 } } - return + return ans } \ No newline at end of file diff --git a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.java b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.java index 9fbf604320adb..511b5cc8b24b0 100644 --- a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.java +++ b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.java @@ -1,17 +1,19 @@ class Solution { public int longestConsecutive(int[] nums) { - Set s = new HashSet<>(); - for (int x : nums) { - s.add(x); + int n = nums.length; + if (n < 2) { + return n; } - int ans = 0; - for (int x : nums) { - if (!s.contains(x - 1)) { - int y = x + 1; - while (s.contains(y)) { - ++y; - } - ans = Math.max(ans, y - x); + Arrays.sort(nums); + int ans = 1, t = 1; + for (int i = 1; i < n; ++i) { + if (nums[i] == nums[i - 1]) { + continue; + } + if (nums[i] == nums[i - 1] + 1) { + ans = Math.max(ans, ++t); + } else { + t = 1; } } return ans; diff --git a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.js b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.js index 9fcb550988044..626571486477c 100644 --- a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.js +++ b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.js @@ -3,15 +3,21 @@ * @return {number} */ var longestConsecutive = function (nums) { - const s = new Set(nums); - let ans = 0; - for (const x of nums) { - if (!s.has(x - 1)) { - let y = x + 1; - while (s.has(y)) { - y++; - } - ans = Math.max(ans, y - x); + const n = nums.length; + if (n < 2) { + return n; + } + nums.sort((a, b) => a - b); + let ans = 1; + let t = 1; + for (let i = 1; i < n; ++i) { + if (nums[i] === nums[i - 1]) { + continue; + } + if (nums[i] === nums[i - 1] + 1) { + ans = Math.max(ans, ++t); + } else { + t = 1; } } return ans; diff --git a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.py b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.py index cd60849601a20..2f769cf2e22de 100644 --- a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.py +++ b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.py @@ -1,11 +1,16 @@ class Solution: def longestConsecutive(self, nums: List[int]) -> int: - s = set(nums) - ans = 0 - for x in nums: - if x - 1 not in s: - y = x + 1 - while y in s: - y += 1 - ans = max(ans, y - x) + n = len(nums) + if n < 2: + return n + nums.sort() + ans = t = 1 + for a, b in pairwise(nums): + if a == b: + continue + if a + 1 == b: + t += 1 + ans = max(ans, t) + else: + t = 1 return ans diff --git a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.ts b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.ts index 7e593ca8830d1..fb0fc69cfc134 100644 --- a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.ts +++ b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.ts @@ -1,13 +1,19 @@ function longestConsecutive(nums: number[]): number { - const s: Set = new Set(nums); - let ans = 0; - for (const x of s) { - if (!s.has(x - 1)) { - let y = x + 1; - while (s.has(y)) { - y++; - } - ans = Math.max(ans, y - x); + const n = nums.length; + if (n < 2) { + return n; + } + let ans = 1; + let t = 1; + nums.sort((a, b) => a - b); + for (let i = 1; i < n; ++i) { + if (nums[i] === nums[i - 1]) { + continue; + } + if (nums[i] === nums[i - 1] + 1) { + ans = Math.max(ans, ++t); + } else { + t = 1; } } return ans; diff --git a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.cpp b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.cpp new file mode 100644 index 0000000000000..63963f9f4512b --- /dev/null +++ b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int longestConsecutive(vector& nums) { + unordered_set s(nums.begin(), nums.end()); + int ans = 0; + for (int x : nums) { + if (!s.count(x - 1)) { + int y = x + 1; + while (s.count(y)) { + y++; + } + ans = max(ans, y - x); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.go b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.go new file mode 100644 index 0000000000000..1a38e03b11467 --- /dev/null +++ b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.go @@ -0,0 +1,16 @@ +func longestConsecutive(nums []int) (ans int) { + s := map[int]bool{} + for _, x := range nums { + s[x] = true + } + for _, x := range nums { + if !s[x-1] { + y := x + 1 + for s[y] { + y++ + } + ans = max(ans, y-x) + } + } + return +} \ No newline at end of file diff --git a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.java b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.java new file mode 100644 index 0000000000000..9fbf604320adb --- /dev/null +++ b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.java @@ -0,0 +1,19 @@ +class Solution { + public int longestConsecutive(int[] nums) { + Set s = new HashSet<>(); + for (int x : nums) { + s.add(x); + } + int ans = 0; + for (int x : nums) { + if (!s.contains(x - 1)) { + int y = x + 1; + while (s.contains(y)) { + ++y; + } + ans = Math.max(ans, y - x); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.js b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.js new file mode 100644 index 0000000000000..9fcb550988044 --- /dev/null +++ b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.js @@ -0,0 +1,18 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var longestConsecutive = function (nums) { + const s = new Set(nums); + let ans = 0; + for (const x of nums) { + if (!s.has(x - 1)) { + let y = x + 1; + while (s.has(y)) { + y++; + } + ans = Math.max(ans, y - x); + } + } + return ans; +}; diff --git a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.py b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.py new file mode 100644 index 0000000000000..cd60849601a20 --- /dev/null +++ b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + s = set(nums) + ans = 0 + for x in nums: + if x - 1 not in s: + y = x + 1 + while y in s: + y += 1 + ans = max(ans, y - x) + return ans diff --git a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.ts b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.ts new file mode 100644 index 0000000000000..7e593ca8830d1 --- /dev/null +++ b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.ts @@ -0,0 +1,14 @@ +function longestConsecutive(nums: number[]): number { + const s: Set = new Set(nums); + let ans = 0; + for (const x of s) { + if (!s.has(x - 1)) { + let y = x + 1; + while (s.has(y)) { + y++; + } + ans = Math.max(ans, y - x); + } + } + return ans; +} diff --git a/solution/0100-0199/0129.Sum Root to Leaf Numbers/Solution.c b/solution/0100-0199/0129.Sum Root to Leaf Numbers/Solution.c index 7e9f3a3707ed9..251ad39c99873 100644 --- a/solution/0100-0199/0129.Sum Root to Leaf Numbers/Solution.c +++ b/solution/0100-0199/0129.Sum Root to Leaf Numbers/Solution.c @@ -20,4 +20,4 @@ int dfs(struct TreeNode* root, int num) { int sumNumbers(struct TreeNode* root) { return dfs(root, 0); -} +} \ No newline at end of file diff --git a/solution/0100-0199/0129.Sum Root to Leaf Numbers/Solution.cpp b/solution/0100-0199/0129.Sum Root to Leaf Numbers/Solution.cpp index 5d8b91c83c7c2..6fc3138eaa0ea 100644 --- a/solution/0100-0199/0129.Sum Root to Leaf Numbers/Solution.cpp +++ b/solution/0100-0199/0129.Sum Root to Leaf Numbers/Solution.cpp @@ -1,23 +1,23 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int sumNumbers(TreeNode* root) { - function dfs = [&](TreeNode* root, int s) -> int { - if (!root) return 0; - s = s * 10 + root->val; - if (!root->left && !root->right) return s; - return dfs(root->left, s) + dfs(root->right, s); - }; - return dfs(root, 0); - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int sumNumbers(TreeNode* root) { + function dfs = [&](TreeNode* root, int s) -> int { + if (!root) return 0; + s = s * 10 + root->val; + if (!root->left && !root->right) return s; + return dfs(root->left, s) + dfs(root->right, s); + }; + return dfs(root, 0); + } }; \ No newline at end of file diff --git a/solution/0100-0199/0130.Surrounded Regions/Solution2.cpp b/solution/0100-0199/0130.Surrounded Regions/Solution2.cpp new file mode 100644 index 0000000000000..8661754713bce --- /dev/null +++ b/solution/0100-0199/0130.Surrounded Regions/Solution2.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + vector p; + + void solve(vector>& board) { + int m = board.size(), n = board[0].size(); + p.resize(m * n + 1); + for (int i = 0; i < p.size(); ++i) p[i] = i; + vector dirs = {-1, 0, 1, 0, -1}; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (board[i][j] == 'O') { + if (i == 0 || i == m - 1 || j == 0 || j == n - 1) + p[find(i * n + j)] = find(m * n); + else { + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (board[x][y] == 'O') p[find(x * n + y)] = find(i * n + j); + } + } + } + } + } + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (board[i][j] == 'O' && find(i * n + j) != find(m * n)) + board[i][j] = 'X'; + } + + int find(int x) { + if (p[x] != x) p[x] = find(p[x]); + return p[x]; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0130.Surrounded Regions/Solution2.go b/solution/0100-0199/0130.Surrounded Regions/Solution2.go new file mode 100644 index 0000000000000..d4c0bead9475e --- /dev/null +++ b/solution/0100-0199/0130.Surrounded Regions/Solution2.go @@ -0,0 +1,38 @@ +func solve(board [][]byte) { + m, n := len(board), len(board[0]) + p := make([]int, m*n+1) + for i := range p { + p[i] = i + } + var find func(x int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + dirs := []int{-1, 0, 1, 0, -1} + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if board[i][j] == 'O' { + if i == 0 || i == m-1 || j == 0 || j == n-1 { + p[find(i*n+j)] = find(m * n) + } else { + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if board[x][y] == 'O' { + p[find(x*n+y)] = find(i*n + j) + } + } + } + } + } + } + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if board[i][j] == 'O' && find(i*n+j) != find(m*n) { + board[i][j] = 'X' + } + } + } +} \ No newline at end of file diff --git a/solution/0100-0199/0130.Surrounded Regions/Solution2.java b/solution/0100-0199/0130.Surrounded Regions/Solution2.java new file mode 100644 index 0000000000000..9baf054b4f6af --- /dev/null +++ b/solution/0100-0199/0130.Surrounded Regions/Solution2.java @@ -0,0 +1,44 @@ +class Solution { + private int[] p; + + public void solve(char[][] board) { + int m = board.length; + int n = board[0].length; + p = new int[m * n + 1]; + for (int i = 0; i < p.length; ++i) { + p[i] = i; + } + int[] dirs = {-1, 0, 1, 0, -1}; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (board[i][j] == 'O') { + if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { + p[find(i * n + j)] = find(m * n); + } else { + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k]; + int y = j + dirs[k + 1]; + if (board[x][y] == 'O') { + p[find(x * n + y)] = find(i * n + j); + } + } + } + } + } + } + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (board[i][j] == 'O' && find(i * n + j) != find(m * n)) { + board[i][j] = 'X'; + } + } + } + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0130.Surrounded Regions/Solution2.py b/solution/0100-0199/0130.Surrounded Regions/Solution2.py new file mode 100644 index 0000000000000..1a9c792a2ac11 --- /dev/null +++ b/solution/0100-0199/0130.Surrounded Regions/Solution2.py @@ -0,0 +1,27 @@ +class Solution: + def solve(self, board: List[List[str]]) -> None: + """ + Do not return anything, modify board in-place instead. + """ + + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + m, n = len(board), len(board[0]) + p = list(range(m * n + 1)) + for i in range(m): + for j in range(n): + if board[i][j] == 'O': + if i == 0 or i == m - 1 or j == 0 or j == n - 1: + p[find(i * n + j)] = find(m * n) + else: + for a, b in [(-1, 0), (1, 0), (0, -1), (0, 1)]: + x, y = i + a, j + b + if board[x][y] == 'O': + p[find(x * n + y)] = find(i * n + j) + for i in range(m): + for j in range(n): + if board[i][j] == 'O' and find(i * n + j) != find(m * n): + board[i][j] = 'X' diff --git a/solution/0100-0199/0130.Surrounded Regions/Solution2.ts b/solution/0100-0199/0130.Surrounded Regions/Solution2.ts new file mode 100644 index 0000000000000..d2bf9f4c1d73c --- /dev/null +++ b/solution/0100-0199/0130.Surrounded Regions/Solution2.ts @@ -0,0 +1,42 @@ +/** + Do not return anything, modify board in-place instead. + */ +function solve(board: string[][]): void { + const m = board.length; + const n = board[0].length; + let p = new Array(m * n + 1); + for (let i = 0; i < p.length; ++i) { + p[i] = i; + } + function find(x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + const dirs = [-1, 0, 1, 0, -1]; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (board[i][j] == 'O') { + if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { + p[find(i * n + j)] = find(m * n); + } else { + for (let k = 0; k < 4; ++k) { + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (board[x][y] == 'O') { + p[find(x * n + y)] = find(i * n + j); + } + } + } + } + } + } + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (board[i][j] == 'O' && find(i * n + j) != find(m * n)) { + board[i][j] = 'X'; + } + } + } +} diff --git a/solution/0100-0199/0131.Palindrome Partitioning/Solution.cpp b/solution/0100-0199/0131.Palindrome Partitioning/Solution.cpp index f98e5408f031d..e5397fdbf168c 100644 --- a/solution/0100-0199/0131.Palindrome Partitioning/Solution.cpp +++ b/solution/0100-0199/0131.Palindrome Partitioning/Solution.cpp @@ -1,30 +1,30 @@ -class Solution { -public: - vector> partition(string s) { - int n = s.size(); - bool f[n][n]; - memset(f, true, sizeof(f)); - for (int i = n - 1; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - f[i][j] = s[i] == s[j] && f[i + 1][j - 1]; - } - } - vector> ans; - vector t; - function dfs = [&](int i) { - if (i == n) { - ans.push_back(t); - return; - } - for (int j = i; j < n; ++j) { - if (f[i][j]) { - t.push_back(s.substr(i, j - i + 1)); - dfs(j + 1); - t.pop_back(); - } - } - }; - dfs(0); - return ans; - } +class Solution { +public: + vector> partition(string s) { + int n = s.size(); + bool f[n][n]; + memset(f, true, sizeof(f)); + for (int i = n - 1; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + f[i][j] = s[i] == s[j] && f[i + 1][j - 1]; + } + } + vector> ans; + vector t; + function dfs = [&](int i) { + if (i == n) { + ans.push_back(t); + return; + } + for (int j = i; j < n; ++j) { + if (f[i][j]) { + t.push_back(s.substr(i, j - i + 1)); + dfs(j + 1); + t.pop_back(); + } + } + }; + dfs(0); + return ans; + } }; \ No newline at end of file diff --git a/solution/0100-0199/0131.Palindrome Partitioning/Solution.cs b/solution/0100-0199/0131.Palindrome Partitioning/Solution.cs index cf90cec707e9a..cd30c546517df 100644 --- a/solution/0100-0199/0131.Palindrome Partitioning/Solution.cs +++ b/solution/0100-0199/0131.Palindrome Partitioning/Solution.cs @@ -36,4 +36,4 @@ private void dfs(int i) { } } } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0132.Palindrome Partitioning II/Solution.cpp b/solution/0100-0199/0132.Palindrome Partitioning II/Solution.cpp index 5a23e3990b687..05402be952676 100644 --- a/solution/0100-0199/0132.Palindrome Partitioning II/Solution.cpp +++ b/solution/0100-0199/0132.Palindrome Partitioning II/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - int minCut(string s) { - int n = s.size(); - bool g[n][n]; - memset(g, true, sizeof(g)); - for (int i = n - 1; ~i; --i) { - for (int j = i + 1; j < n; ++j) { - g[i][j] = s[i] == s[j] && g[i + 1][j - 1]; - } - } - int f[n]; - iota(f, f + n, 0); - for (int i = 1; i < n; ++i) { - for (int j = 0; j <= i; ++j) { - if (g[j][i]) { - f[i] = min(f[i], j ? 1 + f[j - 1] : 0); - } - } - } - return f[n - 1]; - } -}; +class Solution { +public: + int minCut(string s) { + int n = s.size(); + bool g[n][n]; + memset(g, true, sizeof(g)); + for (int i = n - 1; ~i; --i) { + for (int j = i + 1; j < n; ++j) { + g[i][j] = s[i] == s[j] && g[i + 1][j - 1]; + } + } + int f[n]; + iota(f, f + n, 0); + for (int i = 1; i < n; ++i) { + for (int j = 0; j <= i; ++j) { + if (g[j][i]) { + f[i] = min(f[i], j ? 1 + f[j - 1] : 0); + } + } + } + return f[n - 1]; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0132.Palindrome Partitioning II/Solution.cs b/solution/0100-0199/0132.Palindrome Partitioning II/Solution.cs index 6a3e6be7ba41d..0c582524df1c3 100644 --- a/solution/0100-0199/0132.Palindrome Partitioning II/Solution.cs +++ b/solution/0100-0199/0132.Palindrome Partitioning II/Solution.cs @@ -1,26 +1,26 @@ -public class Solution { - public int MinCut(string s) { - int n = s.Length; - bool[,] g = new bool[n,n]; - int[] f = new int[n]; - for (int i = 0; i < n; ++i) { - f[i] = i; - for (int j = 0; j < n; ++j) { - g[i,j] = true; - } - } - for (int i = n - 1; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - g[i,j] = s[i] == s[j] && g[i + 1,j - 1]; - } - } - for (int i = 1; i < n; ++i) { - for (int j = 0; j <= i; ++j) { - if (g[j,i]) { - f[i] = Math.Min(f[i], j > 0 ? 1 + f[j - 1] : 0); - } - } - } - return f[n - 1]; - } -} \ No newline at end of file +public class Solution { + public int MinCut(string s) { + int n = s.Length; + bool[,] g = new bool[n,n]; + int[] f = new int[n]; + for (int i = 0; i < n; ++i) { + f[i] = i; + for (int j = 0; j < n; ++j) { + g[i,j] = true; + } + } + for (int i = n - 1; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + g[i,j] = s[i] == s[j] && g[i + 1,j - 1]; + } + } + for (int i = 1; i < n; ++i) { + for (int j = 0; j <= i; ++j) { + if (g[j,i]) { + f[i] = Math.Min(f[i], j > 0 ? 1 + f[j - 1] : 0); + } + } + } + return f[n - 1]; + } +} diff --git a/solution/0100-0199/0132.Palindrome Partitioning II/Solution.java b/solution/0100-0199/0132.Palindrome Partitioning II/Solution.java index 6bb02d8a2b459..b424efd8d65e2 100644 --- a/solution/0100-0199/0132.Palindrome Partitioning II/Solution.java +++ b/solution/0100-0199/0132.Palindrome Partitioning II/Solution.java @@ -1,26 +1,26 @@ -class Solution { - public int minCut(String s) { - int n = s.length(); - boolean[][] g = new boolean[n][n]; - for (var row : g) { - Arrays.fill(row, true); - } - for (int i = n - 1; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - g[i][j] = s.charAt(i) == s.charAt(j) && g[i + 1][j - 1]; - } - } - int[] f = new int[n]; - for (int i = 0; i < n; ++i) { - f[i] = i; - } - for (int i = 1; i < n; ++i) { - for (int j = 0; j <= i; ++j) { - if (g[j][i]) { - f[i] = Math.min(f[i], j > 0 ? 1 + f[j - 1] : 0); - } - } - } - return f[n - 1]; - } +class Solution { + public int minCut(String s) { + int n = s.length(); + boolean[][] g = new boolean[n][n]; + for (var row : g) { + Arrays.fill(row, true); + } + for (int i = n - 1; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + g[i][j] = s.charAt(i) == s.charAt(j) && g[i + 1][j - 1]; + } + } + int[] f = new int[n]; + for (int i = 0; i < n; ++i) { + f[i] = i; + } + for (int i = 1; i < n; ++i) { + for (int j = 0; j <= i; ++j) { + if (g[j][i]) { + f[i] = Math.min(f[i], j > 0 ? 1 + f[j - 1] : 0); + } + } + } + return f[n - 1]; + } } \ No newline at end of file diff --git a/solution/0100-0199/0132.Palindrome Partitioning II/Solution.py b/solution/0100-0199/0132.Palindrome Partitioning II/Solution.py index d2a7b44ffc9a0..39e56e61a23ee 100644 --- a/solution/0100-0199/0132.Palindrome Partitioning II/Solution.py +++ b/solution/0100-0199/0132.Palindrome Partitioning II/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def minCut(self, s: str) -> int: - n = len(s) - g = [[True] * n for _ in range(n)] - for i in range(n - 1, -1, -1): - for j in range(i + 1, n): - g[i][j] = s[i] == s[j] and g[i + 1][j - 1] - f = list(range(n)) - for i in range(1, n): - for j in range(i + 1): - if g[j][i]: - f[i] = min(f[i], 1 + f[j - 1] if j else 0) - return f[-1] +class Solution: + def minCut(self, s: str) -> int: + n = len(s) + g = [[True] * n for _ in range(n)] + for i in range(n - 1, -1, -1): + for j in range(i + 1, n): + g[i][j] = s[i] == s[j] and g[i + 1][j - 1] + f = list(range(n)) + for i in range(1, n): + for j in range(i + 1): + if g[j][i]: + f[i] = min(f[i], 1 + f[j - 1] if j else 0) + return f[-1] diff --git a/solution/0100-0199/0134.Gas Station/Solution.cs b/solution/0100-0199/0134.Gas Station/Solution.cs index 27d665cfcf3f2..90a6a38e43b78 100644 --- a/solution/0100-0199/0134.Gas Station/Solution.cs +++ b/solution/0100-0199/0134.Gas Station/Solution.cs @@ -15,4 +15,4 @@ public int CanCompleteCircuit(int[] gas, int[] cost) { } return s < 0 ? -1 : i; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0135.Candy/Solution.cs b/solution/0100-0199/0135.Candy/Solution.cs index 2cd3afd075731..e1e575315a442 100644 --- a/solution/0100-0199/0135.Candy/Solution.cs +++ b/solution/0100-0199/0135.Candy/Solution.cs @@ -21,4 +21,4 @@ public int Candy(int[] ratings) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0135.Candy/Solution.java b/solution/0100-0199/0135.Candy/Solution.java index 12695f93146a2..0fcbd2d60ca2a 100644 --- a/solution/0100-0199/0135.Candy/Solution.java +++ b/solution/0100-0199/0135.Candy/Solution.java @@ -1,27 +1,24 @@ class Solution { public int candy(int[] ratings) { int n = ratings.length; - int up = 0; - int down = 0; - int peak = 0; - int candies = 1; - for (int i = 1; i < n; i++) { - if (ratings[i - 1] < ratings[i]) { - up++; - peak = up + 1; - down = 0; - candies += peak; - } else if (ratings[i] == ratings[i - 1]) { - peak = 0; - up = 0; - down = 0; - candies++; - } else { - down++; - up = 0; - candies += down + (peak > down ? 0 : 1); + int[] left = new int[n]; + int[] right = new int[n]; + Arrays.fill(left, 1); + Arrays.fill(right, 1); + for (int i = 1; i < n; ++i) { + if (ratings[i] > ratings[i - 1]) { + left[i] = left[i - 1] + 1; } } - return candies; + for (int i = n - 2; i >= 0; --i) { + if (ratings[i] > ratings[i + 1]) { + right[i] = right[i + 1] + 1; + } + } + int ans = 0; + for (int i = 0; i < n; ++i) { + ans += Math.max(left[i], right[i]); + } + return ans; } } \ No newline at end of file diff --git a/solution/0100-0199/0135.Candy/Solution2.java b/solution/0100-0199/0135.Candy/Solution2.java new file mode 100644 index 0000000000000..12695f93146a2 --- /dev/null +++ b/solution/0100-0199/0135.Candy/Solution2.java @@ -0,0 +1,27 @@ +class Solution { + public int candy(int[] ratings) { + int n = ratings.length; + int up = 0; + int down = 0; + int peak = 0; + int candies = 1; + for (int i = 1; i < n; i++) { + if (ratings[i - 1] < ratings[i]) { + up++; + peak = up + 1; + down = 0; + candies += peak; + } else if (ratings[i] == ratings[i - 1]) { + peak = 0; + up = 0; + down = 0; + candies++; + } else { + down++; + up = 0; + candies += down + (peak > down ? 0 : 1); + } + } + return candies; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0136.Single Number/Solution.c b/solution/0100-0199/0136.Single Number/Solution.c index ad50d8cf6fee1..6ad35a3a8cc9d 100644 --- a/solution/0100-0199/0136.Single Number/Solution.c +++ b/solution/0100-0199/0136.Single Number/Solution.c @@ -4,4 +4,4 @@ int singleNumber(int* nums, int numsSize) { ans ^= nums[i]; } return ans; -} +} \ No newline at end of file diff --git a/solution/0100-0199/0136.Single Number/Solution.cpp b/solution/0100-0199/0136.Single Number/Solution.cpp index c6842521fed94..7b59d6f83771c 100644 --- a/solution/0100-0199/0136.Single Number/Solution.cpp +++ b/solution/0100-0199/0136.Single Number/Solution.cpp @@ -1,10 +1,10 @@ -class Solution { -public: - int singleNumber(vector& nums) { - int ans = 0; - for (int v : nums) { - ans ^= v; - } - return ans; - } +class Solution { +public: + int singleNumber(vector& nums) { + int ans = 0; + for (int v : nums) { + ans ^= v; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0100-0199/0136.Single Number/Solution.cs b/solution/0100-0199/0136.Single Number/Solution.cs index 8b1ae0b65afe4..79897b5fedf24 100644 --- a/solution/0100-0199/0136.Single Number/Solution.cs +++ b/solution/0100-0199/0136.Single Number/Solution.cs @@ -1,5 +1,5 @@ -public class Solution { - public int SingleNumber(int[] nums) { - return nums.Aggregate(0, (a, b) => a ^ b); - } -} \ No newline at end of file +public class Solution { + public int SingleNumber(int[] nums) { + return nums.Aggregate(0, (a, b) => a ^ b); + } +} diff --git a/solution/0100-0199/0136.Single Number/Solution.swift b/solution/0100-0199/0136.Single Number/Solution.swift index 8c30c39212bc4..c96076bc766b2 100644 --- a/solution/0100-0199/0136.Single Number/Solution.swift +++ b/solution/0100-0199/0136.Single Number/Solution.swift @@ -1,5 +1,5 @@ -class Solution { - func singleNumber(_ nums: [Int]) -> Int { - return nums.reduce(0, ^) - } -} \ No newline at end of file +class Solution { + func singleNumber(_ nums: [Int]) -> Int { + return nums.reduce(0, ^) + } +} diff --git a/solution/0100-0199/0136.Single Number/Solution2.java b/solution/0100-0199/0136.Single Number/Solution2.java new file mode 100644 index 0000000000000..6365dafe0bed7 --- /dev/null +++ b/solution/0100-0199/0136.Single Number/Solution2.java @@ -0,0 +1,5 @@ +class Solution { + public int singleNumber(int[] nums) { + return Arrays.stream(nums).reduce(0, (a, b) -> a ^ b); + } +} \ No newline at end of file diff --git a/solution/0100-0199/0137.Single Number II/Solution.c b/solution/0100-0199/0137.Single Number II/Solution.c index 3f9071a95c109..9cad93286be68 100644 --- a/solution/0100-0199/0137.Single Number II/Solution.c +++ b/solution/0100-0199/0137.Single Number II/Solution.c @@ -10,4 +10,4 @@ int singleNumber(int* nums, int numsSize) { ans |= (uint) (count % 3) << i; } return ans; -} +} \ No newline at end of file diff --git a/solution/0100-0199/0137.Single Number II/Solution.cpp b/solution/0100-0199/0137.Single Number II/Solution.cpp index b25b7f6719028..689660fc4046a 100644 --- a/solution/0100-0199/0137.Single Number II/Solution.cpp +++ b/solution/0100-0199/0137.Single Number II/Solution.cpp @@ -1,13 +1,15 @@ class Solution { public: int singleNumber(vector& nums) { - int a = 0, b = 0; - for (int c : nums) { - int aa = (~a & b & c) | (a & ~b & ~c); - int bb = ~a & (b ^ c); - a = aa; - b = bb; + int ans = 0; + for (int i = 0; i < 32; ++i) { + int cnt = 0; + for (int num : nums) { + cnt += ((num >> i) & 1); + } + cnt %= 3; + ans |= cnt << i; } - return b; + return ans; } }; \ No newline at end of file diff --git a/solution/0100-0199/0137.Single Number II/Solution.go b/solution/0100-0199/0137.Single Number II/Solution.go index 6804939ba4fd4..9a356422512c4 100644 --- a/solution/0100-0199/0137.Single Number II/Solution.go +++ b/solution/0100-0199/0137.Single Number II/Solution.go @@ -1,9 +1,12 @@ func singleNumber(nums []int) int { - a, b := 0, 0 - for _, c := range nums { - aa := (^a & b & c) | (a & ^b & ^c) - bb := ^a & (b ^ c) - a, b = aa, bb + ans := int32(0) + for i := 0; i < 32; i++ { + cnt := int32(0) + for _, num := range nums { + cnt += int32(num) >> i & 1 + } + cnt %= 3 + ans |= cnt << i } - return b + return int(ans) } \ No newline at end of file diff --git a/solution/0100-0199/0137.Single Number II/Solution.java b/solution/0100-0199/0137.Single Number II/Solution.java index 72199d5a1e165..aeb87c549b3a2 100644 --- a/solution/0100-0199/0137.Single Number II/Solution.java +++ b/solution/0100-0199/0137.Single Number II/Solution.java @@ -1,12 +1,14 @@ class Solution { public int singleNumber(int[] nums) { - int a = 0, b = 0; - for (int c : nums) { - int aa = (~a & b & c) | (a & ~b & ~c); - int bb = ~a & (b ^ c); - a = aa; - b = bb; + int ans = 0; + for (int i = 0; i < 32; i++) { + int cnt = 0; + for (int num : nums) { + cnt += num >> i & 1; + } + cnt %= 3; + ans |= cnt << i; } - return b; + return ans; } } \ No newline at end of file diff --git a/solution/0100-0199/0137.Single Number II/Solution.py b/solution/0100-0199/0137.Single Number II/Solution.py index a3a46e19a5376..23a50267abee4 100644 --- a/solution/0100-0199/0137.Single Number II/Solution.py +++ b/solution/0100-0199/0137.Single Number II/Solution.py @@ -1,8 +1,11 @@ class Solution: def singleNumber(self, nums: List[int]) -> int: - a = b = 0 - for c in nums: - aa = (~a & b & c) | (a & ~b & ~c) - bb = ~a & (b ^ c) - a, b = aa, bb - return b + ans = 0 + for i in range(32): + cnt = sum(num >> i & 1 for num in nums) + if cnt % 3: + if i == 31: + ans -= 1 << i + else: + ans |= 1 << i + return ans diff --git a/solution/0100-0199/0137.Single Number II/Solution.swift b/solution/0100-0199/0137.Single Number II/Solution.swift index e2edcd7ed0a7a..146800714261c 100644 --- a/solution/0100-0199/0137.Single Number II/Solution.swift +++ b/solution/0100-0199/0137.Single Number II/Solution.swift @@ -9,4 +9,4 @@ class Solution { } return a[n - 1] } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0137.Single Number II/Solution.ts b/solution/0100-0199/0137.Single Number II/Solution.ts index 8bf6cb06721f8..6962d4a16aa33 100644 --- a/solution/0100-0199/0137.Single Number II/Solution.ts +++ b/solution/0100-0199/0137.Single Number II/Solution.ts @@ -1,11 +1,8 @@ function singleNumber(nums: number[]): number { - let a = 0; - let b = 0; - for (const c of nums) { - const aa = (~a & b & c) | (a & ~b & ~c); - const bb = ~a & (b ^ c); - a = aa; - b = bb; + let ans = 0; + for (let i = 0; i < 32; i++) { + const count = nums.reduce((r, v) => r + ((v >> i) & 1), 0); + ans |= count % 3 << i; } - return b; + return ans; } diff --git a/solution/0100-0199/0137.Single Number II/Solution2.cpp b/solution/0100-0199/0137.Single Number II/Solution2.cpp new file mode 100644 index 0000000000000..b25b7f6719028 --- /dev/null +++ b/solution/0100-0199/0137.Single Number II/Solution2.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int singleNumber(vector& nums) { + int a = 0, b = 0; + for (int c : nums) { + int aa = (~a & b & c) | (a & ~b & ~c); + int bb = ~a & (b ^ c); + a = aa; + b = bb; + } + return b; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0137.Single Number II/Solution2.go b/solution/0100-0199/0137.Single Number II/Solution2.go new file mode 100644 index 0000000000000..6804939ba4fd4 --- /dev/null +++ b/solution/0100-0199/0137.Single Number II/Solution2.go @@ -0,0 +1,9 @@ +func singleNumber(nums []int) int { + a, b := 0, 0 + for _, c := range nums { + aa := (^a & b & c) | (a & ^b & ^c) + bb := ^a & (b ^ c) + a, b = aa, bb + } + return b +} \ No newline at end of file diff --git a/solution/0100-0199/0137.Single Number II/Solution2.java b/solution/0100-0199/0137.Single Number II/Solution2.java new file mode 100644 index 0000000000000..72199d5a1e165 --- /dev/null +++ b/solution/0100-0199/0137.Single Number II/Solution2.java @@ -0,0 +1,12 @@ +class Solution { + public int singleNumber(int[] nums) { + int a = 0, b = 0; + for (int c : nums) { + int aa = (~a & b & c) | (a & ~b & ~c); + int bb = ~a & (b ^ c); + a = aa; + b = bb; + } + return b; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0137.Single Number II/Solution2.py b/solution/0100-0199/0137.Single Number II/Solution2.py new file mode 100644 index 0000000000000..a3a46e19a5376 --- /dev/null +++ b/solution/0100-0199/0137.Single Number II/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def singleNumber(self, nums: List[int]) -> int: + a = b = 0 + for c in nums: + aa = (~a & b & c) | (a & ~b & ~c) + bb = ~a & (b ^ c) + a, b = aa, bb + return b diff --git a/solution/0100-0199/0137.Single Number II/Solution2.rs b/solution/0100-0199/0137.Single Number II/Solution2.rs new file mode 100644 index 0000000000000..02cfaa9248d64 --- /dev/null +++ b/solution/0100-0199/0137.Single Number II/Solution2.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn single_number(nums: Vec) -> i32 { + let mut a = 0; + let mut b = 0; + + for c in nums { + let aa = (!a & b & c) | (a & !b & !c); + let bb = !a & (b ^ c); + a = aa; + b = bb; + } + + return b; + } +} diff --git a/solution/0100-0199/0137.Single Number II/Solution2.ts b/solution/0100-0199/0137.Single Number II/Solution2.ts new file mode 100644 index 0000000000000..8bf6cb06721f8 --- /dev/null +++ b/solution/0100-0199/0137.Single Number II/Solution2.ts @@ -0,0 +1,11 @@ +function singleNumber(nums: number[]): number { + let a = 0; + let b = 0; + for (const c of nums) { + const aa = (~a & b & c) | (a & ~b & ~c); + const bb = ~a & (b ^ c); + a = aa; + b = bb; + } + return b; +} diff --git a/solution/0100-0199/0138.Copy List with Random Pointer/Solution.cpp b/solution/0100-0199/0138.Copy List with Random Pointer/Solution.cpp index a98a121581a14..48858e8ac32bd 100644 --- a/solution/0100-0199/0138.Copy List with Random Pointer/Solution.cpp +++ b/solution/0100-0199/0138.Copy List with Random Pointer/Solution.cpp @@ -16,28 +16,19 @@ class Node { class Solution { public: Node* copyRandomList(Node* head) { - if (!head) { - return nullptr; + unordered_map d; + Node* dummy = new Node(0); + Node* tail = dummy; + for (auto cur = head; cur; cur = cur->next) { + tail->next = new Node(cur->val); + tail = tail->next; + d[cur] = tail; } - for (Node* cur = head; cur;) { - Node* node = new Node(cur->val); - node->next = cur->next; - cur->next = node; - cur = node->next; + tail = dummy->next; + for (auto cur = head; cur; cur = cur->next) { + tail->random = d[cur->random]; + tail = tail->next; } - for (Node* cur = head; cur; cur = cur->next->next) { - if (cur->random) { - cur->next->random = cur->random->next; - } - } - Node* ans = head->next; - for (Node* cur = head; cur;) { - Node* nxt = cur->next; - if (nxt) { - cur->next = nxt->next; - } - cur = nxt; - } - return ans; + return dummy->next; } }; \ No newline at end of file diff --git a/solution/0100-0199/0138.Copy List with Random Pointer/Solution.cs b/solution/0100-0199/0138.Copy List with Random Pointer/Solution.cs index 901c7ecc99bcb..97a43f56c2934 100644 --- a/solution/0100-0199/0138.Copy List with Random Pointer/Solution.cs +++ b/solution/0100-0199/0138.Copy List with Random Pointer/Solution.cs @@ -15,27 +15,19 @@ public Node(int _val) { public class Solution { public Node CopyRandomList(Node head) { - if (head == null) { - return null; + Dictionary d = new Dictionary(); + Node dummy = new Node(0); + Node tail = dummy; + for (Node cur = head; cur != null; cur = cur.next) { + tail.next = new Node(cur.val); + tail = tail.next; + d[cur] = tail; } - for (Node cur = head; cur != null; ) { - Node node = new Node(cur.val, cur.next); - cur.next = node; - cur = node.next; + tail = dummy.next; + for (Node cur = head; cur != null; cur = cur.next) { + tail.random = cur.random == null ? null : d[cur.random]; + tail = tail.next; } - for (Node cur = head; cur != null; cur = cur.next.next) { - if (cur.random != null) { - cur.next.random = cur.random.next; - } - } - Node ans = head.next; - for (Node cur = head; cur != null; ) { - Node nxt = cur.next; - if (nxt != null) { - cur.next = nxt.next; - } - cur = nxt; - } - return ans; + return dummy.next; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0138.Copy List with Random Pointer/Solution.go b/solution/0100-0199/0138.Copy List with Random Pointer/Solution.go index 8039efadcbe65..08ed594b862b9 100644 --- a/solution/0100-0199/0138.Copy List with Random Pointer/Solution.go +++ b/solution/0100-0199/0138.Copy List with Random Pointer/Solution.go @@ -8,26 +8,18 @@ */ func copyRandomList(head *Node) *Node { - if head == nil { - return nil + d := map[*Node]*Node{} + dummy := &Node{} + tail := dummy + for cur := head; cur != nil; cur = cur.Next { + tail.Next = &Node{Val: cur.Val} + tail = tail.Next + d[cur] = tail } - for cur := head; cur != nil; { - node := &Node{cur.Val, cur.Next, nil} - cur.Next = node - cur = node.Next + tail = dummy.Next + for cur := head; cur != nil; cur = cur.Next { + tail.Random = d[cur.Random] + tail = tail.Next } - for cur := head; cur != nil; cur = cur.Next.Next { - if cur.Random != nil { - cur.Next.Random = cur.Random.Next - } - } - ans := head.Next - for cur := head; cur != nil; { - nxt := cur.Next - if nxt != nil { - cur.Next = nxt.Next - } - cur = nxt - } - return ans + return dummy.Next } \ No newline at end of file diff --git a/solution/0100-0199/0138.Copy List with Random Pointer/Solution.java b/solution/0100-0199/0138.Copy List with Random Pointer/Solution.java index 9ed0bdedf01f1..2bce78d217257 100644 --- a/solution/0100-0199/0138.Copy List with Random Pointer/Solution.java +++ b/solution/0100-0199/0138.Copy List with Random Pointer/Solution.java @@ -14,27 +14,19 @@ public Node(int val) { */ class Solution { public Node copyRandomList(Node head) { - if (head == null) { - return null; + Map d = new HashMap<>(); + Node dummy = new Node(0); + Node tail = dummy; + for (Node cur = head; cur != null; cur = cur.next) { + tail.next = new Node(cur.val); + tail = tail.next; + d.put(cur, tail); } - for (Node cur = head; cur != null;) { - Node node = new Node(cur.val, cur.next); - cur.next = node; - cur = node.next; + tail = dummy.next; + for (Node cur = head; cur != null; cur = cur.next) { + tail.random = d.get(cur.random); + tail = tail.next; } - for (Node cur = head; cur != null; cur = cur.next.next) { - if (cur.random != null) { - cur.next.random = cur.random.next; - } - } - Node ans = head.next; - for (Node cur = head; cur != null;) { - Node nxt = cur.next; - if (nxt != null) { - cur.next = nxt.next; - } - cur = nxt; - } - return ans; + return dummy.next; } } \ No newline at end of file diff --git a/solution/0100-0199/0138.Copy List with Random Pointer/Solution.js b/solution/0100-0199/0138.Copy List with Random Pointer/Solution.js index 93fd2cf31a78b..b7cd78df5c464 100644 --- a/solution/0100-0199/0138.Copy List with Random Pointer/Solution.js +++ b/solution/0100-0199/0138.Copy List with Random Pointer/Solution.js @@ -12,26 +12,18 @@ * @return {Node} */ var copyRandomList = function (head) { - if (!head) { - return null; + const d = new Map(); + const dummy = new Node(0); + let tail = dummy; + for (let cur = head; cur; cur = cur.next) { + tail.next = new Node(cur.val); + tail = tail.next; + d.set(cur, tail); } - for (let cur = head; cur; ) { - const node = new Node(cur.val, cur.next, null); - cur.next = node; - cur = node.next; + tail = dummy.next; + for (let cur = head; cur; cur = cur.next) { + tail.random = d.get(cur.random); + tail = tail.next; } - for (let cur = head; cur; cur = cur.next.next) { - if (cur.random) { - cur.next.random = cur.random.next; - } - } - const ans = head.next; - for (let cur = head; cur; ) { - const nxt = cur.next; - if (nxt) { - cur.next = nxt.next; - } - cur = nxt; - } - return ans; + return dummy.next; }; diff --git a/solution/0100-0199/0138.Copy List with Random Pointer/Solution.py b/solution/0100-0199/0138.Copy List with Random Pointer/Solution.py index e70ccac9789b0..57797589c37c6 100644 --- a/solution/0100-0199/0138.Copy List with Random Pointer/Solution.py +++ b/solution/0100-0199/0138.Copy List with Random Pointer/Solution.py @@ -10,25 +10,18 @@ def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): class Solution: def copyRandomList(self, head: "Node") -> "Node": - if head is None: - return None + d = {} + dummy = tail = Node(0) cur = head while cur: - node = Node(cur.val, cur.next) - cur.next = node - cur = node.next - - cur = head - while cur: - if cur.random: - cur.next.random = cur.random.next - cur = cur.next.next - - ans = head.next + tail.next = Node(cur.val) + tail = tail.next + d[cur] = tail + cur = cur.next + tail = dummy.next cur = head while cur: - nxt = cur.next - if nxt: - cur.next = nxt.next - cur = nxt - return ans + tail.random = d.get(cur.random) + tail = tail.next + cur = cur.next + return dummy.next diff --git a/solution/0100-0199/0138.Copy List with Random Pointer/Solution2.cpp b/solution/0100-0199/0138.Copy List with Random Pointer/Solution2.cpp new file mode 100644 index 0000000000000..a98a121581a14 --- /dev/null +++ b/solution/0100-0199/0138.Copy List with Random Pointer/Solution2.cpp @@ -0,0 +1,43 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + Node* next; + Node* random; + + Node(int _val) { + val = _val; + next = NULL; + random = NULL; + } +}; +*/ +class Solution { +public: + Node* copyRandomList(Node* head) { + if (!head) { + return nullptr; + } + for (Node* cur = head; cur;) { + Node* node = new Node(cur->val); + node->next = cur->next; + cur->next = node; + cur = node->next; + } + for (Node* cur = head; cur; cur = cur->next->next) { + if (cur->random) { + cur->next->random = cur->random->next; + } + } + Node* ans = head->next; + for (Node* cur = head; cur;) { + Node* nxt = cur->next; + if (nxt) { + cur->next = nxt->next; + } + cur = nxt; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0138.Copy List with Random Pointer/Solution2.cs b/solution/0100-0199/0138.Copy List with Random Pointer/Solution2.cs new file mode 100644 index 0000000000000..c05d1da4a1065 --- /dev/null +++ b/solution/0100-0199/0138.Copy List with Random Pointer/Solution2.cs @@ -0,0 +1,41 @@ +/* +// Definition for a Node. +public class Node { + public int val; + public Node next; + public Node random; + + public Node(int _val) { + val = _val; + next = null; + random = null; + } +} +*/ + +public class Solution { + public Node CopyRandomList(Node head) { + if (head == null) { + return null; + } + for (Node cur = head; cur != null; ) { + Node node = new Node(cur.val, cur.next); + cur.next = node; + cur = node.next; + } + for (Node cur = head; cur != null; cur = cur.next.next) { + if (cur.random != null) { + cur.next.random = cur.random.next; + } + } + Node ans = head.next; + for (Node cur = head; cur != null; ) { + Node nxt = cur.next; + if (nxt != null) { + cur.next = nxt.next; + } + cur = nxt; + } + return ans; + } +} diff --git a/solution/0100-0199/0138.Copy List with Random Pointer/Solution2.go b/solution/0100-0199/0138.Copy List with Random Pointer/Solution2.go new file mode 100644 index 0000000000000..8039efadcbe65 --- /dev/null +++ b/solution/0100-0199/0138.Copy List with Random Pointer/Solution2.go @@ -0,0 +1,33 @@ +/** + * Definition for a Node. + * type Node struct { + * Val int + * Next *Node + * Random *Node + * } + */ + +func copyRandomList(head *Node) *Node { + if head == nil { + return nil + } + for cur := head; cur != nil; { + node := &Node{cur.Val, cur.Next, nil} + cur.Next = node + cur = node.Next + } + for cur := head; cur != nil; cur = cur.Next.Next { + if cur.Random != nil { + cur.Next.Random = cur.Random.Next + } + } + ans := head.Next + for cur := head; cur != nil; { + nxt := cur.Next + if nxt != nil { + cur.Next = nxt.Next + } + cur = nxt + } + return ans +} \ No newline at end of file diff --git a/solution/0100-0199/0138.Copy List with Random Pointer/Solution2.java b/solution/0100-0199/0138.Copy List with Random Pointer/Solution2.java new file mode 100644 index 0000000000000..9ed0bdedf01f1 --- /dev/null +++ b/solution/0100-0199/0138.Copy List with Random Pointer/Solution2.java @@ -0,0 +1,40 @@ +/* +// Definition for a Node. +class Node { + int val; + Node next; + Node random; + + public Node(int val) { + this.val = val; + this.next = null; + this.random = null; + } +} +*/ +class Solution { + public Node copyRandomList(Node head) { + if (head == null) { + return null; + } + for (Node cur = head; cur != null;) { + Node node = new Node(cur.val, cur.next); + cur.next = node; + cur = node.next; + } + for (Node cur = head; cur != null; cur = cur.next.next) { + if (cur.random != null) { + cur.next.random = cur.random.next; + } + } + Node ans = head.next; + for (Node cur = head; cur != null;) { + Node nxt = cur.next; + if (nxt != null) { + cur.next = nxt.next; + } + cur = nxt; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0138.Copy List with Random Pointer/Solution2.js b/solution/0100-0199/0138.Copy List with Random Pointer/Solution2.js new file mode 100644 index 0000000000000..93fd2cf31a78b --- /dev/null +++ b/solution/0100-0199/0138.Copy List with Random Pointer/Solution2.js @@ -0,0 +1,37 @@ +/** + * // Definition for a Node. + * function Node(val, next, random) { + * this.val = val; + * this.next = next; + * this.random = random; + * }; + */ + +/** + * @param {Node} head + * @return {Node} + */ +var copyRandomList = function (head) { + if (!head) { + return null; + } + for (let cur = head; cur; ) { + const node = new Node(cur.val, cur.next, null); + cur.next = node; + cur = node.next; + } + for (let cur = head; cur; cur = cur.next.next) { + if (cur.random) { + cur.next.random = cur.random.next; + } + } + const ans = head.next; + for (let cur = head; cur; ) { + const nxt = cur.next; + if (nxt) { + cur.next = nxt.next; + } + cur = nxt; + } + return ans; +}; diff --git a/solution/0100-0199/0138.Copy List with Random Pointer/Solution2.py b/solution/0100-0199/0138.Copy List with Random Pointer/Solution2.py new file mode 100644 index 0000000000000..e70ccac9789b0 --- /dev/null +++ b/solution/0100-0199/0138.Copy List with Random Pointer/Solution2.py @@ -0,0 +1,34 @@ +""" +# Definition for a Node. +class Node: + def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): + self.val = int(x) + self.next = next + self.random = random +""" + + +class Solution: + def copyRandomList(self, head: "Node") -> "Node": + if head is None: + return None + cur = head + while cur: + node = Node(cur.val, cur.next) + cur.next = node + cur = node.next + + cur = head + while cur: + if cur.random: + cur.next.random = cur.random.next + cur = cur.next.next + + ans = head.next + cur = head + while cur: + nxt = cur.next + if nxt: + cur.next = nxt.next + cur = nxt + return ans diff --git a/solution/0100-0199/0139.Word Break/Solution.cs b/solution/0100-0199/0139.Word Break/Solution.cs index 5489c98dc3267..ecefc297618a4 100644 --- a/solution/0100-0199/0139.Word Break/Solution.cs +++ b/solution/0100-0199/0139.Word Break/Solution.cs @@ -14,4 +14,4 @@ public bool WordBreak(string s, IList wordDict) { } return f[n]; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0139.Word Break/Solution2.cpp b/solution/0100-0199/0139.Word Break/Solution2.cpp new file mode 100644 index 0000000000000..3803071f30cc3 --- /dev/null +++ b/solution/0100-0199/0139.Word Break/Solution2.cpp @@ -0,0 +1,46 @@ +class Trie { +public: + vector children; + bool isEnd; + Trie() + : children(26) + , isEnd(false) {} + + void insert(string word) { + Trie* node = this; + for (char c : word) { + c -= 'a'; + if (!node->children[c]) node->children[c] = new Trie(); + node = node->children[c]; + } + node->isEnd = true; + } +}; + +class Solution { +public: + bool wordBreak(string s, vector& wordDict) { + Trie trie; + for (auto& w : wordDict) { + trie.insert(w); + } + int n = s.size(); + vector f(n + 1); + f[n] = true; + for (int i = n - 1; ~i; --i) { + Trie* node = ≜ + for (int j = i; j < n; ++j) { + int k = s[j] - 'a'; + if (!node->children[k]) { + break; + } + node = node->children[k]; + if (node->isEnd && f[j + 1]) { + f[i] = true; + break; + } + } + } + return f[0]; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0139.Word Break/Solution2.cs b/solution/0100-0199/0139.Word Break/Solution2.cs new file mode 100644 index 0000000000000..21e625ba1b9aa --- /dev/null +++ b/solution/0100-0199/0139.Word Break/Solution2.cs @@ -0,0 +1,48 @@ +public class Solution { + public bool WordBreak(string s, IList wordDict) { + Trie trie = new Trie(); + foreach (string w in wordDict) { + trie.Insert(w); + } + int n = s.Length; + bool[] f = new bool[n + 1]; + f[n] = true; + for (int i = n - 1; i >= 0; --i) { + Trie node = trie; + for (int j = i; j < n; ++j) { + int k = s[j] - 'a'; + if (node.Children[k] == null) { + break; + } + node = node.Children[k]; + if (node.IsEnd && f[j + 1]) { + f[i] = true; + break; + } + } + } + return f[0]; + } +} + +class Trie { + public Trie[] Children { get; set; } + public bool IsEnd { get; set; } + + public Trie() { + Children = new Trie[26]; + IsEnd = false; + } + + public void Insert(string word) { + Trie node = this; + foreach (char c in word) { + int i = c - 'a'; + if (node.Children[i] == null) { + node.Children[i] = new Trie(); + } + node = node.Children[i]; + } + node.IsEnd = true; + } +} diff --git a/solution/0100-0199/0139.Word Break/Solution2.go b/solution/0100-0199/0139.Word Break/Solution2.go new file mode 100644 index 0000000000000..ec4d2bb880be9 --- /dev/null +++ b/solution/0100-0199/0139.Word Break/Solution2.go @@ -0,0 +1,45 @@ +type trie struct { + children [26]*trie + isEnd bool +} + +func newTrie() *trie { + return &trie{} +} + +func (t *trie) insert(w string) { + node := t + for _, c := range w { + c -= 'a' + if node.children[c] == nil { + node.children[c] = newTrie() + } + node = node.children[c] + } + node.isEnd = true +} + +func wordBreak(s string, wordDict []string) bool { + trie := newTrie() + for _, w := range wordDict { + trie.insert(w) + } + n := len(s) + f := make([]bool, n+1) + f[n] = true + for i := n - 1; i >= 0; i-- { + node := trie + for j := i; j < n; j++ { + k := s[j] - 'a' + if node.children[k] == nil { + break + } + node = node.children[k] + if node.isEnd && f[j+1] { + f[i] = true + break + } + } + } + return f[0] +} \ No newline at end of file diff --git a/solution/0100-0199/0139.Word Break/Solution2.java b/solution/0100-0199/0139.Word Break/Solution2.java new file mode 100644 index 0000000000000..e60edc23808ba --- /dev/null +++ b/solution/0100-0199/0139.Word Break/Solution2.java @@ -0,0 +1,43 @@ +class Solution { + public boolean wordBreak(String s, List wordDict) { + Trie trie = new Trie(); + for (String w : wordDict) { + trie.insert(w); + } + int n = s.length(); + boolean[] f = new boolean[n + 1]; + f[n] = true; + for (int i = n - 1; i >= 0; --i) { + Trie node = trie; + for (int j = i; j < n; ++j) { + int k = s.charAt(j) - 'a'; + if (node.children[k] == null) { + break; + } + node = node.children[k]; + if (node.isEnd && f[j + 1]) { + f[i] = true; + break; + } + } + } + return f[0]; + } +} + +class Trie { + Trie[] children = new Trie[26]; + boolean isEnd = false; + + public void insert(String w) { + Trie node = this; + for (int i = 0; i < w.length(); ++i) { + int j = w.charAt(i) - 'a'; + if (node.children[j] == null) { + node.children[j] = new Trie(); + } + node = node.children[j]; + } + node.isEnd = true; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0139.Word Break/Solution2.py b/solution/0100-0199/0139.Word Break/Solution2.py new file mode 100644 index 0000000000000..0d3ed5d00a6e3 --- /dev/null +++ b/solution/0100-0199/0139.Word Break/Solution2.py @@ -0,0 +1,34 @@ +class Trie: + def __init__(self): + self.children: List[Trie | None] = [None] * 26 + self.isEnd = False + + def insert(self, w: str): + node = self + for c in w: + idx = ord(c) - ord('a') + if not node.children[idx]: + node.children[idx] = Trie() + node = node.children[idx] + node.isEnd = True + + +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + trie = Trie() + for w in wordDict: + trie.insert(w) + n = len(s) + f = [False] * (n + 1) + f[n] = True + for i in range(n - 1, -1, -1): + node = trie + for j in range(i, n): + idx = ord(s[j]) - ord('a') + if not node.children[idx]: + break + node = node.children[idx] + if node.isEnd and f[j + 1]: + f[i] = True + break + return f[0] diff --git a/solution/0100-0199/0139.Word Break/Solution2.ts b/solution/0100-0199/0139.Word Break/Solution2.ts new file mode 100644 index 0000000000000..18ecd3b67129b --- /dev/null +++ b/solution/0100-0199/0139.Word Break/Solution2.ts @@ -0,0 +1,46 @@ +function wordBreak(s: string, wordDict: string[]): boolean { + const trie = new Trie(); + for (const w of wordDict) { + trie.insert(w); + } + const n = s.length; + const f: boolean[] = new Array(n + 1).fill(false); + f[n] = true; + for (let i = n - 1; i >= 0; --i) { + let node: Trie = trie; + for (let j = i; j < n; ++j) { + const k = s.charCodeAt(j) - 97; + if (!node.children[k]) { + break; + } + node = node.children[k]; + if (node.isEnd && f[j + 1]) { + f[i] = true; + break; + } + } + } + return f[0]; +} + +class Trie { + children: Trie[]; + isEnd: boolean; + + constructor() { + this.children = new Array(26); + this.isEnd = false; + } + + insert(w: string): void { + let node: Trie = this; + for (const c of w) { + const i = c.charCodeAt(0) - 97; + if (!node.children[i]) { + node.children[i] = new Trie(); + } + node = node.children[i]; + } + node.isEnd = true; + } +} diff --git a/solution/0100-0199/0141.Linked List Cycle/Solution.cs b/solution/0100-0199/0141.Linked List Cycle/Solution.cs index 2b11ea0541a8a..53fb9e54456a2 100644 --- a/solution/0100-0199/0141.Linked List Cycle/Solution.cs +++ b/solution/0100-0199/0141.Linked List Cycle/Solution.cs @@ -22,4 +22,4 @@ public bool HasCycle(ListNode head) { } return false; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0141.Linked List Cycle/Solution.ts b/solution/0100-0199/0141.Linked List Cycle/Solution.ts index d96f37301869c..3c8474d62b607 100644 --- a/solution/0100-0199/0141.Linked List Cycle/Solution.ts +++ b/solution/0100-0199/0141.Linked List Cycle/Solution.ts @@ -11,14 +11,14 @@ */ function hasCycle(head: ListNode | null): boolean { - let slow = head; - let fast = head; - while (fast !== null && fast.next !== null) { - slow = slow.next; - fast = fast.next.next; - if (slow === fast) { + const set = new Set(); + let node = head; + while (node !== null) { + if (set.has(node)) { return true; } + set.add(node); + node = node.next; } return false; } diff --git a/solution/0100-0199/0141.Linked List Cycle/Solution2.ts b/solution/0100-0199/0141.Linked List Cycle/Solution2.ts new file mode 100644 index 0000000000000..d96f37301869c --- /dev/null +++ b/solution/0100-0199/0141.Linked List Cycle/Solution2.ts @@ -0,0 +1,24 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function hasCycle(head: ListNode | null): boolean { + let slow = head; + let fast = head; + while (fast !== null && fast.next !== null) { + slow = slow.next; + fast = fast.next.next; + if (slow === fast) { + return true; + } + } + return false; +} diff --git a/solution/0100-0199/0142.Linked List Cycle II/Solution.cpp b/solution/0100-0199/0142.Linked List Cycle II/Solution.cpp index 73e56d90b5b2b..480c200cce75d 100644 --- a/solution/0100-0199/0142.Linked List Cycle II/Solution.cpp +++ b/solution/0100-0199/0142.Linked List Cycle II/Solution.cpp @@ -1,28 +1,28 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode* detectCycle(ListNode* head) { - ListNode* fast = head; - ListNode* slow = head; - while (fast && fast->next) { - slow = slow->next; - fast = fast->next->next; - if (slow == fast) { - ListNode* ans = head; - while (ans != slow) { - ans = ans->next; - slow = slow->next; - } - return ans; - } - } - return nullptr; - } +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* detectCycle(ListNode* head) { + ListNode* fast = head; + ListNode* slow = head; + while (fast && fast->next) { + slow = slow->next; + fast = fast->next->next; + if (slow == fast) { + ListNode* ans = head; + while (ans != slow) { + ans = ans->next; + slow = slow->next; + } + return ans; + } + } + return nullptr; + } }; \ No newline at end of file diff --git a/solution/0100-0199/0142.Linked List Cycle II/Solution.java b/solution/0100-0199/0142.Linked List Cycle II/Solution.java index 225214bbdd7b2..d97ce63041d60 100644 --- a/solution/0100-0199/0142.Linked List Cycle II/Solution.java +++ b/solution/0100-0199/0142.Linked List Cycle II/Solution.java @@ -1,29 +1,29 @@ -/** - * Definition for singly-linked list. - * class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode detectCycle(ListNode head) { - ListNode fast = head, slow = head; - while (fast != null && fast.next != null) { - slow = slow.next; - fast = fast.next.next; - if (slow == fast) { - ListNode ans = head; - while (ans != slow) { - ans = ans.next; - slow = slow.next; - } - return ans; - } - } - return null; - } +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode detectCycle(ListNode head) { + ListNode fast = head, slow = head; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + if (slow == fast) { + ListNode ans = head; + while (ans != slow) { + ans = ans.next; + slow = slow.next; + } + return ans; + } + } + return null; + } } \ No newline at end of file diff --git a/solution/0100-0199/0142.Linked List Cycle II/Solution.py b/solution/0100-0199/0142.Linked List Cycle II/Solution.py index 27a1ff63fb1ac..e28f848a4834c 100644 --- a/solution/0100-0199/0142.Linked List Cycle II/Solution.py +++ b/solution/0100-0199/0142.Linked List Cycle II/Solution.py @@ -1,19 +1,19 @@ -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, x): -# self.val = x -# self.next = None - - -class Solution: - def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: - fast = slow = head - while fast and fast.next: - slow = slow.next - fast = fast.next.next - if slow == fast: - ans = head - while ans != slow: - ans = ans.next - slow = slow.next - return ans +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + + +class Solution: + def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: + fast = slow = head + while fast and fast.next: + slow = slow.next + fast = fast.next.next + if slow == fast: + ans = head + while ans != slow: + ans = ans.next + slow = slow.next + return ans diff --git a/solution/0100-0199/0143.Reorder List/Solution.cpp b/solution/0100-0199/0143.Reorder List/Solution.cpp index af3cea5f9cc87..0c4ace2764e19 100644 --- a/solution/0100-0199/0143.Reorder List/Solution.cpp +++ b/solution/0100-0199/0143.Reorder List/Solution.cpp @@ -1,41 +1,46 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - void reorderList(ListNode* head) { - ListNode* fast = head; - ListNode* slow = head; - while (fast->next && fast->next->next) { - slow = slow->next; - fast = fast->next->next; - } - - ListNode* cur = slow->next; - slow->next = nullptr; - - ListNode* pre = nullptr; - while (cur) { - ListNode* t = cur->next; - cur->next = pre; - pre = cur; - cur = t; - } - cur = head; - - while (pre) { - ListNode* t = pre->next; - pre->next = cur->next; - cur->next = pre; - cur = pre->next; - pre = t; - } - } +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + void reorderList(ListNode* head) { + // 快慢指针找到链表中点 + ListNode* fast = head; + ListNode* slow = head; + while (fast->next && fast->next->next) { + slow = slow->next; + fast = fast->next->next; + } + + // cur 指向右半部分链表 + ListNode* cur = slow->next; + slow->next = nullptr; + + // 反转右半部分链表 + ListNode* pre = nullptr; + while (cur) { + ListNode* t = cur->next; + cur->next = pre; + pre = cur; + cur = t; + } + cur = head; + + // 此时 cur, pre 分别指向链表左右两半的第一个节点 + // 合并 + while (pre) { + ListNode* t = pre->next; + pre->next = cur->next; + cur->next = pre; + cur = pre->next; + pre = t; + } + } }; \ No newline at end of file diff --git a/solution/0100-0199/0143.Reorder List/Solution.cs b/solution/0100-0199/0143.Reorder List/Solution.cs index a20269fd30d77..bd97cca252210 100644 --- a/solution/0100-0199/0143.Reorder List/Solution.cs +++ b/solution/0100-0199/0143.Reorder List/Solution.cs @@ -1,41 +1,46 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } - * } - */ -public class Solution { - public void ReorderList(ListNode head) { - ListNode slow = head; - ListNode fast = head; - while (fast.next != null && fast.next.next != null) { - slow = slow.next; - fast = fast.next.next; - } - - ListNode cur = slow.next; - slow.next = null; - - ListNode pre = null; - while (cur != null) { - ListNode t = cur.next; - cur.next = pre; - pre = cur; - cur = t; - } - cur = head; - - while (pre != null) { - ListNode t = pre.next; - pre.next = cur.next; - cur.next = pre; - cur = pre.next; - pre = t; - } - } -} \ No newline at end of file +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public void ReorderList(ListNode head) { + // 快慢指针找到链表中点 + ListNode slow = head; + ListNode fast = head; + while (fast.next != null && fast.next.next != null) { + slow = slow.next; + fast = fast.next.next; + } + + // cur 指向右半部分链表 + ListNode cur = slow.next; + slow.next = null; + + // 反转右半部分链表 + ListNode pre = null; + while (cur != null) { + ListNode t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + cur = head; + + // 此时 cur, pre 分别指向链表左右两半的第一个节点 + // 合并 + while (pre != null) { + ListNode t = pre.next; + pre.next = cur.next; + cur.next = pre; + cur = pre.next; + pre = t; + } + } +} diff --git a/solution/0100-0199/0143.Reorder List/Solution.go b/solution/0100-0199/0143.Reorder List/Solution.go index e1a7283ea32d0..666b7b7b6cc38 100644 --- a/solution/0100-0199/0143.Reorder List/Solution.go +++ b/solution/0100-0199/0143.Reorder List/Solution.go @@ -6,14 +6,17 @@ * } */ func reorderList(head *ListNode) { + // 快慢指针找到链表中点 fast, slow := head, head for fast.Next != nil && fast.Next.Next != nil { slow, fast = slow.Next, fast.Next.Next } + // cur 指向右半部分链表 cur := slow.Next slow.Next = nil + // 反转右半部分链表 var pre *ListNode for cur != nil { t := cur.Next @@ -22,6 +25,8 @@ func reorderList(head *ListNode) { } cur = head + // 此时 cur, pre 分别指向链表左右两半的第一个节点 + // 合并 for pre != nil { t := pre.Next pre.Next = cur.Next diff --git a/solution/0100-0199/0143.Reorder List/Solution.java b/solution/0100-0199/0143.Reorder List/Solution.java index cf96d6b5fe715..c89fc20a4556e 100644 --- a/solution/0100-0199/0143.Reorder List/Solution.java +++ b/solution/0100-0199/0143.Reorder List/Solution.java @@ -1,39 +1,44 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public void reorderList(ListNode head) { - ListNode fast = head, slow = head; - while (fast.next != null && fast.next.next != null) { - slow = slow.next; - fast = fast.next.next; - } - - ListNode cur = slow.next; - slow.next = null; - - ListNode pre = null; - while (cur != null) { - ListNode t = cur.next; - cur.next = pre; - pre = cur; - cur = t; - } - cur = head; - - while (pre != null) { - ListNode t = pre.next; - pre.next = cur.next; - cur.next = pre; - cur = pre.next; - pre = t; - } - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public void reorderList(ListNode head) { + // 快慢指针找到链表中点 + ListNode fast = head, slow = head; + while (fast.next != null && fast.next.next != null) { + slow = slow.next; + fast = fast.next.next; + } + + // cur 指向右半部分链表 + ListNode cur = slow.next; + slow.next = null; + + // 反转右半部分链表 + ListNode pre = null; + while (cur != null) { + ListNode t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + cur = head; + + // 此时 cur, pre 分别指向链表左右两半的第一个节点 + // 合并 + while (pre != null) { + ListNode t = pre.next; + pre.next = cur.next; + cur.next = pre; + cur = pre.next; + pre = t; + } + } } \ No newline at end of file diff --git a/solution/0100-0199/0143.Reorder List/Solution.js b/solution/0100-0199/0143.Reorder List/Solution.js index 52146399cbe0b..a2a0b00578789 100644 --- a/solution/0100-0199/0143.Reorder List/Solution.js +++ b/solution/0100-0199/0143.Reorder List/Solution.js @@ -10,6 +10,7 @@ * @return {void} Do not return anything, modify head in-place instead. */ var reorderList = function (head) { + // 快慢指针找到链表中点 let slow = head; let fast = head; while (fast.next && fast.next.next) { @@ -17,9 +18,11 @@ var reorderList = function (head) { fast = fast.next.next; } + // cur 指向右半部分链表 let cur = slow.next; slow.next = null; + // 反转右半部分链表 let pre = null; while (cur) { const t = cur.next; @@ -29,6 +32,8 @@ var reorderList = function (head) { } cur = head; + // 此时 cur, pre 分别指向链表左右两半的第一个节点 + // 合并 while (pre) { const t = pre.next; pre.next = cur.next; diff --git a/solution/0100-0199/0143.Reorder List/Solution.py b/solution/0100-0199/0143.Reorder List/Solution.py index 4e96beffce499..3eb0caf08c97f 100644 --- a/solution/0100-0199/0143.Reorder List/Solution.py +++ b/solution/0100-0199/0143.Reorder List/Solution.py @@ -1,27 +1,32 @@ -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def reorderList(self, head: Optional[ListNode]) -> None: - fast = slow = head - while fast.next and fast.next.next: - slow = slow.next - fast = fast.next.next - - cur = slow.next - slow.next = None - - pre = None - while cur: - t = cur.next - cur.next = pre - pre, cur = cur, t - cur = head - - while pre: - t = pre.next - pre.next = cur.next - cur.next = pre - cur, pre = pre.next, t +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reorderList(self, head: Optional[ListNode]) -> None: + # 快慢指针找到链表中点 + fast = slow = head + while fast.next and fast.next.next: + slow = slow.next + fast = fast.next.next + + # cur 指向右半部分链表 + cur = slow.next + slow.next = None + + # 反转右半部分链表 + pre = None + while cur: + t = cur.next + cur.next = pre + pre, cur = cur, t + cur = head + + # 此时 cur, pre 分别指向链表左右两半的第一个节点 + # 合并 + while pre: + t = pre.next + pre.next = cur.next + cur.next = pre + cur, pre = pre.next, t diff --git a/solution/0100-0199/0143.Reorder List/Solution.ts b/solution/0100-0199/0143.Reorder List/Solution.ts index 778989284db22..e38b213aeb7d1 100644 --- a/solution/0100-0199/0143.Reorder List/Solution.ts +++ b/solution/0100-0199/0143.Reorder List/Solution.ts @@ -14,27 +14,19 @@ Do not return anything, modify head in-place instead. */ function reorderList(head: ListNode | null): void { - let slow = head; - let fast = head; - - while (fast != null && fast.next != null) { - slow = slow.next; - fast = fast.next.next; - } - - let next = slow.next; - slow.next = null; - while (next != null) { - [next.next, slow, next] = [slow, next, next.next]; + const arr = []; + let node = head; + while (node.next != null) { + arr.push(node); + node = node.next; } - - let left = head; - let right = slow; - while (right.next != null) { - const next = left.next; - left.next = right; - right = right.next; - left.next.next = next; - left = left.next.next; + let l = 0; + let r = arr.length - 1; + while (l < r) { + const start = arr[l]; + const end = arr[r]; + [end.next.next, start.next, end.next] = [start.next, end.next, null]; + l++; + r--; } } diff --git a/solution/0100-0199/0143.Reorder List/Solution2.ts b/solution/0100-0199/0143.Reorder List/Solution2.ts new file mode 100644 index 0000000000000..6c502f4ce741e --- /dev/null +++ b/solution/0100-0199/0143.Reorder List/Solution2.ts @@ -0,0 +1,40 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +/** + Do not return anything, modify head in-place instead. + */ +function reorderList(head: ListNode | null): void { + let slow = head; + let fast = head; + // 找到中心节点 + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + // 反转节点 + let next = slow.next; + slow.next = null; + while (next != null) { + [next.next, slow, next] = [slow, next, next.next]; + } + // 合并 + let left = head; + let right = slow; + while (right.next != null) { + const next = left.next; + left.next = right; + right = right.next; + left.next.next = next; + left = left.next.next; + } +} diff --git a/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution.java b/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution.java index 49a11091f32e8..7d90054c94d98 100644 --- a/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution.java +++ b/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution.java @@ -14,27 +14,20 @@ * } */ class Solution { + private List ans; + public List preorderTraversal(TreeNode root) { - List ans = new ArrayList<>(); - while (root != null) { - if (root.left == null) { - ans.add(root.val); - root = root.right; - } else { - TreeNode prev = root.left; - while (prev.right != null && prev.right != root) { - prev = prev.right; - } - if (prev.right == null) { - ans.add(root.val); - prev.right = root; - root = root.left; - } else { - prev.right = null; - root = root.right; - } - } - } + ans = new ArrayList<>(); + dfs(root); return ans; } + + private void dfs(TreeNode root) { + if (root == null) { + return; + } + ans.add(root.val); + dfs(root.left); + dfs(root.right); + } } \ No newline at end of file diff --git a/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution.py b/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution.py index 74d66707a92a5..39938612939ae 100644 --- a/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution.py +++ b/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution.py @@ -6,20 +6,14 @@ # self.right = right class Solution: def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + def dfs(root): + if root is None: + return + nonlocal ans + ans.append(root.val) + dfs(root.left) + dfs(root.right) + ans = [] - while root: - if root.left is None: - ans.append(root.val) - root = root.right - else: - prev = root.left - while prev.right and prev.right != root: - prev = prev.right - if prev.right is None: - ans.append(root.val) - prev.right = root - root = root.left - else: - prev.right = None - root = root.right + dfs(root) return ans diff --git a/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution.ts b/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution.ts index 1ddd5477c42e5..9e3ee928fba45 100644 --- a/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution.ts +++ b/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution.ts @@ -14,24 +14,13 @@ function preorderTraversal(root: TreeNode | null): number[] { let ans = []; - while (root) { - if (!root.left) { - ans.push(root.val); - root = root.right; - } else { - let prev = root.left; - while (prev.right && prev.right != root) { - prev = prev.right; - } - if (!prev.right) { - ans.push(root.val); - prev.right = root; - root = root.left; - } else { - prev.right = null; - root = root.right; - } - } + if (!root) return ans; + let stk = [root]; + while (stk.length) { + let node = stk.pop(); + ans.push(node.val); + if (node.right) stk.push(node.right); + if (node.left) stk.push(node.left); } return ans; } diff --git a/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution2.java b/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution2.java new file mode 100644 index 0000000000000..87ac34d706a15 --- /dev/null +++ b/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution2.java @@ -0,0 +1,36 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List preorderTraversal(TreeNode root) { + List ans = new ArrayList<>(); + if (root == null) { + return ans; + } + Deque stk = new ArrayDeque<>(); + stk.push(root); + while (!stk.isEmpty()) { + TreeNode node = stk.pop(); + ans.add(node.val); + if (node.right != null) { + stk.push(node.right); + } + if (node.left != null) { + stk.push(node.left); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution2.py b/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution2.py new file mode 100644 index 0000000000000..9ee042d27bc7c --- /dev/null +++ b/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution2.py @@ -0,0 +1,20 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + if root is None: + return ans + stk = [root] + while stk: + node = stk.pop() + ans.append(node.val) + if node.right: + stk.append(node.right) + if node.left: + stk.append(node.left) + return ans diff --git a/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution2.rs b/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution2.rs new file mode 100644 index 0000000000000..b91f1e2f9e075 --- /dev/null +++ b/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution2.rs @@ -0,0 +1,41 @@ +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn preorder_traversal(mut root: Option>>) -> Vec { + let mut res = vec![]; + if root.is_none() { + return res; + } + let mut stack = vec![]; + while root.is_some() || stack.len() != 0 { + if root.is_some() { + let val = root.as_ref().unwrap().as_ref().borrow().val; + let left = root.as_ref().unwrap().as_ref().borrow_mut().left.take(); + res.push(val); + stack.push(root); + root = left; + } else { + root = stack.pop().unwrap().as_ref().unwrap().as_ref().borrow_mut().right.take(); + } + } + res + } +} diff --git a/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution2.ts b/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution2.ts new file mode 100644 index 0000000000000..1ddd5477c42e5 --- /dev/null +++ b/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution2.ts @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function preorderTraversal(root: TreeNode | null): number[] { + let ans = []; + while (root) { + if (!root.left) { + ans.push(root.val); + root = root.right; + } else { + let prev = root.left; + while (prev.right && prev.right != root) { + prev = prev.right; + } + if (!prev.right) { + ans.push(root.val); + prev.right = root; + root = root.left; + } else { + prev.right = null; + root = root.right; + } + } + } + return ans; +} diff --git a/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution3.java b/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution3.java new file mode 100644 index 0000000000000..49a11091f32e8 --- /dev/null +++ b/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution3.java @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List preorderTraversal(TreeNode root) { + List ans = new ArrayList<>(); + while (root != null) { + if (root.left == null) { + ans.add(root.val); + root = root.right; + } else { + TreeNode prev = root.left; + while (prev.right != null && prev.right != root) { + prev = prev.right; + } + if (prev.right == null) { + ans.add(root.val); + prev.right = root; + root = root.left; + } else { + prev.right = null; + root = root.right; + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution3.py b/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution3.py new file mode 100644 index 0000000000000..74d66707a92a5 --- /dev/null +++ b/solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution3.py @@ -0,0 +1,25 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + while root: + if root.left is None: + ans.append(root.val) + root = root.right + else: + prev = root.left + while prev.right and prev.right != root: + prev = prev.right + if prev.right is None: + ans.append(root.val) + prev.right = root + root = root.left + else: + prev.right = None + root = root.right + return ans diff --git a/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution.java b/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution.java index 7748c1a4d3629..3ea04e251f96c 100644 --- a/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution.java +++ b/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution.java @@ -14,27 +14,20 @@ * } */ class Solution { + private List ans; + public List postorderTraversal(TreeNode root) { - LinkedList ans = new LinkedList<>(); - while (root != null) { - if (root.right == null) { - ans.addFirst(root.val); - root = root.left; - } else { - TreeNode next = root.right; - while (next.left != null && next.left != root) { - next = next.left; - } - if (next.left == null) { - ans.addFirst(root.val); - next.left = root; - root = root.right; - } else { - next.left = null; - root = root.left; - } - } - } + ans = new ArrayList<>(); + dfs(root); return ans; } + + private void dfs(TreeNode root) { + if (root == null) { + return; + } + dfs(root.left); + dfs(root.right); + ans.add(root.val); + } } \ No newline at end of file diff --git a/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution.py b/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution.py index 0c53813278e3f..fd82c36dd68b1 100644 --- a/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution.py +++ b/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution.py @@ -6,20 +6,14 @@ # self.right = right class Solution: def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + def dfs(root): + if root is None: + return + dfs(root.left) + dfs(root.right) + nonlocal ans + ans.append(root.val) + ans = [] - while root: - if root.right is None: - ans.append(root.val) - root = root.left - else: - next = root.right - while next.left and next.left != root: - next = next.left - if next.left != root: - ans.append(root.val) - next.left = root - root = root.right - else: - next.left = None - root = root.left - return ans[::-1] + dfs(root) + return ans diff --git a/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution2.java b/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution2.java new file mode 100644 index 0000000000000..959951072919b --- /dev/null +++ b/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution2.java @@ -0,0 +1,36 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List postorderTraversal(TreeNode root) { + LinkedList ans = new LinkedList<>(); + if (root == null) { + return ans; + } + Deque stk = new ArrayDeque<>(); + stk.push(root); + while (!stk.isEmpty()) { + TreeNode node = stk.pop(); + ans.addFirst(node.val); + if (node.left != null) { + stk.push(node.left); + } + if (node.right != null) { + stk.push(node.right); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution2.py b/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution2.py new file mode 100644 index 0000000000000..2e60ecb12507e --- /dev/null +++ b/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution2.py @@ -0,0 +1,20 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + if root is None: + return ans + stk = [root] + while stk: + node = stk.pop() + ans.append(node.val) + if node.left: + stk.append(node.left) + if node.right: + stk.append(node.right) + return ans[::-1] diff --git a/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution2.rs b/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution2.rs new file mode 100644 index 0000000000000..1b126a82165ac --- /dev/null +++ b/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution2.rs @@ -0,0 +1,43 @@ +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn postorder_traversal(mut root: Option>>) -> Vec { + let mut res = vec![]; + let mut stack = vec![]; + while root.is_some() || !stack.is_empty() { + if root.is_some() { + let next = root.as_mut().unwrap().borrow_mut().left.take(); + stack.push(root); + root = next; + } else { + root = stack.pop().unwrap(); + let next = root.as_mut().unwrap().borrow_mut().right.take(); + if next.is_some() { + stack.push(root); + } else { + res.push(root.as_ref().unwrap().borrow().val); + } + root = next; + } + } + res + } +} diff --git a/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution2.ts b/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution2.ts new file mode 100644 index 0000000000000..e86e8aa1c12aa --- /dev/null +++ b/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution2.ts @@ -0,0 +1,21 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function postorderTraversal(root: TreeNode | null): number[] { + if (root == null) { + return []; + } + const { val, left, right } = root; + return [...postorderTraversal(left), ...postorderTraversal(right), val]; +} diff --git a/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution3.java b/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution3.java new file mode 100644 index 0000000000000..7748c1a4d3629 --- /dev/null +++ b/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution3.java @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List postorderTraversal(TreeNode root) { + LinkedList ans = new LinkedList<>(); + while (root != null) { + if (root.right == null) { + ans.addFirst(root.val); + root = root.left; + } else { + TreeNode next = root.right; + while (next.left != null && next.left != root) { + next = next.left; + } + if (next.left == null) { + ans.addFirst(root.val); + next.left = root; + root = root.right; + } else { + next.left = null; + root = root.left; + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution3.py b/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution3.py new file mode 100644 index 0000000000000..0c53813278e3f --- /dev/null +++ b/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution3.py @@ -0,0 +1,25 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + while root: + if root.right is None: + ans.append(root.val) + root = root.left + else: + next = root.right + while next.left and next.left != root: + next = next.left + if next.left != root: + ans.append(root.val) + next.left = root + root = root.right + else: + next.left = None + root = root.left + return ans[::-1] diff --git a/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution3.ts b/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution3.ts new file mode 100644 index 0000000000000..6712beeed285f --- /dev/null +++ b/solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution3.ts @@ -0,0 +1,38 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function postorderTraversal(root: TreeNode | null): number[] { + const res = []; + while (root != null) { + const { val, left, right } = root; + if (right == null) { + res.push(val); + root = left; + } else { + let next = right; + while (next.left != null && next.left != root) { + next = next.left; + } + if (next.left == null) { + res.push(val); + next.left = root; + root = right; + } else { + next.left = null; + root = left; + } + } + } + return res.reverse(); +} diff --git a/solution/0100-0199/0146.LRU Cache/Solution.cs b/solution/0100-0199/0146.LRU Cache/Solution.cs index d3f375860f849..a43d2901155ce 100644 --- a/solution/0100-0199/0146.LRU Cache/Solution.cs +++ b/solution/0100-0199/0146.LRU Cache/Solution.cs @@ -1,76 +1,76 @@ -public class LRUCache { - class Node { - public Node Prev; - public Node Next; - public int Key; - public int Val; - } - - private Node head = new Node(); - private Node tail = new Node(); - private Dictionary cache = new Dictionary(); - private readonly int capacity; - private int size; - - public LRUCache(int capacity) { - this.capacity = capacity; - head.Next = tail; - tail.Prev = head; - } - - public int Get(int key) { - Node node; - if (cache.TryGetValue(key, out node)) { - moveToHead(node); - return node.Val; - } - return -1; - } - - public void Put(int key, int Val) { - Node node; - if (cache.TryGetValue(key, out node)) { - moveToHead(node); - node.Val = Val; - } else { - node = new Node() { Key = key, Val = Val }; - cache.Add(key, node); - addToHead(node); - if (++size > capacity) { - node = removeTail(); - cache.Remove(node.Key); - --size; - } - } - } - - private void moveToHead(Node node) { - removeNode(node); - addToHead(node); - } - - private void removeNode(Node node) { - node.Prev.Next = node.Next; - node.Next.Prev = node.Prev; - } - - private void addToHead(Node node) { - node.Next = head.Next; - node.Prev = head; - head.Next = node; - node.Next.Prev = node; - } - - private Node removeTail() { - Node node = tail.Prev; - removeNode(node); - return node; - } -} - -/** - * Your LRUCache object will be instantiated and called as such: - * LRUCache obj = new LRUCache(capacity); - * int param_1 = obj.Get(key); - * obj.Put(key,Val); - */ \ No newline at end of file +public class LRUCache { + class Node { + public Node Prev; + public Node Next; + public int Key; + public int Val; + } + + private Node head = new Node(); + private Node tail = new Node(); + private Dictionary cache = new Dictionary(); + private readonly int capacity; + private int size; + + public LRUCache(int capacity) { + this.capacity = capacity; + head.Next = tail; + tail.Prev = head; + } + + public int Get(int key) { + Node node; + if (cache.TryGetValue(key, out node)) { + moveToHead(node); + return node.Val; + } + return -1; + } + + public void Put(int key, int Val) { + Node node; + if (cache.TryGetValue(key, out node)) { + moveToHead(node); + node.Val = Val; + } else { + node = new Node() { Key = key, Val = Val }; + cache.Add(key, node); + addToHead(node); + if (++size > capacity) { + node = removeTail(); + cache.Remove(node.Key); + --size; + } + } + } + + private void moveToHead(Node node) { + removeNode(node); + addToHead(node); + } + + private void removeNode(Node node) { + node.Prev.Next = node.Next; + node.Next.Prev = node.Prev; + } + + private void addToHead(Node node) { + node.Next = head.Next; + node.Prev = head; + head.Next = node; + node.Next.Prev = node; + } + + private Node removeTail() { + Node node = tail.Prev; + removeNode(node); + return node; + } +} + +/** + * Your LRUCache object will be instantiated and called as such: + * LRUCache obj = new LRUCache(capacity); + * int param_1 = obj.Get(key); + * obj.Put(key,Val); + */ diff --git a/solution/0100-0199/0146.LRU Cache/Solution.py b/solution/0100-0199/0146.LRU Cache/Solution.py index d76142234ee0d..76457b08d8cfd 100644 --- a/solution/0100-0199/0146.LRU Cache/Solution.py +++ b/solution/0100-0199/0146.LRU Cache/Solution.py @@ -1,64 +1,64 @@ -class Node: - def __init__(self, key=0, val=0): - self.key = key - self.val = val - self.prev = None - self.next = None - - -class LRUCache: - def __init__(self, capacity: int): - self.cache = {} - self.head = Node() - self.tail = Node() - self.capacity = capacity - self.size = 0 - self.head.next = self.tail - self.tail.prev = self.head - - def get(self, key: int) -> int: - if key not in self.cache: - return -1 - node = self.cache[key] - self.move_to_head(node) - return node.val - - def put(self, key: int, value: int) -> None: - if key in self.cache: - node = self.cache[key] - node.val = value - self.move_to_head(node) - else: - node = Node(key, value) - self.cache[key] = node - self.add_to_head(node) - self.size += 1 - if self.size > self.capacity: - node = self.remove_tail() - self.cache.pop(node.key) - self.size -= 1 - - def move_to_head(self, node): - self.remove_node(node) - self.add_to_head(node) - - def remove_node(self, node): - node.prev.next = node.next - node.next.prev = node.prev - - def add_to_head(self, node): - node.next = self.head.next - node.prev = self.head - self.head.next = node - node.next.prev = node - - def remove_tail(self): - node = self.tail.prev - self.remove_node(node) - return node - - -# Your LRUCache object will be instantiated and called as such: -# obj = LRUCache(capacity) -# param_1 = obj.get(key) -# obj.put(key,value) +class Node: + def __init__(self, key=0, val=0): + self.key = key + self.val = val + self.prev = None + self.next = None + + +class LRUCache: + def __init__(self, capacity: int): + self.cache = {} + self.head = Node() + self.tail = Node() + self.capacity = capacity + self.size = 0 + self.head.next = self.tail + self.tail.prev = self.head + + def get(self, key: int) -> int: + if key not in self.cache: + return -1 + node = self.cache[key] + self.move_to_head(node) + return node.val + + def put(self, key: int, value: int) -> None: + if key in self.cache: + node = self.cache[key] + node.val = value + self.move_to_head(node) + else: + node = Node(key, value) + self.cache[key] = node + self.add_to_head(node) + self.size += 1 + if self.size > self.capacity: + node = self.remove_tail() + self.cache.pop(node.key) + self.size -= 1 + + def move_to_head(self, node): + self.remove_node(node) + self.add_to_head(node) + + def remove_node(self, node): + node.prev.next = node.next + node.next.prev = node.prev + + def add_to_head(self, node): + node.next = self.head.next + node.prev = self.head + self.head.next = node + node.next.prev = node + + def remove_tail(self): + node = self.tail.prev + self.remove_node(node) + return node + + +# Your LRUCache object will be instantiated and called as such: +# obj = LRUCache(capacity) +# param_1 = obj.get(key) +# obj.put(key,value) diff --git a/solution/0100-0199/0148.Sort List/Solution.cs b/solution/0100-0199/0148.Sort List/Solution.cs index 6cd02f2490770..fc6c6d8c95300 100644 --- a/solution/0100-0199/0148.Sort List/Solution.cs +++ b/solution/0100-0199/0148.Sort List/Solution.cs @@ -44,4 +44,4 @@ public ListNode SortList(ListNode head) { cur.next = l1 == null ? l2 : l1; return dummy.next; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0149.Max Points on a Line/Solution.cpp b/solution/0100-0199/0149.Max Points on a Line/Solution.cpp index 652bda32cd9a2..21695515a1c67 100644 --- a/solution/0100-0199/0149.Max Points on a Line/Solution.cpp +++ b/solution/0100-0199/0149.Max Points on a Line/Solution.cpp @@ -1,21 +1,20 @@ class Solution { public: - int gcd(int a, int b) { - return b == 0 ? a : gcd(b, a % b); - } int maxPoints(vector>& points) { int n = points.size(); int ans = 1; for (int i = 0; i < n; ++i) { int x1 = points[i][0], y1 = points[i][1]; - unordered_map cnt; for (int j = i + 1; j < n; ++j) { int x2 = points[j][0], y2 = points[j][1]; - int dx = x2 - x1, dy = y2 - y1; - int g = gcd(dx, dy); - string k = to_string(dx / g) + "." + to_string(dy / g); - cnt[k]++; - ans = max(ans, cnt[k] + 1); + int cnt = 2; + for (int k = j + 1; k < n; ++k) { + int x3 = points[k][0], y3 = points[k][1]; + int a = (y2 - y1) * (x3 - x1); + int b = (y3 - y1) * (x2 - x1); + cnt += a == b; + } + ans = max(ans, cnt); } } return ans; diff --git a/solution/0100-0199/0149.Max Points on a Line/Solution.cs b/solution/0100-0199/0149.Max Points on a Line/Solution.cs index ef9c2ec59a4bc..76103e3b29bd8 100644 --- a/solution/0100-0199/0149.Max Points on a Line/Solution.cs +++ b/solution/0100-0199/0149.Max Points on a Line/Solution.cs @@ -1,4 +1,4 @@ -public class Solution { +public class Solution { public int MaxPoints(int[][] points) { int n = points.Length; int ans = 1; @@ -22,4 +22,4 @@ public int MaxPoints(int[][] points) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0149.Max Points on a Line/Solution.go b/solution/0100-0199/0149.Max Points on a Line/Solution.go index cfe43a1f4eea2..a927c47f8b05e 100644 --- a/solution/0100-0199/0149.Max Points on a Line/Solution.go +++ b/solution/0100-0199/0149.Max Points on a Line/Solution.go @@ -1,27 +1,23 @@ func maxPoints(points [][]int) int { n := len(points) ans := 1 - type pair struct{ x, y int } for i := 0; i < n; i++ { x1, y1 := points[i][0], points[i][1] - cnt := map[pair]int{} for j := i + 1; j < n; j++ { x2, y2 := points[j][0], points[j][1] - dx, dy := x2-x1, y2-y1 - g := gcd(dx, dy) - k := pair{dx / g, dy / g} - cnt[k]++ - if ans < cnt[k]+1 { - ans = cnt[k] + 1 + cnt := 2 + for k := j + 1; k < n; k++ { + x3, y3 := points[k][0], points[k][1] + a := (y2 - y1) * (x3 - x1) + b := (y3 - y1) * (x2 - x1) + if a == b { + cnt++ + } + } + if ans < cnt { + ans = cnt } } } return ans -} - -func gcd(a, b int) int { - if b == 0 { - return a - } - return gcd(b, a%b) } \ No newline at end of file diff --git a/solution/0100-0199/0149.Max Points on a Line/Solution.java b/solution/0100-0199/0149.Max Points on a Line/Solution.java index d5bdd8a09ccde..50cd575683dba 100644 --- a/solution/0100-0199/0149.Max Points on a Line/Solution.java +++ b/solution/0100-0199/0149.Max Points on a Line/Solution.java @@ -4,20 +4,20 @@ public int maxPoints(int[][] points) { int ans = 1; for (int i = 0; i < n; ++i) { int x1 = points[i][0], y1 = points[i][1]; - Map cnt = new HashMap<>(); for (int j = i + 1; j < n; ++j) { int x2 = points[j][0], y2 = points[j][1]; - int dx = x2 - x1, dy = y2 - y1; - int g = gcd(dx, dy); - String k = (dx / g) + "." + (dy / g); - cnt.put(k, cnt.getOrDefault(k, 0) + 1); - ans = Math.max(ans, cnt.get(k) + 1); + int cnt = 2; + for (int k = j + 1; k < n; ++k) { + int x3 = points[k][0], y3 = points[k][1]; + int a = (y2 - y1) * (x3 - x1); + int b = (y3 - y1) * (x2 - x1); + if (a == b) { + ++cnt; + } + } + ans = Math.max(ans, cnt); } } return ans; } - - private int gcd(int a, int b) { - return b == 0 ? a : gcd(b, a % b); - } } \ No newline at end of file diff --git a/solution/0100-0199/0149.Max Points on a Line/Solution.py b/solution/0100-0199/0149.Max Points on a Line/Solution.py index 090c8e5c1ec44..f424b0bd918d1 100644 --- a/solution/0100-0199/0149.Max Points on a Line/Solution.py +++ b/solution/0100-0199/0149.Max Points on a Line/Solution.py @@ -1,18 +1,16 @@ class Solution: def maxPoints(self, points: List[List[int]]) -> int: - def gcd(a, b): - return a if b == 0 else gcd(b, a % b) - n = len(points) ans = 1 for i in range(n): x1, y1 = points[i] - cnt = Counter() for j in range(i + 1, n): x2, y2 = points[j] - dx, dy = x2 - x1, y2 - y1 - g = gcd(dx, dy) - k = (dx // g, dy // g) - cnt[k] += 1 - ans = max(ans, cnt[k] + 1) + cnt = 2 + for k in range(j + 1, n): + x3, y3 = points[k] + a = (y2 - y1) * (x3 - x1) + b = (y3 - y1) * (x2 - x1) + cnt += a == b + ans = max(ans, cnt) return ans diff --git a/solution/0100-0199/0149.Max Points on a Line/Solution2.cpp b/solution/0100-0199/0149.Max Points on a Line/Solution2.cpp new file mode 100644 index 0000000000000..652bda32cd9a2 --- /dev/null +++ b/solution/0100-0199/0149.Max Points on a Line/Solution2.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } + int maxPoints(vector>& points) { + int n = points.size(); + int ans = 1; + for (int i = 0; i < n; ++i) { + int x1 = points[i][0], y1 = points[i][1]; + unordered_map cnt; + for (int j = i + 1; j < n; ++j) { + int x2 = points[j][0], y2 = points[j][1]; + int dx = x2 - x1, dy = y2 - y1; + int g = gcd(dx, dy); + string k = to_string(dx / g) + "." + to_string(dy / g); + cnt[k]++; + ans = max(ans, cnt[k] + 1); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0149.Max Points on a Line/Solution2.go b/solution/0100-0199/0149.Max Points on a Line/Solution2.go new file mode 100644 index 0000000000000..cfe43a1f4eea2 --- /dev/null +++ b/solution/0100-0199/0149.Max Points on a Line/Solution2.go @@ -0,0 +1,27 @@ +func maxPoints(points [][]int) int { + n := len(points) + ans := 1 + type pair struct{ x, y int } + for i := 0; i < n; i++ { + x1, y1 := points[i][0], points[i][1] + cnt := map[pair]int{} + for j := i + 1; j < n; j++ { + x2, y2 := points[j][0], points[j][1] + dx, dy := x2-x1, y2-y1 + g := gcd(dx, dy) + k := pair{dx / g, dy / g} + cnt[k]++ + if ans < cnt[k]+1 { + ans = cnt[k] + 1 + } + } + } + return ans +} + +func gcd(a, b int) int { + if b == 0 { + return a + } + return gcd(b, a%b) +} \ No newline at end of file diff --git a/solution/0100-0199/0149.Max Points on a Line/Solution2.java b/solution/0100-0199/0149.Max Points on a Line/Solution2.java new file mode 100644 index 0000000000000..d5bdd8a09ccde --- /dev/null +++ b/solution/0100-0199/0149.Max Points on a Line/Solution2.java @@ -0,0 +1,23 @@ +class Solution { + public int maxPoints(int[][] points) { + int n = points.length; + int ans = 1; + for (int i = 0; i < n; ++i) { + int x1 = points[i][0], y1 = points[i][1]; + Map cnt = new HashMap<>(); + for (int j = i + 1; j < n; ++j) { + int x2 = points[j][0], y2 = points[j][1]; + int dx = x2 - x1, dy = y2 - y1; + int g = gcd(dx, dy); + String k = (dx / g) + "." + (dy / g); + cnt.put(k, cnt.getOrDefault(k, 0) + 1); + ans = Math.max(ans, cnt.get(k) + 1); + } + } + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} \ No newline at end of file diff --git a/solution/0100-0199/0149.Max Points on a Line/Solution2.py b/solution/0100-0199/0149.Max Points on a Line/Solution2.py new file mode 100644 index 0000000000000..090c8e5c1ec44 --- /dev/null +++ b/solution/0100-0199/0149.Max Points on a Line/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def maxPoints(self, points: List[List[int]]) -> int: + def gcd(a, b): + return a if b == 0 else gcd(b, a % b) + + n = len(points) + ans = 1 + for i in range(n): + x1, y1 = points[i] + cnt = Counter() + for j in range(i + 1, n): + x2, y2 = points[j] + dx, dy = x2 - x1, y2 - y1 + g = gcd(dx, dy) + k = (dx // g, dy // g) + cnt[k] += 1 + ans = max(ans, cnt[k] + 1) + return ans diff --git a/solution/0100-0199/0150.Evaluate Reverse Polish Notation/Solution.cs b/solution/0100-0199/0150.Evaluate Reverse Polish Notation/Solution.cs index 242ee15e87665..163ebd2a94ee3 100644 --- a/solution/0100-0199/0150.Evaluate Reverse Polish Notation/Solution.cs +++ b/solution/0100-0199/0150.Evaluate Reverse Polish Notation/Solution.cs @@ -27,4 +27,4 @@ public int EvalRPN(string[] tokens) { } return stack.Pop(); } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0150.Evaluate Reverse Polish Notation/Solution.py b/solution/0100-0199/0150.Evaluate Reverse Polish Notation/Solution.py index 5e5380822eb7b..63aa16a476034 100644 --- a/solution/0100-0199/0150.Evaluate Reverse Polish Notation/Solution.py +++ b/solution/0100-0199/0150.Evaluate Reverse Polish Notation/Solution.py @@ -1,17 +1,18 @@ +import operator + + class Solution: def evalRPN(self, tokens: List[str]) -> int: - nums = [] - for t in tokens: - if len(t) > 1 or t.isdigit(): - nums.append(int(t)) + opt = { + "+": operator.add, + "-": operator.sub, + "*": operator.mul, + "/": operator.truediv, + } + s = [] + for token in tokens: + if token in opt: + s.append(int(opt[token](s.pop(-2), s.pop(-1)))) else: - if t == "+": - nums[-2] += nums[-1] - elif t == "-": - nums[-2] -= nums[-1] - elif t == "*": - nums[-2] *= nums[-1] - else: - nums[-2] = int(nums[-2] / nums[-1]) - nums.pop() - return nums[0] + s.append(int(token)) + return s[0] diff --git a/solution/0100-0199/0150.Evaluate Reverse Polish Notation/Solution2.py b/solution/0100-0199/0150.Evaluate Reverse Polish Notation/Solution2.py new file mode 100644 index 0000000000000..5e5380822eb7b --- /dev/null +++ b/solution/0100-0199/0150.Evaluate Reverse Polish Notation/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def evalRPN(self, tokens: List[str]) -> int: + nums = [] + for t in tokens: + if len(t) > 1 or t.isdigit(): + nums.append(int(t)) + else: + if t == "+": + nums[-2] += nums[-1] + elif t == "-": + nums[-2] -= nums[-1] + elif t == "*": + nums[-2] *= nums[-1] + else: + nums[-2] = int(nums[-2] / nums[-1]) + nums.pop() + return nums[0] diff --git a/solution/0100-0199/0151.Reverse Words in a String/Solution.cs b/solution/0100-0199/0151.Reverse Words in a String/Solution.cs index 1f0794970722b..6aefaa604e775 100644 --- a/solution/0100-0199/0151.Reverse Words in a String/Solution.cs +++ b/solution/0100-0199/0151.Reverse Words in a String/Solution.cs @@ -2,4 +2,4 @@ public class Solution { public string ReverseWords(string s) { return string.Join(" ", s.Trim().Split(" ").Where(word => !string.IsNullOrEmpty(word) && !string.IsNullOrEmpty(word.Trim())).Reverse()); } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0151.Reverse Words in a String/Solution2.java b/solution/0100-0199/0151.Reverse Words in a String/Solution2.java new file mode 100644 index 0000000000000..627a77c0dacab --- /dev/null +++ b/solution/0100-0199/0151.Reverse Words in a String/Solution2.java @@ -0,0 +1,22 @@ +class Solution { + public String reverseWords(String s) { + List words = new ArrayList<>(); + int n = s.length(); + for (int i = 0; i < n;) { + while (i < n && s.charAt(i) == ' ') { + ++i; + } + if (i < n) { + StringBuilder t = new StringBuilder(); + int j = i; + while (j < n && s.charAt(j) != ' ') { + t.append(s.charAt(j++)); + } + words.add(t.toString()); + i = j; + } + } + Collections.reverse(words); + return String.join(" ", words); + } +} \ No newline at end of file diff --git a/solution/0100-0199/0151.Reverse Words in a String/Solution2.py b/solution/0100-0199/0151.Reverse Words in a String/Solution2.py new file mode 100644 index 0000000000000..70729dcff4fd5 --- /dev/null +++ b/solution/0100-0199/0151.Reverse Words in a String/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def reverseWords(self, s: str) -> str: + ans = [] + i, n = 0, len(s) + while i < n: + while i < n and s[i] == ' ': + i += 1 + if i < n: + j = i + while j < n and s[j] != ' ': + j += 1 + ans.append(s[i:j]) + i = j + return ' '.join(ans[::-1]) diff --git a/solution/0100-0199/0152.Maximum Product Subarray/Solution.cpp b/solution/0100-0199/0152.Maximum Product Subarray/Solution.cpp index 8d311b042a38b..d46d49a39c497 100644 --- a/solution/0100-0199/0152.Maximum Product Subarray/Solution.cpp +++ b/solution/0100-0199/0152.Maximum Product Subarray/Solution.cpp @@ -1,13 +1,13 @@ -class Solution { -public: - int maxProduct(vector& nums) { - int f = nums[0], g = nums[0], ans = nums[0]; - for (int i = 1; i < nums.size(); ++i) { - int ff = f, gg = g; - f = max({nums[i], ff * nums[i], gg * nums[i]}); - g = min({nums[i], ff * nums[i], gg * nums[i]}); - ans = max(ans, f); - } - return ans; - } +class Solution { +public: + int maxProduct(vector& nums) { + int f = nums[0], g = nums[0], ans = nums[0]; + for (int i = 1; i < nums.size(); ++i) { + int ff = f, gg = g; + f = max({nums[i], ff * nums[i], gg * nums[i]}); + g = min({nums[i], ff * nums[i], gg * nums[i]}); + ans = max(ans, f); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0100-0199/0152.Maximum Product Subarray/Solution.cs b/solution/0100-0199/0152.Maximum Product Subarray/Solution.cs index d8abb78e117ba..e77906e33f9fe 100644 --- a/solution/0100-0199/0152.Maximum Product Subarray/Solution.cs +++ b/solution/0100-0199/0152.Maximum Product Subarray/Solution.cs @@ -1,12 +1,12 @@ -public class Solution { - public int MaxProduct(int[] nums) { - int f = nums[0], g = nums[0], ans = nums[0]; - for (int i = 1; i < nums.Length; ++i) { - int ff = f, gg = g; - f = Math.Max(nums[i], Math.Max(ff * nums[i], gg * nums[i])); - g = Math.Min(nums[i], Math.Min(ff * nums[i], gg * nums[i])); - ans = Math.Max(ans, f); - } - return ans; - } -} \ No newline at end of file +public class Solution { + public int MaxProduct(int[] nums) { + int f = nums[0], g = nums[0], ans = nums[0]; + for (int i = 1; i < nums.Length; ++i) { + int ff = f, gg = g; + f = Math.Max(nums[i], Math.Max(ff * nums[i], gg * nums[i])); + g = Math.Min(nums[i], Math.Min(ff * nums[i], gg * nums[i])); + ans = Math.Max(ans, f); + } + return ans; + } +} diff --git a/solution/0100-0199/0152.Maximum Product Subarray/Solution.java b/solution/0100-0199/0152.Maximum Product Subarray/Solution.java index b0775d6a24e61..2e218f0c64555 100644 --- a/solution/0100-0199/0152.Maximum Product Subarray/Solution.java +++ b/solution/0100-0199/0152.Maximum Product Subarray/Solution.java @@ -1,12 +1,12 @@ -class Solution { - public int maxProduct(int[] nums) { - int f = nums[0], g = nums[0], ans = nums[0]; - for (int i = 1; i < nums.length; ++i) { - int ff = f, gg = g; - f = Math.max(nums[i], Math.max(ff * nums[i], gg * nums[i])); - g = Math.min(nums[i], Math.min(ff * nums[i], gg * nums[i])); - ans = Math.max(ans, f); - } - return ans; - } +class Solution { + public int maxProduct(int[] nums) { + int f = nums[0], g = nums[0], ans = nums[0]; + for (int i = 1; i < nums.length; ++i) { + int ff = f, gg = g; + f = Math.max(nums[i], Math.max(ff * nums[i], gg * nums[i])); + g = Math.min(nums[i], Math.min(ff * nums[i], gg * nums[i])); + ans = Math.max(ans, f); + } + return ans; + } } \ No newline at end of file diff --git a/solution/0100-0199/0152.Maximum Product Subarray/Solution.py b/solution/0100-0199/0152.Maximum Product Subarray/Solution.py index 880fff8b43dfb..99acb3cd3ee0b 100644 --- a/solution/0100-0199/0152.Maximum Product Subarray/Solution.py +++ b/solution/0100-0199/0152.Maximum Product Subarray/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def maxProduct(self, nums: List[int]) -> int: - ans = f = g = nums[0] - for x in nums[1:]: - ff, gg = f, g - f = max(x, ff * x, gg * x) - g = min(x, ff * x, gg * x) - ans = max(ans, f) - return ans +class Solution: + def maxProduct(self, nums: List[int]) -> int: + ans = f = g = nums[0] + for x in nums[1:]: + ff, gg = f, g + f = max(x, ff * x, gg * x) + g = min(x, ff * x, gg * x) + ans = max(ans, f) + return ans diff --git a/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/Solution.cpp b/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/Solution.cpp index 9d9e0d56518f6..8922acfd56990 100644 --- a/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/Solution.cpp +++ b/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - int findMin(vector& nums) { - int n = nums.size(); - if (nums[0] <= nums[n - 1]) return nums[0]; - int left = 0, right = n - 1; - while (left < right) { - int mid = (left + right) >> 1; - if (nums[0] <= nums[mid]) - left = mid + 1; - else - right = mid; - } - return nums[left]; - } +class Solution { +public: + int findMin(vector& nums) { + int n = nums.size(); + if (nums[0] <= nums[n - 1]) return nums[0]; + int left = 0, right = n - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[0] <= nums[mid]) + left = mid + 1; + else + right = mid; + } + return nums[left]; + } }; \ No newline at end of file diff --git a/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/Solution.java b/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/Solution.java index 106116d6cc9aa..b340dbf521a85 100644 --- a/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/Solution.java +++ b/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/Solution.java @@ -1,18 +1,18 @@ -class Solution { - public int findMin(int[] nums) { - int n = nums.length; - if (nums[0] <= nums[n - 1]) { - return nums[0]; - } - int left = 0, right = n - 1; - while (left < right) { - int mid = (left + right) >> 1; - if (nums[0] <= nums[mid]) { - left = mid + 1; - } else { - right = mid; - } - } - return nums[left]; - } +class Solution { + public int findMin(int[] nums) { + int n = nums.length; + if (nums[0] <= nums[n - 1]) { + return nums[0]; + } + int left = 0, right = n - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[0] <= nums[mid]) { + left = mid + 1; + } else { + right = mid; + } + } + return nums[left]; + } } \ No newline at end of file diff --git a/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/Solution.js b/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/Solution.js index 3b44f813e7c5e..3380b45480688 100644 --- a/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/Solution.js +++ b/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/Solution.js @@ -3,19 +3,13 @@ * @return {number} */ var findMin = function (nums) { - const n = nums.length; - if (nums[0] <= nums[n - 1]) { - return nums[0]; + let l = 0, + r = nums.length - 1; + if (nums[l] < nums[r]) return nums[0]; + while (l < r) { + const m = (l + r) >> 1; + if (nums[m] > nums[r]) l = m + 1; + else r = m; } - let left = 0, - right = n - 1; - while (left < right) { - const mid = (left + right) >> 1; - if (nums[0] <= nums[mid]) { - left = mid + 1; - } else { - right = mid; - } - } - return nums[left]; + return nums[l]; }; diff --git a/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/Solution.py b/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/Solution.py index d88dd85f92a29..ac347799344bd 100644 --- a/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/Solution.py +++ b/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def findMin(self, nums: List[int]) -> int: - if nums[0] <= nums[-1]: - return nums[0] - left, right = 0, len(nums) - 1 - while left < right: - mid = (left + right) >> 1 - if nums[0] <= nums[mid]: - left = mid + 1 - else: - right = mid - return nums[left] +class Solution: + def findMin(self, nums: List[int]) -> int: + if nums[0] <= nums[-1]: + return nums[0] + left, right = 0, len(nums) - 1 + while left < right: + mid = (left + right) >> 1 + if nums[0] <= nums[mid]: + left = mid + 1 + else: + right = mid + return nums[left] diff --git a/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/Solution.cpp b/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/Solution.cpp index 3d316e8796b4f..7e8a71de9ccb1 100644 --- a/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/Solution.cpp +++ b/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - int findMin(vector& nums) { - int left = 0, right = nums.size() - 1; - while (left < right) { - int mid = (left + right) >> 1; - if (nums[mid] > nums[right]) - left = mid + 1; - else if (nums[mid] < nums[right]) - right = mid; - else - --right; - } - return nums[left]; - } +class Solution { +public: + int findMin(vector& nums) { + int left = 0, right = nums.size() - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] > nums[right]) + left = mid + 1; + else if (nums[mid] < nums[right]) + right = mid; + else + --right; + } + return nums[left]; + } }; \ No newline at end of file diff --git a/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/Solution.java b/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/Solution.java index ea9602d92151d..e314613f7f3e5 100644 --- a/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/Solution.java +++ b/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/Solution.java @@ -1,16 +1,16 @@ -class Solution { - public int findMin(int[] nums) { - int left = 0, right = nums.length - 1; - while (left < right) { - int mid = (left + right) >> 1; - if (nums[mid] > nums[right]) { - left = mid + 1; - } else if (nums[mid] < nums[right]) { - right = mid; - } else { - --right; - } - } - return nums[left]; - } +class Solution { + public int findMin(int[] nums) { + int left = 0, right = nums.length - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] > nums[right]) { + left = mid + 1; + } else if (nums[mid] < nums[right]) { + right = mid; + } else { + --right; + } + } + return nums[left]; + } } \ No newline at end of file diff --git a/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/Solution.py b/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/Solution.py index c12bf034f03ec..aeada206b6d36 100644 --- a/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/Solution.py +++ b/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def findMin(self, nums: List[int]) -> int: - left, right = 0, len(nums) - 1 - while left < right: - mid = (left + right) >> 1 - if nums[mid] > nums[right]: - left = mid + 1 - elif nums[mid] < nums[right]: - right = mid - else: - right -= 1 - return nums[left] +class Solution: + def findMin(self, nums: List[int]) -> int: + left, right = 0, len(nums) - 1 + while left < right: + mid = (left + right) >> 1 + if nums[mid] > nums[right]: + left = mid + 1 + elif nums[mid] < nums[right]: + right = mid + else: + right -= 1 + return nums[left] diff --git a/solution/0100-0199/0155.Min Stack/Solution.cs b/solution/0100-0199/0155.Min Stack/Solution.cs index 0ea023fb1192e..d62740f48c0fa 100644 --- a/solution/0100-0199/0155.Min Stack/Solution.cs +++ b/solution/0100-0199/0155.Min Stack/Solution.cs @@ -1,25 +1,25 @@ public class MinStack { private Stack stk1 = new Stack(); private Stack stk2 = new Stack(); - + public MinStack() { stk2.Push(int.MaxValue); } - + public void Push(int x) { stk1.Push(x); stk2.Push(Math.Min(x, GetMin())); } - + public void Pop() { stk1.Pop(); stk2.Pop(); } - + public int Top() { return stk1.Peek(); } - + public int GetMin() { return stk2.Peek(); } @@ -32,4 +32,4 @@ public int GetMin() { * obj.Pop(); * int param_3 = obj.Top(); * int param_4 = obj.GetMin(); - */ \ No newline at end of file + */ diff --git a/solution/0100-0199/0160.Intersection of Two Linked Lists/Solution.swift b/solution/0100-0199/0160.Intersection of Two Linked Lists/Solution.swift index 6e15cff69fe12..fa41e06ad2024 100644 --- a/solution/0100-0199/0160.Intersection of Two Linked Lists/Solution.swift +++ b/solution/0100-0199/0160.Intersection of Two Linked Lists/Solution.swift @@ -20,4 +20,4 @@ class Solution { } return a } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0163.Missing Ranges/Solution.cpp b/solution/0100-0199/0163.Missing Ranges/Solution.cpp index 47454ae71cdf7..3b10868398a49 100644 --- a/solution/0100-0199/0163.Missing Ranges/Solution.cpp +++ b/solution/0100-0199/0163.Missing Ranges/Solution.cpp @@ -1,22 +1,22 @@ -class Solution { -public: - vector> findMissingRanges(vector& nums, int lower, int upper) { - int n = nums.size(); - if (n == 0) { - return {{lower, upper}}; - } - vector> ans; - if (nums[0] > lower) { - ans.push_back({lower, nums[0] - 1}); - } - for (int i = 1; i < nums.size(); ++i) { - if (nums[i] - nums[i - 1] > 1) { - ans.push_back({nums[i - 1] + 1, nums[i] - 1}); - } - } - if (nums[n - 1] < upper) { - ans.push_back({nums[n - 1] + 1, upper}); - } - return ans; - } +class Solution { +public: + vector> findMissingRanges(vector& nums, int lower, int upper) { + int n = nums.size(); + if (n == 0) { + return {{lower, upper}}; + } + vector> ans; + if (nums[0] > lower) { + ans.push_back({lower, nums[0] - 1}); + } + for (int i = 1; i < nums.size(); ++i) { + if (nums[i] - nums[i - 1] > 1) { + ans.push_back({nums[i - 1] + 1, nums[i] - 1}); + } + } + if (nums[n - 1] < upper) { + ans.push_back({nums[n - 1] + 1, upper}); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0100-0199/0163.Missing Ranges/Solution.java b/solution/0100-0199/0163.Missing Ranges/Solution.java index 3f882d888c2f7..3031f723312a4 100644 --- a/solution/0100-0199/0163.Missing Ranges/Solution.java +++ b/solution/0100-0199/0163.Missing Ranges/Solution.java @@ -1,21 +1,21 @@ -class Solution { - public List> findMissingRanges(int[] nums, int lower, int upper) { - int n = nums.length; - if (n == 0) { - return List.of(List.of(lower, upper)); - } - List> ans = new ArrayList<>(); - if (nums[0] > lower) { - ans.add(List.of(lower, nums[0] - 1)); - } - for (int i = 1; i < n; ++i) { - if (nums[i] - nums[i - 1] > 1) { - ans.add(List.of(nums[i - 1] + 1, nums[i] - 1)); - } - } - if (nums[n - 1] < upper) { - ans.add(List.of(nums[n - 1] + 1, upper)); - } - return ans; - } +class Solution { + public List> findMissingRanges(int[] nums, int lower, int upper) { + int n = nums.length; + if (n == 0) { + return List.of(List.of(lower, upper)); + } + List> ans = new ArrayList<>(); + if (nums[0] > lower) { + ans.add(List.of(lower, nums[0] - 1)); + } + for (int i = 1; i < n; ++i) { + if (nums[i] - nums[i - 1] > 1) { + ans.add(List.of(nums[i - 1] + 1, nums[i] - 1)); + } + } + if (nums[n - 1] < upper) { + ans.add(List.of(nums[n - 1] + 1, upper)); + } + return ans; + } } \ No newline at end of file diff --git a/solution/0100-0199/0163.Missing Ranges/Solution.py b/solution/0100-0199/0163.Missing Ranges/Solution.py index 18e9817b7eb39..161b8cace3680 100644 --- a/solution/0100-0199/0163.Missing Ranges/Solution.py +++ b/solution/0100-0199/0163.Missing Ranges/Solution.py @@ -1,16 +1,16 @@ -class Solution: - def findMissingRanges( - self, nums: List[int], lower: int, upper: int - ) -> List[List[int]]: - n = len(nums) - if n == 0: - return [[lower, upper]] - ans = [] - if nums[0] > lower: - ans.append([lower, nums[0] - 1]) - for a, b in pairwise(nums): - if b - a > 1: - ans.append([a + 1, b - 1]) - if nums[-1] < upper: - ans.append([nums[-1] + 1, upper]) - return ans +class Solution: + def findMissingRanges( + self, nums: List[int], lower: int, upper: int + ) -> List[List[int]]: + n = len(nums) + if n == 0: + return [[lower, upper]] + ans = [] + if nums[0] > lower: + ans.append([lower, nums[0] - 1]) + for a, b in pairwise(nums): + if b - a > 1: + ans.append([a + 1, b - 1]) + if nums[-1] < upper: + ans.append([nums[-1] + 1, upper]) + return ans diff --git a/solution/0100-0199/0164.Maximum Gap/Solution.cs b/solution/0100-0199/0164.Maximum Gap/Solution.cs index 8f809f9c60baf..b6ab11dfc48d7 100644 --- a/solution/0100-0199/0164.Maximum Gap/Solution.cs +++ b/solution/0100-0199/0164.Maximum Gap/Solution.cs @@ -36,4 +36,4 @@ public int MaximumGap(int[] nums) { } return result; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0165.Compare Version Numbers/Solution.cs b/solution/0100-0199/0165.Compare Version Numbers/Solution.cs index b03ac8a2a4ea0..c737e6d48485a 100644 --- a/solution/0100-0199/0165.Compare Version Numbers/Solution.cs +++ b/solution/0100-0199/0165.Compare Version Numbers/Solution.cs @@ -15,4 +15,4 @@ public int CompareVersion(string version1, string version2) { } return 0; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.cpp b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.cpp index adb7e5c33f7a7..1ef864c0a3520 100644 --- a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.cpp +++ b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.cpp @@ -1,16 +1,12 @@ -class Solution { +class Solution { public: vector twoSum(vector& numbers, int target) { - for (int i = 0, j = numbers.size() - 1;;) { - int x = numbers[i] + numbers[j]; - if (x == target) { + for (int i = 0, n = numbers.size();; ++i) { + int x = target - numbers[i]; + int j = lower_bound(numbers.begin() + i + 1, numbers.end(), x) - numbers.begin(); + if (j < n && numbers[j] == x) { return {i + 1, j + 1}; } - if (x < target) { - ++i; - } else { - --j; - } } } }; \ No newline at end of file diff --git a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.go b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.go index 46953ecfc354a..55cd99718c99b 100644 --- a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.go +++ b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.go @@ -1,13 +1,9 @@ func twoSum(numbers []int, target int) []int { - for i, j := 0, len(numbers)-1; ; { - x := numbers[i] + numbers[j] - if x == target { + for i, n := 0, len(numbers); ; i++ { + x := target - numbers[i] + j := sort.SearchInts(numbers[i+1:], x) + i + 1 + if j < n && numbers[j] == x { return []int{i + 1, j + 1} } - if x < target { - i++ - } else { - j-- - } } } \ No newline at end of file diff --git a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.java b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.java index 589685cd501c4..6f0b546d8a8ce 100644 --- a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.java +++ b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.java @@ -1,14 +1,18 @@ class Solution { public int[] twoSum(int[] numbers, int target) { - for (int i = 0, j = numbers.length - 1;;) { - int x = numbers[i] + numbers[j]; - if (x == target) { - return new int[] {i + 1, j + 1}; + for (int i = 0, n = numbers.length;; ++i) { + int x = target - numbers[i]; + int l = i + 1, r = n - 1; + while (l < r) { + int mid = (l + r) >> 1; + if (numbers[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } } - if (x < target) { - ++i; - } else { - --j; + if (numbers[l] == x) { + return new int[] {i + 1, l + 1}; } } } diff --git a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.js b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.js index 4193ac9cc012e..64a0a47681e05 100644 --- a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.js +++ b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.js @@ -4,15 +4,21 @@ * @return {number[]} */ var twoSum = function (numbers, target) { - for (let i = 0, j = numbers.length - 1; ; ) { - const x = numbers[i] + numbers[j]; - if (x === target) { - return [i + 1, j + 1]; + const n = numbers.length; + for (let i = 0; ; ++i) { + const x = target - numbers[i]; + let l = i + 1; + let r = n - 1; + while (l < r) { + const mid = (l + r) >> 1; + if (numbers[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } } - if (x < target) { - ++i; - } else { - --j; + if (numbers[l] === x) { + return [i + 1, l + 1]; } } }; diff --git a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.py b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.py index b6fb591ca09bd..89f69645e7dc5 100644 --- a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.py +++ b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.py @@ -1,11 +1,8 @@ class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: - i, j = 0, len(numbers) - 1 - while i < j: - x = numbers[i] + numbers[j] - if x == target: + n = len(numbers) + for i in range(n - 1): + x = target - numbers[i] + j = bisect_left(numbers, x, lo=i + 1) + if j < n and numbers[j] == x: return [i + 1, j + 1] - if x < target: - i += 1 - else: - j -= 1 diff --git a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.ts b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.ts index b1032d620f46b..d79faf9ec8e87 100644 --- a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.ts +++ b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.ts @@ -1,13 +1,19 @@ function twoSum(numbers: number[], target: number): number[] { - for (let i = 0, j = numbers.length - 1; ; ) { - const x = numbers[i] + numbers[j]; - if (x === target) { - return [i + 1, j + 1]; + const n = numbers.length; + for (let i = 0; ; ++i) { + const x = target - numbers[i]; + let l = i + 1; + let r = n - 1; + while (l < r) { + const mid = (l + r) >> 1; + if (numbers[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } } - if (x < target) { - ++i; - } else { - --j; + if (numbers[l] === x) { + return [i + 1, l + 1]; } } } diff --git a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution2.cpp b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution2.cpp new file mode 100644 index 0000000000000..0539f562ecea0 --- /dev/null +++ b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector twoSum(vector& numbers, int target) { + for (int i = 0, j = numbers.size() - 1;;) { + int x = numbers[i] + numbers[j]; + if (x == target) { + return {i + 1, j + 1}; + } + if (x < target) { + ++i; + } else { + --j; + } + } + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution2.go b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution2.go new file mode 100644 index 0000000000000..46953ecfc354a --- /dev/null +++ b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution2.go @@ -0,0 +1,13 @@ +func twoSum(numbers []int, target int) []int { + for i, j := 0, len(numbers)-1; ; { + x := numbers[i] + numbers[j] + if x == target { + return []int{i + 1, j + 1} + } + if x < target { + i++ + } else { + j-- + } + } +} \ No newline at end of file diff --git a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution2.java b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution2.java new file mode 100644 index 0000000000000..589685cd501c4 --- /dev/null +++ b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public int[] twoSum(int[] numbers, int target) { + for (int i = 0, j = numbers.length - 1;;) { + int x = numbers[i] + numbers[j]; + if (x == target) { + return new int[] {i + 1, j + 1}; + } + if (x < target) { + ++i; + } else { + --j; + } + } + } +} \ No newline at end of file diff --git a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution2.js b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution2.js new file mode 100644 index 0000000000000..4193ac9cc012e --- /dev/null +++ b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution2.js @@ -0,0 +1,18 @@ +/** + * @param {number[]} numbers + * @param {number} target + * @return {number[]} + */ +var twoSum = function (numbers, target) { + for (let i = 0, j = numbers.length - 1; ; ) { + const x = numbers[i] + numbers[j]; + if (x === target) { + return [i + 1, j + 1]; + } + if (x < target) { + ++i; + } else { + --j; + } + } +}; diff --git a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution2.py b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution2.py new file mode 100644 index 0000000000000..b6fb591ca09bd --- /dev/null +++ b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def twoSum(self, numbers: List[int], target: int) -> List[int]: + i, j = 0, len(numbers) - 1 + while i < j: + x = numbers[i] + numbers[j] + if x == target: + return [i + 1, j + 1] + if x < target: + i += 1 + else: + j -= 1 diff --git a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution2.ts b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution2.ts new file mode 100644 index 0000000000000..b1032d620f46b --- /dev/null +++ b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution2.ts @@ -0,0 +1,13 @@ +function twoSum(numbers: number[], target: number): number[] { + for (let i = 0, j = numbers.length - 1; ; ) { + const x = numbers[i] + numbers[j]; + if (x === target) { + return [i + 1, j + 1]; + } + if (x < target) { + ++i; + } else { + --j; + } + } +} diff --git a/solution/0100-0199/0168.Excel Sheet Column Title/Solution.cs b/solution/0100-0199/0168.Excel Sheet Column Title/Solution.cs index 256042d2c3cea..6c21bc0e1b365 100644 --- a/solution/0100-0199/0168.Excel Sheet Column Title/Solution.cs +++ b/solution/0100-0199/0168.Excel Sheet Column Title/Solution.cs @@ -8,4 +8,4 @@ public string ConvertToTitle(int columnNumber) { } return new string(res.ToString().Reverse().ToArray()); } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0169.Majority Element/Solution.cs b/solution/0100-0199/0169.Majority Element/Solution.cs index bf49d4552bfac..341cf5f4dd5e2 100644 --- a/solution/0100-0199/0169.Majority Element/Solution.cs +++ b/solution/0100-0199/0169.Majority Element/Solution.cs @@ -11,4 +11,4 @@ public int MajorityElement(int[] nums) { } return m; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0169.Majority Element/Solution.php b/solution/0100-0199/0169.Majority Element/Solution.php index f7ae73d5f25b4..59b3d9d537277 100644 --- a/solution/0100-0199/0169.Majority Element/Solution.php +++ b/solution/0100-0199/0169.Majority Element/Solution.php @@ -18,4 +18,4 @@ function majorityElement($nums) { } return $m; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0172.Factorial Trailing Zeroes/Solution.cpp b/solution/0100-0199/0172.Factorial Trailing Zeroes/Solution.cpp index 54a7e93e3fffb..0548171db4c53 100644 --- a/solution/0100-0199/0172.Factorial Trailing Zeroes/Solution.cpp +++ b/solution/0100-0199/0172.Factorial Trailing Zeroes/Solution.cpp @@ -1,11 +1,11 @@ -class Solution { -public: - int trailingZeroes(int n) { - int ans = 0; - while (n) { - n /= 5; - ans += n; - } - return ans; - } +class Solution { +public: + int trailingZeroes(int n) { + int ans = 0; + while (n) { + n /= 5; + ans += n; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0100-0199/0172.Factorial Trailing Zeroes/Solution.java b/solution/0100-0199/0172.Factorial Trailing Zeroes/Solution.java index 030ddb17b63ee..1669c7dbf98d4 100644 --- a/solution/0100-0199/0172.Factorial Trailing Zeroes/Solution.java +++ b/solution/0100-0199/0172.Factorial Trailing Zeroes/Solution.java @@ -1,10 +1,10 @@ -class Solution { - public int trailingZeroes(int n) { - int ans = 0; - while (n > 0) { - n /= 5; - ans += n; - } - return ans; - } +class Solution { + public int trailingZeroes(int n) { + int ans = 0; + while (n > 0) { + n /= 5; + ans += n; + } + return ans; + } } \ No newline at end of file diff --git a/solution/0100-0199/0172.Factorial Trailing Zeroes/Solution.py b/solution/0100-0199/0172.Factorial Trailing Zeroes/Solution.py index 4f64e26ddaf49..159c3b331678f 100644 --- a/solution/0100-0199/0172.Factorial Trailing Zeroes/Solution.py +++ b/solution/0100-0199/0172.Factorial Trailing Zeroes/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def trailingZeroes(self, n: int) -> int: - ans = 0 - while n: - n //= 5 - ans += n - return ans +class Solution: + def trailingZeroes(self, n: int) -> int: + ans = 0 + while n: + n //= 5 + ans += n + return ans diff --git a/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.cpp b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.cpp index 1e9939f2773f1..0eed13a02fa89 100644 --- a/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.cpp +++ b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.cpp @@ -11,25 +11,27 @@ */ class BSTIterator { public: - stack stack; + vector vals; + int cur; BSTIterator(TreeNode* root) { - for (; root != nullptr; root = root->left) { - stack.push(root); - } + cur = 0; + inorder(root); } int next() { - TreeNode* cur = stack.top(); - stack.pop(); - TreeNode* node = cur->right; - for (; node != nullptr; node = node->left) { - stack.push(node); - } - return cur->val; + return vals[cur++]; } bool hasNext() { - return !stack.empty(); + return cur < vals.size(); + } + + void inorder(TreeNode* root) { + if (root) { + inorder(root->left); + vals.push_back(root->val); + inorder(root->right); + } } }; diff --git a/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.java b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.java index 6c3360256ff92..c505606d664fa 100644 --- a/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.java +++ b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.java @@ -14,24 +14,27 @@ * } */ class BSTIterator { - private Deque stack = new LinkedList<>(); + private int cur = 0; + private List vals = new ArrayList<>(); public BSTIterator(TreeNode root) { - for (; root != null; root = root.left) { - stack.offerLast(root); - } + inorder(root); } public int next() { - TreeNode cur = stack.pollLast(); - for (TreeNode node = cur.right; node != null; node = node.left) { - stack.offerLast(node); - } - return cur.val; + return vals.get(cur++); } public boolean hasNext() { - return !stack.isEmpty(); + return cur < vals.size(); + } + + private void inorder(TreeNode root) { + if (root != null) { + inorder(root.left); + vals.add(root.val); + inorder(root.right); + } } } diff --git a/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.py b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.py index a8b20b7895704..1452325073795 100644 --- a/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.py +++ b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.py @@ -6,21 +6,23 @@ # self.right = right class BSTIterator: def __init__(self, root: TreeNode): - self.stack = [] - while root: - self.stack.append(root) - root = root.left + def inorder(root): + if root: + inorder(root.left) + self.vals.append(root.val) + inorder(root.right) + + self.cur = 0 + self.vals = [] + inorder(root) def next(self) -> int: - cur = self.stack.pop() - node = cur.right - while node: - self.stack.append(node) - node = node.left - return cur.val + res = self.vals[self.cur] + self.cur += 1 + return res def hasNext(self) -> bool: - return len(self.stack) > 0 + return self.cur < len(self.vals) # Your BSTIterator object will be instantiated and called as such: diff --git a/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.rs b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.rs index 6fb31ff8823d8..fac969c93c207 100644 --- a/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.rs +++ b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.rs @@ -17,7 +17,8 @@ // } // } struct BSTIterator { - stack: Vec>>>, + vals: Vec, + index: usize, } use std::rc::Rc; @@ -27,34 +28,31 @@ use std::cell::RefCell; * If you need a mutable reference, change it to `&mut self` instead. */ impl BSTIterator { - fn dfs( - mut root: Option>>, - stack: &mut Vec>>> - ) { - if root.is_some() { - let left = root.as_mut().unwrap().borrow_mut().left.take(); - stack.push(root); - Self::dfs(left, stack); + fn inorder(root: &Option>>, res: &mut Vec) { + if let Some(node) = root { + let node = node.as_ref().borrow(); + Self::inorder(&node.left, res); + res.push(node.val); + Self::inorder(&node.right, res); } } fn new(root: Option>>) -> Self { - let mut stack = vec![]; - Self::dfs(root, &mut stack); - BSTIterator { stack } + let mut vals = vec![]; + Self::inorder(&root, &mut vals); + BSTIterator { + vals, + index: 0, + } } fn next(&mut self) -> i32 { - let node = self.stack.pop().unwrap().unwrap(); - let mut node = node.borrow_mut(); - if node.right.is_some() { - Self::dfs(node.right.take(), &mut self.stack); - } - node.val + self.index += 1; + self.vals[self.index - 1] } fn has_next(&self) -> bool { - self.stack.len() != 0 + self.index != self.vals.len() } }/** * Your BSTIterator object will be instantiated and called as such: diff --git a/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.ts b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.ts index 93318516340cf..03202ffa799e8 100644 --- a/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.ts +++ b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution.ts @@ -13,34 +13,30 @@ */ class BSTIterator { - private stack: TreeNode[]; + private data: number[]; + private index: number; constructor(root: TreeNode | null) { - this.stack = []; + this.index = 0; + this.data = []; const dfs = (root: TreeNode | null) => { if (root == null) { return; } - this.stack.push(root); - dfs(root.left); + const { val, left, right } = root; + dfs(left); + this.data.push(val); + dfs(right); }; dfs(root); } next(): number { - const { val, right } = this.stack.pop(); - if (right) { - let cur = right; - while (cur != null) { - this.stack.push(cur); - cur = cur.left; - } - } - return val; + return this.data[this.index++]; } hasNext(): boolean { - return this.stack.length !== 0; + return this.index < this.data.length; } } diff --git a/solution/0100-0199/0173.Binary Search Tree Iterator/Solution2.cpp b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution2.cpp new file mode 100644 index 0000000000000..1e9939f2773f1 --- /dev/null +++ b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution2.cpp @@ -0,0 +1,41 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class BSTIterator { +public: + stack stack; + BSTIterator(TreeNode* root) { + for (; root != nullptr; root = root->left) { + stack.push(root); + } + } + + int next() { + TreeNode* cur = stack.top(); + stack.pop(); + TreeNode* node = cur->right; + for (; node != nullptr; node = node->left) { + stack.push(node); + } + return cur->val; + } + + bool hasNext() { + return !stack.empty(); + } +}; + +/** + * Your BSTIterator object will be instantiated and called as such: + * BSTIterator* obj = new BSTIterator(root); + * int param_1 = obj->next(); + * bool param_2 = obj->hasNext(); + */ \ No newline at end of file diff --git a/solution/0100-0199/0173.Binary Search Tree Iterator/Solution2.java b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution2.java new file mode 100644 index 0000000000000..6c3360256ff92 --- /dev/null +++ b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution2.java @@ -0,0 +1,43 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class BSTIterator { + private Deque stack = new LinkedList<>(); + + public BSTIterator(TreeNode root) { + for (; root != null; root = root.left) { + stack.offerLast(root); + } + } + + public int next() { + TreeNode cur = stack.pollLast(); + for (TreeNode node = cur.right; node != null; node = node.left) { + stack.offerLast(node); + } + return cur.val; + } + + public boolean hasNext() { + return !stack.isEmpty(); + } +} + +/** + * Your BSTIterator object will be instantiated and called as such: + * BSTIterator obj = new BSTIterator(root); + * int param_1 = obj.next(); + * boolean param_2 = obj.hasNext(); + */ \ No newline at end of file diff --git a/solution/0100-0199/0173.Binary Search Tree Iterator/Solution2.py b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution2.py new file mode 100644 index 0000000000000..a8b20b7895704 --- /dev/null +++ b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution2.py @@ -0,0 +1,29 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class BSTIterator: + def __init__(self, root: TreeNode): + self.stack = [] + while root: + self.stack.append(root) + root = root.left + + def next(self) -> int: + cur = self.stack.pop() + node = cur.right + while node: + self.stack.append(node) + node = node.left + return cur.val + + def hasNext(self) -> bool: + return len(self.stack) > 0 + + +# Your BSTIterator object will be instantiated and called as such: +# obj = BSTIterator(root) +# param_1 = obj.next() +# param_2 = obj.hasNext() diff --git a/solution/0100-0199/0173.Binary Search Tree Iterator/Solution2.rs b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution2.rs new file mode 100644 index 0000000000000..6fb31ff8823d8 --- /dev/null +++ b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution2.rs @@ -0,0 +1,64 @@ +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +struct BSTIterator { + stack: Vec>>>, +} + +use std::rc::Rc; +use std::cell::RefCell; +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl BSTIterator { + fn dfs( + mut root: Option>>, + stack: &mut Vec>>> + ) { + if root.is_some() { + let left = root.as_mut().unwrap().borrow_mut().left.take(); + stack.push(root); + Self::dfs(left, stack); + } + } + + fn new(root: Option>>) -> Self { + let mut stack = vec![]; + Self::dfs(root, &mut stack); + BSTIterator { stack } + } + + fn next(&mut self) -> i32 { + let node = self.stack.pop().unwrap().unwrap(); + let mut node = node.borrow_mut(); + if node.right.is_some() { + Self::dfs(node.right.take(), &mut self.stack); + } + node.val + } + + fn has_next(&self) -> bool { + self.stack.len() != 0 + } +}/** + * Your BSTIterator object will be instantiated and called as such: + * let obj = BSTIterator::new(root); + * let ret_1: i32 = obj.next(); + * let ret_2: bool = obj.has_next(); + */ diff --git a/solution/0100-0199/0173.Binary Search Tree Iterator/Solution2.ts b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution2.ts new file mode 100644 index 0000000000000..93318516340cf --- /dev/null +++ b/solution/0100-0199/0173.Binary Search Tree Iterator/Solution2.ts @@ -0,0 +1,52 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +class BSTIterator { + private stack: TreeNode[]; + + constructor(root: TreeNode | null) { + this.stack = []; + const dfs = (root: TreeNode | null) => { + if (root == null) { + return; + } + this.stack.push(root); + dfs(root.left); + }; + dfs(root); + } + + next(): number { + const { val, right } = this.stack.pop(); + if (right) { + let cur = right; + while (cur != null) { + this.stack.push(cur); + cur = cur.left; + } + } + return val; + } + + hasNext(): boolean { + return this.stack.length !== 0; + } +} + +/** + * Your BSTIterator object will be instantiated and called as such: + * var obj = new BSTIterator(root) + * var param_1 = obj.next() + * var param_2 = obj.hasNext() + */ diff --git a/solution/0100-0199/0174.Dungeon Game/Solution.cs b/solution/0100-0199/0174.Dungeon Game/Solution.cs index a79a7c0fda46b..386a2a0672649 100644 --- a/solution/0100-0199/0174.Dungeon Game/Solution.cs +++ b/solution/0100-0199/0174.Dungeon Game/Solution.cs @@ -14,4 +14,4 @@ public int CalculateMinimumHP(int[][] dungeon) { } return dp[0][0]; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0176.Second Highest Salary/Solution.sql b/solution/0100-0199/0176.Second Highest Salary/Solution.sql index 544b575360dc6..1ea512900371e 100644 --- a/solution/0100-0199/0176.Second Highest Salary/Solution.sql +++ b/solution/0100-0199/0176.Second Highest Salary/Solution.sql @@ -1,3 +1,8 @@ # Write your MySQL query statement below -WITH T AS (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rk FROM Employee) -SELECT (SELECT DISTINCT salary FROM T WHERE rk = 2) AS SecondHighestSalary; +SELECT + ( + SELECT DISTINCT salary + FROM Employee + ORDER BY salary DESC + LIMIT 1, 1 + ) AS SecondHighestSalary; diff --git a/solution/0100-0199/0176.Second Highest Salary/Solution2.sql b/solution/0100-0199/0176.Second Highest Salary/Solution2.sql new file mode 100644 index 0000000000000..143b62f3ff89e --- /dev/null +++ b/solution/0100-0199/0176.Second Highest Salary/Solution2.sql @@ -0,0 +1,4 @@ +# Write your MySQL query statement below +SELECT MAX(salary) AS SecondHighestSalary +FROM Employee +WHERE salary < (SELECT MAX(salary) FROM Employee); diff --git a/solution/0100-0199/0176.Second Highest Salary/Solution3.sql b/solution/0100-0199/0176.Second Highest Salary/Solution3.sql new file mode 100644 index 0000000000000..544b575360dc6 --- /dev/null +++ b/solution/0100-0199/0176.Second Highest Salary/Solution3.sql @@ -0,0 +1,3 @@ +# Write your MySQL query statement below +WITH T AS (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rk FROM Employee) +SELECT (SELECT DISTINCT salary FROM T WHERE rk = 2) AS SecondHighestSalary; diff --git a/solution/0100-0199/0177.Nth Highest Salary/Solution.sql b/solution/0100-0199/0177.Nth Highest Salary/Solution.sql index 46c94d4bbac81..fe651bc09270d 100644 --- a/solution/0100-0199/0177.Nth Highest Salary/Solution.sql +++ b/solution/0100-0199/0177.Nth Highest Salary/Solution.sql @@ -10,4 +10,4 @@ BEGIN LIMIT 1 OFFSET N ) ); -END \ No newline at end of file +END diff --git a/solution/0100-0199/0178.Rank Scores/Solution2.sql b/solution/0100-0199/0178.Rank Scores/Solution2.sql new file mode 100644 index 0000000000000..c7e14daa244fc --- /dev/null +++ b/solution/0100-0199/0178.Rank Scores/Solution2.sql @@ -0,0 +1,19 @@ +SELECT + Score, + CONVERT(rk, SIGNED) `Rank` +FROM + ( + SELECT + Score, + IF(@latest = Score, @rank, @rank := @rank + 1) rk, + @latest := Score + FROM + Scores, + ( + SELECT + @rank := 0, + @latest := NULL + ) tmp + ORDER BY + Score DESC + ) s; diff --git a/solution/0100-0199/0179.Largest Number/Solution.cs b/solution/0100-0199/0179.Largest Number/Solution.cs index 2b5248ed76e28..8db13b28833ae 100644 --- a/solution/0100-0199/0179.Largest Number/Solution.cs +++ b/solution/0100-0199/0179.Largest Number/Solution.cs @@ -10,7 +10,7 @@ public int Compare(string left, string right) { return Compare(left, right, 0, 0); } - + private int Compare(string left, string right, int lBegin, int rBegin) { var len = Math.Min(left.Length - lBegin, right.Length - rBegin); @@ -21,7 +21,7 @@ private int Compare(string left, string right, int lBegin, int rBegin) return left[lBegin + i] < right[rBegin + i] ? -1 : 1; } } - + if (left.Length - lBegin == right.Length - rBegin) { return 0; @@ -41,7 +41,7 @@ public class Solution { public string LargestNumber(int[] nums) { var sb = new StringBuilder(); var strs = nums.Select(n => n.ToString(CultureInfo.InvariantCulture)).OrderByDescending(s => s, new Comparer()); - + var nonZeroOccurred = false; foreach (var str in strs) { @@ -51,4 +51,4 @@ public string LargestNumber(int[] nums) { } return sb.Length == 0 ? "0" : sb.ToString(); } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0180.Consecutive Numbers/Solution.sql b/solution/0100-0199/0180.Consecutive Numbers/Solution.sql index 3a472cbadaea1..7aad2d6a14e60 100644 --- a/solution/0100-0199/0180.Consecutive Numbers/Solution.sql +++ b/solution/0100-0199/0180.Consecutive Numbers/Solution.sql @@ -1,16 +1,6 @@ # Write your MySQL query statement below -WITH - T AS ( - SELECT - *, - IF(num = (LAG(num) OVER ()), 0, 1) AS st - FROM Logs - ), - S AS ( - SELECT *, SUM(st) OVER (ORDER BY id) AS p - FROM T - ) -SELECT DISTINCT num AS ConsecutiveNums -FROM S -GROUP BY p -HAVING COUNT(1) >= 3; +SELECT DISTINCT l2.num AS ConsecutiveNums +FROM + Logs AS l1 + JOIN Logs AS l2 ON l1.id = l2.id - 1 AND l1.num = l2.num + JOIN Logs AS l3 ON l2.id = l3.id - 1 AND l2.num = l3.num; diff --git a/solution/0100-0199/0180.Consecutive Numbers/Solution2.sql b/solution/0100-0199/0180.Consecutive Numbers/Solution2.sql new file mode 100644 index 0000000000000..8c681ff66e42e --- /dev/null +++ b/solution/0100-0199/0180.Consecutive Numbers/Solution2.sql @@ -0,0 +1,12 @@ +# Write your MySQL query statement below +WITH + T AS ( + SELECT + *, + LAG(num) OVER () AS a, + LEAD(num) OVER () AS b + FROM Logs + ) +SELECT DISTINCT num AS ConsecutiveNums +FROM T +WHERE a = num AND b = num; diff --git a/solution/0100-0199/0180.Consecutive Numbers/Solution3.sql b/solution/0100-0199/0180.Consecutive Numbers/Solution3.sql new file mode 100644 index 0000000000000..3a472cbadaea1 --- /dev/null +++ b/solution/0100-0199/0180.Consecutive Numbers/Solution3.sql @@ -0,0 +1,16 @@ +# Write your MySQL query statement below +WITH + T AS ( + SELECT + *, + IF(num = (LAG(num) OVER ()), 0, 1) AS st + FROM Logs + ), + S AS ( + SELECT *, SUM(st) OVER (ORDER BY id) AS p + FROM T + ) +SELECT DISTINCT num AS ConsecutiveNums +FROM S +GROUP BY p +HAVING COUNT(1) >= 3; diff --git a/solution/0100-0199/0181.Employees Earning More Than Their Managers/Solution2.sql b/solution/0100-0199/0181.Employees Earning More Than Their Managers/Solution2.sql new file mode 100644 index 0000000000000..b285eab38d01a --- /dev/null +++ b/solution/0100-0199/0181.Employees Earning More Than Their Managers/Solution2.sql @@ -0,0 +1,7 @@ +# Write your MySQL query statement below +SELECT + e1.name AS Employee +FROM + Employee AS e1 + JOIN Employee AS e2 ON e1.managerId = e2.id +WHERE e1.salary > e2.salary; diff --git a/solution/0100-0199/0182.Duplicate Emails/Solution2.sql b/solution/0100-0199/0182.Duplicate Emails/Solution2.sql new file mode 100644 index 0000000000000..e2dc32798e6d0 --- /dev/null +++ b/solution/0100-0199/0182.Duplicate Emails/Solution2.sql @@ -0,0 +1,5 @@ +SELECT DISTINCT p1.email +FROM + person AS p1, + person AS p2 +WHERE p1.id != p2.id AND p1.email = p2.email; diff --git a/solution/0100-0199/0183.Customers Who Never Order/Solution2.sql b/solution/0100-0199/0183.Customers Who Never Order/Solution2.sql new file mode 100644 index 0000000000000..3c70366a60f37 --- /dev/null +++ b/solution/0100-0199/0183.Customers Who Never Order/Solution2.sql @@ -0,0 +1,6 @@ +# Write your MySQL query statement below +SELECT name AS Customers +FROM + Customers AS c + LEFT JOIN Orders AS o ON c.id = o.customerId +WHERE o.id IS NULL; diff --git a/solution/0100-0199/0184.Department Highest Salary/Solution2.sql b/solution/0100-0199/0184.Department Highest Salary/Solution2.sql new file mode 100644 index 0000000000000..a37fb894428a8 --- /dev/null +++ b/solution/0100-0199/0184.Department Highest Salary/Solution2.sql @@ -0,0 +1,18 @@ +# Write your MySQL query statement below +WITH + T AS ( + SELECT + d.name AS department, + e.name AS employee, + salary, + RANK() OVER ( + PARTITION BY d.name + ORDER BY salary DESC + ) AS rk + FROM + Employee AS e + JOIN Department AS d ON e.departmentId = d.id + ) +SELECT department, employee, salary +FROM T +WHERE rk = 1; diff --git a/solution/0100-0199/0185.Department Top Three Salaries/Solution.sql b/solution/0100-0199/0185.Department Top Three Salaries/Solution.sql index 688fb4f39f0e0..5fc874fbe2ea3 100644 --- a/solution/0100-0199/0185.Department Top Three Salaries/Solution.sql +++ b/solution/0100-0199/0185.Department Top Three Salaries/Solution.sql @@ -1,16 +1,15 @@ -# Write your MySQL query statement below -WITH - T AS ( - SELECT - *, - DENSE_RANK() OVER ( - PARTITION BY departmentId - ORDER BY salary DESC - ) AS rk - FROM Employee - ) -SELECT d.name AS Department, t.name AS Employee, salary AS Salary +SELECT + Department.NAME AS Department, + Employee.NAME AS Employee, + Salary FROM - T AS t - JOIN Department AS d ON t.departmentId = d.id -WHERE rk <= 3; + Employee, + Department +WHERE + Employee.DepartmentId = Department.Id + AND ( + SELECT + COUNT(DISTINCT e2.Salary) + FROM Employee AS e2 + WHERE e2.Salary > Employee.Salary AND Employee.DepartmentId = e2.DepartmentId + ) < 3; diff --git a/solution/0100-0199/0185.Department Top Three Salaries/Solution2.sql b/solution/0100-0199/0185.Department Top Three Salaries/Solution2.sql new file mode 100644 index 0000000000000..688fb4f39f0e0 --- /dev/null +++ b/solution/0100-0199/0185.Department Top Three Salaries/Solution2.sql @@ -0,0 +1,16 @@ +# Write your MySQL query statement below +WITH + T AS ( + SELECT + *, + DENSE_RANK() OVER ( + PARTITION BY departmentId + ORDER BY salary DESC + ) AS rk + FROM Employee + ) +SELECT d.name AS Department, t.name AS Employee, salary AS Salary +FROM + T AS t + JOIN Department AS d ON t.departmentId = d.id +WHERE rk <= 3; diff --git a/solution/0100-0199/0187.Repeated DNA Sequences/Solution.cs b/solution/0100-0199/0187.Repeated DNA Sequences/Solution.cs index ab624353dc87b..43918d3859ed7 100644 --- a/solution/0100-0199/0187.Repeated DNA Sequences/Solution.cs +++ b/solution/0100-0199/0187.Repeated DNA Sequences/Solution.cs @@ -13,4 +13,4 @@ public IList FindRepeatedDnaSequences(string s) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0187.Repeated DNA Sequences/Solution2.go b/solution/0100-0199/0187.Repeated DNA Sequences/Solution2.go new file mode 100644 index 0000000000000..5e959427d9678 --- /dev/null +++ b/solution/0100-0199/0187.Repeated DNA Sequences/Solution2.go @@ -0,0 +1,18 @@ +func findRepeatedDnaSequences(s string) []string { + hashCode := map[byte]int{'A': 0, 'C': 1, 'G': 2, 'T': 3} + ans, cnt, left, right := []string{}, map[int]int{}, 0, 0 + + sha, multi := 0, int(math.Pow(4, 9)) + for ; right < len(s); right++ { + sha = sha*4 + hashCode[s[right]] + if right-left+1 < 10 { + continue + } + cnt[sha]++ + if cnt[sha] == 2 { + ans = append(ans, s[left:right+1]) + } + sha, left = sha-multi*hashCode[s[left]], left+1 + } + return ans +} \ No newline at end of file diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.cpp b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.cpp index 7b3a8c12af12f..af219b245d51d 100644 --- a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.cpp +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.cpp @@ -2,17 +2,23 @@ class Solution { public: int maxProfit(int k, vector& prices) { int n = prices.size(); - int f[k + 1][2]; - memset(f, 0, sizeof(f)); - for (int j = 1; j <= k; ++j) { - f[j][1] = -prices[0]; - } - for (int i = 1; i < n; ++i) { - for (int j = k; j; --j) { - f[j][0] = max(f[j][1] + prices[i], f[j][0]); - f[j][1] = max(f[j - 1][0] - prices[i], f[j][1]); + int f[n][k + 1][2]; + memset(f, -1, sizeof(f)); + function dfs = [&](int i, int j, int k) -> int { + if (i >= n) { + return 0; } - } - return f[k][0]; + if (f[i][j][k] != -1) { + return f[i][j][k]; + } + int ans = dfs(i + 1, j, k); + if (k) { + ans = max(ans, prices[i] + dfs(i + 1, j, 0)); + } else if (j) { + ans = max(ans, -prices[i] + dfs(i + 1, j - 1, 1)); + } + return f[i][j][k] = ans; + }; + return dfs(0, k, 0); } }; \ No newline at end of file diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.cs b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.cs index 34873399e26d1..3576531b03f9d 100644 --- a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.cs +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.cs @@ -1,16 +1,35 @@ public class Solution { + private int[,,] f; + private int[] prices; + private int n; + public int MaxProfit(int k, int[] prices) { - int n = prices.Length; - int[,] f = new int[k + 1, 2]; - for (int j = 1; j <= k; ++j) { - f[j, 1] = -prices[0]; - } - for (int i = 1; i < n; ++i) { - for (int j = k; j > 0; --j) { - f[j, 0] = Math.Max(f[j, 1] + prices[i], f[j, 0]); - f[j, 1] = Math.Max(f[j - 1, 0] - prices[i], f[j, 1]); + n = prices.Length; + f = new int[n, k + 1, 2]; + this.prices = prices; + for (int i = 0; i < n; ++i) { + for (int j = 0; j <= k; ++j) { + f[i, j, 0] = -1; + f[i, j, 1] = -1; } } - return f[k, 0]; + return dfs(0, k, 0); + } + + private int dfs(int i, int j, int k) { + if (i >= n) { + return 0; + } + if (f[i, j, k] != -1) { + return f[i, j, k]; + } + int ans = dfs(i + 1, j, k); + if (k > 0) { + ans = Math.Max(ans, prices[i] + dfs(i + 1, j, 0)); + } + else if (j > 0) { + ans = Math.Max(ans, -prices[i] + dfs(i + 1, j - 1, 1)); + } + return f[i, j, k] = ans; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.go b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.go index b46b1ee2a1052..379cd329a2c32 100644 --- a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.go +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.go @@ -1,13 +1,28 @@ func maxProfit(k int, prices []int) int { - f := make([][2]int, k+1) - for j := 1; j <= k; j++ { - f[j][1] = -prices[0] + n := len(prices) + f := make([][][2]int, n) + for i := range f { + f[i] = make([][2]int, k+1) + for j := range f[i] { + f[i][j] = [2]int{-1, -1} + } } - for _, x := range prices[1:] { - for j := k; j > 0; j-- { - f[j][0] = max(f[j][1]+x, f[j][0]) - f[j][1] = max(f[j-1][0]-x, f[j][1]) + var dfs func(i, j, k int) int + dfs = func(i, j, k int) int { + if i >= n { + return 0 + } + if f[i][j][k] != -1 { + return f[i][j][k] + } + ans := dfs(i+1, j, k) + if k > 0 { + ans = max(ans, prices[i]+dfs(i+1, j, 0)) + } else if j > 0 { + ans = max(ans, -prices[i]+dfs(i+1, j-1, 1)) } + f[i][j][k] = ans + return ans } - return f[k][0] + return dfs(0, k, 0) } \ No newline at end of file diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.java b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.java index a07ee146c0ff5..83cdfcc2965fc 100644 --- a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.java +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.java @@ -1,16 +1,28 @@ class Solution { + private Integer[][][] f; + private int[] prices; + private int n; + public int maxProfit(int k, int[] prices) { - int n = prices.length; - int[][] f = new int[k + 1][2]; - for (int j = 1; j <= k; ++j) { - f[j][1] = -prices[0]; + n = prices.length; + this.prices = prices; + f = new Integer[n][k + 1][2]; + return dfs(0, k, 0); + } + + private int dfs(int i, int j, int k) { + if (i >= n) { + return 0; + } + if (f[i][j][k] != null) { + return f[i][j][k]; } - for (int i = 1; i < n; ++i) { - for (int j = k; j > 0; --j) { - f[j][0] = Math.max(f[j][1] + prices[i], f[j][0]); - f[j][1] = Math.max(f[j - 1][0] - prices[i], f[j][1]); - } + int ans = dfs(i + 1, j, k); + if (k > 0) { + ans = Math.max(ans, prices[i] + dfs(i + 1, j, 0)); + } else if (j > 0) { + ans = Math.max(ans, -prices[i] + dfs(i + 1, j - 1, 1)); } - return f[k][0]; + return f[i][j][k] = ans; } } \ No newline at end of file diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.py b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.py index 7fccce5b36a0b..71362bcc47987 100644 --- a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.py +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.py @@ -1,10 +1,14 @@ class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: - f = [[0] * 2 for _ in range(k + 1)] - for j in range(1, k + 1): - f[j][1] = -prices[0] - for x in prices[1:]: - for j in range(k, 0, -1): - f[j][0] = max(f[j][1] + x, f[j][0]) - f[j][1] = max(f[j - 1][0] - x, f[j][1]) - return f[k][0] + @cache + def dfs(i: int, j: int, k: int) -> int: + if i >= len(prices): + return 0 + ans = dfs(i + 1, j, k) + if k: + ans = max(ans, prices[i] + dfs(i + 1, j, 0)) + elif j: + ans = max(ans, -prices[i] + dfs(i + 1, j - 1, 1)) + return ans + + return dfs(0, k, 0) diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.ts b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.ts index ebb8dac40abde..92c6c3118c265 100644 --- a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.ts +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution.ts @@ -1,13 +1,22 @@ function maxProfit(k: number, prices: number[]): number { - const f = Array.from({ length: k + 1 }, () => Array.from({ length: 2 }, () => 0)); - for (let j = 1; j <= k; ++j) { - f[j][1] = -prices[0]; - } - for (const x of prices.slice(1)) { - for (let j = k; j; --j) { - f[j][0] = Math.max(f[j][1] + x, f[j][0]); - f[j][1] = Math.max(f[j - 1][0] - x, f[j][1]); + const n = prices.length; + const f = Array.from({ length: n }, () => + Array.from({ length: k + 1 }, () => Array.from({ length: 2 }, () => -1)), + ); + const dfs = (i: number, j: number, k: number): number => { + if (i >= n) { + return 0; } - } - return f[k][0]; + if (f[i][j][k] !== -1) { + return f[i][j][k]; + } + let ans = dfs(i + 1, j, k); + if (k) { + ans = Math.max(ans, prices[i] + dfs(i + 1, j, 0)); + } else if (j) { + ans = Math.max(ans, -prices[i] + dfs(i + 1, j - 1, 1)); + } + return (f[i][j][k] = ans); + }; + return dfs(0, k, 0); } diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.cpp b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.cpp new file mode 100644 index 0000000000000..b16509b1c8676 --- /dev/null +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int maxProfit(int k, vector& prices) { + int n = prices.size(); + int f[n][k + 1][2]; + memset(f, 0, sizeof(f)); + for (int j = 1; j <= k; ++j) { + f[0][j][1] = -prices[0]; + } + for (int i = 1; i < n; ++i) { + for (int j = 1; j <= k; ++j) { + f[i][j][0] = max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]); + f[i][j][1] = max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]); + } + } + return f[n - 1][k][0]; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.cs b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.cs new file mode 100644 index 0000000000000..476dc18a13c36 --- /dev/null +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.cs @@ -0,0 +1,16 @@ +public class Solution { + public int MaxProfit(int k, int[] prices) { + int n = prices.Length; + int[,,] f = new int[n, k + 1, 2]; + for (int j = 1; j <= k; ++j) { + f[0, j, 1] = -prices[0]; + } + for (int i = 1; i < n; ++i) { + for (int j = 1; j <= k; ++j) { + f[i, j, 0] = Math.Max(f[i - 1, j, 1] + prices[i], f[i - 1, j, 0]); + f[i, j, 1] = Math.Max(f[i - 1, j - 1, 0] - prices[i], f[i - 1, j, 1]); + } + } + return f[n - 1, k, 0]; + } +} diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.go b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.go new file mode 100644 index 0000000000000..73df885994c53 --- /dev/null +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.go @@ -0,0 +1,17 @@ +func maxProfit(k int, prices []int) int { + n := len(prices) + f := make([][][2]int, n) + for i := range f { + f[i] = make([][2]int, k+1) + } + for j := 1; j <= k; j++ { + f[0][j][1] = -prices[0] + } + for i := 1; i < n; i++ { + for j := 1; j <= k; j++ { + f[i][j][0] = max(f[i-1][j][1]+prices[i], f[i-1][j][0]) + f[i][j][1] = max(f[i-1][j-1][0]-prices[i], f[i-1][j][1]) + } + } + return f[n-1][k][0] +} \ No newline at end of file diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.java b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.java new file mode 100644 index 0000000000000..108105cffad9f --- /dev/null +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public int maxProfit(int k, int[] prices) { + int n = prices.length; + int[][][] f = new int[n][k + 1][2]; + for (int j = 1; j <= k; ++j) { + f[0][j][1] = -prices[0]; + } + for (int i = 1; i < n; ++i) { + for (int j = 1; j <= k; ++j) { + f[i][j][0] = Math.max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]); + f[i][j][1] = Math.max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]); + } + } + return f[n - 1][k][0]; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.py b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.py new file mode 100644 index 0000000000000..71260358c1804 --- /dev/null +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def maxProfit(self, k: int, prices: List[int]) -> int: + n = len(prices) + f = [[[0] * 2 for _ in range(k + 1)] for _ in range(n)] + for j in range(1, k + 1): + f[0][j][1] = -prices[0] + for i, x in enumerate(prices[1:], 1): + for j in range(1, k + 1): + f[i][j][0] = max(f[i - 1][j][1] + x, f[i - 1][j][0]) + f[i][j][1] = max(f[i - 1][j - 1][0] - x, f[i - 1][j][1]) + return f[n - 1][k][0] diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.ts b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.ts new file mode 100644 index 0000000000000..3d26c62f66269 --- /dev/null +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.ts @@ -0,0 +1,16 @@ +function maxProfit(k: number, prices: number[]): number { + const n = prices.length; + const f = Array.from({ length: n }, () => + Array.from({ length: k + 1 }, () => Array.from({ length: 2 }, () => 0)), + ); + for (let j = 1; j <= k; ++j) { + f[0][j][1] = -prices[0]; + } + for (let i = 1; i < n; ++i) { + for (let j = 1; j <= k; ++j) { + f[i][j][0] = Math.max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]); + f[i][j][1] = Math.max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]); + } + } + return f[n - 1][k][0]; +} diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution3.cpp b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution3.cpp new file mode 100644 index 0000000000000..7b3a8c12af12f --- /dev/null +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution3.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int maxProfit(int k, vector& prices) { + int n = prices.size(); + int f[k + 1][2]; + memset(f, 0, sizeof(f)); + for (int j = 1; j <= k; ++j) { + f[j][1] = -prices[0]; + } + for (int i = 1; i < n; ++i) { + for (int j = k; j; --j) { + f[j][0] = max(f[j][1] + prices[i], f[j][0]); + f[j][1] = max(f[j - 1][0] - prices[i], f[j][1]); + } + } + return f[k][0]; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution3.cs b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution3.cs new file mode 100644 index 0000000000000..c79099b6371cf --- /dev/null +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution3.cs @@ -0,0 +1,16 @@ +public class Solution { + public int MaxProfit(int k, int[] prices) { + int n = prices.Length; + int[,] f = new int[k + 1, 2]; + for (int j = 1; j <= k; ++j) { + f[j, 1] = -prices[0]; + } + for (int i = 1; i < n; ++i) { + for (int j = k; j > 0; --j) { + f[j, 0] = Math.Max(f[j, 1] + prices[i], f[j, 0]); + f[j, 1] = Math.Max(f[j - 1, 0] - prices[i], f[j, 1]); + } + } + return f[k, 0]; + } +} diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution3.go b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution3.go new file mode 100644 index 0000000000000..b46b1ee2a1052 --- /dev/null +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution3.go @@ -0,0 +1,13 @@ +func maxProfit(k int, prices []int) int { + f := make([][2]int, k+1) + for j := 1; j <= k; j++ { + f[j][1] = -prices[0] + } + for _, x := range prices[1:] { + for j := k; j > 0; j-- { + f[j][0] = max(f[j][1]+x, f[j][0]) + f[j][1] = max(f[j-1][0]-x, f[j][1]) + } + } + return f[k][0] +} \ No newline at end of file diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution3.java b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution3.java new file mode 100644 index 0000000000000..a07ee146c0ff5 --- /dev/null +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution3.java @@ -0,0 +1,16 @@ +class Solution { + public int maxProfit(int k, int[] prices) { + int n = prices.length; + int[][] f = new int[k + 1][2]; + for (int j = 1; j <= k; ++j) { + f[j][1] = -prices[0]; + } + for (int i = 1; i < n; ++i) { + for (int j = k; j > 0; --j) { + f[j][0] = Math.max(f[j][1] + prices[i], f[j][0]); + f[j][1] = Math.max(f[j - 1][0] - prices[i], f[j][1]); + } + } + return f[k][0]; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution3.py b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution3.py new file mode 100644 index 0000000000000..7fccce5b36a0b --- /dev/null +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution3.py @@ -0,0 +1,10 @@ +class Solution: + def maxProfit(self, k: int, prices: List[int]) -> int: + f = [[0] * 2 for _ in range(k + 1)] + for j in range(1, k + 1): + f[j][1] = -prices[0] + for x in prices[1:]: + for j in range(k, 0, -1): + f[j][0] = max(f[j][1] + x, f[j][0]) + f[j][1] = max(f[j - 1][0] - x, f[j][1]) + return f[k][0] diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution3.ts b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution3.ts new file mode 100644 index 0000000000000..ebb8dac40abde --- /dev/null +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution3.ts @@ -0,0 +1,13 @@ +function maxProfit(k: number, prices: number[]): number { + const f = Array.from({ length: k + 1 }, () => Array.from({ length: 2 }, () => 0)); + for (let j = 1; j <= k; ++j) { + f[j][1] = -prices[0]; + } + for (const x of prices.slice(1)) { + for (let j = k; j; --j) { + f[j][0] = Math.max(f[j][1] + x, f[j][0]); + f[j][1] = Math.max(f[j - 1][0] - x, f[j][1]); + } + } + return f[k][0]; +} diff --git a/solution/0100-0199/0189.Rotate Array/Solution.cs b/solution/0100-0199/0189.Rotate Array/Solution.cs index 3fd210142d5b5..5239a767a707f 100644 --- a/solution/0100-0199/0189.Rotate Array/Solution.cs +++ b/solution/0100-0199/0189.Rotate Array/Solution.cs @@ -17,4 +17,4 @@ private void reverse(int i, int j) { nums[j] = t; } } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0189.Rotate Array/Solution.py b/solution/0100-0199/0189.Rotate Array/Solution.py index fe175a18c49d3..d43f0faebd211 100644 --- a/solution/0100-0199/0189.Rotate Array/Solution.py +++ b/solution/0100-0199/0189.Rotate Array/Solution.py @@ -1,4 +1,12 @@ -class Solution: - def rotate(self, nums: List[int], k: int) -> None: - k %= len(nums) - nums[:] = nums[-k:] + nums[:-k] +class Solution: + def rotate(self, nums: List[int], k: int) -> None: + def reverse(i: int, j: int): + while i < j: + nums[i], nums[j] = nums[j], nums[i] + i, j = i + 1, j - 1 + + n = len(nums) + k %= n + reverse(0, n - 1) + reverse(0, k - 1) + reverse(k, n - 1) diff --git a/solution/0100-0199/0189.Rotate Array/Solution2.py b/solution/0100-0199/0189.Rotate Array/Solution2.py new file mode 100644 index 0000000000000..2ca1930ff6c1f --- /dev/null +++ b/solution/0100-0199/0189.Rotate Array/Solution2.py @@ -0,0 +1,4 @@ +class Solution: + def rotate(self, nums: List[int], k: int) -> None: + k %= len(nums) + nums[:] = nums[-k:] + nums[:-k] diff --git a/solution/0100-0199/0190.Reverse Bits/Solution.cpp b/solution/0100-0199/0190.Reverse Bits/Solution.cpp index e8f82fc6b4773..8447fe17f9d6e 100644 --- a/solution/0100-0199/0190.Reverse Bits/Solution.cpp +++ b/solution/0100-0199/0190.Reverse Bits/Solution.cpp @@ -1,4 +1,4 @@ -class Solution { +class Solution { public: uint32_t reverseBits(uint32_t n) { uint32_t res = 0; diff --git a/solution/0100-0199/0190.Reverse Bits/Solution.js b/solution/0100-0199/0190.Reverse Bits/Solution.js index ebacb7472f556..db72df44be60d 100644 --- a/solution/0100-0199/0190.Reverse Bits/Solution.js +++ b/solution/0100-0199/0190.Reverse Bits/Solution.js @@ -8,5 +8,6 @@ var reverseBits = function (n) { res |= (n & 1) << (31 - i); n >>>= 1; } + // 无符号右移 return res >>> 0; }; diff --git a/solution/0100-0199/0191.Number of 1 Bits/Solution.c b/solution/0100-0199/0191.Number of 1 Bits/Solution.c index a8e5df62a9e2e..4df8e7a375944 100644 --- a/solution/0100-0199/0191.Number of 1 Bits/Solution.c +++ b/solution/0100-0199/0191.Number of 1 Bits/Solution.c @@ -5,4 +5,4 @@ int hammingWeight(uint32_t n) { ans++; } return ans; -} +} \ No newline at end of file diff --git a/solution/0100-0199/0191.Number of 1 Bits/Solution.ts b/solution/0100-0199/0191.Number of 1 Bits/Solution.ts new file mode 100644 index 0000000000000..6085d8ff0332e --- /dev/null +++ b/solution/0100-0199/0191.Number of 1 Bits/Solution.ts @@ -0,0 +1,8 @@ +function hammingWeight(n: number): number { + let ans: number = 0; + while (n !== 0) { + ans++; + n &= n - 1; + } + return ans; +} diff --git a/solution/0100-0199/0191.Number of 1 Bits/Solution2.cpp b/solution/0100-0199/0191.Number of 1 Bits/Solution2.cpp new file mode 100644 index 0000000000000..d8687bb91432b --- /dev/null +++ b/solution/0100-0199/0191.Number of 1 Bits/Solution2.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int hammingWeight(uint32_t n) { + int ans = 0; + while (n) { + n -= (n & -n); + ++ans; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0191.Number of 1 Bits/Solution2.go b/solution/0100-0199/0191.Number of 1 Bits/Solution2.go new file mode 100644 index 0000000000000..065062979d51d --- /dev/null +++ b/solution/0100-0199/0191.Number of 1 Bits/Solution2.go @@ -0,0 +1,8 @@ +func hammingWeight(num uint32) int { + ans := 0 + for num != 0 { + num -= (num & -num) + ans++ + } + return ans +} \ No newline at end of file diff --git a/solution/0100-0199/0191.Number of 1 Bits/Solution2.java b/solution/0100-0199/0191.Number of 1 Bits/Solution2.java new file mode 100644 index 0000000000000..8229c54b48cb1 --- /dev/null +++ b/solution/0100-0199/0191.Number of 1 Bits/Solution2.java @@ -0,0 +1,11 @@ +public class Solution { + // you need to treat n as an unsigned value + public int hammingWeight(int n) { + int ans = 0; + while (n != 0) { + n -= (n & -n); + ++ans; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0191.Number of 1 Bits/Solution2.py b/solution/0100-0199/0191.Number of 1 Bits/Solution2.py new file mode 100644 index 0000000000000..a4aba7c40b124 --- /dev/null +++ b/solution/0100-0199/0191.Number of 1 Bits/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def hammingWeight(self, n: int) -> int: + ans = 0 + while n: + n -= n & -n + ans += 1 + return ans diff --git a/solution/0100-0199/0191.Number of 1 Bits/Solution2.rs b/solution/0100-0199/0191.Number of 1 Bits/Solution2.rs new file mode 100644 index 0000000000000..efd75dca3810c --- /dev/null +++ b/solution/0100-0199/0191.Number of 1 Bits/Solution2.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn hammingWeight(mut n: u32) -> i32 { + let mut res = 0; + while n != 0 { + n &= n - 1; + res += 1; + } + res + } +} diff --git a/solution/0100-0199/0196.Delete Duplicate Emails/Solution2.sql b/solution/0100-0199/0196.Delete Duplicate Emails/Solution2.sql new file mode 100644 index 0000000000000..73470c5b60c89 --- /dev/null +++ b/solution/0100-0199/0196.Delete Duplicate Emails/Solution2.sql @@ -0,0 +1,17 @@ +# Write your MySQL query statement below +DELETE FROM Person +WHERE + id NOT IN ( + SELECT id + FROM + ( + SELECT + id, + ROW_NUMBER() OVER ( + PARTITION BY email + ORDER BY id + ) AS rk + FROM Person + ) AS p + WHERE rk = 1 + ); diff --git a/solution/0100-0199/0196.Delete Duplicate Emails/Solution3.sql b/solution/0100-0199/0196.Delete Duplicate Emails/Solution3.sql new file mode 100644 index 0000000000000..55f0e9ca8607e --- /dev/null +++ b/solution/0100-0199/0196.Delete Duplicate Emails/Solution3.sql @@ -0,0 +1,5 @@ +DELETE p2 +FROM + person AS p1 + JOIN person AS p2 ON p1.email = p2.email +WHERE p1.id < p2.id; diff --git a/solution/0100-0199/0197.Rising Temperature/Solution.sql b/solution/0100-0199/0197.Rising Temperature/Solution.sql index ee7f7f22250ed..e8ecebaee69ef 100644 --- a/solution/0100-0199/0197.Rising Temperature/Solution.sql +++ b/solution/0100-0199/0197.Rising Temperature/Solution.sql @@ -3,4 +3,4 @@ SELECT w1.id FROM Weather AS w1 JOIN Weather AS w2 - ON SUBDATE(w1.recordDate, 1) = w2.recordDate AND w1.temperature > w2.temperature; + ON DATEDIFF(w1.recordDate, w2.recordDate) = 1 AND w1.temperature > w2.temperature; diff --git a/solution/0100-0199/0197.Rising Temperature/Solution2.sql b/solution/0100-0199/0197.Rising Temperature/Solution2.sql new file mode 100644 index 0000000000000..ee7f7f22250ed --- /dev/null +++ b/solution/0100-0199/0197.Rising Temperature/Solution2.sql @@ -0,0 +1,6 @@ +# Write your MySQL query statement below +SELECT w1.id +FROM + Weather AS w1 + JOIN Weather AS w2 + ON SUBDATE(w1.recordDate, 1) = w2.recordDate AND w1.temperature > w2.temperature; diff --git a/solution/0100-0199/0198.House Robber/Solution.cpp b/solution/0100-0199/0198.House Robber/Solution.cpp index e76e67863d859..2ecfee368e8fa 100644 --- a/solution/0100-0199/0198.House Robber/Solution.cpp +++ b/solution/0100-0199/0198.House Robber/Solution.cpp @@ -1,12 +1,13 @@ -class Solution { -public: - int rob(vector& nums) { - int f = 0, g = 0; - for (int& x : nums) { - int ff = max(f, g); - g = f + x; - f = ff; - } - return max(f, g); - } +class Solution { +public: + int rob(vector& nums) { + int n = nums.size(); + int f[n + 1]; + memset(f, 0, sizeof(f)); + f[1] = nums[0]; + for (int i = 2; i <= n; ++i) { + f[i] = max(f[i - 1], f[i - 2] + nums[i - 1]); + } + return f[n]; + } }; \ No newline at end of file diff --git a/solution/0100-0199/0198.House Robber/Solution.go b/solution/0100-0199/0198.House Robber/Solution.go index 35cc30969e50b..52f08ae2d5f14 100644 --- a/solution/0100-0199/0198.House Robber/Solution.go +++ b/solution/0100-0199/0198.House Robber/Solution.go @@ -1,7 +1,9 @@ func rob(nums []int) int { - f, g := 0, 0 - for _, x := range nums { - f, g = max(f, g), f+x + n := len(nums) + f := make([]int, n+1) + f[1] = nums[0] + for i := 2; i <= n; i++ { + f[i] = max(f[i-1], f[i-2]+nums[i-1]) } - return max(f, g) + return f[n] } \ No newline at end of file diff --git a/solution/0100-0199/0198.House Robber/Solution.java b/solution/0100-0199/0198.House Robber/Solution.java index b5ae78ad1e391..e493219c3617c 100644 --- a/solution/0100-0199/0198.House Robber/Solution.java +++ b/solution/0100-0199/0198.House Robber/Solution.java @@ -1,11 +1,11 @@ -class Solution { - public int rob(int[] nums) { - int f = 0, g = 0; - for (int x : nums) { - int ff = Math.max(f, g); - g = f + x; - f = ff; - } - return Math.max(f, g); - } +class Solution { + public int rob(int[] nums) { + int n = nums.length; + int[] f = new int[n + 1]; + f[1] = nums[0]; + for (int i = 2; i <= n; ++i) { + f[i] = Math.max(f[i - 1], f[i - 2] + nums[i - 1]); + } + return f[n]; + } } \ No newline at end of file diff --git a/solution/0100-0199/0198.House Robber/Solution.py b/solution/0100-0199/0198.House Robber/Solution.py index 6bba868883e66..c270a36802c3a 100644 --- a/solution/0100-0199/0198.House Robber/Solution.py +++ b/solution/0100-0199/0198.House Robber/Solution.py @@ -1,6 +1,8 @@ -class Solution: - def rob(self, nums: List[int]) -> int: - f = g = 0 - for x in nums: - f, g = max(f, g), f + x - return max(f, g) +class Solution: + def rob(self, nums: List[int]) -> int: + n = len(nums) + f = [0] * (n + 1) + f[1] = nums[0] + for i in range(2, n + 1): + f[i] = max(f[i - 1], f[i - 2] + nums[i - 1]) + return f[n] diff --git a/solution/0100-0199/0198.House Robber/Solution.ts b/solution/0100-0199/0198.House Robber/Solution.ts index 37f93d27df129..f603cd3876e25 100644 --- a/solution/0100-0199/0198.House Robber/Solution.ts +++ b/solution/0100-0199/0198.House Robber/Solution.ts @@ -1,7 +1,9 @@ function rob(nums: number[]): number { - let [f, g] = [0, 0]; - for (const x of nums) { - [f, g] = [Math.max(f, g), f + x]; + const n = nums.length; + const f: number[] = Array(n + 1).fill(0); + f[1] = nums[0]; + for (let i = 2; i <= n; ++i) { + f[i] = Math.max(f[i - 1], f[i - 2] + nums[i - 1]); } - return Math.max(f, g); + return f[n]; } diff --git a/solution/0100-0199/0198.House Robber/Solution2.cpp b/solution/0100-0199/0198.House Robber/Solution2.cpp new file mode 100644 index 0000000000000..10928ea139406 --- /dev/null +++ b/solution/0100-0199/0198.House Robber/Solution2.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int rob(vector& nums) { + int f = 0, g = 0; + for (int& x : nums) { + int ff = max(f, g); + g = f + x; + f = ff; + } + return max(f, g); + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0198.House Robber/Solution2.go b/solution/0100-0199/0198.House Robber/Solution2.go new file mode 100644 index 0000000000000..35cc30969e50b --- /dev/null +++ b/solution/0100-0199/0198.House Robber/Solution2.go @@ -0,0 +1,7 @@ +func rob(nums []int) int { + f, g := 0, 0 + for _, x := range nums { + f, g = max(f, g), f+x + } + return max(f, g) +} \ No newline at end of file diff --git a/solution/0100-0199/0198.House Robber/Solution2.java b/solution/0100-0199/0198.House Robber/Solution2.java new file mode 100644 index 0000000000000..d6491685a06e3 --- /dev/null +++ b/solution/0100-0199/0198.House Robber/Solution2.java @@ -0,0 +1,11 @@ +class Solution { + public int rob(int[] nums) { + int f = 0, g = 0; + for (int x : nums) { + int ff = Math.max(f, g); + g = f + x; + f = ff; + } + return Math.max(f, g); + } +} \ No newline at end of file diff --git a/solution/0100-0199/0198.House Robber/Solution2.py b/solution/0100-0199/0198.House Robber/Solution2.py new file mode 100644 index 0000000000000..b1afd4af8730f --- /dev/null +++ b/solution/0100-0199/0198.House Robber/Solution2.py @@ -0,0 +1,6 @@ +class Solution: + def rob(self, nums: List[int]) -> int: + f = g = 0 + for x in nums: + f, g = max(f, g), f + x + return max(f, g) diff --git a/solution/0100-0199/0198.House Robber/Solution2.ts b/solution/0100-0199/0198.House Robber/Solution2.ts new file mode 100644 index 0000000000000..37f93d27df129 --- /dev/null +++ b/solution/0100-0199/0198.House Robber/Solution2.ts @@ -0,0 +1,7 @@ +function rob(nums: number[]): number { + let [f, g] = [0, 0]; + for (const x of nums) { + [f, g] = [Math.max(f, g), f + x]; + } + return Math.max(f, g); +} diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.cpp b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.cpp new file mode 100644 index 0000000000000..67808eccccedc --- /dev/null +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.cpp @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector rightSideView(TreeNode* root) { + vector ans; + function dfs = [&](TreeNode* node, int depth) { + if (!node) { + return; + } + if (depth == ans.size()) { + ans.emplace_back(node->val); + } + dfs(node->right, depth + 1); + dfs(node->left, depth + 1); + }; + dfs(root, 0); + return ans; + } +}; \ No newline at end of file diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.go b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.go new file mode 100644 index 0000000000000..26827861a38d1 --- /dev/null +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.go @@ -0,0 +1,23 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func rightSideView(root *TreeNode) (ans []int) { + var dfs func(*TreeNode, int) + dfs = func(node *TreeNode, depth int) { + if node == nil { + return + } + if depth == len(ans) { + ans = append(ans, node.Val) + } + dfs(node.Right, depth+1) + dfs(node.Left, depth+1) + } + dfs(root, 0) + return +} \ No newline at end of file diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.java b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.java new file mode 100644 index 0000000000000..49e597711858a --- /dev/null +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.java @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private List ans = new ArrayList<>(); + + public List rightSideView(TreeNode root) { + dfs(root, 0); + return ans; + } + + private void dfs(TreeNode node, int depth) { + if (node == null) { + return; + } + if (depth == ans.size()) { + ans.add(node.val); + } + dfs(node.right, depth + 1); + dfs(node.left, depth + 1); + } +} \ No newline at end of file diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.py b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.py new file mode 100644 index 0000000000000..8680b6976811c --- /dev/null +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.py @@ -0,0 +1,19 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def rightSideView(self, root: Optional[TreeNode]) -> List[int]: + def dfs(node, depth): + if node is None: + return + if depth == len(ans): + ans.append(node.val) + dfs(node.right, depth + 1) + dfs(node.left, depth + 1) + + ans = [] + dfs(root, 0) + return ans diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.ts b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.ts new file mode 100644 index 0000000000000..a548d28b05389 --- /dev/null +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.ts @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function rightSideView(root: TreeNode | null): number[] { + const ans = []; + const dfs = (node: TreeNode | null, depth: number) => { + if (!node) { + return; + } + if (depth == ans.length) { + ans.push(node.val); + } + dfs(node.right, depth + 1); + dfs(node.left, depth + 1); + }; + dfs(root, 0); + return ans; +} diff --git a/solution/0200-0299/0200.Number of Islands/Solution2.cpp b/solution/0200-0299/0200.Number of Islands/Solution2.cpp new file mode 100644 index 0000000000000..3b1157ec545e9 --- /dev/null +++ b/solution/0200-0299/0200.Number of Islands/Solution2.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + int numIslands(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + int ans = 0; + int dirs[5] = {-1, 0, 1, 0, -1}; + function bfs = [&](int i, int j) { + grid[i][j] = '0'; + queue> q; + q.push({i, j}); + vector dirs = {-1, 0, 1, 0, -1}; + while (!q.empty()) { + auto [a, b] = q.front(); + q.pop(); + for (int k = 0; k < 4; ++k) { + int x = a + dirs[k]; + int y = b + dirs[k + 1]; + if (x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size() && grid[x][y] == '1') { + q.push({x, y}); + grid[x][y] = '0'; + } + } + } + }; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == '1') { + bfs(i, j); + ++ans; + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0200.Number of Islands/Solution2.go b/solution/0200-0299/0200.Number of Islands/Solution2.go new file mode 100644 index 0000000000000..1a0a68bf0aa7f --- /dev/null +++ b/solution/0200-0299/0200.Number of Islands/Solution2.go @@ -0,0 +1,29 @@ +func numIslands(grid [][]byte) int { + m, n := len(grid), len(grid[0]) + bfs := func(i, j int) { + grid[i][j] = '0' + q := [][]int{[]int{i, j}} + dirs := []int{-1, 0, 1, 0, -1} + for len(q) > 0 { + p := q[0] + q = q[1:] + for k := 0; k < 4; k++ { + x, y := p[0]+dirs[k], p[1]+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1' { + q = append(q, []int{x, y}) + grid[x][y] = '0' + } + } + } + } + ans := 0 + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if grid[i][j] == '1' { + bfs(i, j) + ans++ + } + } + } + return ans +} \ No newline at end of file diff --git a/solution/0200-0299/0200.Number of Islands/Solution2.java b/solution/0200-0299/0200.Number of Islands/Solution2.java new file mode 100644 index 0000000000000..b00ac88a276df --- /dev/null +++ b/solution/0200-0299/0200.Number of Islands/Solution2.java @@ -0,0 +1,39 @@ +class Solution { + private char[][] grid; + private int m; + private int n; + + public int numIslands(char[][] grid) { + m = grid.length; + n = grid[0].length; + this.grid = grid; + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == '1') { + bfs(i, j); + ++ans; + } + } + } + return ans; + } + + private void bfs(int i, int j) { + grid[i][j] = '0'; + Deque q = new ArrayDeque<>(); + q.offer(new int[] {i, j}); + int[] dirs = {-1, 0, 1, 0, -1}; + while (!q.isEmpty()) { + int[] p = q.poll(); + for (int k = 0; k < 4; ++k) { + int x = p[0] + dirs[k]; + int y = p[1] + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') { + q.offer(new int[] {x, y}); + grid[x][y] = '0'; + } + } + } + } +} \ No newline at end of file diff --git a/solution/0200-0299/0200.Number of Islands/Solution2.py b/solution/0200-0299/0200.Number of Islands/Solution2.py new file mode 100644 index 0000000000000..b3f7ac3f8ec3d --- /dev/null +++ b/solution/0200-0299/0200.Number of Islands/Solution2.py @@ -0,0 +1,22 @@ +class Solution: + def numIslands(self, grid: List[List[str]]) -> int: + def bfs(i, j): + grid[i][j] = '0' + q = deque([(i, j)]) + while q: + i, j = q.popleft() + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n and grid[x][y] == '1': + q.append((x, y)) + grid[x][y] = 0 + + ans = 0 + dirs = (-1, 0, 1, 0, -1) + m, n = len(grid), len(grid[0]) + for i in range(m): + for j in range(n): + if grid[i][j] == '1': + bfs(i, j) + ans += 1 + return ans diff --git a/solution/0200-0299/0200.Number of Islands/Solution2.rs b/solution/0200-0299/0200.Number of Islands/Solution2.rs new file mode 100644 index 0000000000000..b85564f64b07b --- /dev/null +++ b/solution/0200-0299/0200.Number of Islands/Solution2.rs @@ -0,0 +1,41 @@ +use std::collections::VecDeque; + +const DIRS: [i32; 5] = [-1, 0, 1, 0, -1]; + +impl Solution { + pub fn num_islands(grid: Vec>) -> i32 { + fn bfs(grid: &mut Vec>, i: usize, j: usize) { + grid[i][j] = '0'; + let mut queue = VecDeque::from([(i, j)]); + while !queue.is_empty() { + let (i, j) = queue.pop_front().unwrap(); + for k in 0..4 { + let x = (i as i32) + DIRS[k]; + let y = (j as i32) + DIRS[k + 1]; + if + x >= 0 && + (x as usize) < grid.len() && + y >= 0 && + (y as usize) < grid[0].len() && + grid[x as usize][y as usize] == '1' + { + grid[x as usize][y as usize] = '0'; + queue.push_back((x as usize, y as usize)); + } + } + } + } + + let mut grid = grid; + let mut ans = 0; + for i in 0..grid.len() { + for j in 0..grid[0].len() { + if grid[i][j] == '1' { + bfs(&mut grid, i, j); + ans += 1; + } + } + } + ans + } +} diff --git a/solution/0200-0299/0200.Number of Islands/Solution2.ts b/solution/0200-0299/0200.Number of Islands/Solution2.ts new file mode 100644 index 0000000000000..03a5d20cc071b --- /dev/null +++ b/solution/0200-0299/0200.Number of Islands/Solution2.ts @@ -0,0 +1,30 @@ +function numIslands(grid: string[][]): number { + const m = grid.length; + const n = grid[0].length; + let ans = 0; + function bfs(i, j) { + grid[i][j] = '0'; + let q = [[i, j]]; + const dirs = [-1, 0, 1, 0, -1]; + while (q.length) { + [i, j] = q.shift(); + for (let k = 0; k < 4; ++k) { + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') { + q.push([x, y]); + grid[x][y] = '0'; + } + } + } + } + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (grid[i][j] == '1') { + bfs(i, j); + ++ans; + } + } + } + return ans; +} diff --git a/solution/0200-0299/0200.Number of Islands/Solution3.cpp b/solution/0200-0299/0200.Number of Islands/Solution3.cpp new file mode 100644 index 0000000000000..9b2a661ae9beb --- /dev/null +++ b/solution/0200-0299/0200.Number of Islands/Solution3.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + int numIslands(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + vector p(m * n); + iota(p.begin(), p.end(), 0); + function find = [&](int x) -> int { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + }; + int dirs[3] = {1, 0, 1}; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == '1') { + for (int k = 0; k < 2; ++k) { + int x = i + dirs[k]; + int y = j + dirs[k + 1]; + if (x < m && y < n && grid[x][y] == '1') { + p[find(x * n + y)] = find(i * n + j); + } + } + } + } + } + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans += grid[i][j] == '1' && i * n + j == find(i * n + j); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0200.Number of Islands/Solution3.go b/solution/0200-0299/0200.Number of Islands/Solution3.go new file mode 100644 index 0000000000000..17195f2630243 --- /dev/null +++ b/solution/0200-0299/0200.Number of Islands/Solution3.go @@ -0,0 +1,36 @@ +func numIslands(grid [][]byte) int { + m, n := len(grid), len(grid[0]) + p := make([]int, m*n) + for i := range p { + p[i] = i + } + var find func(x int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + dirs := []int{1, 0, 1} + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if grid[i][j] == '1' { + for k := 0; k < 2; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x < m && y < n && grid[x][y] == '1' { + p[find(x*n+y)] = find(i*n + j) + } + } + } + } + } + ans := 0 + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if grid[i][j] == '1' && i*n+j == find(i*n+j) { + ans++ + } + } + } + return ans +} \ No newline at end of file diff --git a/solution/0200-0299/0200.Number of Islands/Solution3.java b/solution/0200-0299/0200.Number of Islands/Solution3.java new file mode 100644 index 0000000000000..d80cbb496c745 --- /dev/null +++ b/solution/0200-0299/0200.Number of Islands/Solution3.java @@ -0,0 +1,42 @@ +class Solution { + private int[] p; + + public int numIslands(char[][] grid) { + int m = grid.length; + int n = grid[0].length; + p = new int[m * n]; + for (int i = 0; i < p.length; ++i) { + p[i] = i; + } + int[] dirs = {1, 0, 1}; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == '1') { + for (int k = 0; k < 2; ++k) { + int x = i + dirs[k]; + int y = j + dirs[k + 1]; + if (x < m && y < n && grid[x][y] == '1') { + p[find(x * n + y)] = find(i * n + j); + } + } + } + } + } + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == '1' && i * n + j == find(i * n + j)) { + ++ans; + } + } + } + return ans; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0200.Number of Islands/Solution3.py b/solution/0200-0299/0200.Number of Islands/Solution3.py new file mode 100644 index 0000000000000..114a27ad5eeab --- /dev/null +++ b/solution/0200-0299/0200.Number of Islands/Solution3.py @@ -0,0 +1,22 @@ +class Solution: + def numIslands(self, grid: List[List[str]]) -> int: + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + dirs = (0, 1, 0) + m, n = len(grid), len(grid[0]) + p = list(range(m * n)) + for i in range(m): + for j in range(n): + if grid[i][j] == '1': + for a, b in pairwise(dirs): + x, y = i + a, j + b + if x < m and y < n and grid[x][y] == '1': + p[find(i * n + j)] = find(x * n + y) + return sum( + grid[i][j] == '1' and i * n + j == find(i * n + j) + for i in range(m) + for j in range(n) + ) diff --git a/solution/0200-0299/0200.Number of Islands/Solution3.rs b/solution/0200-0299/0200.Number of Islands/Solution3.rs new file mode 100644 index 0000000000000..52816e6b285ec --- /dev/null +++ b/solution/0200-0299/0200.Number of Islands/Solution3.rs @@ -0,0 +1,42 @@ +const DIRS: [usize; 3] = [1, 0, 1]; + +impl Solution { + pub fn num_islands(grid: Vec>) -> i32 { + let m = grid.len(); + let n = grid[0].len(); + let mut p: Vec = (0..(m * n) as i32).collect(); + + fn find(p: &mut Vec, x: usize) -> i32 { + if p[x] != (x as i32) { + p[x] = find(p, p[x] as usize); + } + p[x] + } + + for i in 0..m { + for j in 0..n { + if grid[i][j] == '1' { + for k in 0..2 { + let x = i + DIRS[k]; + let y = j + DIRS[k + 1]; + if x < m && y < n && grid[x][y] == '1' { + let f1 = find(&mut p, x * n + y); + let f2 = find(&mut p, i * n + j); + p[f1 as usize] = f2; + } + } + } + } + } + + let mut ans = 0; + for i in 0..m { + for j in 0..n { + if grid[i][j] == '1' && p[i * n + j] == ((i * n + j) as i32) { + ans += 1; + } + } + } + ans + } +} diff --git a/solution/0200-0299/0200.Number of Islands/Solution3.ts b/solution/0200-0299/0200.Number of Islands/Solution3.ts new file mode 100644 index 0000000000000..4bd106f2a028f --- /dev/null +++ b/solution/0200-0299/0200.Number of Islands/Solution3.ts @@ -0,0 +1,37 @@ +function numIslands(grid: string[][]): number { + const m = grid.length; + const n = grid[0].length; + let p = []; + for (let i = 0; i < m * n; ++i) { + p.push(i); + } + function find(x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + const dirs = [1, 0, 1]; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (grid[i][j] == '1') { + for (let k = 0; k < 2; ++k) { + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (x < m && y < n && grid[x][y] == '1') { + p[find(i * n + j)] = find(x * n + y); + } + } + } + } + } + let ans = 0; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (grid[i][j] == '1' && i * n + j == find(i * n + j)) { + ++ans; + } + } + } + return ans; +} diff --git a/solution/0200-0299/0201.Bitwise AND of Numbers Range/Solution.cs b/solution/0200-0299/0201.Bitwise AND of Numbers Range/Solution.cs index eedea5667914f..52cba8994c634 100644 --- a/solution/0200-0299/0201.Bitwise AND of Numbers Range/Solution.cs +++ b/solution/0200-0299/0201.Bitwise AND of Numbers Range/Solution.cs @@ -5,4 +5,4 @@ public int RangeBitwiseAnd(int left, int right) { } return right; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0202.Happy Number/Solution.c b/solution/0200-0299/0202.Happy Number/Solution.c index 84f1716bfc81a..8646c14ac461f 100644 --- a/solution/0200-0299/0202.Happy Number/Solution.c +++ b/solution/0200-0299/0202.Happy Number/Solution.c @@ -15,4 +15,4 @@ bool isHappy(int n) { fast = getNext(getNext(fast)); } return fast == 1; -} +} \ No newline at end of file diff --git a/solution/0200-0299/0202.Happy Number/Solution.cpp b/solution/0200-0299/0202.Happy Number/Solution.cpp index eba21d7574cdb..0513e38b631cf 100644 --- a/solution/0200-0299/0202.Happy Number/Solution.cpp +++ b/solution/0200-0299/0202.Happy Number/Solution.cpp @@ -1,18 +1,15 @@ class Solution { public: bool isHappy(int n) { - auto next = [](int x) { - int y = 0; - for (; x; x /= 10) { - y += pow(x % 10, 2); + unordered_set vis; + while (n != 1 && !vis.count(n)) { + vis.insert(n); + int x = 0; + for (; n; n /= 10) { + x += (n % 10) * (n % 10); } - return y; - }; - int slow = n, fast = next(n); - while (slow != fast) { - slow = next(slow); - fast = next(next(fast)); + n = x; } - return slow == 1; + return n == 1; } }; \ No newline at end of file diff --git a/solution/0200-0299/0202.Happy Number/Solution.go b/solution/0200-0299/0202.Happy Number/Solution.go index 2be0192a9e994..0ed545f959eea 100644 --- a/solution/0200-0299/0202.Happy Number/Solution.go +++ b/solution/0200-0299/0202.Happy Number/Solution.go @@ -1,14 +1,12 @@ func isHappy(n int) bool { - next := func(x int) (y int) { - for ; x > 0; x /= 10 { - y += (x % 10) * (x % 10) + vis := map[int]bool{} + for n != 1 && !vis[n] { + vis[n] = true + x := 0 + for ; n > 0; n /= 10 { + x += (n % 10) * (n % 10) } - return + n = x } - slow, fast := n, next(n) - for slow != fast { - slow = next(slow) - fast = next(next(fast)) - } - return slow == 1 + return n == 1 } \ No newline at end of file diff --git a/solution/0200-0299/0202.Happy Number/Solution.java b/solution/0200-0299/0202.Happy Number/Solution.java index 1688f2aa8897b..c645c59833cea 100644 --- a/solution/0200-0299/0202.Happy Number/Solution.java +++ b/solution/0200-0299/0202.Happy Number/Solution.java @@ -1,18 +1,15 @@ class Solution { public boolean isHappy(int n) { - int slow = n, fast = next(n); - while (slow != fast) { - slow = next(slow); - fast = next(next(fast)); + Set vis = new HashSet<>(); + while (n != 1 && !vis.contains(n)) { + vis.add(n); + int x = 0; + while (n != 0) { + x += (n % 10) * (n % 10); + n /= 10; + } + n = x; } - return slow == 1; - } - - private int next(int x) { - int y = 0; - for (; x > 0; x /= 10) { - y += (x % 10) * (x % 10); - } - return y; + return n == 1; } } \ No newline at end of file diff --git a/solution/0200-0299/0202.Happy Number/Solution.py b/solution/0200-0299/0202.Happy Number/Solution.py index 4899e0bc61dfb..5ee30d5fe9708 100644 --- a/solution/0200-0299/0202.Happy Number/Solution.py +++ b/solution/0200-0299/0202.Happy Number/Solution.py @@ -1,13 +1,11 @@ class Solution: def isHappy(self, n: int) -> bool: - def next(x): - y = 0 - while x: - x, v = divmod(x, 10) - y += v * v - return y - - slow, fast = n, next(n) - while slow != fast: - slow, fast = next(slow), next(next(fast)) - return slow == 1 + vis = set() + while n != 1 and n not in vis: + vis.add(n) + x = 0 + while n: + n, v = divmod(n, 10) + x += v * v + n = x + return n == 1 diff --git a/solution/0200-0299/0202.Happy Number/Solution.rs b/solution/0200-0299/0202.Happy Number/Solution.rs index 5518dcfba1602..3f0e95fceea8d 100644 --- a/solution/0200-0299/0202.Happy Number/Solution.rs +++ b/solution/0200-0299/0202.Happy Number/Solution.rs @@ -1,19 +1,24 @@ +use std::collections::HashSet; impl Solution { - pub fn is_happy(n: i32) -> bool { - let get_next = |mut n: i32| { - let mut res = 0; - while n != 0 { - res += (n % 10).pow(2); - n /= 10; + fn get_next(mut n: i32) -> i32 { + let mut res = 0; + while n != 0 { + res += (n % 10).pow(2); + n /= 10; + } + res + } + + pub fn is_happy(mut n: i32) -> bool { + let mut set = HashSet::new(); + while n != 1 { + let next = Self::get_next(n); + if set.contains(&next) { + return false; } - res - }; - let mut slow = n; - let mut fast = get_next(n); - while slow != fast { - slow = get_next(slow); - fast = get_next(get_next(fast)); + set.insert(next); + n = next; } - slow == 1 + true } } diff --git a/solution/0200-0299/0202.Happy Number/Solution.ts b/solution/0200-0299/0202.Happy Number/Solution.ts index f2791ee88e5ce..a565b2ecf5c12 100644 --- a/solution/0200-0299/0202.Happy Number/Solution.ts +++ b/solution/0200-0299/0202.Happy Number/Solution.ts @@ -7,12 +7,14 @@ function isHappy(n: number): boolean { } return res; }; - - let slow = n; - let fast = getNext(n); - while (slow !== fast) { - slow = getNext(slow); - fast = getNext(getNext(fast)); + const set = new Set(); + while (n !== 1) { + const next = getNext(n); + if (set.has(next)) { + return false; + } + set.add(next); + n = next; } - return fast === 1; + return true; } diff --git a/solution/0200-0299/0202.Happy Number/Solution2.cpp b/solution/0200-0299/0202.Happy Number/Solution2.cpp new file mode 100644 index 0000000000000..eba21d7574cdb --- /dev/null +++ b/solution/0200-0299/0202.Happy Number/Solution2.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + bool isHappy(int n) { + auto next = [](int x) { + int y = 0; + for (; x; x /= 10) { + y += pow(x % 10, 2); + } + return y; + }; + int slow = n, fast = next(n); + while (slow != fast) { + slow = next(slow); + fast = next(next(fast)); + } + return slow == 1; + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0202.Happy Number/Solution2.go b/solution/0200-0299/0202.Happy Number/Solution2.go new file mode 100644 index 0000000000000..2be0192a9e994 --- /dev/null +++ b/solution/0200-0299/0202.Happy Number/Solution2.go @@ -0,0 +1,14 @@ +func isHappy(n int) bool { + next := func(x int) (y int) { + for ; x > 0; x /= 10 { + y += (x % 10) * (x % 10) + } + return + } + slow, fast := n, next(n) + for slow != fast { + slow = next(slow) + fast = next(next(fast)) + } + return slow == 1 +} \ No newline at end of file diff --git a/solution/0200-0299/0202.Happy Number/Solution2.java b/solution/0200-0299/0202.Happy Number/Solution2.java new file mode 100644 index 0000000000000..1688f2aa8897b --- /dev/null +++ b/solution/0200-0299/0202.Happy Number/Solution2.java @@ -0,0 +1,18 @@ +class Solution { + public boolean isHappy(int n) { + int slow = n, fast = next(n); + while (slow != fast) { + slow = next(slow); + fast = next(next(fast)); + } + return slow == 1; + } + + private int next(int x) { + int y = 0; + for (; x > 0; x /= 10) { + y += (x % 10) * (x % 10); + } + return y; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0202.Happy Number/Solution2.py b/solution/0200-0299/0202.Happy Number/Solution2.py new file mode 100644 index 0000000000000..4899e0bc61dfb --- /dev/null +++ b/solution/0200-0299/0202.Happy Number/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def isHappy(self, n: int) -> bool: + def next(x): + y = 0 + while x: + x, v = divmod(x, 10) + y += v * v + return y + + slow, fast = n, next(n) + while slow != fast: + slow, fast = next(slow), next(next(fast)) + return slow == 1 diff --git a/solution/0200-0299/0202.Happy Number/Solution2.rs b/solution/0200-0299/0202.Happy Number/Solution2.rs new file mode 100644 index 0000000000000..5518dcfba1602 --- /dev/null +++ b/solution/0200-0299/0202.Happy Number/Solution2.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn is_happy(n: i32) -> bool { + let get_next = |mut n: i32| { + let mut res = 0; + while n != 0 { + res += (n % 10).pow(2); + n /= 10; + } + res + }; + let mut slow = n; + let mut fast = get_next(n); + while slow != fast { + slow = get_next(slow); + fast = get_next(get_next(fast)); + } + slow == 1 + } +} diff --git a/solution/0200-0299/0202.Happy Number/Solution2.ts b/solution/0200-0299/0202.Happy Number/Solution2.ts new file mode 100644 index 0000000000000..f2791ee88e5ce --- /dev/null +++ b/solution/0200-0299/0202.Happy Number/Solution2.ts @@ -0,0 +1,18 @@ +function isHappy(n: number): boolean { + const getNext = (n: number) => { + let res = 0; + while (n !== 0) { + res += (n % 10) ** 2; + n = Math.floor(n / 10); + } + return res; + }; + + let slow = n; + let fast = getNext(n); + while (slow !== fast) { + slow = getNext(slow); + fast = getNext(getNext(fast)); + } + return fast === 1; +} diff --git a/solution/0200-0299/0203.Remove Linked List Elements/Solution.cpp b/solution/0200-0299/0203.Remove Linked List Elements/Solution.cpp index 03930f4d19189..e66d3b28a5676 100644 --- a/solution/0200-0299/0203.Remove Linked List Elements/Solution.cpp +++ b/solution/0200-0299/0203.Remove Linked List Elements/Solution.cpp @@ -13,4 +13,4 @@ class Solution { } return dummy->next; } -}; +}; \ No newline at end of file diff --git a/solution/0200-0299/0203.Remove Linked List Elements/Solution.cs b/solution/0200-0299/0203.Remove Linked List Elements/Solution.cs index 9c0afd3f42027..0135e7a8e836b 100644 --- a/solution/0200-0299/0203.Remove Linked List Elements/Solution.cs +++ b/solution/0200-0299/0203.Remove Linked List Elements/Solution.cs @@ -22,4 +22,4 @@ public ListNode RemoveElements(ListNode head, int val) { if (newTail != null) newTail.next = null; return newHead; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0204.Count Primes/Solution.cs b/solution/0200-0299/0204.Count Primes/Solution.cs index 6082dac0b75e8..1005833a92b50 100644 --- a/solution/0200-0299/0204.Count Primes/Solution.cs +++ b/solution/0200-0299/0204.Count Primes/Solution.cs @@ -15,4 +15,4 @@ public int CountPrimes(int n) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0205.Isomorphic Strings/Solution.cs b/solution/0200-0299/0205.Isomorphic Strings/Solution.cs index 7f128130fd413..2f86ab52400ca 100644 --- a/solution/0200-0299/0205.Isomorphic Strings/Solution.cs +++ b/solution/0200-0299/0205.Isomorphic Strings/Solution.cs @@ -13,4 +13,4 @@ public bool IsIsomorphic(string s, string t) { } return true; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0205.Isomorphic Strings/Solution.java b/solution/0200-0299/0205.Isomorphic Strings/Solution.java index 3a762e39e1d71..84f7e766b46cd 100644 --- a/solution/0200-0299/0205.Isomorphic Strings/Solution.java +++ b/solution/0200-0299/0205.Isomorphic Strings/Solution.java @@ -1,15 +1,18 @@ class Solution { public boolean isIsomorphic(String s, String t) { - int[] d1 = new int[256]; - int[] d2 = new int[256]; + Map d1 = new HashMap<>(); + Map d2 = new HashMap<>(); int n = s.length(); for (int i = 0; i < n; ++i) { char a = s.charAt(i), b = t.charAt(i); - if (d1[a] != d2[b]) { + if (d1.containsKey(a) && d1.get(a) != b) { return false; } - d1[a] = i + 1; - d2[b] = i + 1; + if (d2.containsKey(b) && d2.get(b) != a) { + return false; + } + d1.put(a, b); + d2.put(b, a); } return true; } diff --git a/solution/0200-0299/0205.Isomorphic Strings/Solution.py b/solution/0200-0299/0205.Isomorphic Strings/Solution.py index 0c598955f4d93..727bd746392d8 100644 --- a/solution/0200-0299/0205.Isomorphic Strings/Solution.py +++ b/solution/0200-0299/0205.Isomorphic Strings/Solution.py @@ -1,9 +1,10 @@ class Solution: def isIsomorphic(self, s: str, t: str) -> bool: - d1, d2 = [0] * 256, [0] * 256 - for i, (a, b) in enumerate(zip(s, t), 1): - a, b = ord(a), ord(b) - if d1[a] != d2[b]: + d1 = {} + d2 = {} + for a, b in zip(s, t): + if (a in d1 and d1[a] != b) or (b in d2 and d2[b] != a): return False - d1[a] = d2[b] = i + d1[a] = b + d2[b] = a return True diff --git a/solution/0200-0299/0205.Isomorphic Strings/Solution2.java b/solution/0200-0299/0205.Isomorphic Strings/Solution2.java new file mode 100644 index 0000000000000..3a762e39e1d71 --- /dev/null +++ b/solution/0200-0299/0205.Isomorphic Strings/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public boolean isIsomorphic(String s, String t) { + int[] d1 = new int[256]; + int[] d2 = new int[256]; + int n = s.length(); + for (int i = 0; i < n; ++i) { + char a = s.charAt(i), b = t.charAt(i); + if (d1[a] != d2[b]) { + return false; + } + d1[a] = i + 1; + d2[b] = i + 1; + } + return true; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0205.Isomorphic Strings/Solution2.py b/solution/0200-0299/0205.Isomorphic Strings/Solution2.py new file mode 100644 index 0000000000000..0c598955f4d93 --- /dev/null +++ b/solution/0200-0299/0205.Isomorphic Strings/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def isIsomorphic(self, s: str, t: str) -> bool: + d1, d2 = [0] * 256, [0] * 256 + for i, (a, b) in enumerate(zip(s, t), 1): + a, b = ord(a), ord(b) + if d1[a] != d2[b]: + return False + d1[a] = d2[b] = i + return True diff --git a/solution/0200-0299/0206.Reverse Linked List/Solution.cs b/solution/0200-0299/0206.Reverse Linked List/Solution.cs index 0cf8d6bd470ff..fd70b47359d14 100644 --- a/solution/0200-0299/0206.Reverse Linked List/Solution.cs +++ b/solution/0200-0299/0206.Reverse Linked List/Solution.cs @@ -21,4 +21,4 @@ public ListNode ReverseList(ListNode head) { } return pre; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0206.Reverse Linked List/Solution2.cpp b/solution/0200-0299/0206.Reverse Linked List/Solution2.cpp new file mode 100644 index 0000000000000..2d4a3a587388a --- /dev/null +++ b/solution/0200-0299/0206.Reverse Linked List/Solution2.cpp @@ -0,0 +1,20 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + if (!head || !head->next) return head; + ListNode* ans = reverseList(head->next); + head->next->next = head; + head->next = nullptr; + return ans; + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0206.Reverse Linked List/Solution2.go b/solution/0200-0299/0206.Reverse Linked List/Solution2.go new file mode 100644 index 0000000000000..4c55cdf095e0d --- /dev/null +++ b/solution/0200-0299/0206.Reverse Linked List/Solution2.go @@ -0,0 +1,16 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func reverseList(head *ListNode) *ListNode { + if head == nil || head.Next == nil { + return head + } + ans := reverseList(head.Next) + head.Next.Next = head + head.Next = nil + return ans +} \ No newline at end of file diff --git a/solution/0200-0299/0206.Reverse Linked List/Solution2.java b/solution/0200-0299/0206.Reverse Linked List/Solution2.java new file mode 100644 index 0000000000000..f5f54358e9f56 --- /dev/null +++ b/solution/0200-0299/0206.Reverse Linked List/Solution2.java @@ -0,0 +1,21 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode reverseList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode ans = reverseList(head.next); + head.next.next = head; + head.next = null; + return ans; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0206.Reverse Linked List/Solution2.py b/solution/0200-0299/0206.Reverse Linked List/Solution2.py new file mode 100644 index 0000000000000..5c8e669780395 --- /dev/null +++ b/solution/0200-0299/0206.Reverse Linked List/Solution2.py @@ -0,0 +1,13 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseList(self, head: ListNode) -> ListNode: + if head is None or head.next is None: + return head + ans = self.reverseList(head.next) + head.next.next = head + head.next = None + return ans diff --git a/solution/0200-0299/0206.Reverse Linked List/Solution2.rs b/solution/0200-0299/0206.Reverse Linked List/Solution2.rs new file mode 100644 index 0000000000000..70b03142add00 --- /dev/null +++ b/solution/0200-0299/0206.Reverse Linked List/Solution2.rs @@ -0,0 +1,32 @@ +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + fn rev(pre: Option>, cur: Option>) -> Option> { + match cur { + None => pre, + Some(mut node) => { + let next = node.next; + node.next = pre; + Self::rev(Some(node), next) + } + } + } + + pub fn reverse_list(head: Option>) -> Option> { + Self::rev(None, head) + } +} diff --git a/solution/0200-0299/0206.Reverse Linked List/Solution2.ts b/solution/0200-0299/0206.Reverse Linked List/Solution2.ts new file mode 100644 index 0000000000000..bad385ded68e0 --- /dev/null +++ b/solution/0200-0299/0206.Reverse Linked List/Solution2.ts @@ -0,0 +1,28 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ +const rev = (pre: ListNode | null, cur: ListNode | null): ListNode | null => { + if (cur == null) { + return pre; + } + const next = cur.next; + cur.next = pre; + return rev(cur, next); +}; + +function reverseList(head: ListNode | null): ListNode | null { + if (head == null) { + return head; + } + const next = head.next; + head.next = null; + return rev(head, next); +} diff --git a/solution/0200-0299/0207.Course Schedule/Solution.cs b/solution/0200-0299/0207.Course Schedule/Solution.cs index 5d11635a0455e..9710ea6b87bfe 100644 --- a/solution/0200-0299/0207.Course Schedule/Solution.cs +++ b/solution/0200-0299/0207.Course Schedule/Solution.cs @@ -28,4 +28,4 @@ public bool CanFinish(int numCourses, int[][] prerequisites) { } return cnt == numCourses; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0208.Implement Trie (Prefix Tree)/Solution.cs b/solution/0200-0299/0208.Implement Trie (Prefix Tree)/Solution.cs index 6ea2f9f61bf0a..e2e0eb0f60679 100644 --- a/solution/0200-0299/0208.Implement Trie (Prefix Tree)/Solution.cs +++ b/solution/0200-0299/0208.Implement Trie (Prefix Tree)/Solution.cs @@ -48,4 +48,4 @@ private Trie SearchPrefix(string s) { * obj.Insert(word); * bool param_2 = obj.Search(word); * bool param_3 = obj.StartsWith(prefix); - */ \ No newline at end of file + */ diff --git a/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.cpp b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.cpp index b6d57f2aaabd5..c1c57533867f9 100644 --- a/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.cpp +++ b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.cpp @@ -2,15 +2,17 @@ class Solution { public: int minSubArrayLen(int target, vector& nums) { int n = nums.size(); - long long s = 0; + vector s(n + 1); + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } int ans = n + 1; - for (int i = 0, j = 0; i < n; ++i) { - s += nums[i]; - while (j < n && s >= target) { - ans = min(ans, i - j + 1); - s -= nums[j++]; + for (int i = 0; i <= n; ++i) { + int j = lower_bound(s.begin(), s.end(), s[i] + target) - s.begin(); + if (j <= n) { + ans = min(ans, j - i); } } - return ans == n + 1 ? 0 : ans; + return ans <= n ? ans : 0; } }; \ No newline at end of file diff --git a/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.cs b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.cs index 7e86e3e907474..0bd157d421679 100644 --- a/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.cs +++ b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.cs @@ -12,4 +12,4 @@ public int MinSubArrayLen(int target, int[] nums) { } return ans == n + 1 ? 0 : ans; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.go b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.go index 37a23211e9740..e9056ac2116e2 100644 --- a/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.go +++ b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.go @@ -1,13 +1,14 @@ func minSubArrayLen(target int, nums []int) int { n := len(nums) - s := 0 + s := make([]int, n+1) + for i, x := range nums { + s[i+1] = s[i] + x + } ans := n + 1 - for i, j := 0, 0; i < n; i++ { - s += nums[i] - for s >= target { - ans = min(ans, i-j+1) - s -= nums[j] - j++ + for i, x := range s { + j := sort.SearchInts(s, x+target) + if j <= n { + ans = min(ans, j-i) } } if ans == n+1 { diff --git a/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.java b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.java index 11b6a8155908b..090d4a04c4f34 100644 --- a/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.java +++ b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.java @@ -1,15 +1,30 @@ class Solution { public int minSubArrayLen(int target, int[] nums) { int n = nums.length; - long s = 0; + long[] s = new long[n + 1]; + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } int ans = n + 1; - for (int i = 0, j = 0; i < n; ++i) { - s += nums[i]; - while (j < n && s >= target) { - ans = Math.min(ans, i - j + 1); - s -= nums[j++]; + for (int i = 0; i <= n; ++i) { + int j = search(s, s[i] + target); + if (j <= n) { + ans = Math.min(ans, j - i); } } return ans <= n ? ans : 0; } + + private int search(long[] nums, long x) { + int l = 0, r = nums.length; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } } \ No newline at end of file diff --git a/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.py b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.py index 86054793f483b..442269416582b 100644 --- a/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.py +++ b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.py @@ -1,12 +1,10 @@ -class Solution: - def minSubArrayLen(self, target: int, nums: List[int]) -> int: - n = len(nums) - ans = n + 1 - s = j = 0 - for i, x in enumerate(nums): - s += x - while j < n and s >= target: - ans = min(ans, i - j + 1) - s -= nums[j] - j += 1 - return ans if ans <= n else 0 +class Solution: + def minSubArrayLen(self, target: int, nums: List[int]) -> int: + n = len(nums) + s = list(accumulate(nums, initial=0)) + ans = n + 1 + for i, x in enumerate(s): + j = bisect_left(s, x + target) + if j <= n: + ans = min(ans, j - i) + return ans if ans <= n else 0 diff --git a/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.ts b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.ts index ef54870682bf6..08ba914dbbbdd 100644 --- a/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.ts +++ b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.ts @@ -1,12 +1,27 @@ function minSubArrayLen(target: number, nums: number[]): number { const n = nums.length; - let s = 0; + const s: number[] = new Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } let ans = n + 1; - for (let i = 0, j = 0; i < n; ++i) { - s += nums[i]; - while (s >= target) { - ans = Math.min(ans, i - j + 1); - s -= nums[j++]; + const search = (x: number) => { + let l = 0; + let r = n + 1; + while (l < r) { + const mid = (l + r) >>> 1; + if (s[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + for (let i = 0; i <= n; ++i) { + const j = search(s[i] + target); + if (j <= n) { + ans = Math.min(ans, j - i); } } return ans === n + 1 ? 0 : ans; diff --git a/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution2.cpp b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution2.cpp new file mode 100644 index 0000000000000..b6d57f2aaabd5 --- /dev/null +++ b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int minSubArrayLen(int target, vector& nums) { + int n = nums.size(); + long long s = 0; + int ans = n + 1; + for (int i = 0, j = 0; i < n; ++i) { + s += nums[i]; + while (j < n && s >= target) { + ans = min(ans, i - j + 1); + s -= nums[j++]; + } + } + return ans == n + 1 ? 0 : ans; + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution2.go b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution2.go new file mode 100644 index 0000000000000..37a23211e9740 --- /dev/null +++ b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution2.go @@ -0,0 +1,17 @@ +func minSubArrayLen(target int, nums []int) int { + n := len(nums) + s := 0 + ans := n + 1 + for i, j := 0, 0; i < n; i++ { + s += nums[i] + for s >= target { + ans = min(ans, i-j+1) + s -= nums[j] + j++ + } + } + if ans == n+1 { + return 0 + } + return ans +} \ No newline at end of file diff --git a/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution2.java b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution2.java new file mode 100644 index 0000000000000..11b6a8155908b --- /dev/null +++ b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public int minSubArrayLen(int target, int[] nums) { + int n = nums.length; + long s = 0; + int ans = n + 1; + for (int i = 0, j = 0; i < n; ++i) { + s += nums[i]; + while (j < n && s >= target) { + ans = Math.min(ans, i - j + 1); + s -= nums[j++]; + } + } + return ans <= n ? ans : 0; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution2.py b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution2.py new file mode 100644 index 0000000000000..6dcbc2480b59f --- /dev/null +++ b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def minSubArrayLen(self, target: int, nums: List[int]) -> int: + n = len(nums) + ans = n + 1 + s = j = 0 + for i, x in enumerate(nums): + s += x + while j < n and s >= target: + ans = min(ans, i - j + 1) + s -= nums[j] + j += 1 + return ans if ans <= n else 0 diff --git a/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution2.ts b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution2.ts new file mode 100644 index 0000000000000..ef54870682bf6 --- /dev/null +++ b/solution/0200-0299/0209.Minimum Size Subarray Sum/Solution2.ts @@ -0,0 +1,13 @@ +function minSubArrayLen(target: number, nums: number[]): number { + const n = nums.length; + let s = 0; + let ans = n + 1; + for (let i = 0, j = 0; i < n; ++i) { + s += nums[i]; + while (s >= target) { + ans = Math.min(ans, i - j + 1); + s -= nums[j++]; + } + } + return ans === n + 1 ? 0 : ans; +} diff --git a/solution/0200-0299/0210.Course Schedule II/Solution.cs b/solution/0200-0299/0210.Course Schedule II/Solution.cs index 5e33944c53fb0..5d36e77aa76cb 100644 --- a/solution/0200-0299/0210.Course Schedule II/Solution.cs +++ b/solution/0200-0299/0210.Course Schedule II/Solution.cs @@ -29,4 +29,4 @@ public int[] FindOrder(int numCourses, int[][] prerequisites) { } return cnt == numCourses ? ans : new int[0]; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0211.Design Add and Search Words Data Structure/Solution.cpp b/solution/0200-0299/0211.Design Add and Search Words Data Structure/Solution.cpp index 06861c936a1e9..858d539d90a8c 100644 --- a/solution/0200-0299/0211.Design Add and Search Words Data Structure/Solution.cpp +++ b/solution/0200-0299/0211.Design Add and Search Words Data Structure/Solution.cpp @@ -64,4 +64,4 @@ class WordDictionary { * WordDictionary* obj = new WordDictionary(); * obj->addWord(word); * bool param_2 = obj->search(word); - */ + */ \ No newline at end of file diff --git a/solution/0200-0299/0213.House Robber II/Solution.cpp b/solution/0200-0299/0213.House Robber II/Solution.cpp index b69d883e07085..b84dd4418d600 100644 --- a/solution/0200-0299/0213.House Robber II/Solution.cpp +++ b/solution/0200-0299/0213.House Robber II/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - int rob(vector& nums) { - int n = nums.size(); - if (n == 1) { - return nums[0]; - } - return max(robRange(nums, 0, n - 2), robRange(nums, 1, n - 1)); - } - - int robRange(vector& nums, int l, int r) { - int f = 0, g = 0; - for (; l <= r; ++l) { - int ff = max(f, g); - g = f + nums[l]; - f = ff; - } - return max(f, g); - } +class Solution { +public: + int rob(vector& nums) { + int n = nums.size(); + if (n == 1) { + return nums[0]; + } + return max(robRange(nums, 0, n - 2), robRange(nums, 1, n - 1)); + } + + int robRange(vector& nums, int l, int r) { + int f = 0, g = 0; + for (; l <= r; ++l) { + int ff = max(f, g); + g = f + nums[l]; + f = ff; + } + return max(f, g); + } }; \ No newline at end of file diff --git a/solution/0200-0299/0213.House Robber II/Solution.java b/solution/0200-0299/0213.House Robber II/Solution.java index 49e0303e1d69c..223d1a667f6d9 100644 --- a/solution/0200-0299/0213.House Robber II/Solution.java +++ b/solution/0200-0299/0213.House Robber II/Solution.java @@ -1,19 +1,19 @@ -class Solution { - public int rob(int[] nums) { - int n = nums.length; - if (n == 1) { - return nums[0]; - } - return Math.max(rob(nums, 0, n - 2), rob(nums, 1, n - 1)); - } - - private int rob(int[] nums, int l, int r) { - int f = 0, g = 0; - for (; l <= r; ++l) { - int ff = Math.max(f, g); - g = f + nums[l]; - f = ff; - } - return Math.max(f, g); - } +class Solution { + public int rob(int[] nums) { + int n = nums.length; + if (n == 1) { + return nums[0]; + } + return Math.max(rob(nums, 0, n - 2), rob(nums, 1, n - 1)); + } + + private int rob(int[] nums, int l, int r) { + int f = 0, g = 0; + for (; l <= r; ++l) { + int ff = Math.max(f, g); + g = f + nums[l]; + f = ff; + } + return Math.max(f, g); + } } \ No newline at end of file diff --git a/solution/0200-0299/0213.House Robber II/Solution.py b/solution/0200-0299/0213.House Robber II/Solution.py index 866aacd7585f9..844328f427344 100644 --- a/solution/0200-0299/0213.House Robber II/Solution.py +++ b/solution/0200-0299/0213.House Robber II/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def rob(self, nums: List[int]) -> int: - def _rob(nums): - f = g = 0 - for x in nums: - f, g = max(f, g), f + x - return max(f, g) - - if len(nums) == 1: - return nums[0] - return max(_rob(nums[1:]), _rob(nums[:-1])) +class Solution: + def rob(self, nums: List[int]) -> int: + def _rob(nums): + f = g = 0 + for x in nums: + f, g = max(f, g), f + x + return max(f, g) + + if len(nums) == 1: + return nums[0] + return max(_rob(nums[1:]), _rob(nums[:-1])) diff --git a/solution/0200-0299/0215.Kth Largest Element in an Array/Solution.rs b/solution/0200-0299/0215.Kth Largest Element in an Array/Solution.rs index 589e6ddb82204..1a47146d1dc77 100644 --- a/solution/0200-0299/0215.Kth Largest Element in an Array/Solution.rs +++ b/solution/0200-0299/0215.Kth Largest Element in an Array/Solution.rs @@ -1,28 +1,29 @@ use rand::Rng; impl Solution { - pub fn find_kth_largest(mut nums: Vec, k: i32) -> i32 { - let k = k as usize; - let n = nums.len(); - let mut l = 0; - let mut r = n; - while l <= k - 1 && l < r { - nums.swap(l, rand::thread_rng().gen_range(l, r)); - let num = nums[l]; - let mut mark = l; - for i in l..r { - if nums[i] > num { - mark += 1; - nums.swap(i, mark); - } - } - nums.swap(l, mark); - if mark + 1 <= k { - l = mark + 1; - } else { - r = mark; + fn sort(nums: &mut Vec, l: usize, r: usize, k: usize) { + if l + 1 > k || l >= r { + return; + } + nums.swap(l, rand::thread_rng().gen_range(l, r)); + let num = nums[l]; + let mut mark = l; + for i in l..r { + if nums[i] > num { + mark += 1; + nums.swap(i, mark); } } + nums.swap(l, mark); + + Self::sort(nums, l, mark, k); + Self::sort(nums, mark + 1, r, k); + } + + pub fn find_kth_largest(mut nums: Vec, k: i32) -> i32 { + let n = nums.len(); + let k = k as usize; + Self::sort(&mut nums, 0, n, k); nums[k - 1] } } diff --git a/solution/0200-0299/0215.Kth Largest Element in an Array/Solution2.rs b/solution/0200-0299/0215.Kth Largest Element in an Array/Solution2.rs new file mode 100644 index 0000000000000..589e6ddb82204 --- /dev/null +++ b/solution/0200-0299/0215.Kth Largest Element in an Array/Solution2.rs @@ -0,0 +1,28 @@ +use rand::Rng; + +impl Solution { + pub fn find_kth_largest(mut nums: Vec, k: i32) -> i32 { + let k = k as usize; + let n = nums.len(); + let mut l = 0; + let mut r = n; + while l <= k - 1 && l < r { + nums.swap(l, rand::thread_rng().gen_range(l, r)); + let num = nums[l]; + let mut mark = l; + for i in l..r { + if nums[i] > num { + mark += 1; + nums.swap(i, mark); + } + } + nums.swap(l, mark); + if mark + 1 <= k { + l = mark + 1; + } else { + r = mark; + } + } + nums[k - 1] + } +} diff --git a/solution/0200-0299/0216.Combination Sum III/Solution.cs b/solution/0200-0299/0216.Combination Sum III/Solution.cs index 973037f8ecf95..493567f4b32db 100644 --- a/solution/0200-0299/0216.Combination Sum III/Solution.cs +++ b/solution/0200-0299/0216.Combination Sum III/Solution.cs @@ -24,4 +24,4 @@ private void dfs(int i, int s) { t.RemoveAt(t.Count - 1); dfs(i + 1, s); } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0216.Combination Sum III/Solution.ts b/solution/0200-0299/0216.Combination Sum III/Solution.ts index c31da18907656..49722f76d1377 100644 --- a/solution/0200-0299/0216.Combination Sum III/Solution.ts +++ b/solution/0200-0299/0216.Combination Sum III/Solution.ts @@ -8,7 +8,7 @@ function combinationSum3(k: number, n: number): number[][] { } return; } - if (i > 9 || i > s || t.length > k) { + if (i > 9 || i > s || t.length >= k) { return; } t.push(i); diff --git a/solution/0200-0299/0216.Combination Sum III/Solution2.cpp b/solution/0200-0299/0216.Combination Sum III/Solution2.cpp new file mode 100644 index 0000000000000..3184a41a6695c --- /dev/null +++ b/solution/0200-0299/0216.Combination Sum III/Solution2.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + vector> combinationSum3(int k, int n) { + vector> ans; + vector t; + function dfs = [&](int i, int s) { + if (s == 0) { + if (t.size() == k) { + ans.emplace_back(t); + } + return; + } + if (i > 9 || i > s || t.size() >= k) { + return; + } + for (int j = i; j <= 9; ++j) { + t.emplace_back(j); + dfs(j + 1, s - j); + t.pop_back(); + } + }; + dfs(1, n); + return ans; + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0216.Combination Sum III/Solution2.cs b/solution/0200-0299/0216.Combination Sum III/Solution2.cs new file mode 100644 index 0000000000000..20c4d3f55e511 --- /dev/null +++ b/solution/0200-0299/0216.Combination Sum III/Solution2.cs @@ -0,0 +1,28 @@ +public class Solution { + private List> ans = new List>(); + private List t = new List(); + private int k; + + public IList> CombinationSum3(int k, int n) { + this.k = k; + dfs(1, n); + return ans; + } + + private void dfs(int i, int s) { + if (s == 0) { + if (t.Count == k) { + ans.Add(new List(t)); + } + return; + } + if (i > 9 || i > s || t.Count >= k) { + return; + } + for (int j = i; j <= 9; ++j) { + t.Add(j); + dfs(j + 1, s - j); + t.RemoveAt(t.Count - 1); + } + } +} diff --git a/solution/0200-0299/0216.Combination Sum III/Solution2.go b/solution/0200-0299/0216.Combination Sum III/Solution2.go new file mode 100644 index 0000000000000..c115a4e4f7230 --- /dev/null +++ b/solution/0200-0299/0216.Combination Sum III/Solution2.go @@ -0,0 +1,22 @@ +func combinationSum3(k int, n int) (ans [][]int) { + t := []int{} + var dfs func(i, s int) + dfs = func(i, s int) { + if s == 0 { + if len(t) == k { + ans = append(ans, slices.Clone(t)) + } + return + } + if i > 9 || i > s || len(t) >= k { + return + } + for j := i; j <= 9; j++ { + t = append(t, j) + dfs(j+1, s-j) + t = t[:len(t)-1] + } + } + dfs(1, n) + return +} \ No newline at end of file diff --git a/solution/0200-0299/0216.Combination Sum III/Solution2.java b/solution/0200-0299/0216.Combination Sum III/Solution2.java new file mode 100644 index 0000000000000..7952f51d04bec --- /dev/null +++ b/solution/0200-0299/0216.Combination Sum III/Solution2.java @@ -0,0 +1,28 @@ +class Solution { + private List> ans = new ArrayList<>(); + private List t = new ArrayList<>(); + private int k; + + public List> combinationSum3(int k, int n) { + this.k = k; + dfs(1, n); + return ans; + } + + private void dfs(int i, int s) { + if (s == 0) { + if (t.size() == k) { + ans.add(new ArrayList<>(t)); + } + return; + } + if (i > 9 || i > s || t.size() >= k) { + return; + } + for (int j = i; j <= 9; ++j) { + t.add(j); + dfs(j + 1, s - j); + t.remove(t.size() - 1); + } + } +} \ No newline at end of file diff --git a/solution/0200-0299/0216.Combination Sum III/Solution2.py b/solution/0200-0299/0216.Combination Sum III/Solution2.py new file mode 100644 index 0000000000000..f792355bf46d3 --- /dev/null +++ b/solution/0200-0299/0216.Combination Sum III/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def combinationSum3(self, k: int, n: int) -> List[List[int]]: + def dfs(i: int, s: int): + if s == 0: + if len(t) == k: + ans.append(t[:]) + return + if i > 9 or i > s or len(t) >= k: + return + for j in range(i, 10): + t.append(j) + dfs(j + 1, s - j) + t.pop() + + ans = [] + t = [] + dfs(1, n) + return ans diff --git a/solution/0200-0299/0216.Combination Sum III/Solution2.ts b/solution/0200-0299/0216.Combination Sum III/Solution2.ts new file mode 100644 index 0000000000000..4ef554c5a2fca --- /dev/null +++ b/solution/0200-0299/0216.Combination Sum III/Solution2.ts @@ -0,0 +1,22 @@ +function combinationSum3(k: number, n: number): number[][] { + const ans: number[][] = []; + const t: number[] = []; + const dfs = (i: number, s: number) => { + if (s === 0) { + if (t.length === k) { + ans.push(t.slice()); + } + return; + } + if (i > 9 || i > s || t.length >= k) { + return; + } + for (let j = i; j <= 9; ++j) { + t.push(j); + dfs(j + 1, s - j); + t.pop(); + } + }; + dfs(1, n); + return ans; +} diff --git a/solution/0200-0299/0216.Combination Sum III/Solution3.cpp b/solution/0200-0299/0216.Combination Sum III/Solution3.cpp new file mode 100644 index 0000000000000..80996238ef455 --- /dev/null +++ b/solution/0200-0299/0216.Combination Sum III/Solution3.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + vector> combinationSum3(int k, int n) { + vector> ans; + for (int mask = 0; mask < 1 << 9; ++mask) { + if (__builtin_popcount(mask) == k) { + int s = 0; + vector t; + for (int i = 0; i < 9; ++i) { + if (mask >> i & 1) { + t.push_back(i + 1); + s += i + 1; + } + } + if (s == n) { + ans.emplace_back(t); + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0216.Combination Sum III/Solution3.cs b/solution/0200-0299/0216.Combination Sum III/Solution3.cs new file mode 100644 index 0000000000000..74038f6628788 --- /dev/null +++ b/solution/0200-0299/0216.Combination Sum III/Solution3.cs @@ -0,0 +1,30 @@ +public class Solution { + public IList> CombinationSum3(int k, int n) { + List> ans = new List>(); + for (int mask = 0; mask < 1 << 9; ++mask) { + if (bitCount(mask) == k) { + List t = new List(); + int s = 0; + for (int i = 0; i < 9; ++i) { + if ((mask >> i & 1) == 1) { + s += i + 1; + t.Add(i + 1); + } + } + if (s == n) { + ans.Add(t); + } + } + } + return ans; + } + + private int bitCount(int x) { + int cnt = 0; + while (x > 0) { + x -= x & -x; + ++cnt; + } + return cnt; + } +} diff --git a/solution/0200-0299/0216.Combination Sum III/Solution3.go b/solution/0200-0299/0216.Combination Sum III/Solution3.go new file mode 100644 index 0000000000000..4cfa4149e5a14 --- /dev/null +++ b/solution/0200-0299/0216.Combination Sum III/Solution3.go @@ -0,0 +1,18 @@ +func combinationSum3(k int, n int) (ans [][]int) { + for mask := 0; mask < 1<<9; mask++ { + if bits.OnesCount(uint(mask)) == k { + t := []int{} + s := 0 + for i := 0; i < 9; i++ { + if mask>>i&1 == 1 { + s += i + 1 + t = append(t, i+1) + } + } + if s == n { + ans = append(ans, t) + } + } + } + return +} \ No newline at end of file diff --git a/solution/0200-0299/0216.Combination Sum III/Solution3.java b/solution/0200-0299/0216.Combination Sum III/Solution3.java new file mode 100644 index 0000000000000..71863842a9e22 --- /dev/null +++ b/solution/0200-0299/0216.Combination Sum III/Solution3.java @@ -0,0 +1,21 @@ +class Solution { + public List> combinationSum3(int k, int n) { + List> ans = new ArrayList<>(); + for (int mask = 0; mask < 1 << 9; ++mask) { + if (Integer.bitCount(mask) == k) { + List t = new ArrayList<>(); + int s = 0; + for (int i = 0; i < 9; ++i) { + if ((mask >> i & 1) == 1) { + s += (i + 1); + t.add(i + 1); + } + } + if (s == n) { + ans.add(t); + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0216.Combination Sum III/Solution3.py b/solution/0200-0299/0216.Combination Sum III/Solution3.py new file mode 100644 index 0000000000000..cb3b066a29fa2 --- /dev/null +++ b/solution/0200-0299/0216.Combination Sum III/Solution3.py @@ -0,0 +1,9 @@ +class Solution: + def combinationSum3(self, k: int, n: int) -> List[List[int]]: + ans = [] + for mask in range(1 << 9): + if mask.bit_count() == k: + t = [i + 1 for i in range(9) if mask >> i & 1] + if sum(t) == n: + ans.append(t) + return ans diff --git a/solution/0200-0299/0216.Combination Sum III/Solution3.ts b/solution/0200-0299/0216.Combination Sum III/Solution3.ts new file mode 100644 index 0000000000000..fd92c8cbc83a5 --- /dev/null +++ b/solution/0200-0299/0216.Combination Sum III/Solution3.ts @@ -0,0 +1,28 @@ +function combinationSum3(k: number, n: number): number[][] { + const ans: number[][] = []; + for (let mask = 0; mask < 1 << 9; ++mask) { + if (bitCount(mask) === k) { + const t: number[] = []; + let s = 0; + for (let i = 0; i < 9; ++i) { + if (mask & (1 << i)) { + t.push(i + 1); + s += i + 1; + } + } + if (s === n) { + ans.push(t); + } + } + } + return ans; +} + +function bitCount(i: number): number { + i = i - ((i >>> 1) & 0x55555555); + i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); + i = (i + (i >>> 4)) & 0x0f0f0f0f; + i = i + (i >>> 8); + i = i + (i >>> 16); + return i & 0x3f; +} diff --git a/solution/0200-0299/0217.Contains Duplicate/Solution.c b/solution/0200-0299/0217.Contains Duplicate/Solution.c index 817ad770015f7..8798b29e2dd37 100644 --- a/solution/0200-0299/0217.Contains Duplicate/Solution.c +++ b/solution/0200-0299/0217.Contains Duplicate/Solution.c @@ -10,4 +10,4 @@ bool containsDuplicate(int* nums, int numsSize) { } } return 0; -} +} \ No newline at end of file diff --git a/solution/0200-0299/0217.Contains Duplicate/Solution.cpp b/solution/0200-0299/0217.Contains Duplicate/Solution.cpp index 6a7700278869b..c9ca21471bc75 100644 --- a/solution/0200-0299/0217.Contains Duplicate/Solution.cpp +++ b/solution/0200-0299/0217.Contains Duplicate/Solution.cpp @@ -1,7 +1,12 @@ class Solution { public: bool containsDuplicate(vector& nums) { - unordered_set s(nums.begin(), nums.end()); - return s.size() < nums.size(); + sort(nums.begin(), nums.end()); + for (int i = 0; i < nums.size() - 1; ++i) { + if (nums[i] == nums[i + 1]) { + return true; + } + } + return false; } }; \ No newline at end of file diff --git a/solution/0200-0299/0217.Contains Duplicate/Solution.cs b/solution/0200-0299/0217.Contains Duplicate/Solution.cs index d5d5675ded6d9..b6c326b257195 100644 --- a/solution/0200-0299/0217.Contains Duplicate/Solution.cs +++ b/solution/0200-0299/0217.Contains Duplicate/Solution.cs @@ -2,4 +2,4 @@ public class Solution { public bool ContainsDuplicate(int[] nums) { return nums.Distinct().Count() < nums.Length; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0217.Contains Duplicate/Solution.go b/solution/0200-0299/0217.Contains Duplicate/Solution.go index 9398bd9bc4a6b..499b95823d2bf 100644 --- a/solution/0200-0299/0217.Contains Duplicate/Solution.go +++ b/solution/0200-0299/0217.Contains Duplicate/Solution.go @@ -1,10 +1,9 @@ func containsDuplicate(nums []int) bool { - s := map[int]bool{} - for _, v := range nums { - if s[v] { + sort.Ints(nums) + for i, v := range nums[1:] { + if v == nums[i] { return true } - s[v] = true } return false } \ No newline at end of file diff --git a/solution/0200-0299/0217.Contains Duplicate/Solution.java b/solution/0200-0299/0217.Contains Duplicate/Solution.java index eaea8517af8de..117f2885c1f37 100644 --- a/solution/0200-0299/0217.Contains Duplicate/Solution.java +++ b/solution/0200-0299/0217.Contains Duplicate/Solution.java @@ -1,8 +1,8 @@ class Solution { public boolean containsDuplicate(int[] nums) { - Set s = new HashSet<>(); - for (int num : nums) { - if (!s.add(num)) { + Arrays.sort(nums); + for (int i = 0; i < nums.length - 1; ++i) { + if (nums[i] == nums[i + 1]) { return true; } } diff --git a/solution/0200-0299/0217.Contains Duplicate/Solution.php b/solution/0200-0299/0217.Contains Duplicate/Solution.php index 1fa06b370b261..7ba65d0a365d2 100644 --- a/solution/0200-0299/0217.Contains Duplicate/Solution.php +++ b/solution/0200-0299/0217.Contains Duplicate/Solution.php @@ -7,4 +7,4 @@ function containsDuplicate($nums) { $numsUnique = array_unique($nums); return count($nums) != count($numsUnique); } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0217.Contains Duplicate/Solution.py b/solution/0200-0299/0217.Contains Duplicate/Solution.py index df5f85541cb0d..61e8fe60f36ec 100644 --- a/solution/0200-0299/0217.Contains Duplicate/Solution.py +++ b/solution/0200-0299/0217.Contains Duplicate/Solution.py @@ -1,3 +1,3 @@ class Solution: def containsDuplicate(self, nums: List[int]) -> bool: - return len(set(nums)) < len(nums) + return any(a == b for a, b in pairwise(sorted(nums))) diff --git a/solution/0200-0299/0217.Contains Duplicate/Solution.rs b/solution/0200-0299/0217.Contains Duplicate/Solution.rs index 4cd30e955c03e..5a10b54b4c078 100644 --- a/solution/0200-0299/0217.Contains Duplicate/Solution.rs +++ b/solution/0200-0299/0217.Contains Duplicate/Solution.rs @@ -1,6 +1,12 @@ -use std::collections::HashSet; impl Solution { - pub fn contains_duplicate(nums: Vec) -> bool { - nums.iter().collect::>().len() != nums.len() + pub fn contains_duplicate(mut nums: Vec) -> bool { + nums.sort(); + let n = nums.len(); + for i in 1..n { + if nums[i - 1] == nums[i] { + return true; + } + } + false } } diff --git a/solution/0200-0299/0217.Contains Duplicate/Solution.ts b/solution/0200-0299/0217.Contains Duplicate/Solution.ts index 33c799c32a6ac..7e995654415b0 100644 --- a/solution/0200-0299/0217.Contains Duplicate/Solution.ts +++ b/solution/0200-0299/0217.Contains Duplicate/Solution.ts @@ -1,3 +1,10 @@ function containsDuplicate(nums: number[]): boolean { - return new Set(nums).size !== nums.length; + nums.sort((a, b) => a - b); + const n = nums.length; + for (let i = 1; i < n; i++) { + if (nums[i - 1] === nums[i]) { + return true; + } + } + return false; } diff --git a/solution/0200-0299/0217.Contains Duplicate/Solution2.cpp b/solution/0200-0299/0217.Contains Duplicate/Solution2.cpp new file mode 100644 index 0000000000000..6a7700278869b --- /dev/null +++ b/solution/0200-0299/0217.Contains Duplicate/Solution2.cpp @@ -0,0 +1,7 @@ +class Solution { +public: + bool containsDuplicate(vector& nums) { + unordered_set s(nums.begin(), nums.end()); + return s.size() < nums.size(); + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0217.Contains Duplicate/Solution2.go b/solution/0200-0299/0217.Contains Duplicate/Solution2.go new file mode 100644 index 0000000000000..9398bd9bc4a6b --- /dev/null +++ b/solution/0200-0299/0217.Contains Duplicate/Solution2.go @@ -0,0 +1,10 @@ +func containsDuplicate(nums []int) bool { + s := map[int]bool{} + for _, v := range nums { + if s[v] { + return true + } + s[v] = true + } + return false +} \ No newline at end of file diff --git a/solution/0200-0299/0217.Contains Duplicate/Solution2.java b/solution/0200-0299/0217.Contains Duplicate/Solution2.java new file mode 100644 index 0000000000000..eaea8517af8de --- /dev/null +++ b/solution/0200-0299/0217.Contains Duplicate/Solution2.java @@ -0,0 +1,11 @@ +class Solution { + public boolean containsDuplicate(int[] nums) { + Set s = new HashSet<>(); + for (int num : nums) { + if (!s.add(num)) { + return true; + } + } + return false; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0217.Contains Duplicate/Solution2.py b/solution/0200-0299/0217.Contains Duplicate/Solution2.py new file mode 100644 index 0000000000000..df5f85541cb0d --- /dev/null +++ b/solution/0200-0299/0217.Contains Duplicate/Solution2.py @@ -0,0 +1,3 @@ +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + return len(set(nums)) < len(nums) diff --git a/solution/0200-0299/0217.Contains Duplicate/Solution2.rs b/solution/0200-0299/0217.Contains Duplicate/Solution2.rs new file mode 100644 index 0000000000000..4cd30e955c03e --- /dev/null +++ b/solution/0200-0299/0217.Contains Duplicate/Solution2.rs @@ -0,0 +1,6 @@ +use std::collections::HashSet; +impl Solution { + pub fn contains_duplicate(nums: Vec) -> bool { + nums.iter().collect::>().len() != nums.len() + } +} diff --git a/solution/0200-0299/0217.Contains Duplicate/Solution2.ts b/solution/0200-0299/0217.Contains Duplicate/Solution2.ts new file mode 100644 index 0000000000000..33c799c32a6ac --- /dev/null +++ b/solution/0200-0299/0217.Contains Duplicate/Solution2.ts @@ -0,0 +1,3 @@ +function containsDuplicate(nums: number[]): boolean { + return new Set(nums).size !== nums.length; +} diff --git a/solution/0200-0299/0218.The Skyline Problem/Solution.cpp b/solution/0200-0299/0218.The Skyline Problem/Solution.cpp index 1e645f7e42886..640437c730511 100644 --- a/solution/0200-0299/0218.The Skyline Problem/Solution.cpp +++ b/solution/0200-0299/0218.The Skyline Problem/Solution.cpp @@ -33,4 +33,4 @@ class Solution { } return res; } -}; +}; \ No newline at end of file diff --git a/solution/0200-0299/0219.Contains Duplicate II/Solution.cs b/solution/0200-0299/0219.Contains Duplicate II/Solution.cs index 04ec7d863967a..51b42bf62b60b 100644 --- a/solution/0200-0299/0219.Contains Duplicate II/Solution.cs +++ b/solution/0200-0299/0219.Contains Duplicate II/Solution.cs @@ -9,4 +9,4 @@ public bool ContainsNearbyDuplicate(int[] nums, int k) { } return false; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0219.Contains Duplicate II/Solution.php b/solution/0200-0299/0219.Contains Duplicate II/Solution.php index 05102bd518d4d..c45e959b0bf19 100644 --- a/solution/0200-0299/0219.Contains Duplicate II/Solution.php +++ b/solution/0200-0299/0219.Contains Duplicate II/Solution.php @@ -15,4 +15,4 @@ function containsNearbyDuplicate($nums, $k) { } return false; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0220.Contains Duplicate III/Solution.cs b/solution/0200-0299/0220.Contains Duplicate III/Solution.cs index 2a6d8162526a6..ba19ab77fe15d 100644 --- a/solution/0200-0299/0220.Contains Duplicate III/Solution.cs +++ b/solution/0200-0299/0220.Contains Duplicate III/Solution.cs @@ -20,4 +20,4 @@ public bool ContainsNearbyAlmostDuplicate(int[] nums, int k, int t) { } return false; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0221.Maximal Square/Solution.cs b/solution/0200-0299/0221.Maximal Square/Solution.cs index 3a3374465539c..ba4f27dfdb01d 100644 --- a/solution/0200-0299/0221.Maximal Square/Solution.cs +++ b/solution/0200-0299/0221.Maximal Square/Solution.cs @@ -1,4 +1,4 @@ -public class Solution { +public class Solution { public int MaximalSquare(char[][] matrix) { int m = matrix.Length, n = matrix[0].Length; var dp = new int[m + 1, n + 1]; @@ -16,4 +16,4 @@ public int MaximalSquare(char[][] matrix) { } return mx * mx; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.cpp b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.cpp index f5e8b2b3c4da1..e92e935e770bb 100644 --- a/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.cpp +++ b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.cpp @@ -15,19 +15,6 @@ class Solution { if (!root) { return 0; } - int left = depth(root->left); - int right = depth(root->right); - if (left == right) { - return (1 << left) + countNodes(root->right); - } - return (1 << right) + countNodes(root->left); - } - - int depth(TreeNode* root) { - int d = 0; - for (; root; root = root->left) { - ++d; - } - return d; + return 1 + countNodes(root->left) + countNodes(root->right); } }; \ No newline at end of file diff --git a/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.cs b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.cs index 6dfe18a4c94e1..3100321868577 100644 --- a/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.cs +++ b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.cs @@ -1,4 +1,4 @@ -/** +/** * Definition for a binary tree node. * public class TreeNode { * public int val; @@ -16,19 +16,6 @@ public int CountNodes(TreeNode root) { if (root == null) { return 0; } - int left = depth(root.left); - int right = depth(root.right); - if (left == right) { - return (1 << left) + CountNodes(root.right); - } - return (1 << right) + CountNodes(root.left); - } - - private int depth(TreeNode root) { - int d = 0; - for (; root != null; root = root.left) { - ++d; - } - return d; + return 1 + CountNodes(root.left) + CountNodes(root.right); } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.go b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.go index ed5836dc2e69f..ce54473a4e19c 100644 --- a/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.go +++ b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.go @@ -10,16 +10,5 @@ func countNodes(root *TreeNode) int { if root == nil { return 0 } - left, right := depth(root.Left), depth(root.Right) - if left == right { - return (1 << left) + countNodes(root.Right) - } - return (1 << right) + countNodes(root.Left) -} - -func depth(root *TreeNode) (d int) { - for ; root != nil; root = root.Left { - d++ - } - return + return 1 + countNodes(root.Left) + countNodes(root.Right) } \ No newline at end of file diff --git a/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.java b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.java index 70a5b235766ee..0e399eb4c4cad 100644 --- a/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.java +++ b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.java @@ -18,19 +18,6 @@ public int countNodes(TreeNode root) { if (root == null) { return 0; } - int left = depth(root.left); - int right = depth(root.right); - if (left == right) { - return (1 << left) + countNodes(root.right); - } - return (1 << right) + countNodes(root.left); - } - - private int depth(TreeNode root) { - int d = 0; - for (; root != null; root = root.left) { - ++d; - } - return d; + return 1 + countNodes(root.left) + countNodes(root.right); } } \ No newline at end of file diff --git a/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.js b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.js index bfcfa46f05bb4..b322887613cce 100644 --- a/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.js +++ b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.js @@ -11,20 +11,8 @@ * @return {number} */ var countNodes = function (root) { - const depth = root => { - let d = 0; - for (; root; root = root.left) { - ++d; - } - return d; - }; if (!root) { return 0; } - const left = depth(root.left); - const right = depth(root.right); - if (left == right) { - return (1 << left) + countNodes(root.right); - } - return (1 << right) + countNodes(root.left); + return 1 + countNodes(root.left) + countNodes(root.right); }; diff --git a/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.py b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.py index 90c22faec1ecb..0a0809e0807d4 100644 --- a/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.py +++ b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution.py @@ -6,16 +6,6 @@ # self.right = right class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: - def depth(root): - d = 0 - while root: - d += 1 - root = root.left - return d - if root is None: return 0 - left, right = depth(root.left), depth(root.right) - if left == right: - return (1 << left) + self.countNodes(root.right) - return (1 << right) + self.countNodes(root.left) + return 1 + self.countNodes(root.left) + self.countNodes(root.right) diff --git a/solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.cpp b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.cpp new file mode 100644 index 0000000000000..f5e8b2b3c4da1 --- /dev/null +++ b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.cpp @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int countNodes(TreeNode* root) { + if (!root) { + return 0; + } + int left = depth(root->left); + int right = depth(root->right); + if (left == right) { + return (1 << left) + countNodes(root->right); + } + return (1 << right) + countNodes(root->left); + } + + int depth(TreeNode* root) { + int d = 0; + for (; root; root = root->left) { + ++d; + } + return d; + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.cs b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.cs new file mode 100644 index 0000000000000..53cfe780a0bcc --- /dev/null +++ b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.cs @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + public int CountNodes(TreeNode root) { + if (root == null) { + return 0; + } + int left = depth(root.left); + int right = depth(root.right); + if (left == right) { + return (1 << left) + CountNodes(root.right); + } + return (1 << right) + CountNodes(root.left); + } + + private int depth(TreeNode root) { + int d = 0; + for (; root != null; root = root.left) { + ++d; + } + return d; + } +} diff --git a/solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.go b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.go new file mode 100644 index 0000000000000..ed5836dc2e69f --- /dev/null +++ b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.go @@ -0,0 +1,25 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func countNodes(root *TreeNode) int { + if root == nil { + return 0 + } + left, right := depth(root.Left), depth(root.Right) + if left == right { + return (1 << left) + countNodes(root.Right) + } + return (1 << right) + countNodes(root.Left) +} + +func depth(root *TreeNode) (d int) { + for ; root != nil; root = root.Left { + d++ + } + return +} \ No newline at end of file diff --git a/solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.java b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.java new file mode 100644 index 0000000000000..70a5b235766ee --- /dev/null +++ b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.java @@ -0,0 +1,36 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int countNodes(TreeNode root) { + if (root == null) { + return 0; + } + int left = depth(root.left); + int right = depth(root.right); + if (left == right) { + return (1 << left) + countNodes(root.right); + } + return (1 << right) + countNodes(root.left); + } + + private int depth(TreeNode root) { + int d = 0; + for (; root != null; root = root.left) { + ++d; + } + return d; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.js b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.js new file mode 100644 index 0000000000000..bfcfa46f05bb4 --- /dev/null +++ b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.js @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var countNodes = function (root) { + const depth = root => { + let d = 0; + for (; root; root = root.left) { + ++d; + } + return d; + }; + if (!root) { + return 0; + } + const left = depth(root.left); + const right = depth(root.right); + if (left == right) { + return (1 << left) + countNodes(root.right); + } + return (1 << right) + countNodes(root.left); +}; diff --git a/solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.py b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.py new file mode 100644 index 0000000000000..90c22faec1ecb --- /dev/null +++ b/solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.py @@ -0,0 +1,21 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def countNodes(self, root: Optional[TreeNode]) -> int: + def depth(root): + d = 0 + while root: + d += 1 + root = root.left + return d + + if root is None: + return 0 + left, right = depth(root.left), depth(root.right) + if left == right: + return (1 << left) + self.countNodes(root.right) + return (1 << right) + self.countNodes(root.left) diff --git a/solution/0200-0299/0223.Rectangle Area/Solution.cs b/solution/0200-0299/0223.Rectangle Area/Solution.cs index 4e5561f3edf24..31cbacafd6e5f 100644 --- a/solution/0200-0299/0223.Rectangle Area/Solution.cs +++ b/solution/0200-0299/0223.Rectangle Area/Solution.cs @@ -1,4 +1,4 @@ -public class Solution { +public class Solution { public int ComputeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { int a = (ax2 - ax1) * (ay2 - ay1); int b = (bx2 - bx1) * (by2 - by1); @@ -6,4 +6,4 @@ public int ComputeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int int height = Math.Min(ay2, by2) - Math.Max(ay1, by1); return a + b - Math.Max(height, 0) * Math.Max(width, 0); } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0223.Rectangle Area/Solution.java b/solution/0200-0299/0223.Rectangle Area/Solution.java index 6625187e0a1c7..53bc6d2bd99f7 100644 --- a/solution/0200-0299/0223.Rectangle Area/Solution.java +++ b/solution/0200-0299/0223.Rectangle Area/Solution.java @@ -6,4 +6,4 @@ public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int int height = Math.min(ay2, by2) - Math.max(ay1, by1); return a + b - Math.max(height, 0) * Math.max(width, 0); } -} +} \ No newline at end of file diff --git a/solution/0200-0299/0224.Basic Calculator/Solution.cs b/solution/0200-0299/0224.Basic Calculator/Solution.cs index 2d9f929d159eb..778cef6e3c652 100644 --- a/solution/0200-0299/0224.Basic Calculator/Solution.cs +++ b/solution/0200-0299/0224.Basic Calculator/Solution.cs @@ -32,4 +32,4 @@ public int Calculate(string s) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0226.Invert Binary Tree/Solution2.cpp b/solution/0200-0299/0226.Invert Binary Tree/Solution2.cpp new file mode 100644 index 0000000000000..b38cbe84aa21a --- /dev/null +++ b/solution/0200-0299/0226.Invert Binary Tree/Solution2.cpp @@ -0,0 +1,24 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* invertTree(TreeNode* root) { + if (!root) { + return root; + } + TreeNode* l = invertTree(root->left); + TreeNode* r = invertTree(root->right); + root->left = r; + root->right = l; + return root; + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0226.Invert Binary Tree/Solution2.go b/solution/0200-0299/0226.Invert Binary Tree/Solution2.go new file mode 100644 index 0000000000000..cc5dd1fe6ddcf --- /dev/null +++ b/solution/0200-0299/0226.Invert Binary Tree/Solution2.go @@ -0,0 +1,16 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func invertTree(root *TreeNode) *TreeNode { + if root == nil { + return root + } + l, r := invertTree(root.Left), invertTree(root.Right) + root.Left, root.Right = r, l + return root +} \ No newline at end of file diff --git a/solution/0200-0299/0226.Invert Binary Tree/Solution2.java b/solution/0200-0299/0226.Invert Binary Tree/Solution2.java new file mode 100644 index 0000000000000..fd6036ec7a765 --- /dev/null +++ b/solution/0200-0299/0226.Invert Binary Tree/Solution2.java @@ -0,0 +1,27 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode invertTree(TreeNode root) { + if (root == null) { + return null; + } + TreeNode l = invertTree(root.left); + TreeNode r = invertTree(root.right); + root.left = r; + root.right = l; + return root; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0226.Invert Binary Tree/Solution2.js b/solution/0200-0299/0226.Invert Binary Tree/Solution2.js new file mode 100644 index 0000000000000..ab4248be39f48 --- /dev/null +++ b/solution/0200-0299/0226.Invert Binary Tree/Solution2.js @@ -0,0 +1,22 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {TreeNode} + */ +var invertTree = function (root) { + if (!root) { + return root; + } + const l = invertTree(root.left); + const r = invertTree(root.right); + root.left = r; + root.right = l; + return root; +}; diff --git a/solution/0200-0299/0226.Invert Binary Tree/Solution2.py b/solution/0200-0299/0226.Invert Binary Tree/Solution2.py new file mode 100644 index 0000000000000..4bf14d65fa36c --- /dev/null +++ b/solution/0200-0299/0226.Invert Binary Tree/Solution2.py @@ -0,0 +1,13 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + if root is None: + return None + l, r = self.invertTree(root.left), self.invertTree(root.right) + root.left, root.right = r, l + return root diff --git a/solution/0200-0299/0226.Invert Binary Tree/Solution2.ts b/solution/0200-0299/0226.Invert Binary Tree/Solution2.ts new file mode 100644 index 0000000000000..d87a5413b484a --- /dev/null +++ b/solution/0200-0299/0226.Invert Binary Tree/Solution2.ts @@ -0,0 +1,24 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function invertTree(root: TreeNode | null): TreeNode | null { + if (!root) { + return root; + } + const l = invertTree(root.left); + const r = invertTree(root.right); + root.left = r; + root.right = l; + return root; +} diff --git a/solution/0200-0299/0228.Summary Ranges/Solution.cs b/solution/0200-0299/0228.Summary Ranges/Solution.cs index 2c5803f7fe353..c1d93741d99e4 100644 --- a/solution/0200-0299/0228.Summary Ranges/Solution.cs +++ b/solution/0200-0299/0228.Summary Ranges/Solution.cs @@ -14,4 +14,4 @@ public IList SummaryRanges(int[] nums) { public string f(int[] nums, int i, int j) { return i == j ? nums[i].ToString() : string.Format("{0}->{1}", nums[i], nums[j]); } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0229.Majority Element II/Solution.cs b/solution/0200-0299/0229.Majority Element II/Solution.cs index 47fec4fb63ecd..c7e61c4c8a942 100644 --- a/solution/0200-0299/0229.Majority Element II/Solution.cs +++ b/solution/0200-0299/0229.Majority Element II/Solution.cs @@ -33,4 +33,4 @@ public IList MajorityElement(int[] nums) { ans.Add(m2); return ans.Where(m => nums.Count(n => n == m) > nums.Length / 3).ToList(); } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0229.Majority Element II/Solution.php b/solution/0200-0299/0229.Majority Element II/Solution.php index a77f2de8d86b1..eac27c0f1413c 100644 --- a/solution/0200-0299/0229.Majority Element II/Solution.php +++ b/solution/0200-0299/0229.Majority Element II/Solution.php @@ -14,4 +14,4 @@ function majorityElement($nums) { } return array_unique($rs); } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0230.Kth Smallest Element in a BST/Solution2.cpp b/solution/0200-0299/0230.Kth Smallest Element in a BST/Solution2.cpp new file mode 100644 index 0000000000000..8249eb097c9b4 --- /dev/null +++ b/solution/0200-0299/0230.Kth Smallest Element in a BST/Solution2.cpp @@ -0,0 +1,51 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class BST { +public: + BST(TreeNode* root) + : root(root) { + count(root); + } + + int kthSmallest(int k) { + TreeNode* node = root; + while (node) { + int v = !node->left ? 0 : cnt[node->left]; + if (v == k - 1) return node->val; + if (v < k - 1) { + node = node->right; + k -= (v + 1); + } else + node = node->left; + } + return 0; + } + +private: + TreeNode* root; + unordered_map cnt; + + int count(TreeNode* root) { + if (!root) return 0; + int n = 1 + count(root->left) + count(root->right); + cnt[root] = n; + return n; + } +}; + +class Solution { +public: + int kthSmallest(TreeNode* root, int k) { + BST bst(root); + return bst.kthSmallest(k); + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0230.Kth Smallest Element in a BST/Solution2.go b/solution/0200-0299/0230.Kth Smallest Element in a BST/Solution2.go new file mode 100644 index 0000000000000..f42ba492e51e4 --- /dev/null +++ b/solution/0200-0299/0230.Kth Smallest Element in a BST/Solution2.go @@ -0,0 +1,52 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +type BST struct { + cnt map[*TreeNode]int + root *TreeNode +} + +func newBST(root *TreeNode) *BST { + var count func(*TreeNode) int + cnt := map[*TreeNode]int{} + count = func(root *TreeNode) int { + if root == nil { + return 0 + } + n := 1 + count(root.Left) + count(root.Right) + cnt[root] = n + return n + } + count(root) + return &BST{cnt, root} +} + +func (bst *BST) kthSmallest(k int) int { + node := bst.root + for node != nil { + v := 0 + if node.Left != nil { + v = bst.cnt[node.Left] + } + if v == k-1 { + return node.Val + } + if v < k-1 { + k -= (v + 1) + node = node.Right + } else { + node = node.Left + } + } + return 0 +} + +func kthSmallest(root *TreeNode, k int) int { + bst := newBST(root) + return bst.kthSmallest(k) +} \ No newline at end of file diff --git a/solution/0200-0299/0230.Kth Smallest Element in a BST/Solution2.java b/solution/0200-0299/0230.Kth Smallest Element in a BST/Solution2.java new file mode 100644 index 0000000000000..93e5a47a839b4 --- /dev/null +++ b/solution/0200-0299/0230.Kth Smallest Element in a BST/Solution2.java @@ -0,0 +1,57 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int kthSmallest(TreeNode root, int k) { + BST bst = new BST(root); + return bst.kthSmallest(k); + } +} + +class BST { + private TreeNode root; + private Map cnt = new HashMap<>(); + + public BST(TreeNode root) { + this.root = root; + count(root); + } + + public int kthSmallest(int k) { + TreeNode node = root; + while (node != null) { + int v = node.left == null ? 0 : cnt.get(node.left); + if (v == k - 1) { + return node.val; + } + if (v < k - 1) { + node = node.right; + k -= (v + 1); + } else { + node = node.left; + } + } + return 0; + } + + private int count(TreeNode root) { + if (root == null) { + return 0; + } + int n = 1 + count(root.left) + count(root.right); + cnt.put(root, n); + return n; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0230.Kth Smallest Element in a BST/Solution2.py b/solution/0200-0299/0230.Kth Smallest Element in a BST/Solution2.py new file mode 100644 index 0000000000000..99950f716f141 --- /dev/null +++ b/solution/0200-0299/0230.Kth Smallest Element in a BST/Solution2.py @@ -0,0 +1,38 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right + + +class BST: + def __init__(self, root): + self.cnt = Counter() + self.root = root + self.count(root) + + def kthSmallest(self, k): + node = self.root + while node: + if self.cnt[node.left] == k - 1: + return node.val + if self.cnt[node.left] < k - 1: + k -= self.cnt[node.left] + 1 + node = node.right + else: + node = node.left + return 0 + + def count(self, root): + if root is None: + return 0 + n = 1 + self.count(root.left) + self.count(root.right) + self.cnt[root] = n + return n + + +class Solution: + def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: + bst = BST(root) + return bst.kthSmallest(k) diff --git a/solution/0200-0299/0231.Power of Two/Solution2.cpp b/solution/0200-0299/0231.Power of Two/Solution2.cpp new file mode 100644 index 0000000000000..96c3b686b27b8 --- /dev/null +++ b/solution/0200-0299/0231.Power of Two/Solution2.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + bool isPowerOfTwo(int n) { + return n > 0 && n == (n & (-n)); + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0231.Power of Two/Solution2.go b/solution/0200-0299/0231.Power of Two/Solution2.go new file mode 100644 index 0000000000000..844f64250af53 --- /dev/null +++ b/solution/0200-0299/0231.Power of Two/Solution2.go @@ -0,0 +1,3 @@ +func isPowerOfTwo(n int) bool { + return n > 0 && n == (n&(-n)) +} \ No newline at end of file diff --git a/solution/0200-0299/0231.Power of Two/Solution2.java b/solution/0200-0299/0231.Power of Two/Solution2.java new file mode 100644 index 0000000000000..054840fe4d0ef --- /dev/null +++ b/solution/0200-0299/0231.Power of Two/Solution2.java @@ -0,0 +1,5 @@ +class Solution { + public boolean isPowerOfTwo(int n) { + return n > 0 && n == (n & (-n)); + } +} \ No newline at end of file diff --git a/solution/0200-0299/0231.Power of Two/Solution2.js b/solution/0200-0299/0231.Power of Two/Solution2.js new file mode 100644 index 0000000000000..d0b7a66d9343c --- /dev/null +++ b/solution/0200-0299/0231.Power of Two/Solution2.js @@ -0,0 +1,7 @@ +/** + * @param {number} n + * @return {boolean} + */ +var isPowerOfTwo = function (n) { + return n > 0 && n == (n & -n); +}; diff --git a/solution/0200-0299/0231.Power of Two/Solution2.py b/solution/0200-0299/0231.Power of Two/Solution2.py new file mode 100644 index 0000000000000..328e4828ca906 --- /dev/null +++ b/solution/0200-0299/0231.Power of Two/Solution2.py @@ -0,0 +1,3 @@ +class Solution: + def isPowerOfTwo(self, n: int) -> bool: + return n > 0 and n == n & (-n) diff --git a/solution/0200-0299/0231.Power of Two/Solution2.ts b/solution/0200-0299/0231.Power of Two/Solution2.ts new file mode 100644 index 0000000000000..bfb580cec5184 --- /dev/null +++ b/solution/0200-0299/0231.Power of Two/Solution2.ts @@ -0,0 +1,3 @@ +function isPowerOfTwo(n: number): boolean { + return n > 0 && (n & (n - 1)) === 0; +} diff --git a/solution/0200-0299/0233.Number of Digit One/Solution.cs b/solution/0200-0299/0233.Number of Digit One/Solution.cs index 92638269267df..99e08f7131d09 100644 --- a/solution/0200-0299/0233.Number of Digit One/Solution.cs +++ b/solution/0200-0299/0233.Number of Digit One/Solution.cs @@ -4,7 +4,7 @@ public int CountDigitOne(int n) { if (n < 10) return 1; return CountDigitOne(n / 10 - 1) * 10 + n / 10 + CountDigitOneOfN(n / 10) * (n % 10 + 1) + (n % 10 >= 1 ? 1 : 0); } - + private int CountDigitOneOfN(int n) { var count = 0; while (n > 0) @@ -14,4 +14,4 @@ private int CountDigitOneOfN(int n) { } return count; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0234.Palindrome Linked List/Solution.cs b/solution/0200-0299/0234.Palindrome Linked List/Solution.cs index a3e4a3851d7c1..ac22b6c89e0a0 100644 --- a/solution/0200-0299/0234.Palindrome Linked List/Solution.cs +++ b/solution/0200-0299/0234.Palindrome Linked List/Solution.cs @@ -35,4 +35,4 @@ public bool IsPalindrome(ListNode head) { } return true; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/Solution2.cpp b/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/Solution2.cpp new file mode 100644 index 0000000000000..7352365e3cc19 --- /dev/null +++ b/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/Solution2.cpp @@ -0,0 +1,22 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ + +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if (root->val < min(p->val, q->val)) { + return lowestCommonAncestor(root->right, p, q); + } + if (root->val > max(p->val, q->val)) { + return lowestCommonAncestor(root->left, p, q); + } + return root; + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/Solution2.go b/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/Solution2.go new file mode 100644 index 0000000000000..d662a5e3317ec --- /dev/null +++ b/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/Solution2.go @@ -0,0 +1,18 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { + if root.Val < p.Val && root.Val < q.Val { + return lowestCommonAncestor(root.Right, p, q) + } + if root.Val > p.Val && root.Val > q.Val { + return lowestCommonAncestor(root.Left, p, q) + } + return root +} \ No newline at end of file diff --git a/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/Solution2.java b/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/Solution2.java new file mode 100644 index 0000000000000..3dac1cd232d08 --- /dev/null +++ b/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/Solution2.java @@ -0,0 +1,21 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root.val < Math.min(p.val, q.val)) { + return lowestCommonAncestor(root.right, p, q); + } + if (root.val > Math.max(p.val, q.val)) { + return lowestCommonAncestor(root.left, p, q); + } + return root; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/Solution2.py b/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/Solution2.py new file mode 100644 index 0000000000000..21cf69a4f7812 --- /dev/null +++ b/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/Solution2.py @@ -0,0 +1,17 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution: + def lowestCommonAncestor( + self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode' + ) -> 'TreeNode': + if root.val < min(p.val, q.val): + return self.lowestCommonAncestor(root.right, p, q) + if root.val > max(p.val, q.val): + return self.lowestCommonAncestor(root.left, p, q) + return root diff --git a/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/Solution2.ts b/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/Solution2.ts new file mode 100644 index 0000000000000..767340ae6f213 --- /dev/null +++ b/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/Solution2.ts @@ -0,0 +1,23 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function lowestCommonAncestor( + root: TreeNode | null, + p: TreeNode | null, + q: TreeNode | null, +): TreeNode | null { + if (root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q); + if (root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q); + return root; +} diff --git a/solution/0200-0299/0237.Delete Node in a Linked List/Solution.cs b/solution/0200-0299/0237.Delete Node in a Linked List/Solution.cs new file mode 100644 index 0000000000000..0a87c4dac46ad --- /dev/null +++ b/solution/0200-0299/0237.Delete Node in a Linked List/Solution.cs @@ -0,0 +1,14 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int x) { val = x; } + * } + */ +public class Solution { + public void DeleteNode(ListNode node) { + node.val = node.next.val; + node.next = node.next.next; + } +} diff --git a/solution/0200-0299/0238.Product of Array Except Self/Solution.cpp b/solution/0200-0299/0238.Product of Array Except Self/Solution.cpp index 0146a5837782c..2bf63be6e53dc 100644 --- a/solution/0200-0299/0238.Product of Array Except Self/Solution.cpp +++ b/solution/0200-0299/0238.Product of Array Except Self/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - vector productExceptSelf(vector& nums) { - int n = nums.size(); - vector ans(n); - for (int i = 0, left = 1; i < n; ++i) { - ans[i] = left; - left *= nums[i]; - } - for (int i = n - 1, right = 1; ~i; --i) { - ans[i] *= right; - right *= nums[i]; - } - return ans; - } +class Solution { +public: + vector productExceptSelf(vector& nums) { + int n = nums.size(); + vector ans(n); + for (int i = 0, left = 1; i < n; ++i) { + ans[i] = left; + left *= nums[i]; + } + for (int i = n - 1, right = 1; ~i; --i) { + ans[i] *= right; + right *= nums[i]; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0200-0299/0238.Product of Array Except Self/Solution.cs b/solution/0200-0299/0238.Product of Array Except Self/Solution.cs index 8fab12a56e6a0..2fbe063c31545 100644 --- a/solution/0200-0299/0238.Product of Array Except Self/Solution.cs +++ b/solution/0200-0299/0238.Product of Array Except Self/Solution.cs @@ -12,4 +12,4 @@ public int[] ProductExceptSelf(int[] nums) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0238.Product of Array Except Self/Solution.java b/solution/0200-0299/0238.Product of Array Except Self/Solution.java index 9db0680f84ac7..743103195804d 100644 --- a/solution/0200-0299/0238.Product of Array Except Self/Solution.java +++ b/solution/0200-0299/0238.Product of Array Except Self/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public int[] productExceptSelf(int[] nums) { - int n = nums.length; - int[] ans = new int[n]; - for (int i = 0, left = 1; i < n; ++i) { - ans[i] = left; - left *= nums[i]; - } - for (int i = n - 1, right = 1; i >= 0; --i) { - ans[i] *= right; - right *= nums[i]; - } - return ans; - } +class Solution { + public int[] productExceptSelf(int[] nums) { + int n = nums.length; + int[] ans = new int[n]; + for (int i = 0, left = 1; i < n; ++i) { + ans[i] = left; + left *= nums[i]; + } + for (int i = n - 1, right = 1; i >= 0; --i) { + ans[i] *= right; + right *= nums[i]; + } + return ans; + } } \ No newline at end of file diff --git a/solution/0200-0299/0238.Product of Array Except Self/Solution.php b/solution/0200-0299/0238.Product of Array Except Self/Solution.php index cc9eb92603798..db4bcdf26e658 100644 --- a/solution/0200-0299/0238.Product of Array Except Self/Solution.php +++ b/solution/0200-0299/0238.Product of Array Except Self/Solution.php @@ -16,4 +16,4 @@ function productExceptSelf($nums) { } return $ans; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0238.Product of Array Except Self/Solution.py b/solution/0200-0299/0238.Product of Array Except Self/Solution.py index 6543affb07483..7cbe17500fbc8 100644 --- a/solution/0200-0299/0238.Product of Array Except Self/Solution.py +++ b/solution/0200-0299/0238.Product of Array Except Self/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def productExceptSelf(self, nums: List[int]) -> List[int]: - n = len(nums) - ans = [0] * n - left = right = 1 - for i, x in enumerate(nums): - ans[i] = left - left *= x - for i in range(n - 1, -1, -1): - ans[i] *= right - right *= nums[i] - return ans +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + n = len(nums) + ans = [0] * n + left = right = 1 + for i, x in enumerate(nums): + ans[i] = left + left *= x + for i in range(n - 1, -1, -1): + ans[i] *= right + right *= nums[i] + return ans diff --git a/solution/0200-0299/0238.Product of Array Except Self/Solution2.ts b/solution/0200-0299/0238.Product of Array Except Self/Solution2.ts new file mode 100644 index 0000000000000..312ea12c153ab --- /dev/null +++ b/solution/0200-0299/0238.Product of Array Except Self/Solution2.ts @@ -0,0 +1,3 @@ +function productExceptSelf(nums: number[]): number[] { + return nums.map((_, i) => nums.reduce((pre, val, j) => pre * (i === j ? 1 : val), 1)); +} diff --git a/solution/0200-0299/0239.Sliding Window Maximum/Solution.cpp b/solution/0200-0299/0239.Sliding Window Maximum/Solution.cpp index 0d3f7865cf7a8..68d456193d462 100644 --- a/solution/0200-0299/0239.Sliding Window Maximum/Solution.cpp +++ b/solution/0200-0299/0239.Sliding Window Maximum/Solution.cpp @@ -1,19 +1,18 @@ class Solution { public: vector maxSlidingWindow(vector& nums, int k) { - deque q; + priority_queue> q; + int n = nums.size(); + for (int i = 0; i < k - 1; ++i) { + q.push({nums[i], -i}); + } vector ans; - for (int i = 0; i < nums.size(); ++i) { - if (!q.empty() && i - k + 1 > q.front()) { - q.pop_front(); - } - while (!q.empty() && nums[q.back()] <= nums[i]) { - q.pop_back(); - } - q.push_back(i); - if (i >= k - 1) { - ans.emplace_back(nums[q.front()]); + for (int i = k - 1; i < n; ++i) { + q.push({nums[i], -i}); + while (-q.top().second <= i - k) { + q.pop(); } + ans.emplace_back(q.top().first); } return ans; } diff --git a/solution/0200-0299/0239.Sliding Window Maximum/Solution.go b/solution/0200-0299/0239.Sliding Window Maximum/Solution.go index cd8b8d3991bbc..84ce201c6191a 100644 --- a/solution/0200-0299/0239.Sliding Window Maximum/Solution.go +++ b/solution/0200-0299/0239.Sliding Window Maximum/Solution.go @@ -1,16 +1,27 @@ func maxSlidingWindow(nums []int, k int) (ans []int) { - q := []int{} - for i, v := range nums { - if len(q) > 0 && i-k+1 > q[0] { - q = q[1:] - } - for len(q) > 0 && nums[q[len(q)-1]] <= v { - q = q[:len(q)-1] - } - q = append(q, i) - if i >= k-1 { - ans = append(ans, nums[q[0]]) + q := hp{} + for i, v := range nums[:k-1] { + heap.Push(&q, pair{v, i}) + } + for i := k - 1; i < len(nums); i++ { + heap.Push(&q, pair{nums[i], i}) + for q[0].i <= i-k { + heap.Pop(&q) } + ans = append(ans, q[0].v) } - return ans -} \ No newline at end of file + return +} + +type pair struct{ v, i int } + +type hp []pair + +func (h hp) Len() int { return len(h) } +func (h hp) Less(i, j int) bool { + a, b := h[i], h[j] + return a.v > b.v || (a.v == b.v && i < j) +} +func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } +func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } \ No newline at end of file diff --git a/solution/0200-0299/0239.Sliding Window Maximum/Solution.java b/solution/0200-0299/0239.Sliding Window Maximum/Solution.java index 7ffd8cb0ccbb3..019d3bc6a4937 100644 --- a/solution/0200-0299/0239.Sliding Window Maximum/Solution.java +++ b/solution/0200-0299/0239.Sliding Window Maximum/Solution.java @@ -1,19 +1,18 @@ class Solution { public int[] maxSlidingWindow(int[] nums, int k) { + PriorityQueue q + = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]); int n = nums.length; + for (int i = 0; i < k - 1; ++i) { + q.offer(new int[] {nums[i], i}); + } int[] ans = new int[n - k + 1]; - Deque q = new ArrayDeque<>(); - for (int i = 0, j = 0; i < n; ++i) { - if (!q.isEmpty() && i - k + 1 > q.peekFirst()) { - q.pollFirst(); - } - while (!q.isEmpty() && nums[q.peekLast()] <= nums[i]) { - q.pollLast(); - } - q.offer(i); - if (i >= k - 1) { - ans[j++] = nums[q.peekFirst()]; + for (int i = k - 1, j = 0; i < n; ++i) { + q.offer(new int[] {nums[i], i}); + while (q.peek()[1] <= i - k) { + q.poll(); } + ans[j++] = q.peek()[0]; } return ans; } diff --git a/solution/0200-0299/0239.Sliding Window Maximum/Solution.py b/solution/0200-0299/0239.Sliding Window Maximum/Solution.py index a56c12edce31f..08dea6fd15ea5 100644 --- a/solution/0200-0299/0239.Sliding Window Maximum/Solution.py +++ b/solution/0200-0299/0239.Sliding Window Maximum/Solution.py @@ -1,13 +1,11 @@ class Solution: def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: - q = deque() + q = [(-v, i) for i, v in enumerate(nums[: k - 1])] + heapify(q) ans = [] - for i, v in enumerate(nums): - if q and i - k + 1 > q[0]: - q.popleft() - while q and nums[q[-1]] <= v: - q.pop() - q.append(i) - if i >= k - 1: - ans.append(nums[q[0]]) + for i in range(k - 1, len(nums)): + heappush(q, (-nums[i], i)) + while q[0][1] <= i - k: + heappop(q) + ans.append(-q[0][0]) return ans diff --git a/solution/0200-0299/0239.Sliding Window Maximum/Solution2.cpp b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.cpp new file mode 100644 index 0000000000000..0d3f7865cf7a8 --- /dev/null +++ b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + vector maxSlidingWindow(vector& nums, int k) { + deque q; + vector ans; + for (int i = 0; i < nums.size(); ++i) { + if (!q.empty() && i - k + 1 > q.front()) { + q.pop_front(); + } + while (!q.empty() && nums[q.back()] <= nums[i]) { + q.pop_back(); + } + q.push_back(i); + if (i >= k - 1) { + ans.emplace_back(nums[q.front()]); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0239.Sliding Window Maximum/Solution2.go b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.go new file mode 100644 index 0000000000000..cd8b8d3991bbc --- /dev/null +++ b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.go @@ -0,0 +1,16 @@ +func maxSlidingWindow(nums []int, k int) (ans []int) { + q := []int{} + for i, v := range nums { + if len(q) > 0 && i-k+1 > q[0] { + q = q[1:] + } + for len(q) > 0 && nums[q[len(q)-1]] <= v { + q = q[:len(q)-1] + } + q = append(q, i) + if i >= k-1 { + ans = append(ans, nums[q[0]]) + } + } + return ans +} \ No newline at end of file diff --git a/solution/0200-0299/0239.Sliding Window Maximum/Solution2.java b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.java new file mode 100644 index 0000000000000..7ffd8cb0ccbb3 --- /dev/null +++ b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.java @@ -0,0 +1,20 @@ +class Solution { + public int[] maxSlidingWindow(int[] nums, int k) { + int n = nums.length; + int[] ans = new int[n - k + 1]; + Deque q = new ArrayDeque<>(); + for (int i = 0, j = 0; i < n; ++i) { + if (!q.isEmpty() && i - k + 1 > q.peekFirst()) { + q.pollFirst(); + } + while (!q.isEmpty() && nums[q.peekLast()] <= nums[i]) { + q.pollLast(); + } + q.offer(i); + if (i >= k - 1) { + ans[j++] = nums[q.peekFirst()]; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0239.Sliding Window Maximum/Solution2.py b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.py new file mode 100644 index 0000000000000..a56c12edce31f --- /dev/null +++ b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: + q = deque() + ans = [] + for i, v in enumerate(nums): + if q and i - k + 1 > q[0]: + q.popleft() + while q and nums[q[-1]] <= v: + q.pop() + q.append(i) + if i >= k - 1: + ans.append(nums[q[0]]) + return ans diff --git a/solution/0200-0299/0240.Search a 2D Matrix II/Solution.cpp b/solution/0200-0299/0240.Search a 2D Matrix II/Solution.cpp index e33f992add84e..bcbfc5d984f71 100644 --- a/solution/0200-0299/0240.Search a 2D Matrix II/Solution.cpp +++ b/solution/0200-0299/0240.Search a 2D Matrix II/Solution.cpp @@ -1,14 +1,11 @@ class Solution { public: bool searchMatrix(vector>& matrix, int target) { - int m = matrix.size(), n = matrix[0].size(); - int i = m - 1, j = 0; - while (i >= 0 && j < n) { - if (matrix[i][j] == target) return true; - if (matrix[i][j] > target) - --i; - else - ++j; + for (auto& row : matrix) { + int j = lower_bound(row.begin(), row.end(), target) - row.begin(); + if (j < matrix[0].size() && row[j] == target) { + return true; + } } return false; } diff --git a/solution/0200-0299/0240.Search a 2D Matrix II/Solution.cs b/solution/0200-0299/0240.Search a 2D Matrix II/Solution.cs index 9721f3b7d3f25..c3be37795c064 100644 --- a/solution/0200-0299/0240.Search a 2D Matrix II/Solution.cs +++ b/solution/0200-0299/0240.Search a 2D Matrix II/Solution.cs @@ -1,22 +1,11 @@ public class Solution { public bool SearchMatrix(int[][] matrix, int target) { - int m = matrix.Length, n = matrix[0].Length; - int i = m - 1, j = 0; - while (i >= 0 && j < n) - { - if (matrix[i][j] == target) - { + foreach (int[] row in matrix) { + int j = Array.BinarySearch(row, target); + if (j >= 0) { return true; } - if (matrix[i][j] > target) - { - --i; - } - else - { - ++j; - } } return false; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0240.Search a 2D Matrix II/Solution.go b/solution/0200-0299/0240.Search a 2D Matrix II/Solution.go index 88e40fc7348c0..4e859676472ee 100644 --- a/solution/0200-0299/0240.Search a 2D Matrix II/Solution.go +++ b/solution/0200-0299/0240.Search a 2D Matrix II/Solution.go @@ -1,15 +1,9 @@ func searchMatrix(matrix [][]int, target int) bool { - m, n := len(matrix), len(matrix[0]) - i, j := m-1, 0 - for i >= 0 && j < n { - if matrix[i][j] == target { + for _, row := range matrix { + j := sort.SearchInts(row, target) + if j < len(matrix[0]) && row[j] == target { return true } - if matrix[i][j] > target { - i-- - } else { - j++ - } } return false } \ No newline at end of file diff --git a/solution/0200-0299/0240.Search a 2D Matrix II/Solution.java b/solution/0200-0299/0240.Search a 2D Matrix II/Solution.java index 40b7622c79c42..7bffd3cea62e0 100644 --- a/solution/0200-0299/0240.Search a 2D Matrix II/Solution.java +++ b/solution/0200-0299/0240.Search a 2D Matrix II/Solution.java @@ -1,16 +1,10 @@ class Solution { public boolean searchMatrix(int[][] matrix, int target) { - int m = matrix.length, n = matrix[0].length; - int i = m - 1, j = 0; - while (i >= 0 && j < n) { - if (matrix[i][j] == target) { + for (var row : matrix) { + int j = Arrays.binarySearch(row, target); + if (j >= 0) { return true; } - if (matrix[i][j] > target) { - --i; - } else { - ++j; - } } return false; } diff --git a/solution/0200-0299/0240.Search a 2D Matrix II/Solution.py b/solution/0200-0299/0240.Search a 2D Matrix II/Solution.py index 08bd1ef8378c3..03ddb3ec0f2cb 100644 --- a/solution/0200-0299/0240.Search a 2D Matrix II/Solution.py +++ b/solution/0200-0299/0240.Search a 2D Matrix II/Solution.py @@ -1,12 +1,7 @@ class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: - m, n = len(matrix), len(matrix[0]) - i, j = m - 1, 0 - while i >= 0 and j < n: - if matrix[i][j] == target: + for row in matrix: + j = bisect_left(row, target) + if j < len(matrix[0]) and row[j] == target: return True - if matrix[i][j] > target: - i -= 1 - else: - j += 1 return False diff --git a/solution/0200-0299/0240.Search a 2D Matrix II/Solution.ts b/solution/0200-0299/0240.Search a 2D Matrix II/Solution.ts index c0bc191e5e44e..bf1cea5bb060b 100644 --- a/solution/0200-0299/0240.Search a 2D Matrix II/Solution.ts +++ b/solution/0200-0299/0240.Search a 2D Matrix II/Solution.ts @@ -1,15 +1,18 @@ function searchMatrix(matrix: number[][], target: number): boolean { - let m = matrix.length, - n = matrix[0].length; - let i = m - 1, - j = 0; - while (i >= 0 && j < n) { - let cur = matrix[i][j]; - if (cur == target) return true; - if (cur > target) { - --i; - } else { - ++j; + const n = matrix[0].length; + for (const row of matrix) { + let left = 0, + right = n; + while (left < right) { + const mid = (left + right) >> 1; + if (row[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + if (left != n && row[left] == target) { + return true; } } return false; diff --git a/solution/0200-0299/0240.Search a 2D Matrix II/Solution2.cpp b/solution/0200-0299/0240.Search a 2D Matrix II/Solution2.cpp new file mode 100644 index 0000000000000..581e4d79c39ce --- /dev/null +++ b/solution/0200-0299/0240.Search a 2D Matrix II/Solution2.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + int m = matrix.size(), n = matrix[0].size(); + int i = m - 1, j = 0; + while (i >= 0 && j < n) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0240.Search a 2D Matrix II/Solution2.cs b/solution/0200-0299/0240.Search a 2D Matrix II/Solution2.cs new file mode 100644 index 0000000000000..784680c70bd1d --- /dev/null +++ b/solution/0200-0299/0240.Search a 2D Matrix II/Solution2.cs @@ -0,0 +1,17 @@ +public class Solution { + public bool SearchMatrix(int[][] matrix, int target) { + int m = matrix.Length, n = matrix[0].Length; + int i = m - 1, j = 0; + while (i >= 0 && j < n) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; + } +} diff --git a/solution/0200-0299/0240.Search a 2D Matrix II/Solution2.go b/solution/0200-0299/0240.Search a 2D Matrix II/Solution2.go new file mode 100644 index 0000000000000..88e40fc7348c0 --- /dev/null +++ b/solution/0200-0299/0240.Search a 2D Matrix II/Solution2.go @@ -0,0 +1,15 @@ +func searchMatrix(matrix [][]int, target int) bool { + m, n := len(matrix), len(matrix[0]) + i, j := m-1, 0 + for i >= 0 && j < n { + if matrix[i][j] == target { + return true + } + if matrix[i][j] > target { + i-- + } else { + j++ + } + } + return false +} \ No newline at end of file diff --git a/solution/0200-0299/0240.Search a 2D Matrix II/Solution2.java b/solution/0200-0299/0240.Search a 2D Matrix II/Solution2.java new file mode 100644 index 0000000000000..40b7622c79c42 --- /dev/null +++ b/solution/0200-0299/0240.Search a 2D Matrix II/Solution2.java @@ -0,0 +1,17 @@ +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + int m = matrix.length, n = matrix[0].length; + int i = m - 1, j = 0; + while (i >= 0 && j < n) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0240.Search a 2D Matrix II/Solution2.py b/solution/0200-0299/0240.Search a 2D Matrix II/Solution2.py new file mode 100644 index 0000000000000..08bd1ef8378c3 --- /dev/null +++ b/solution/0200-0299/0240.Search a 2D Matrix II/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + m, n = len(matrix), len(matrix[0]) + i, j = m - 1, 0 + while i >= 0 and j < n: + if matrix[i][j] == target: + return True + if matrix[i][j] > target: + i -= 1 + else: + j += 1 + return False diff --git a/solution/0200-0299/0240.Search a 2D Matrix II/Solution2.ts b/solution/0200-0299/0240.Search a 2D Matrix II/Solution2.ts new file mode 100644 index 0000000000000..c0bc191e5e44e --- /dev/null +++ b/solution/0200-0299/0240.Search a 2D Matrix II/Solution2.ts @@ -0,0 +1,16 @@ +function searchMatrix(matrix: number[][], target: number): boolean { + let m = matrix.length, + n = matrix[0].length; + let i = m - 1, + j = 0; + while (i >= 0 && j < n) { + let cur = matrix[i][j]; + if (cur == target) return true; + if (cur > target) { + --i; + } else { + ++j; + } + } + return false; +} diff --git a/solution/0200-0299/0242.Valid Anagram/Solution.c b/solution/0200-0299/0242.Valid Anagram/Solution.c index c587839b70b95..afd8f6c275a85 100644 --- a/solution/0200-0299/0242.Valid Anagram/Solution.c +++ b/solution/0200-0299/0242.Valid Anagram/Solution.c @@ -1,18 +1,14 @@ +int cmp(const void* a, const void* b) { + return *(char*) a - *(char*) b; +} + bool isAnagram(char* s, char* t) { int n = strlen(s); int m = strlen(t); if (n != m) { return 0; } - int count[26] = {0}; - for (int i = 0; i < n; i++) { - count[s[i] - 'a']++; - count[t[i] - 'a']--; - } - for (int i = 0; i < 26; i++) { - if (count[i]) { - return 0; - } - } - return 1; -} + qsort(s, n, sizeof(char), cmp); + qsort(t, n, sizeof(char), cmp); + return !strcmp(s, t); +} \ No newline at end of file diff --git a/solution/0200-0299/0242.Valid Anagram/Solution.cs b/solution/0200-0299/0242.Valid Anagram/Solution.cs index 6cc4edf02f36b..c547deca9ccc4 100644 --- a/solution/0200-0299/0242.Valid Anagram/Solution.cs +++ b/solution/0200-0299/0242.Valid Anagram/Solution.cs @@ -10,4 +10,4 @@ public bool IsAnagram(string s, string t) { } return cnt.All(x => x == 0); } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0242.Valid Anagram/Solution.rs b/solution/0200-0299/0242.Valid Anagram/Solution.rs index 67c3d83f9db13..7ac53d2de6105 100644 --- a/solution/0200-0299/0242.Valid Anagram/Solution.rs +++ b/solution/0200-0299/0242.Valid Anagram/Solution.rs @@ -5,12 +5,15 @@ impl Solution { if n != m { return false; } - let (s, t) = (s.as_bytes(), t.as_bytes()); - let mut count = [0; 26]; + let mut s = s.chars().collect::>(); + let mut t = t.chars().collect::>(); + s.sort(); + t.sort(); for i in 0..n { - count[(s[i] - b'a') as usize] += 1; - count[(t[i] - b'a') as usize] -= 1; + if s[i] != t[i] { + return false; + } } - count.iter().all(|&c| c == 0) + true } } diff --git a/solution/0200-0299/0242.Valid Anagram/Solution2.c b/solution/0200-0299/0242.Valid Anagram/Solution2.c new file mode 100644 index 0000000000000..5729dc2676426 --- /dev/null +++ b/solution/0200-0299/0242.Valid Anagram/Solution2.c @@ -0,0 +1,18 @@ +bool isAnagram(char* s, char* t) { + int n = strlen(s); + int m = strlen(t); + if (n != m) { + return 0; + } + int count[26] = {0}; + for (int i = 0; i < n; i++) { + count[s[i] - 'a']++; + count[t[i] - 'a']--; + } + for (int i = 0; i < 26; i++) { + if (count[i]) { + return 0; + } + } + return 1; +} \ No newline at end of file diff --git a/solution/0200-0299/0242.Valid Anagram/Solution2.py b/solution/0200-0299/0242.Valid Anagram/Solution2.py new file mode 100644 index 0000000000000..29ef749394226 --- /dev/null +++ b/solution/0200-0299/0242.Valid Anagram/Solution2.py @@ -0,0 +1,3 @@ +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + return Counter(s) == Counter(t) diff --git a/solution/0200-0299/0242.Valid Anagram/Solution2.rs b/solution/0200-0299/0242.Valid Anagram/Solution2.rs new file mode 100644 index 0000000000000..67c3d83f9db13 --- /dev/null +++ b/solution/0200-0299/0242.Valid Anagram/Solution2.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn is_anagram(s: String, t: String) -> bool { + let n = s.len(); + let m = t.len(); + if n != m { + return false; + } + let (s, t) = (s.as_bytes(), t.as_bytes()); + let mut count = [0; 26]; + for i in 0..n { + count[(s[i] - b'a') as usize] += 1; + count[(t[i] - b'a') as usize] -= 1; + } + count.iter().all(|&c| c == 0) + } +} diff --git a/solution/0200-0299/0256.Paint House/Solution.cpp b/solution/0200-0299/0256.Paint House/Solution.cpp index 6fe98738d9949..3044d747236a6 100644 --- a/solution/0200-0299/0256.Paint House/Solution.cpp +++ b/solution/0200-0299/0256.Paint House/Solution.cpp @@ -10,4 +10,4 @@ class Solution { } return min(r, min(g, b)); } -}; +}; \ No newline at end of file diff --git a/solution/0200-0299/0256.Paint House/Solution.java b/solution/0200-0299/0256.Paint House/Solution.java index ae3818897c538..880acb4df9fea 100644 --- a/solution/0200-0299/0256.Paint House/Solution.java +++ b/solution/0200-0299/0256.Paint House/Solution.java @@ -9,4 +9,4 @@ public int minCost(int[][] costs) { } return Math.min(r, Math.min(g, b)); } -} +} \ No newline at end of file diff --git a/solution/0200-0299/0257.Binary Tree Paths/Solution.cpp b/solution/0200-0299/0257.Binary Tree Paths/Solution.cpp index ec432c3233f55..ba119ef84a687 100644 --- a/solution/0200-0299/0257.Binary Tree Paths/Solution.cpp +++ b/solution/0200-0299/0257.Binary Tree Paths/Solution.cpp @@ -1,44 +1,44 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - vector binaryTreePaths(TreeNode* root) { - vector ans; - vector t; - function dfs = [&](TreeNode* root) { - if (!root) { - return; - } - t.push_back(to_string(root->val)); - if (!root->left && !root->right) { - ans.push_back(join(t)); - } else { - dfs(root->left); - dfs(root->right); - } - t.pop_back(); - }; - dfs(root); - return ans; - } - - string join(vector& t, string sep = "->") { - string ans; - for (int i = 0; i < t.size(); ++i) { - if (i > 0) { - ans += sep; - } - ans += t[i]; - } - return ans; - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector binaryTreePaths(TreeNode* root) { + vector ans; + vector t; + function dfs = [&](TreeNode* root) { + if (!root) { + return; + } + t.push_back(to_string(root->val)); + if (!root->left && !root->right) { + ans.push_back(join(t)); + } else { + dfs(root->left); + dfs(root->right); + } + t.pop_back(); + }; + dfs(root); + return ans; + } + + string join(vector& t, string sep = "->") { + string ans; + for (int i = 0; i < t.size(); ++i) { + if (i > 0) { + ans += sep; + } + ans += t[i]; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0200-0299/0257.Binary Tree Paths/Solution.java b/solution/0200-0299/0257.Binary Tree Paths/Solution.java index 8c9d4611cb15a..0c81fbc992a8b 100644 --- a/solution/0200-0299/0257.Binary Tree Paths/Solution.java +++ b/solution/0200-0299/0257.Binary Tree Paths/Solution.java @@ -1,38 +1,38 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private List ans = new ArrayList<>(); - private List t = new ArrayList<>(); - - public List binaryTreePaths(TreeNode root) { - dfs(root); - return ans; - } - - private void dfs(TreeNode root) { - if (root == null) { - return; - } - t.add(root.val + ""); - if (root.left == null && root.right == null) { - ans.add(String.join("->", t)); - } else { - dfs(root.left); - dfs(root.right); - } - t.remove(t.size() - 1); - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private List ans = new ArrayList<>(); + private List t = new ArrayList<>(); + + public List binaryTreePaths(TreeNode root) { + dfs(root); + return ans; + } + + private void dfs(TreeNode root) { + if (root == null) { + return; + } + t.add(root.val + ""); + if (root.left == null && root.right == null) { + ans.add(String.join("->", t)); + } else { + dfs(root.left); + dfs(root.right); + } + t.remove(t.size() - 1); + } } \ No newline at end of file diff --git a/solution/0200-0299/0257.Binary Tree Paths/Solution.py b/solution/0200-0299/0257.Binary Tree Paths/Solution.py index 312c5e43b71a5..851920a5ba158 100644 --- a/solution/0200-0299/0257.Binary Tree Paths/Solution.py +++ b/solution/0200-0299/0257.Binary Tree Paths/Solution.py @@ -1,23 +1,23 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]: - def dfs(root: Optional[TreeNode]): - if root is None: - return - t.append(str(root.val)) - if root.left is None and root.right is None: - ans.append("->".join(t)) - else: - dfs(root.left) - dfs(root.right) - t.pop() - - ans = [] - t = [] - dfs(root) - return ans +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]: + def dfs(root: Optional[TreeNode]): + if root is None: + return + t.append(str(root.val)) + if root.left is None and root.right is None: + ans.append("->".join(t)) + else: + dfs(root.left) + dfs(root.right) + t.pop() + + ans = [] + t = [] + dfs(root) + return ans diff --git a/solution/0200-0299/0258.Add Digits/Solution.rs b/solution/0200-0299/0258.Add Digits/Solution.rs index dcd23f532bf85..5f180f1bd5c94 100644 --- a/solution/0200-0299/0258.Add Digits/Solution.rs +++ b/solution/0200-0299/0258.Add Digits/Solution.rs @@ -1,5 +1,14 @@ impl Solution { - pub fn add_digits(mut num: i32) -> i32 { - ((num - 1) % 9) + 1 + pub fn add_digits(num: i32) -> i32 { + if num < 10 { + return num; + } + Self::add_digits( + num + .to_string() + .chars() + .map(|c| c.to_string().parse::().unwrap()) + .sum::() + ) } } diff --git a/solution/0200-0299/0258.Add Digits/Solution2.rs b/solution/0200-0299/0258.Add Digits/Solution2.rs new file mode 100644 index 0000000000000..dcd23f532bf85 --- /dev/null +++ b/solution/0200-0299/0258.Add Digits/Solution2.rs @@ -0,0 +1,5 @@ +impl Solution { + pub fn add_digits(mut num: i32) -> i32 { + ((num - 1) % 9) + 1 + } +} diff --git a/solution/0200-0299/0260.Single Number III/Solution.cs b/solution/0200-0299/0260.Single Number III/Solution.cs index 57d5087e50f8d..af1c057070916 100644 --- a/solution/0200-0299/0260.Single Number III/Solution.cs +++ b/solution/0200-0299/0260.Single Number III/Solution.cs @@ -11,4 +11,4 @@ public int[] SingleNumber(int[] nums) { int b = xs ^ a; return new int[] {a, b}; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0263.Ugly Number/Solution.php b/solution/0200-0299/0263.Ugly Number/Solution.php index 703037afa57b6..da20726524d8d 100644 --- a/solution/0200-0299/0263.Ugly Number/Solution.php +++ b/solution/0200-0299/0263.Ugly Number/Solution.php @@ -17,4 +17,4 @@ function isUgly($n) { } return $n == 1; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0264.Ugly Number II/Solution.cpp b/solution/0200-0299/0264.Ugly Number II/Solution.cpp index 9bd1a3e0a14af..a5334855ddb7b 100644 --- a/solution/0200-0299/0264.Ugly Number II/Solution.cpp +++ b/solution/0200-0299/0264.Ugly Number II/Solution.cpp @@ -1,16 +1,22 @@ class Solution { public: int nthUglyNumber(int n) { - vector dp(n); - dp[0] = 1; - int p2 = 0, p3 = 0, p5 = 0; - for (int i = 1; i < n; ++i) { - int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; - dp[i] = min(next2, min(next3, next5)); - if (dp[i] == next2) ++p2; - if (dp[i] == next3) ++p3; - if (dp[i] == next5) ++p5; + priority_queue, greater> q; + q.push(1l); + unordered_set vis{{1l}}; + long ans = 1; + vector f = {2, 3, 5}; + while (n--) { + ans = q.top(); + q.pop(); + for (int& v : f) { + long nxt = ans * v; + if (!vis.count(nxt)) { + vis.insert(nxt); + q.push(nxt); + } + } } - return dp[n - 1]; + return (int) ans; } }; \ No newline at end of file diff --git a/solution/0200-0299/0264.Ugly Number II/Solution.cs b/solution/0200-0299/0264.Ugly Number II/Solution.cs index 2237ab0baccdc..9179cb2c6fca6 100644 --- a/solution/0200-0299/0264.Ugly Number II/Solution.cs +++ b/solution/0200-0299/0264.Ugly Number II/Solution.cs @@ -18,4 +18,4 @@ public int NthUglyNumber(int n) { } return dp[n - 1]; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0264.Ugly Number II/Solution.go b/solution/0200-0299/0264.Ugly Number II/Solution.go index b6204b937c703..1232c4e6c911d 100644 --- a/solution/0200-0299/0264.Ugly Number II/Solution.go +++ b/solution/0200-0299/0264.Ugly Number II/Solution.go @@ -1,19 +1,34 @@ func nthUglyNumber(n int) int { - dp := make([]int, n) - dp[0] = 1 - p2, p3, p5 := 0, 0, 0 - for i := 1; i < n; i++ { - next2, next3, next5 := dp[p2]*2, dp[p3]*3, dp[p5]*5 - dp[i] = min(next2, min(next3, next5)) - if dp[i] == next2 { - p2++ - } - if dp[i] == next3 { - p3++ - } - if dp[i] == next5 { - p5++ + h := IntHeap([]int{1}) + heap.Init(&h) + ans := 1 + vis := map[int]bool{1: true} + for n > 0 { + ans = heap.Pop(&h).(int) + for _, v := range []int{2, 3, 5} { + nxt := ans * v + if !vis[nxt] { + vis[nxt] = true + heap.Push(&h, nxt) + } } + n-- } - return dp[n-1] + return ans +} + +type IntHeap []int + +func (h IntHeap) Len() int { return len(h) } +func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } +func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *IntHeap) Push(x any) { + *h = append(*h, x.(int)) +} +func (h *IntHeap) Pop() any { + old := *h + n := len(old) + x := old[n-1] + *h = old[0 : n-1] + return x } \ No newline at end of file diff --git a/solution/0200-0299/0264.Ugly Number II/Solution.java b/solution/0200-0299/0264.Ugly Number II/Solution.java index 8689e9dce620d..f7eeea2be6349 100644 --- a/solution/0200-0299/0264.Ugly Number II/Solution.java +++ b/solution/0200-0299/0264.Ugly Number II/Solution.java @@ -1,15 +1,20 @@ class Solution { public int nthUglyNumber(int n) { - int[] dp = new int[n]; - dp[0] = 1; - int p2 = 0, p3 = 0, p5 = 0; - for (int i = 1; i < n; ++i) { - int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; - dp[i] = Math.min(next2, Math.min(next3, next5)); - if (dp[i] == next2) ++p2; - if (dp[i] == next3) ++p3; - if (dp[i] == next5) ++p5; + Set vis = new HashSet<>(); + PriorityQueue q = new PriorityQueue<>(); + int[] f = new int[] {2, 3, 5}; + q.offer(1L); + vis.add(1L); + long ans = 0; + while (n-- > 0) { + ans = q.poll(); + for (int v : f) { + long next = ans * v; + if (vis.add(next)) { + q.offer(next); + } + } } - return dp[n - 1]; + return (int) ans; } } \ No newline at end of file diff --git a/solution/0200-0299/0264.Ugly Number II/Solution.py b/solution/0200-0299/0264.Ugly Number II/Solution.py index a2427e7cfaea6..38ddc3b458a6b 100644 --- a/solution/0200-0299/0264.Ugly Number II/Solution.py +++ b/solution/0200-0299/0264.Ugly Number II/Solution.py @@ -1,14 +1,13 @@ class Solution: def nthUglyNumber(self, n: int) -> int: - dp = [1] * n - p2 = p3 = p5 = 0 - for i in range(1, n): - next2, next3, next5 = dp[p2] * 2, dp[p3] * 3, dp[p5] * 5 - dp[i] = min(next2, next3, next5) - if dp[i] == next2: - p2 += 1 - if dp[i] == next3: - p3 += 1 - if dp[i] == next5: - p5 += 1 - return dp[n - 1] + h = [1] + vis = {1} + ans = 1 + for _ in range(n): + ans = heappop(h) + for v in [2, 3, 5]: + nxt = ans * v + if nxt not in vis: + vis.add(nxt) + heappush(h, nxt) + return ans diff --git a/solution/0200-0299/0264.Ugly Number II/Solution2.cpp b/solution/0200-0299/0264.Ugly Number II/Solution2.cpp new file mode 100644 index 0000000000000..9bd1a3e0a14af --- /dev/null +++ b/solution/0200-0299/0264.Ugly Number II/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int nthUglyNumber(int n) { + vector dp(n); + dp[0] = 1; + int p2 = 0, p3 = 0, p5 = 0; + for (int i = 1; i < n; ++i) { + int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; + dp[i] = min(next2, min(next3, next5)); + if (dp[i] == next2) ++p2; + if (dp[i] == next3) ++p3; + if (dp[i] == next5) ++p5; + } + return dp[n - 1]; + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0264.Ugly Number II/Solution2.go b/solution/0200-0299/0264.Ugly Number II/Solution2.go new file mode 100644 index 0000000000000..b6204b937c703 --- /dev/null +++ b/solution/0200-0299/0264.Ugly Number II/Solution2.go @@ -0,0 +1,19 @@ +func nthUglyNumber(n int) int { + dp := make([]int, n) + dp[0] = 1 + p2, p3, p5 := 0, 0, 0 + for i := 1; i < n; i++ { + next2, next3, next5 := dp[p2]*2, dp[p3]*3, dp[p5]*5 + dp[i] = min(next2, min(next3, next5)) + if dp[i] == next2 { + p2++ + } + if dp[i] == next3 { + p3++ + } + if dp[i] == next5 { + p5++ + } + } + return dp[n-1] +} \ No newline at end of file diff --git a/solution/0200-0299/0264.Ugly Number II/Solution2.java b/solution/0200-0299/0264.Ugly Number II/Solution2.java new file mode 100644 index 0000000000000..8689e9dce620d --- /dev/null +++ b/solution/0200-0299/0264.Ugly Number II/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public int nthUglyNumber(int n) { + int[] dp = new int[n]; + dp[0] = 1; + int p2 = 0, p3 = 0, p5 = 0; + for (int i = 1; i < n; ++i) { + int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; + dp[i] = Math.min(next2, Math.min(next3, next5)); + if (dp[i] == next2) ++p2; + if (dp[i] == next3) ++p3; + if (dp[i] == next5) ++p5; + } + return dp[n - 1]; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0264.Ugly Number II/Solution2.py b/solution/0200-0299/0264.Ugly Number II/Solution2.py new file mode 100644 index 0000000000000..ebe1e4414fa47 --- /dev/null +++ b/solution/0200-0299/0264.Ugly Number II/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def nthUglyNumber(self, n: int) -> int: + dp = [1] * n + p2 = p3 = p5 = 0 + for i in range(1, n): + next2, next3, next5 = dp[p2] * 2, dp[p3] * 3, dp[p5] * 5 + dp[i] = min(next2, next3, next5) + if dp[i] == next2: + p2 += 1 + if dp[i] == next3: + p3 += 1 + if dp[i] == next5: + p5 += 1 + return dp[-1] diff --git a/solution/0200-0299/0266.Palindrome Permutation/Solution.cpp b/solution/0200-0299/0266.Palindrome Permutation/Solution.cpp index 9a2828859f2e3..f2001f7dc4a3e 100644 --- a/solution/0200-0299/0266.Palindrome Permutation/Solution.cpp +++ b/solution/0200-0299/0266.Palindrome Permutation/Solution.cpp @@ -1,14 +1,14 @@ -class Solution { -public: - bool canPermutePalindrome(string s) { - vector cnt(26); - for (char& c : s) { - ++cnt[c - 'a']; - } - int odd = 0; - for (int x : cnt) { - odd += x & 1; - } - return odd < 2; - } +class Solution { +public: + bool canPermutePalindrome(string s) { + vector cnt(26); + for (char& c : s) { + ++cnt[c - 'a']; + } + int odd = 0; + for (int x : cnt) { + odd += x & 1; + } + return odd < 2; + } }; \ No newline at end of file diff --git a/solution/0200-0299/0266.Palindrome Permutation/Solution.java b/solution/0200-0299/0266.Palindrome Permutation/Solution.java index b22bfecff0c8e..2222b1e65918b 100644 --- a/solution/0200-0299/0266.Palindrome Permutation/Solution.java +++ b/solution/0200-0299/0266.Palindrome Permutation/Solution.java @@ -1,13 +1,13 @@ -class Solution { - public boolean canPermutePalindrome(String s) { - int[] cnt = new int[26]; - for (char c : s.toCharArray()) { - ++cnt[c - 'a']; - } - int odd = 0; - for (int x : cnt) { - odd += x & 1; - } - return odd < 2; - } +class Solution { + public boolean canPermutePalindrome(String s) { + int[] cnt = new int[26]; + for (char c : s.toCharArray()) { + ++cnt[c - 'a']; + } + int odd = 0; + for (int x : cnt) { + odd += x & 1; + } + return odd < 2; + } } \ No newline at end of file diff --git a/solution/0200-0299/0266.Palindrome Permutation/Solution.py b/solution/0200-0299/0266.Palindrome Permutation/Solution.py index 34a2e7ee1b592..9d8c8ee002e4d 100644 --- a/solution/0200-0299/0266.Palindrome Permutation/Solution.py +++ b/solution/0200-0299/0266.Palindrome Permutation/Solution.py @@ -1,3 +1,3 @@ -class Solution: - def canPermutePalindrome(self, s: str) -> bool: - return sum(v & 1 for v in Counter(s).values()) < 2 +class Solution: + def canPermutePalindrome(self, s: str) -> bool: + return sum(v & 1 for v in Counter(s).values()) < 2 diff --git a/solution/0200-0299/0268.Missing Number/Solution.php b/solution/0200-0299/0268.Missing Number/Solution.php index 0b00ca7c7a214..fb1288a11e103 100644 --- a/solution/0200-0299/0268.Missing Number/Solution.php +++ b/solution/0200-0299/0268.Missing Number/Solution.php @@ -11,4 +11,4 @@ function missingNumber($nums) { } return $sumN; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0268.Missing Number/Solution2.cpp b/solution/0200-0299/0268.Missing Number/Solution2.cpp new file mode 100644 index 0000000000000..d92de10a39cec --- /dev/null +++ b/solution/0200-0299/0268.Missing Number/Solution2.cpp @@ -0,0 +1,7 @@ +class Solution { +public: + int missingNumber(vector& nums) { + int n = nums.size(); + return (1 + n) * n / 2 - accumulate(nums.begin(), nums.end(), 0); + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0268.Missing Number/Solution2.go b/solution/0200-0299/0268.Missing Number/Solution2.go new file mode 100644 index 0000000000000..3bb7e6d3ae531 --- /dev/null +++ b/solution/0200-0299/0268.Missing Number/Solution2.go @@ -0,0 +1,8 @@ +func missingNumber(nums []int) (ans int) { + n := len(nums) + ans = n + for i, v := range nums { + ans += i - v + } + return +} \ No newline at end of file diff --git a/solution/0200-0299/0268.Missing Number/Solution2.java b/solution/0200-0299/0268.Missing Number/Solution2.java new file mode 100644 index 0000000000000..1a59f9eb87dd9 --- /dev/null +++ b/solution/0200-0299/0268.Missing Number/Solution2.java @@ -0,0 +1,10 @@ +class Solution { + public int missingNumber(int[] nums) { + int n = nums.length; + int ans = n; + for (int i = 0; i < n; ++i) { + ans += i - nums[i]; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0268.Missing Number/Solution2.js b/solution/0200-0299/0268.Missing Number/Solution2.js new file mode 100644 index 0000000000000..de7e7a8d29e70 --- /dev/null +++ b/solution/0200-0299/0268.Missing Number/Solution2.js @@ -0,0 +1,12 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var missingNumber = function (nums) { + const n = nums.length; + let ans = n; + for (let i = 0; i < n; ++i) { + ans += i - nums[i]; + } + return ans; +}; diff --git a/solution/0200-0299/0268.Missing Number/Solution2.py b/solution/0200-0299/0268.Missing Number/Solution2.py new file mode 100644 index 0000000000000..1f3004decc270 --- /dev/null +++ b/solution/0200-0299/0268.Missing Number/Solution2.py @@ -0,0 +1,4 @@ +class Solution: + def missingNumber(self, nums: List[int]) -> int: + n = len(nums) + return (1 + n) * n // 2 - sum(nums) diff --git a/solution/0200-0299/0268.Missing Number/Solution2.rs b/solution/0200-0299/0268.Missing Number/Solution2.rs new file mode 100644 index 0000000000000..3683a7cd386e4 --- /dev/null +++ b/solution/0200-0299/0268.Missing Number/Solution2.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn missing_number(nums: Vec) -> i32 { + let n = nums.len() as i32; + let mut ans = n; + for (i, &v) in nums.iter().enumerate() { + ans += (i as i32) - v; + } + ans + } +} diff --git a/solution/0200-0299/0268.Missing Number/Solution2.ts b/solution/0200-0299/0268.Missing Number/Solution2.ts new file mode 100644 index 0000000000000..addfece0b17d5 --- /dev/null +++ b/solution/0200-0299/0268.Missing Number/Solution2.ts @@ -0,0 +1,8 @@ +function missingNumber(nums: number[]): number { + const n = nums.length; + let ans = n; + for (let i = 0; i < n; ++i) { + ans += i - nums[i]; + } + return ans; +} diff --git a/solution/0200-0299/0269.Alien Dictionary/Solution.java b/solution/0200-0299/0269.Alien Dictionary/Solution.java index 6892b9d99f5ab..b21fb7cf681c8 100644 --- a/solution/0200-0299/0269.Alien Dictionary/Solution.java +++ b/solution/0200-0299/0269.Alien Dictionary/Solution.java @@ -1,4 +1,5 @@ class Solution { + public String alienOrder(String[] words) { boolean[][] g = new boolean[26][26]; boolean[] s = new boolean[26]; diff --git a/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.cpp b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.cpp index c2fab05399bc6..61cc6a4bce845 100644 --- a/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.cpp +++ b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.cpp @@ -14,18 +14,19 @@ class Solution { int closestValue(TreeNode* root, double target) { int ans = root->val; double mi = INT_MAX; - while (root) { + function dfs = [&](TreeNode* root) { + if (!root) { + return; + } + dfs(root->left); double t = abs(root->val - target); - if (t < mi || (t == mi && root->val < ans)) { + if (t < mi) { mi = t; ans = root->val; } - if (root->val > target) { - root = root->left; - } else { - root = root->right; - } - } + dfs(root->right); + }; + dfs(root); return ans; } }; \ No newline at end of file diff --git a/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.go b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.go index 8a8758813ce63..b1e17dd8781e4 100644 --- a/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.go +++ b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.go @@ -9,17 +9,19 @@ func closestValue(root *TreeNode, target float64) int { ans := root.Val mi := math.MaxFloat64 - for root != nil { + var dfs func(*TreeNode) + dfs = func(root *TreeNode) { + if root == nil { + return + } + dfs(root.Left) t := math.Abs(float64(root.Val) - target) - if t < mi || (t == mi && root.Val < ans) { + if t < mi { mi = t ans = root.Val } - if float64(root.Val) > target { - root = root.Left - } else { - root = root.Right - } + dfs(root.Right) } + dfs(root) return ans } \ No newline at end of file diff --git a/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.java b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.java index ae5cebd683662..1ec07608c6b0f 100644 --- a/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.java +++ b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.java @@ -14,21 +14,26 @@ * } */ class Solution { + private int ans; + private double target; + private double mi = Double.MAX_VALUE; + public int closestValue(TreeNode root, double target) { - int ans = root.val; - double mi = Double.MAX_VALUE; - while (root != null) { - double t = Math.abs(root.val - target); - if (t < mi || (t == mi && root.val < ans)) { - mi = t; - ans = root.val; - } - if (root.val > target) { - root = root.left; - } else { - root = root.right; - } - } + this.target = target; + dfs(root); return ans; } + + private void dfs(TreeNode root) { + if (root == null) { + return; + } + dfs(root.left); + double t = Math.abs(root.val - target); + if (t < mi) { + mi = t; + ans = root.val; + } + dfs(root.right); + } } \ No newline at end of file diff --git a/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.js b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.js index 1638d5543d566..0b0874bb98597 100644 --- a/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.js +++ b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.js @@ -12,19 +12,20 @@ * @return {number} */ var closestValue = function (root, target) { + let mi = Infinity; let ans = root.val; - let mi = Number.MAX_VALUE; - while (root) { + const dfs = root => { + if (!root) { + return; + } + dfs(root.left); const t = Math.abs(root.val - target); - if (t < mi || (t === mi && root.val < ans)) { + if (t < mi) { mi = t; ans = root.val; } - if (root.val > target) { - root = root.left; - } else { - root = root.right; - } - } + dfs(root.right); + }; + dfs(root); return ans; }; diff --git a/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.py b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.py index a978b3389c646..ff66a2eb47d2c 100644 --- a/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.py +++ b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.py @@ -6,14 +6,17 @@ # self.right = right class Solution: def closestValue(self, root: Optional[TreeNode], target: float) -> int: - ans, mi = root.val, inf - while root: + def dfs(root): + if root is None: + return + dfs(root.left) + nonlocal ans, mi t = abs(root.val - target) - if t < mi or (t == mi and root.val < ans): + if t < mi: mi = t ans = root.val - if root.val > target: - root = root.left - else: - root = root.right + dfs(root.right) + + ans, mi = root.val, inf + dfs(root) return ans diff --git a/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution2.cpp b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution2.cpp new file mode 100644 index 0000000000000..c2fab05399bc6 --- /dev/null +++ b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution2.cpp @@ -0,0 +1,31 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int closestValue(TreeNode* root, double target) { + int ans = root->val; + double mi = INT_MAX; + while (root) { + double t = abs(root->val - target); + if (t < mi || (t == mi && root->val < ans)) { + mi = t; + ans = root->val; + } + if (root->val > target) { + root = root->left; + } else { + root = root->right; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution2.go b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution2.go new file mode 100644 index 0000000000000..8a8758813ce63 --- /dev/null +++ b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution2.go @@ -0,0 +1,25 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func closestValue(root *TreeNode, target float64) int { + ans := root.Val + mi := math.MaxFloat64 + for root != nil { + t := math.Abs(float64(root.Val) - target) + if t < mi || (t == mi && root.Val < ans) { + mi = t + ans = root.Val + } + if float64(root.Val) > target { + root = root.Left + } else { + root = root.Right + } + } + return ans +} \ No newline at end of file diff --git a/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution2.java b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution2.java new file mode 100644 index 0000000000000..ae5cebd683662 --- /dev/null +++ b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution2.java @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int closestValue(TreeNode root, double target) { + int ans = root.val; + double mi = Double.MAX_VALUE; + while (root != null) { + double t = Math.abs(root.val - target); + if (t < mi || (t == mi && root.val < ans)) { + mi = t; + ans = root.val; + } + if (root.val > target) { + root = root.left; + } else { + root = root.right; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution2.js b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution2.js new file mode 100644 index 0000000000000..1638d5543d566 --- /dev/null +++ b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution2.js @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} target + * @return {number} + */ +var closestValue = function (root, target) { + let ans = root.val; + let mi = Number.MAX_VALUE; + while (root) { + const t = Math.abs(root.val - target); + if (t < mi || (t === mi && root.val < ans)) { + mi = t; + ans = root.val; + } + if (root.val > target) { + root = root.left; + } else { + root = root.right; + } + } + return ans; +}; diff --git a/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution2.py b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution2.py new file mode 100644 index 0000000000000..a978b3389c646 --- /dev/null +++ b/solution/0200-0299/0270.Closest Binary Search Tree Value/Solution2.py @@ -0,0 +1,19 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def closestValue(self, root: Optional[TreeNode], target: float) -> int: + ans, mi = root.val, inf + while root: + t = abs(root.val - target) + if t < mi or (t == mi and root.val < ans): + mi = t + ans = root.val + if root.val > target: + root = root.left + else: + root = root.right + return ans diff --git a/solution/0200-0299/0271.Encode and Decode Strings/Solution.py b/solution/0200-0299/0271.Encode and Decode Strings/Solution.py index b7c324773de4a..14f4138252fdd 100644 --- a/solution/0200-0299/0271.Encode and Decode Strings/Solution.py +++ b/solution/0200-0299/0271.Encode and Decode Strings/Solution.py @@ -1,21 +1,11 @@ class Codec: def encode(self, strs: List[str]) -> str: """Encodes a list of strings to a single string.""" - ans = [] - for s in strs: - ans.append('{:4}'.format(len(s)) + s) - return ''.join(ans) + return chr(257).join(strs) def decode(self, s: str) -> List[str]: """Decodes a single string to a list of strings.""" - ans = [] - i, n = 0, len(s) - while i < n: - size = int(s[i : i + 4]) - i += 4 - ans.append(s[i : i + size]) - i += size - return ans + return s.split(chr(257)) # Your Codec object will be instantiated and called as such: diff --git a/solution/0200-0299/0271.Encode and Decode Strings/Solution2.py b/solution/0200-0299/0271.Encode and Decode Strings/Solution2.py new file mode 100644 index 0000000000000..b7c324773de4a --- /dev/null +++ b/solution/0200-0299/0271.Encode and Decode Strings/Solution2.py @@ -0,0 +1,23 @@ +class Codec: + def encode(self, strs: List[str]) -> str: + """Encodes a list of strings to a single string.""" + ans = [] + for s in strs: + ans.append('{:4}'.format(len(s)) + s) + return ''.join(ans) + + def decode(self, s: str) -> List[str]: + """Decodes a single string to a list of strings.""" + ans = [] + i, n = 0, len(s) + while i < n: + size = int(s[i : i + 4]) + i += 4 + ans.append(s[i : i + size]) + i += size + return ans + + +# Your Codec object will be instantiated and called as such: +# codec = Codec() +# codec.decode(codec.encode(strs)) diff --git a/solution/0200-0299/0272.Closest Binary Search Tree Value II/Solution.java b/solution/0200-0299/0272.Closest Binary Search Tree Value II/Solution.java index 1debf51c8a7d9..019c7a21bd436 100644 --- a/solution/0200-0299/0272.Closest Binary Search Tree Value II/Solution.java +++ b/solution/0200-0299/0272.Closest Binary Search Tree Value II/Solution.java @@ -14,6 +14,7 @@ * } */ class Solution { + private List ans; private double target; private int k; diff --git a/solution/0200-0299/0273.Integer to English Words/Solution.cs b/solution/0200-0299/0273.Integer to English Words/Solution.cs index e52511dc87e27..6b23780f59ab1 100644 --- a/solution/0200-0299/0273.Integer to English Words/Solution.cs +++ b/solution/0200-0299/0273.Integer to English Words/Solution.cs @@ -85,4 +85,4 @@ private string NumberToWordsInternal(int num) return JoinParts(part1, "Hundred", part2); } } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0273.Integer to English Words/Solution.java b/solution/0200-0299/0273.Integer to English Words/Solution.java index 64317aa43c5f9..fccc886b3a5c6 100644 --- a/solution/0200-0299/0273.Integer to English Words/Solution.java +++ b/solution/0200-0299/0273.Integer to English Words/Solution.java @@ -68,4 +68,4 @@ private String get3Digits(int num) { } return sb.toString(); } -} +} \ No newline at end of file diff --git a/solution/0200-0299/0273.Integer to English Words/Solution2.java b/solution/0200-0299/0273.Integer to English Words/Solution2.java new file mode 100644 index 0000000000000..d95f476755855 --- /dev/null +++ b/solution/0200-0299/0273.Integer to English Words/Solution2.java @@ -0,0 +1,36 @@ +class Solution { + private String[] lt20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", + "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", + "Seventeen", "Eighteen", "Nineteen"}; + private String[] tens + = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; + private String[] thousands = {"Billion", "Million", "Thousand", ""}; + + public String numberToWords(int num) { + if (num == 0) { + return "Zero"; + } + StringBuilder sb = new StringBuilder(); + for (int i = 1000000000, j = 0; i > 0; i /= 1000, ++j) { + if (num / i == 0) { + continue; + } + sb.append(transfer(num / i)).append(thousands[j]).append(' '); + num %= i; + } + return sb.toString().trim(); + } + + private String transfer(int num) { + if (num == 0) { + return ""; + } + if (num < 20) { + return lt20[num] + " "; + } + if (num < 100) { + return tens[num / 10] + " " + transfer(num % 10); + } + return lt20[num / 100] + " Hundred " + transfer(num % 100); + } +} \ No newline at end of file diff --git a/solution/0200-0299/0274.H-Index/Solution.cpp b/solution/0200-0299/0274.H-Index/Solution.cpp index 317768a082737..9c7eead1812ef 100644 --- a/solution/0200-0299/0274.H-Index/Solution.cpp +++ b/solution/0200-0299/0274.H-Index/Solution.cpp @@ -1,17 +1,12 @@ class Solution { public: int hIndex(vector& citations) { - int n = citations.size(); - int cnt[n + 1]; - memset(cnt, 0, sizeof(cnt)); - for (int x : citations) { - ++cnt[min(x, n)]; - } - for (int h = n, s = 0;; --h) { - s += cnt[h]; - if (s >= h) { + sort(citations.rbegin(), citations.rend()); + for (int h = citations.size(); h; --h) { + if (citations[h - 1] >= h) { return h; } } + return 0; } }; \ No newline at end of file diff --git a/solution/0200-0299/0274.H-Index/Solution.go b/solution/0200-0299/0274.H-Index/Solution.go index 92748cf08ac12..33a9dfd57e3e6 100644 --- a/solution/0200-0299/0274.H-Index/Solution.go +++ b/solution/0200-0299/0274.H-Index/Solution.go @@ -1,13 +1,10 @@ func hIndex(citations []int) int { + sort.Ints(citations) n := len(citations) - cnt := make([]int, n+1) - for _, x := range citations { - cnt[min(x, n)]++ - } - for h, s := n, 0; ; h-- { - s += cnt[h] - if s >= h { + for h := n; h > 0; h-- { + if citations[n-h] >= h { return h } } + return 0 } \ No newline at end of file diff --git a/solution/0200-0299/0274.H-Index/Solution.java b/solution/0200-0299/0274.H-Index/Solution.java index f1881c73fe0e5..801ca76f12e2b 100644 --- a/solution/0200-0299/0274.H-Index/Solution.java +++ b/solution/0200-0299/0274.H-Index/Solution.java @@ -1,15 +1,12 @@ class Solution { public int hIndex(int[] citations) { + Arrays.sort(citations); int n = citations.length; - int[] cnt = new int[n + 1]; - for (int x : citations) { - ++cnt[Math.min(x, n)]; - } - for (int h = n, s = 0;; --h) { - s += cnt[h]; - if (s >= h) { + for (int h = n; h > 0; --h) { + if (citations[n - h] >= h) { return h; } } + return 0; } } \ No newline at end of file diff --git a/solution/0200-0299/0274.H-Index/Solution.py b/solution/0200-0299/0274.H-Index/Solution.py index 6ff3254824b24..b1e687d124cfd 100644 --- a/solution/0200-0299/0274.H-Index/Solution.py +++ b/solution/0200-0299/0274.H-Index/Solution.py @@ -1,11 +1,7 @@ -class Solution: - def hIndex(self, citations: List[int]) -> int: - n = len(citations) - cnt = [0] * (n + 1) - for x in citations: - cnt[min(x, n)] += 1 - s = 0 - for h in range(n, -1, -1): - s += cnt[h] - if s >= h: - return h +class Solution: + def hIndex(self, citations: List[int]) -> int: + citations.sort(reverse=True) + for h in range(len(citations), 0, -1): + if citations[h - 1] >= h: + return h + return 0 diff --git a/solution/0200-0299/0274.H-Index/Solution.ts b/solution/0200-0299/0274.H-Index/Solution.ts index e8dce206fa640..088c419c6d850 100644 --- a/solution/0200-0299/0274.H-Index/Solution.ts +++ b/solution/0200-0299/0274.H-Index/Solution.ts @@ -1,13 +1,9 @@ function hIndex(citations: number[]): number { - const n: number = citations.length; - const cnt: number[] = new Array(n + 1).fill(0); - for (const x of citations) { - ++cnt[Math.min(x, n)]; - } - for (let h = n, s = 0; ; --h) { - s += cnt[h]; - if (s >= h) { + citations.sort((a, b) => b - a); + for (let h = citations.length; h; --h) { + if (citations[h - 1] >= h) { return h; } } + return 0; } diff --git a/solution/0200-0299/0274.H-Index/Solution2.cpp b/solution/0200-0299/0274.H-Index/Solution2.cpp new file mode 100644 index 0000000000000..317768a082737 --- /dev/null +++ b/solution/0200-0299/0274.H-Index/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int hIndex(vector& citations) { + int n = citations.size(); + int cnt[n + 1]; + memset(cnt, 0, sizeof(cnt)); + for (int x : citations) { + ++cnt[min(x, n)]; + } + for (int h = n, s = 0;; --h) { + s += cnt[h]; + if (s >= h) { + return h; + } + } + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0274.H-Index/Solution2.go b/solution/0200-0299/0274.H-Index/Solution2.go new file mode 100644 index 0000000000000..92748cf08ac12 --- /dev/null +++ b/solution/0200-0299/0274.H-Index/Solution2.go @@ -0,0 +1,13 @@ +func hIndex(citations []int) int { + n := len(citations) + cnt := make([]int, n+1) + for _, x := range citations { + cnt[min(x, n)]++ + } + for h, s := n, 0; ; h-- { + s += cnt[h] + if s >= h { + return h + } + } +} \ No newline at end of file diff --git a/solution/0200-0299/0274.H-Index/Solution2.java b/solution/0200-0299/0274.H-Index/Solution2.java new file mode 100644 index 0000000000000..f1881c73fe0e5 --- /dev/null +++ b/solution/0200-0299/0274.H-Index/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public int hIndex(int[] citations) { + int n = citations.length; + int[] cnt = new int[n + 1]; + for (int x : citations) { + ++cnt[Math.min(x, n)]; + } + for (int h = n, s = 0;; --h) { + s += cnt[h]; + if (s >= h) { + return h; + } + } + } +} \ No newline at end of file diff --git a/solution/0200-0299/0274.H-Index/Solution2.py b/solution/0200-0299/0274.H-Index/Solution2.py new file mode 100644 index 0000000000000..62c52e0796cd3 --- /dev/null +++ b/solution/0200-0299/0274.H-Index/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def hIndex(self, citations: List[int]) -> int: + n = len(citations) + cnt = [0] * (n + 1) + for x in citations: + cnt[min(x, n)] += 1 + s = 0 + for h in range(n, -1, -1): + s += cnt[h] + if s >= h: + return h diff --git a/solution/0200-0299/0274.H-Index/Solution2.ts b/solution/0200-0299/0274.H-Index/Solution2.ts new file mode 100644 index 0000000000000..e8dce206fa640 --- /dev/null +++ b/solution/0200-0299/0274.H-Index/Solution2.ts @@ -0,0 +1,13 @@ +function hIndex(citations: number[]): number { + const n: number = citations.length; + const cnt: number[] = new Array(n + 1).fill(0); + for (const x of citations) { + ++cnt[Math.min(x, n)]; + } + for (let h = n, s = 0; ; --h) { + s += cnt[h]; + if (s >= h) { + return h; + } + } +} diff --git a/solution/0200-0299/0274.H-Index/Solution3.cpp b/solution/0200-0299/0274.H-Index/Solution3.cpp new file mode 100644 index 0000000000000..7f1d499b7c528 --- /dev/null +++ b/solution/0200-0299/0274.H-Index/Solution3.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int hIndex(vector& citations) { + int l = 0, r = citations.size(); + while (l < r) { + int mid = (l + r + 1) >> 1; + int s = 0; + for (int x : citations) { + if (x >= mid) { + ++s; + } + } + if (s >= mid) { + l = mid; + } else { + r = mid - 1; + } + } + return l; + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0274.H-Index/Solution3.go b/solution/0200-0299/0274.H-Index/Solution3.go new file mode 100644 index 0000000000000..a12695801777d --- /dev/null +++ b/solution/0200-0299/0274.H-Index/Solution3.go @@ -0,0 +1,18 @@ +func hIndex(citations []int) int { + l, r := 0, len(citations) + for l < r { + mid := (l + r + 1) >> 1 + s := 0 + for _, x := range citations { + if x >= mid { + s++ + } + } + if s >= mid { + l = mid + } else { + r = mid - 1 + } + } + return l +} \ No newline at end of file diff --git a/solution/0200-0299/0274.H-Index/Solution3.java b/solution/0200-0299/0274.H-Index/Solution3.java new file mode 100644 index 0000000000000..e55debd5f8e30 --- /dev/null +++ b/solution/0200-0299/0274.H-Index/Solution3.java @@ -0,0 +1,20 @@ +class Solution { + public int hIndex(int[] citations) { + int l = 0, r = citations.length; + while (l < r) { + int mid = (l + r + 1) >> 1; + int s = 0; + for (int x : citations) { + if (x >= mid) { + ++s; + } + } + if (s >= mid) { + l = mid; + } else { + r = mid - 1; + } + } + return l; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0274.H-Index/Solution3.py b/solution/0200-0299/0274.H-Index/Solution3.py new file mode 100644 index 0000000000000..beb3dcbd4e1c7 --- /dev/null +++ b/solution/0200-0299/0274.H-Index/Solution3.py @@ -0,0 +1,10 @@ +class Solution: + def hIndex(self, citations: List[int]) -> int: + l, r = 0, len(citations) + while l < r: + mid = (l + r + 1) >> 1 + if sum(x >= mid for x in citations) >= mid: + l = mid + else: + r = mid - 1 + return l diff --git a/solution/0200-0299/0274.H-Index/Solution3.ts b/solution/0200-0299/0274.H-Index/Solution3.ts new file mode 100644 index 0000000000000..3b251654989f0 --- /dev/null +++ b/solution/0200-0299/0274.H-Index/Solution3.ts @@ -0,0 +1,19 @@ +function hIndex(citations: number[]): number { + let l = 0; + let r = citations.length; + while (l < r) { + const mid = (l + r + 1) >> 1; + let s = 0; + for (const x of citations) { + if (x >= mid) { + ++s; + } + } + if (s >= mid) { + l = mid; + } else { + r = mid - 1; + } + } + return l; +} diff --git a/solution/0200-0299/0275.H-Index II/Solution.cpp b/solution/0200-0299/0275.H-Index II/Solution.cpp index 9a789bd45fa04..c289750176824 100644 --- a/solution/0200-0299/0275.H-Index II/Solution.cpp +++ b/solution/0200-0299/0275.H-Index II/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - int hIndex(vector& citations) { - int n = citations.size(); - int left = 0, right = n; - while (left < right) { - int mid = (left + right + 1) >> 1; - if (citations[n - mid] >= mid) - left = mid; - else - right = mid - 1; - } - return left; - } +class Solution { +public: + int hIndex(vector& citations) { + int n = citations.size(); + int left = 0, right = n; + while (left < right) { + int mid = (left + right + 1) >> 1; + if (citations[n - mid] >= mid) + left = mid; + else + right = mid - 1; + } + return left; + } }; \ No newline at end of file diff --git a/solution/0200-0299/0275.H-Index II/Solution.cs b/solution/0200-0299/0275.H-Index II/Solution.cs index 6b17ee4bc3758..7cde635e3e3cf 100644 --- a/solution/0200-0299/0275.H-Index II/Solution.cs +++ b/solution/0200-0299/0275.H-Index II/Solution.cs @@ -1,15 +1,15 @@ -public class Solution { - public int HIndex(int[] citations) { - int n = citations.Length; - int left = 0, right = n; - while (left < right) { - int mid = (left + right + 1) >> 1; - if (citations[n - mid] >= mid) { - left = mid; - } else { - right = mid - 1; - } - } - return left; - } -} \ No newline at end of file +public class Solution { + public int HIndex(int[] citations) { + int n = citations.Length; + int left = 0, right = n; + while (left < right) { + int mid = (left + right + 1) >> 1; + if (citations[n - mid] >= mid) { + left = mid; + } else { + right = mid - 1; + } + } + return left; + } +} diff --git a/solution/0200-0299/0275.H-Index II/Solution.java b/solution/0200-0299/0275.H-Index II/Solution.java index dccafa3c79c12..0fcbca28c06d9 100644 --- a/solution/0200-0299/0275.H-Index II/Solution.java +++ b/solution/0200-0299/0275.H-Index II/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public int hIndex(int[] citations) { - int n = citations.length; - int left = 0, right = n; - while (left < right) { - int mid = (left + right + 1) >> 1; - if (citations[n - mid] >= mid) { - left = mid; - } else { - right = mid - 1; - } - } - return left; - } +class Solution { + public int hIndex(int[] citations) { + int n = citations.length; + int left = 0, right = n; + while (left < right) { + int mid = (left + right) >>> 1; + if (citations[mid] >= n - mid) { + right = mid; + } else { + left = mid + 1; + } + } + return n - left; + } } \ No newline at end of file diff --git a/solution/0200-0299/0275.H-Index II/Solution.py b/solution/0200-0299/0275.H-Index II/Solution.py index e79b73a4507d2..572d413c29967 100644 --- a/solution/0200-0299/0275.H-Index II/Solution.py +++ b/solution/0200-0299/0275.H-Index II/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def hIndex(self, citations: List[int]) -> int: - n = len(citations) - left, right = 0, n - while left < right: - mid = (left + right + 1) >> 1 - if citations[n - mid] >= mid: - left = mid - else: - right = mid - 1 - return left +class Solution: + def hIndex(self, citations: List[int]) -> int: + n = len(citations) + left, right = 0, n + while left < right: + mid = (left + right + 1) >> 1 + if citations[n - mid] >= mid: + left = mid + else: + right = mid - 1 + return left diff --git a/solution/0200-0299/0279.Perfect Squares/Solution.cpp b/solution/0200-0299/0279.Perfect Squares/Solution.cpp index 0d62886dd7af8..5785d728ff30b 100644 --- a/solution/0200-0299/0279.Perfect Squares/Solution.cpp +++ b/solution/0200-0299/0279.Perfect Squares/Solution.cpp @@ -1,15 +1,18 @@ -class Solution { -public: - int numSquares(int n) { - int m = sqrt(n); - int f[n + 1]; - memset(f, 0x3f, sizeof(f)); - f[0] = 0; - for (int i = 1; i <= m; ++i) { - for (int j = i * i; j <= n; ++j) { - f[j] = min(f[j], f[j - i * i] + 1); - } - } - return f[n]; - } +class Solution { +public: + int numSquares(int n) { + int m = sqrt(n); + int f[m + 1][n + 1]; + memset(f, 0x3f, sizeof(f)); + f[0][0] = 0; + for (int i = 1; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= i * i) { + f[i][j] = min(f[i][j], f[i][j - i * i] + 1); + } + } + } + return f[m][n]; + } }; \ No newline at end of file diff --git a/solution/0200-0299/0279.Perfect Squares/Solution.go b/solution/0200-0299/0279.Perfect Squares/Solution.go index 872300114ab61..5973aca73db5c 100644 --- a/solution/0200-0299/0279.Perfect Squares/Solution.go +++ b/solution/0200-0299/0279.Perfect Squares/Solution.go @@ -1,14 +1,21 @@ func numSquares(n int) int { m := int(math.Sqrt(float64(n))) - f := make([]int, n+1) + f := make([][]int, m+1) + const inf = 1 << 30 for i := range f { - f[i] = 1 << 30 + f[i] = make([]int, n+1) + for j := range f[i] { + f[i][j] = inf + } } - f[0] = 0 + f[0][0] = 0 for i := 1; i <= m; i++ { - for j := i * i; j <= n; j++ { - f[j] = min(f[j], f[j-i*i]+1) + for j := 0; j <= n; j++ { + f[i][j] = f[i-1][j] + if j >= i*i { + f[i][j] = min(f[i][j], f[i][j-i*i]+1) + } } } - return f[n] + return f[m][n] } \ No newline at end of file diff --git a/solution/0200-0299/0279.Perfect Squares/Solution.java b/solution/0200-0299/0279.Perfect Squares/Solution.java index 45f8ae1eb951f..40505ffa422cc 100644 --- a/solution/0200-0299/0279.Perfect Squares/Solution.java +++ b/solution/0200-0299/0279.Perfect Squares/Solution.java @@ -1,14 +1,19 @@ -class Solution { - public int numSquares(int n) { - int m = (int) Math.sqrt(n); - int[] f = new int[n + 1]; - Arrays.fill(f, 1 << 30); - f[0] = 0; - for (int i = 1; i <= m; ++i) { - for (int j = i * i; j <= n; ++j) { - f[j] = Math.min(f[j], f[j - i * i] + 1); - } - } - return f[n]; - } +class Solution { + public int numSquares(int n) { + int m = (int) Math.sqrt(n); + int[][] f = new int[m + 1][n + 1]; + for (var g : f) { + Arrays.fill(g, 1 << 30); + } + f[0][0] = 0; + for (int i = 1; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= i * i) { + f[i][j] = Math.min(f[i][j], f[i][j - i * i] + 1); + } + } + } + return f[m][n]; + } } \ No newline at end of file diff --git a/solution/0200-0299/0279.Perfect Squares/Solution.py b/solution/0200-0299/0279.Perfect Squares/Solution.py index a9498fb58775b..d81d46af8c402 100644 --- a/solution/0200-0299/0279.Perfect Squares/Solution.py +++ b/solution/0200-0299/0279.Perfect Squares/Solution.py @@ -1,8 +1,11 @@ -class Solution: - def numSquares(self, n: int) -> int: - m = int(sqrt(n)) - f = [0] + [inf] * n - for i in range(1, m + 1): - for j in range(i * i, n + 1): - f[j] = min(f[j], f[j - i * i] + 1) - return f[n] +class Solution: + def numSquares(self, n: int) -> int: + m = int(sqrt(n)) + f = [[inf] * (n + 1) for _ in range(m + 1)] + f[0][0] = 0 + for i in range(1, m + 1): + for j in range(n + 1): + f[i][j] = f[i - 1][j] + if j >= i * i: + f[i][j] = min(f[i][j], f[i][j - i * i] + 1) + return f[m][n] diff --git a/solution/0200-0299/0279.Perfect Squares/Solution.ts b/solution/0200-0299/0279.Perfect Squares/Solution.ts index 3a79faca5ba09..0bfc316289b7a 100644 --- a/solution/0200-0299/0279.Perfect Squares/Solution.ts +++ b/solution/0200-0299/0279.Perfect Squares/Solution.ts @@ -1,11 +1,16 @@ function numSquares(n: number): number { const m = Math.floor(Math.sqrt(n)); - const f: number[] = Array(n + 1).fill(1 << 30); - f[0] = 0; + const f: number[][] = Array(m + 1) + .fill(0) + .map(() => Array(n + 1).fill(1 << 30)); + f[0][0] = 0; for (let i = 1; i <= m; ++i) { - for (let j = i * i; j <= n; ++j) { - f[j] = Math.min(f[j], f[j - i * i] + 1); + for (let j = 0; j <= n; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= i * i) { + f[i][j] = Math.min(f[i][j], f[i][j - i * i] + 1); + } } } - return f[n]; + return f[m][n]; } diff --git a/solution/0200-0299/0279.Perfect Squares/Solution2.cpp b/solution/0200-0299/0279.Perfect Squares/Solution2.cpp new file mode 100644 index 0000000000000..f890cec76eecb --- /dev/null +++ b/solution/0200-0299/0279.Perfect Squares/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int numSquares(int n) { + int m = sqrt(n); + int f[n + 1]; + memset(f, 0x3f, sizeof(f)); + f[0] = 0; + for (int i = 1; i <= m; ++i) { + for (int j = i * i; j <= n; ++j) { + f[j] = min(f[j], f[j - i * i] + 1); + } + } + return f[n]; + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0279.Perfect Squares/Solution2.go b/solution/0200-0299/0279.Perfect Squares/Solution2.go new file mode 100644 index 0000000000000..872300114ab61 --- /dev/null +++ b/solution/0200-0299/0279.Perfect Squares/Solution2.go @@ -0,0 +1,14 @@ +func numSquares(n int) int { + m := int(math.Sqrt(float64(n))) + f := make([]int, n+1) + for i := range f { + f[i] = 1 << 30 + } + f[0] = 0 + for i := 1; i <= m; i++ { + for j := i * i; j <= n; j++ { + f[j] = min(f[j], f[j-i*i]+1) + } + } + return f[n] +} \ No newline at end of file diff --git a/solution/0200-0299/0279.Perfect Squares/Solution2.java b/solution/0200-0299/0279.Perfect Squares/Solution2.java new file mode 100644 index 0000000000000..10ab26b5c1c58 --- /dev/null +++ b/solution/0200-0299/0279.Perfect Squares/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public int numSquares(int n) { + int m = (int) Math.sqrt(n); + int[] f = new int[n + 1]; + Arrays.fill(f, 1 << 30); + f[0] = 0; + for (int i = 1; i <= m; ++i) { + for (int j = i * i; j <= n; ++j) { + f[j] = Math.min(f[j], f[j - i * i] + 1); + } + } + return f[n]; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0279.Perfect Squares/Solution2.py b/solution/0200-0299/0279.Perfect Squares/Solution2.py new file mode 100644 index 0000000000000..61acef02ba5ad --- /dev/null +++ b/solution/0200-0299/0279.Perfect Squares/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def numSquares(self, n: int) -> int: + m = int(sqrt(n)) + f = [0] + [inf] * n + for i in range(1, m + 1): + for j in range(i * i, n + 1): + f[j] = min(f[j], f[j - i * i] + 1) + return f[n] diff --git a/solution/0200-0299/0279.Perfect Squares/Solution2.rs b/solution/0200-0299/0279.Perfect Squares/Solution2.rs new file mode 100644 index 0000000000000..2b329a7644132 --- /dev/null +++ b/solution/0200-0299/0279.Perfect Squares/Solution2.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn num_squares(n: i32) -> i32 { + let (row, col) = ((n as f32).sqrt().floor() as usize, n as usize); + let mut dp = vec![i32::MAX; col + 1]; + dp[0] = 0; + for i in 1..=row { + for j in i * i..=col { + dp[j] = std::cmp::min(dp[j], dp[j - i * i] + 1); + } + } + dp[col] + } +} diff --git a/solution/0200-0299/0279.Perfect Squares/Solution2.ts b/solution/0200-0299/0279.Perfect Squares/Solution2.ts new file mode 100644 index 0000000000000..3a79faca5ba09 --- /dev/null +++ b/solution/0200-0299/0279.Perfect Squares/Solution2.ts @@ -0,0 +1,11 @@ +function numSquares(n: number): number { + const m = Math.floor(Math.sqrt(n)); + const f: number[] = Array(n + 1).fill(1 << 30); + f[0] = 0; + for (let i = 1; i <= m; ++i) { + for (let j = i * i; j <= n; ++j) { + f[j] = Math.min(f[j], f[j - i * i] + 1); + } + } + return f[n]; +} diff --git a/solution/0200-0299/0280.Wiggle Sort/Solution.cpp b/solution/0200-0299/0280.Wiggle Sort/Solution.cpp new file mode 100644 index 0000000000000..91572b8c8486b --- /dev/null +++ b/solution/0200-0299/0280.Wiggle Sort/Solution.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + void wiggleSort(vector& nums) { + for (int i = 1; i < nums.size(); ++i) { + if ((i % 2 == 1 && nums[i] < nums[i - 1]) || (i % 2 == 0 && nums[i] > nums[i - 1])) { + swap(nums[i], nums[i - 1]); + } + } + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0283.Move Zeroes/Solution.c b/solution/0200-0299/0283.Move Zeroes/Solution.c index e43efcc3e3bed..f925d23add2c9 100644 --- a/solution/0200-0299/0283.Move Zeroes/Solution.c +++ b/solution/0200-0299/0283.Move Zeroes/Solution.c @@ -9,4 +9,4 @@ void moveZeroes(int* nums, int numsSize) { i++; } } -} +} \ No newline at end of file diff --git a/solution/0200-0299/0283.Move Zeroes/Solution.cpp b/solution/0200-0299/0283.Move Zeroes/Solution.cpp index e9437efb1105b..7fed54ef19b7c 100644 --- a/solution/0200-0299/0283.Move Zeroes/Solution.cpp +++ b/solution/0200-0299/0283.Move Zeroes/Solution.cpp @@ -1,11 +1,11 @@ -class Solution { -public: - void moveZeroes(vector& nums) { - int i = -1, n = nums.size(); - for (int j = 0; j < n; ++j) { - if (nums[j]) { - swap(nums[++i], nums[j]); - } - } - } +class Solution { +public: + void moveZeroes(vector& nums) { + int i = -1, n = nums.size(); + for (int j = 0; j < n; ++j) { + if (nums[j]) { + swap(nums[++i], nums[j]); + } + } + } }; \ No newline at end of file diff --git a/solution/0200-0299/0283.Move Zeroes/Solution.java b/solution/0200-0299/0283.Move Zeroes/Solution.java index 8c788007e7a2a..bd3401ab8a673 100644 --- a/solution/0200-0299/0283.Move Zeroes/Solution.java +++ b/solution/0200-0299/0283.Move Zeroes/Solution.java @@ -1,12 +1,12 @@ -class Solution { - public void moveZeroes(int[] nums) { - int i = -1, n = nums.length; - for (int j = 0; j < n; ++j) { - if (nums[j] != 0) { - int t = nums[++i]; - nums[i] = nums[j]; - nums[j] = t; - } - } - } +class Solution { + public void moveZeroes(int[] nums) { + int i = -1, n = nums.length; + for (int j = 0; j < n; ++j) { + if (nums[j] != 0) { + int t = nums[++i]; + nums[i] = nums[j]; + nums[j] = t; + } + } + } } \ No newline at end of file diff --git a/solution/0200-0299/0283.Move Zeroes/Solution.py b/solution/0200-0299/0283.Move Zeroes/Solution.py index 434a1ff579ab0..f6ec997f91cbb 100644 --- a/solution/0200-0299/0283.Move Zeroes/Solution.py +++ b/solution/0200-0299/0283.Move Zeroes/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def moveZeroes(self, nums: List[int]) -> None: - i = -1 - for j, x in enumerate(nums): - if x: - i += 1 - nums[i], nums[j] = nums[j], nums[i] +class Solution: + def moveZeroes(self, nums: List[int]) -> None: + i = -1 + for j, x in enumerate(nums): + if x: + i += 1 + nums[i], nums[j] = nums[j], nums[i] diff --git a/solution/0200-0299/0285.Inorder Successor in BST/Solution.cpp b/solution/0200-0299/0285.Inorder Successor in BST/Solution.cpp index 7064a902e7421..5f6d680b97a1a 100644 --- a/solution/0200-0299/0285.Inorder Successor in BST/Solution.cpp +++ b/solution/0200-0299/0285.Inorder Successor in BST/Solution.cpp @@ -1,24 +1,24 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { - TreeNode* ans = nullptr; - while (root) { - if (root->val > p->val) { - ans = root; - root = root->left; - } else { - root = root->right; - } - } - return ans; - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { + TreeNode* ans = nullptr; + while (root) { + if (root->val > p->val) { + ans = root; + root = root->left; + } else { + root = root->right; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0200-0299/0285.Inorder Successor in BST/Solution.java b/solution/0200-0299/0285.Inorder Successor in BST/Solution.java index 313e0f609ee0e..e388d684d44fc 100644 --- a/solution/0200-0299/0285.Inorder Successor in BST/Solution.java +++ b/solution/0200-0299/0285.Inorder Successor in BST/Solution.java @@ -1,23 +1,23 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -class Solution { - public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { - TreeNode ans = null; - while (root != null) { - if (root.val > p.val) { - ans = root; - root = root.left; - } else { - root = root.right; - } - } - return ans; - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { + TreeNode ans = null; + while (root != null) { + if (root.val > p.val) { + ans = root; + root = root.left; + } else { + root = root.right; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0200-0299/0285.Inorder Successor in BST/Solution.py b/solution/0200-0299/0285.Inorder Successor in BST/Solution.py index efa797820cdf8..06c22dfa72df1 100644 --- a/solution/0200-0299/0285.Inorder Successor in BST/Solution.py +++ b/solution/0200-0299/0285.Inorder Successor in BST/Solution.py @@ -1,18 +1,18 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None - - -class Solution: - def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> Optional[TreeNode]: - ans = None - while root: - if root.val > p.val: - ans = root - root = root.left - else: - root = root.right - return ans +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution: + def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> Optional[TreeNode]: + ans = None + while root: + if root.val > p.val: + ans = root + root = root.left + else: + root = root.right + return ans diff --git a/solution/0200-0299/0286.Walls and Gates/Solution.py b/solution/0200-0299/0286.Walls and Gates/Solution.py index 5478a4a0ac4ac..463270986315f 100644 --- a/solution/0200-0299/0286.Walls and Gates/Solution.py +++ b/solution/0200-0299/0286.Walls and Gates/Solution.py @@ -1,18 +1,18 @@ -class Solution: - def wallsAndGates(self, rooms: List[List[int]]) -> None: - """ - Do not return anything, modify rooms in-place instead. - """ - m, n = len(rooms), len(rooms[0]) - inf = 2**31 - 1 - q = deque([(i, j) for i in range(m) for j in range(n) if rooms[i][j] == 0]) - d = 0 - while q: - d += 1 - for _ in range(len(q)): - i, j = q.popleft() - for a, b in [[0, 1], [0, -1], [1, 0], [-1, 0]]: - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n and rooms[x][y] == inf: - rooms[x][y] = d - q.append((x, y)) +class Solution: + def wallsAndGates(self, rooms: List[List[int]]) -> None: + """ + Do not return anything, modify rooms in-place instead. + """ + m, n = len(rooms), len(rooms[0]) + inf = 2**31 - 1 + q = deque([(i, j) for i in range(m) for j in range(n) if rooms[i][j] == 0]) + d = 0 + while q: + d += 1 + for _ in range(len(q)): + i, j = q.popleft() + for a, b in [[0, 1], [0, -1], [1, 0], [-1, 0]]: + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n and rooms[x][y] == inf: + rooms[x][y] = d + q.append((x, y)) diff --git a/solution/0200-0299/0287.Find the Duplicate Number/Solution.cpp b/solution/0200-0299/0287.Find the Duplicate Number/Solution.cpp index fd2a87b637bbe..bcf7d77c8743f 100644 --- a/solution/0200-0299/0287.Find the Duplicate Number/Solution.cpp +++ b/solution/0200-0299/0287.Find the Duplicate Number/Solution.cpp @@ -1,19 +1,19 @@ -class Solution { -public: - int findDuplicate(vector& nums) { - int l = 0, r = nums.size() - 1; - while (l < r) { - int mid = (l + r) >> 1; - int cnt = 0; - for (int& v : nums) { - cnt += v <= mid; - } - if (cnt > mid) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } +class Solution { +public: + int findDuplicate(vector& nums) { + int l = 0, r = nums.size() - 1; + while (l < r) { + int mid = (l + r) >> 1; + int cnt = 0; + for (int& v : nums) { + cnt += v <= mid; + } + if (cnt > mid) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } }; \ No newline at end of file diff --git a/solution/0200-0299/0287.Find the Duplicate Number/Solution.java b/solution/0200-0299/0287.Find the Duplicate Number/Solution.java index 92f2fe43eec0b..59d594ff4da2d 100644 --- a/solution/0200-0299/0287.Find the Duplicate Number/Solution.java +++ b/solution/0200-0299/0287.Find the Duplicate Number/Solution.java @@ -1,20 +1,20 @@ -class Solution { - public int findDuplicate(int[] nums) { - int l = 0, r = nums.length - 1; - while (l < r) { - int mid = (l + r) >> 1; - int cnt = 0; - for (int v : nums) { - if (v <= mid) { - ++cnt; - } - } - if (cnt > mid) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } +class Solution { + public int findDuplicate(int[] nums) { + int l = 0, r = nums.length - 1; + while (l < r) { + int mid = (l + r) >> 1; + int cnt = 0; + for (int v : nums) { + if (v <= mid) { + ++cnt; + } + } + if (cnt > mid) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } } \ No newline at end of file diff --git a/solution/0200-0299/0287.Find the Duplicate Number/Solution.py b/solution/0200-0299/0287.Find the Duplicate Number/Solution.py index d93a0b28bcbc8..3fab8dd17d025 100644 --- a/solution/0200-0299/0287.Find the Duplicate Number/Solution.py +++ b/solution/0200-0299/0287.Find the Duplicate Number/Solution.py @@ -1,6 +1,6 @@ -class Solution: - def findDuplicate(self, nums: List[int]) -> int: - def f(x: int) -> bool: - return sum(v <= x for v in nums) > x - - return bisect_left(range(len(nums)), True, key=f) +class Solution: + def findDuplicate(self, nums: List[int]) -> int: + def f(x: int) -> bool: + return sum(v <= x for v in nums) > x + + return bisect_left(range(len(nums)), True, key=f) diff --git a/solution/0200-0299/0289.Game of Life/Solution.cs b/solution/0200-0299/0289.Game of Life/Solution.cs index fdfe30ca03e6c..72707233ebfd6 100644 --- a/solution/0200-0299/0289.Game of Life/Solution.cs +++ b/solution/0200-0299/0289.Game of Life/Solution.cs @@ -31,4 +31,4 @@ public void GameOfLife(int[][] board) { } } } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0290.Word Pattern/Solution.cs b/solution/0200-0299/0290.Word Pattern/Solution.cs index 792ec256076eb..8787383508408 100644 --- a/solution/0200-0299/0290.Word Pattern/Solution.cs +++ b/solution/0200-0299/0290.Word Pattern/Solution.cs @@ -20,4 +20,4 @@ public bool WordPattern(string pattern, string s) { } return true; } -} \ No newline at end of file +} diff --git a/solution/0200-0299/0294.Flip Game II/Solution2.cpp b/solution/0200-0299/0294.Flip Game II/Solution2.cpp new file mode 100644 index 0000000000000..34d207d91c6b2 --- /dev/null +++ b/solution/0200-0299/0294.Flip Game II/Solution2.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + bool canWin(string currentState) { + int n = currentState.size(); + vector sg(n + 1, -1); + sg[0] = 0, sg[1] = 0; + + function win = [&](int i) { + if (sg[i] != -1) return sg[i]; + vector vis(n); + for (int j = 0; j < i - 1; ++j) vis[win(j) ^ win(i - j - 2)] = true; + for (int j = 0; j < n; ++j) + if (!vis[j]) return sg[i] = j; + return 0; + }; + + int ans = 0, i = 0; + while (i < n) { + int j = i; + while (j < n && currentState[j] == '+') ++j; + ans ^= win(j - i); + i = j + 1; + } + return ans > 0; + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0294.Flip Game II/Solution2.go b/solution/0200-0299/0294.Flip Game II/Solution2.go new file mode 100644 index 0000000000000..9597d63285a9a --- /dev/null +++ b/solution/0200-0299/0294.Flip Game II/Solution2.go @@ -0,0 +1,34 @@ +func canWin(currentState string) bool { + n := len(currentState) + sg := make([]int, n+1) + for i := range sg { + sg[i] = -1 + } + var win func(i int) int + win = func(i int) int { + if sg[i] != -1 { + return sg[i] + } + vis := make([]bool, n) + for j := 0; j < i-1; j++ { + vis[win(j)^win(i-j-2)] = true + } + for j := 0; j < n; j++ { + if !vis[j] { + sg[i] = j + return j + } + } + return 0 + } + ans, i := 0, 0 + for i < n { + j := i + for j < n && currentState[j] == '+' { + j++ + } + ans ^= win(j - i) + i = j + 1 + } + return ans > 0 +} \ No newline at end of file diff --git a/solution/0200-0299/0294.Flip Game II/Solution2.java b/solution/0200-0299/0294.Flip Game II/Solution2.java new file mode 100644 index 0000000000000..d22e52856e1fe --- /dev/null +++ b/solution/0200-0299/0294.Flip Game II/Solution2.java @@ -0,0 +1,38 @@ +class Solution { + private int n; + private int[] sg; + + public boolean canWin(String currentState) { + n = currentState.length(); + sg = new int[n + 1]; + Arrays.fill(sg, -1); + int i = 0; + int ans = 0; + while (i < n) { + int j = i; + while (j < n && currentState.charAt(j) == '+') { + ++j; + } + ans ^= win(j - i); + i = j + 1; + } + return ans > 0; + } + + private int win(int i) { + if (sg[i] != -1) { + return sg[i]; + } + boolean[] vis = new boolean[n]; + for (int j = 0; j < i - 1; ++j) { + vis[win(j) ^ win(i - j - 2)] = true; + } + for (int j = 0; j < n; ++j) { + if (!vis[j]) { + sg[i] = j; + return j; + } + } + return 0; + } +} \ No newline at end of file diff --git a/solution/0200-0299/0294.Flip Game II/Solution2.py b/solution/0200-0299/0294.Flip Game II/Solution2.py new file mode 100644 index 0000000000000..0e3f9bb3f8983 --- /dev/null +++ b/solution/0200-0299/0294.Flip Game II/Solution2.py @@ -0,0 +1,25 @@ +class Solution: + def canWin(self, currentState: str) -> bool: + def win(i): + if sg[i] != -1: + return sg[i] + vis = [False] * n + for j in range(i - 1): + vis[win(j) ^ win(i - j - 2)] = True + for j in range(n): + if not vis[j]: + sg[i] = j + return j + return 0 + + n = len(currentState) + sg = [-1] * (n + 1) + sg[0] = sg[1] = 0 + ans = i = 0 + while i < n: + j = i + while j < n and currentState[j] == '+': + j += 1 + ans ^= win(j - i) + i = j + 1 + return ans > 0 diff --git a/solution/0200-0299/0295.Find Median from Data Stream/Solution.cs b/solution/0200-0299/0295.Find Median from Data Stream/Solution.cs index e615ae7364a6f..9ec974fe07e5f 100644 --- a/solution/0200-0299/0295.Find Median from Data Stream/Solution.cs +++ b/solution/0200-0299/0295.Find Median from Data Stream/Solution.cs @@ -20,7 +20,7 @@ private int FindIndex(int val) { } return left; } - + public void AddNum(int num) { if (nums.Count == 0) { nums.Add(num); @@ -34,7 +34,7 @@ public void AddNum(int num) { } } } - + public double FindMedian() { if (nums.Count % 2 == 1) { return (double)nums[nums.Count / 2]; @@ -53,4 +53,4 @@ public double FindMedian() { * MedianFinder obj = new MedianFinder(); * obj.AddNum(num); * double param_2 = obj.FindMedian(); - */ \ No newline at end of file + */ diff --git a/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/Solution.cpp b/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/Solution.cpp index a55345bc92edf..0fccee9619eb2 100644 --- a/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/Solution.cpp +++ b/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/Solution.cpp @@ -47,4 +47,4 @@ class Codec { // Your Codec object will be instantiated and called as such: // Codec ser, deser; -// TreeNode* ans = deser.deserialize(ser.serialize(root)); +// TreeNode* ans = deser.deserialize(ser.serialize(root)); \ No newline at end of file diff --git a/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/Solution.ts b/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/Solution.ts index 79799a58d04b9..12d87a784faf6 100644 --- a/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/Solution.ts +++ b/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/Solution.ts @@ -16,30 +16,14 @@ * Encodes a tree to a single string. */ function serialize(root: TreeNode | null): string { - if (root == null) { - return '#'; - } - const { val, left, right } = root; - return `${val},${serialize(left)},${serialize(right)}`; + return JSON.stringify(root); } /* * Decodes your encoded data to tree. */ function deserialize(data: string): TreeNode | null { - const n = data.length; - if (n === 1) { - return null; - } - const vals = data.split(',').reverse(); - const renew = () => { - const val = vals.pop(); - if (val == null || val === '#') { - return null; - } - return new TreeNode(Number(val), renew(), renew()); - }; - return renew(); + return JSON.parse(data); } /** diff --git a/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/Solution2.ts b/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/Solution2.ts new file mode 100644 index 0000000000000..79799a58d04b9 --- /dev/null +++ b/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/Solution2.ts @@ -0,0 +1,48 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +/* + * Encodes a tree to a single string. + */ +function serialize(root: TreeNode | null): string { + if (root == null) { + return '#'; + } + const { val, left, right } = root; + return `${val},${serialize(left)},${serialize(right)}`; +} + +/* + * Decodes your encoded data to tree. + */ +function deserialize(data: string): TreeNode | null { + const n = data.length; + if (n === 1) { + return null; + } + const vals = data.split(',').reverse(); + const renew = () => { + const val = vals.pop(); + if (val == null || val === '#') { + return null; + } + return new TreeNode(Number(val), renew(), renew()); + }; + return renew(); +} + +/** + * Your functions will be called as such: + * deserialize(serialize(root)); + */ diff --git a/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/Solution.cpp b/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/Solution.cpp index d75840fb2a68b..8548da2a774ae 100644 --- a/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/Solution.cpp +++ b/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/Solution.cpp @@ -1,35 +1,35 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int longestConsecutive(TreeNode* root) { - int ans = 0; - function dfs = [&](TreeNode* root) { - if (!root) { - return 0; - } - int l = dfs(root->left) + 1; - int r = dfs(root->right) + 1; - if (root->left && root->left->val - root->val != 1) { - l = 1; - } - if (root->right && root->right->val - root->val != 1) { - r = 1; - } - int t = max(l, r); - ans = max(ans, t); - return t; - }; - dfs(root); - return ans; - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int longestConsecutive(TreeNode* root) { + int ans = 0; + function dfs = [&](TreeNode* root) { + if (!root) { + return 0; + } + int l = dfs(root->left) + 1; + int r = dfs(root->right) + 1; + if (root->left && root->left->val - root->val != 1) { + l = 1; + } + if (root->right && root->right->val - root->val != 1) { + r = 1; + } + int t = max(l, r); + ans = max(ans, t); + return t; + }; + dfs(root); + return ans; + } }; \ No newline at end of file diff --git a/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/Solution.java b/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/Solution.java index c20b889faa339..d21f2e2e4a0bd 100644 --- a/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/Solution.java +++ b/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/Solution.java @@ -1,40 +1,40 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private int ans; - - public int longestConsecutive(TreeNode root) { - dfs(root); - return ans; - } - - private int dfs(TreeNode root) { - if (root == null) { - return 0; - } - int l = dfs(root.left) + 1; - int r = dfs(root.right) + 1; - if (root.left != null && root.left.val - root.val != 1) { - l = 1; - } - if (root.right != null && root.right.val - root.val != 1) { - r = 1; - } - int t = Math.max(l, r); - ans = Math.max(ans, t); - return t; - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int ans; + + public int longestConsecutive(TreeNode root) { + dfs(root); + return ans; + } + + private int dfs(TreeNode root) { + if (root == null) { + return 0; + } + int l = dfs(root.left) + 1; + int r = dfs(root.right) + 1; + if (root.left != null && root.left.val - root.val != 1) { + l = 1; + } + if (root.right != null && root.right.val - root.val != 1) { + r = 1; + } + int t = Math.max(l, r); + ans = Math.max(ans, t); + return t; + } } \ No newline at end of file diff --git a/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/Solution.py b/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/Solution.py index c7e7eed0d70a2..11a78d86d6205 100644 --- a/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/Solution.py +++ b/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/Solution.py @@ -1,25 +1,25 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def longestConsecutive(self, root: Optional[TreeNode]) -> int: - def dfs(root: Optional[TreeNode]) -> int: - if root is None: - return 0 - l = dfs(root.left) + 1 - r = dfs(root.right) + 1 - if root.left and root.left.val - root.val != 1: - l = 1 - if root.right and root.right.val - root.val != 1: - r = 1 - t = max(l, r) - nonlocal ans - ans = max(ans, t) - return t - - ans = 0 - dfs(root) - return ans +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def longestConsecutive(self, root: Optional[TreeNode]) -> int: + def dfs(root: Optional[TreeNode]) -> int: + if root is None: + return 0 + l = dfs(root.left) + 1 + r = dfs(root.right) + 1 + if root.left and root.left.val - root.val != 1: + l = 1 + if root.right and root.right.val - root.val != 1: + r = 1 + t = max(l, r) + nonlocal ans + ans = max(ans, t) + return t + + ans = 0 + dfs(root) + return ans diff --git a/solution/0200-0299/0299.Bulls and Cows/Solution.php b/solution/0200-0299/0299.Bulls and Cows/Solution.php index 1608c6d4f5bb3..23ecd3530e7a2 100644 --- a/solution/0200-0299/0299.Bulls and Cows/Solution.php +++ b/solution/0200-0299/0299.Bulls and Cows/Solution.php @@ -23,4 +23,4 @@ function getHint($secret, $guess) { } return $cntA . 'A' . $cntB . 'B'; } -} \ No newline at end of file +} diff --git a/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.cpp b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.cpp index 32b00bcd974d8..b5e7fa5f598ea 100644 --- a/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.cpp +++ b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.cpp @@ -1,42 +1,15 @@ -class BinaryIndexedTree { -public: - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int v) { - while (x <= n) { - c[x] = max(c[x], v); - x += x & -x; - } - } - - int query(int x) { - int mx = 0; - while (x) { - mx = max(mx, c[x]); - x -= x & -x; - } - return mx; - } - -private: - int n; - vector c; -}; - -class Solution { -public: - int lengthOfLIS(vector& nums) { - vector s = nums; - sort(s.begin(), s.end()); - s.erase(unique(s.begin(), s.end()), s.end()); - BinaryIndexedTree tree(s.size()); - for (int x : nums) { - x = lower_bound(s.begin(), s.end(), x) - s.begin() + 1; - int t = tree.query(x - 1) + 1; - tree.update(x, t); - } - return tree.query(s.size()); - } +class Solution { +public: + int lengthOfLIS(vector& nums) { + int n = nums.size(); + vector f(n, 1); + for (int i = 1; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + f[i] = max(f[i], f[j] + 1); + } + } + } + return *max_element(f.begin(), f.end()); + } }; \ No newline at end of file diff --git a/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.go b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.go index f0964952f98fb..c4149d2d51925 100644 --- a/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.go +++ b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.go @@ -1,45 +1,17 @@ -type BinaryIndexedTree struct { - n int - c []int -} - -func newBinaryIndexedTree(n int) *BinaryIndexedTree { - return &BinaryIndexedTree{n, make([]int, n+1)} -} - -func (bit *BinaryIndexedTree) update(x, v int) { - for x <= bit.n { - bit.c[x] = max(bit.c[x], v) - x += x & -x - } -} - -func (bit *BinaryIndexedTree) query(x int) int { - mx := 0 - for x > 0 { - mx = max(mx, bit.c[x]) - x -= x & -x - } - return mx -} - func lengthOfLIS(nums []int) int { n := len(nums) - s := make([]int, n) - copy(s, nums) - sort.Ints(s) - m := 0 - for i, x := range s { - if i == 0 || x != s[i-1] { - s[m] = x - m++ - } + f := make([]int, n) + for i := range f { + f[i] = 1 } - tree := newBinaryIndexedTree(m) - for _, x := range nums { - x = sort.SearchInts(s[:m], x) + 1 - t := tree.query(x-1) + 1 - tree.update(x, t) + ans := 1 + for i := 1; i < n; i++ { + for j := 0; j < i; j++ { + if nums[j] < nums[i] { + f[i] = max(f[i], f[j]+1) + ans = max(ans, f[i]) + } + } } - return tree.query(m) + return ans } \ No newline at end of file diff --git a/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.java b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.java index a3ef69c256207..369d2f0413c2c 100644 --- a/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.java +++ b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.java @@ -1,59 +1,17 @@ -class Solution { - public int lengthOfLIS(int[] nums) { - int[] s = nums.clone(); - Arrays.sort(s); - int m = 0; - int n = s.length; - for (int i = 0; i < n; ++i) { - if (i == 0 || s[i] != s[i - 1]) { - s[m++] = s[i]; - } - } - BinaryIndexedTree tree = new BinaryIndexedTree(m); - for (int x : nums) { - x = search(s, x, m); - int t = tree.query(x - 1) + 1; - tree.update(x, t); - } - return tree.query(m); - } - - private int search(int[] nums, int x, int r) { - int l = 0; - while (l < r) { - int mid = (l + r) >> 1; - if (nums[mid] >= x) { - r = mid; - } else { - l = mid + 1; - } - } - return l + 1; - } -} - -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void update(int x, int v) { - while (x <= n) { - c[x] = Math.max(c[x], v); - x += x & -x; - } - } - - public int query(int x) { - int mx = 0; - while (x > 0) { - mx = Math.max(mx, c[x]); - x -= x & -x; - } - return mx; - } +class Solution { + public int lengthOfLIS(int[] nums) { + int n = nums.length; + int[] f = new int[n]; + Arrays.fill(f, 1); + int ans = 1; + for (int i = 1; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + f[i] = Math.max(f[i], f[j] + 1); + } + } + ans = Math.max(ans, f[i]); + } + return ans; + } } \ No newline at end of file diff --git a/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.py b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.py index 93da3555010d0..c0db5c2596876 100644 --- a/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.py +++ b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.py @@ -1,28 +1,9 @@ -class BinaryIndexedTree: - def __init__(self, n: int): - self.n = n - self.c = [0] * (n + 1) - - def update(self, x: int, v: int): - while x <= self.n: - self.c[x] = max(self.c[x], v) - x += x & -x - - def query(self, x: int) -> int: - mx = 0 - while x: - mx = max(mx, self.c[x]) - x -= x & -x - return mx - - -class Solution: - def lengthOfLIS(self, nums: List[int]) -> int: - s = sorted(set(nums)) - m = len(s) - tree = BinaryIndexedTree(m) - for x in nums: - x = bisect_left(s, x) + 1 - t = tree.query(x - 1) + 1 - tree.update(x, t) - return tree.query(m) +class Solution: + def lengthOfLIS(self, nums: List[int]) -> int: + n = len(nums) + f = [1] * n + for i in range(1, n): + for j in range(i): + if nums[j] < nums[i]: + f[i] = max(f[i], f[j] + 1) + return max(f) diff --git a/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.ts b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.ts index 830d94c103efa..12631fca24aa4 100644 --- a/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.ts +++ b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution.ts @@ -1,51 +1,12 @@ -class BinaryIndexedTree { - private n: number; - private c: number[]; - - constructor(n: number) { - this.n = n; - this.c = new Array(n + 1).fill(0); - } - - update(x: number, v: number) { - while (x <= this.n) { - this.c[x] = Math.max(this.c[x], v); - x += x & -x; - } - } - - query(x: number): number { - let mx = 0; - while (x) { - mx = Math.max(mx, this.c[x]); - x -= x & -x; - } - return mx; - } -} - function lengthOfLIS(nums: number[]): number { - const s = [...new Set(nums)].sort((a, b) => a - b); - const m = s.length; - const tree = new BinaryIndexedTree(m); - for (let x of nums) { - x = search(s, x); - const t = tree.query(x - 1) + 1; - tree.update(x, t); - } - return tree.query(m); -} - -function search(nums: number[], x: number): number { - let l = 0, - r = nums.length - 1; - while (l < r) { - const mid = (l + r) >> 1; - if (nums[mid] >= x) { - r = mid; - } else { - l = mid + 1; + const n = nums.length; + const f: number[] = new Array(n).fill(1); + for (let i = 1; i < n; ++i) { + for (let j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + f[i] = Math.max(f[i], f[j] + 1); + } } } - return l + 1; + return Math.max(...f); } diff --git a/solution/0300-0399/0300.Longest Increasing Subsequence/Solution2.cpp b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution2.cpp new file mode 100644 index 0000000000000..f8eceab0f273f --- /dev/null +++ b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution2.cpp @@ -0,0 +1,42 @@ +class BinaryIndexedTree { +public: + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int v) { + while (x <= n) { + c[x] = max(c[x], v); + x += x & -x; + } + } + + int query(int x) { + int mx = 0; + while (x) { + mx = max(mx, c[x]); + x -= x & -x; + } + return mx; + } + +private: + int n; + vector c; +}; + +class Solution { +public: + int lengthOfLIS(vector& nums) { + vector s = nums; + sort(s.begin(), s.end()); + s.erase(unique(s.begin(), s.end()), s.end()); + BinaryIndexedTree tree(s.size()); + for (int x : nums) { + x = lower_bound(s.begin(), s.end(), x) - s.begin() + 1; + int t = tree.query(x - 1) + 1; + tree.update(x, t); + } + return tree.query(s.size()); + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0300.Longest Increasing Subsequence/Solution2.go b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution2.go new file mode 100644 index 0000000000000..f0964952f98fb --- /dev/null +++ b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution2.go @@ -0,0 +1,45 @@ +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + return &BinaryIndexedTree{n, make([]int, n+1)} +} + +func (bit *BinaryIndexedTree) update(x, v int) { + for x <= bit.n { + bit.c[x] = max(bit.c[x], v) + x += x & -x + } +} + +func (bit *BinaryIndexedTree) query(x int) int { + mx := 0 + for x > 0 { + mx = max(mx, bit.c[x]) + x -= x & -x + } + return mx +} + +func lengthOfLIS(nums []int) int { + n := len(nums) + s := make([]int, n) + copy(s, nums) + sort.Ints(s) + m := 0 + for i, x := range s { + if i == 0 || x != s[i-1] { + s[m] = x + m++ + } + } + tree := newBinaryIndexedTree(m) + for _, x := range nums { + x = sort.SearchInts(s[:m], x) + 1 + t := tree.query(x-1) + 1 + tree.update(x, t) + } + return tree.query(m) +} \ No newline at end of file diff --git a/solution/0300-0399/0300.Longest Increasing Subsequence/Solution2.java b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution2.java new file mode 100644 index 0000000000000..913c489f4e3c3 --- /dev/null +++ b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution2.java @@ -0,0 +1,59 @@ +class Solution { + public int lengthOfLIS(int[] nums) { + int[] s = nums.clone(); + Arrays.sort(s); + int m = 0; + int n = s.length; + for (int i = 0; i < n; ++i) { + if (i == 0 || s[i] != s[i - 1]) { + s[m++] = s[i]; + } + } + BinaryIndexedTree tree = new BinaryIndexedTree(m); + for (int x : nums) { + x = search(s, x, m); + int t = tree.query(x - 1) + 1; + tree.update(x, t); + } + return tree.query(m); + } + + private int search(int[] nums, int x, int r) { + int l = 0; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l + 1; + } +} + +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int v) { + while (x <= n) { + c[x] = Math.max(c[x], v); + x += x & -x; + } + } + + public int query(int x) { + int mx = 0; + while (x > 0) { + mx = Math.max(mx, c[x]); + x -= x & -x; + } + return mx; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0300.Longest Increasing Subsequence/Solution2.py b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution2.py new file mode 100644 index 0000000000000..5afe46f9c16ff --- /dev/null +++ b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution2.py @@ -0,0 +1,28 @@ +class BinaryIndexedTree: + def __init__(self, n: int): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x: int, v: int): + while x <= self.n: + self.c[x] = max(self.c[x], v) + x += x & -x + + def query(self, x: int) -> int: + mx = 0 + while x: + mx = max(mx, self.c[x]) + x -= x & -x + return mx + + +class Solution: + def lengthOfLIS(self, nums: List[int]) -> int: + s = sorted(set(nums)) + m = len(s) + tree = BinaryIndexedTree(m) + for x in nums: + x = bisect_left(s, x) + 1 + t = tree.query(x - 1) + 1 + tree.update(x, t) + return tree.query(m) diff --git a/solution/0300-0399/0300.Longest Increasing Subsequence/Solution2.ts b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution2.ts new file mode 100644 index 0000000000000..830d94c103efa --- /dev/null +++ b/solution/0300-0399/0300.Longest Increasing Subsequence/Solution2.ts @@ -0,0 +1,51 @@ +class BinaryIndexedTree { + private n: number; + private c: number[]; + + constructor(n: number) { + this.n = n; + this.c = new Array(n + 1).fill(0); + } + + update(x: number, v: number) { + while (x <= this.n) { + this.c[x] = Math.max(this.c[x], v); + x += x & -x; + } + } + + query(x: number): number { + let mx = 0; + while (x) { + mx = Math.max(mx, this.c[x]); + x -= x & -x; + } + return mx; + } +} + +function lengthOfLIS(nums: number[]): number { + const s = [...new Set(nums)].sort((a, b) => a - b); + const m = s.length; + const tree = new BinaryIndexedTree(m); + for (let x of nums) { + x = search(s, x); + const t = tree.query(x - 1) + 1; + tree.update(x, t); + } + return tree.query(m); +} + +function search(nums: number[], x: number): number { + let l = 0, + r = nums.length - 1; + while (l < r) { + const mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l + 1; +} diff --git a/solution/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/Solution.java b/solution/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/Solution.java index 6506e4e53c8c6..174a042d7f399 100644 --- a/solution/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/Solution.java +++ b/solution/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/Solution.java @@ -1,4 +1,5 @@ class Solution { + public int minArea(char[][] image, int x, int y) { int m = image.length, n = image[0].length; int left = 0, right = x; diff --git a/solution/0300-0399/0303.Range Sum Query - Immutable/Solution.c b/solution/0300-0399/0303.Range Sum Query - Immutable/Solution.c index 885e2f173cd07..d9d64ce6e825c 100644 --- a/solution/0300-0399/0303.Range Sum Query - Immutable/Solution.c +++ b/solution/0300-0399/0303.Range Sum Query - Immutable/Solution.c @@ -1,31 +1,31 @@ -typedef struct { - int* s; -} NumArray; - -NumArray* numArrayCreate(int* nums, int n) { - int* s = malloc(sizeof(int) * (n + 1)); - s[0] = 0; - for (int i = 0; i < n; i++) { - s[i + 1] = s[i] + nums[i]; - } - NumArray* obj = malloc(sizeof(NumArray)); - obj->s = s; - return obj; -} - -int numArraySumRange(NumArray* obj, int left, int right) { - return obj->s[right + 1] - obj->s[left]; -} - -void numArrayFree(NumArray* obj) { - free(obj->s); - free(obj); -} - -/** - * Your NumArray struct will be instantiated and called as such: - * NumArray* obj = numArrayCreate(nums, numsSize); - * int param_1 = numArraySumRange(obj, left, right); - - * numArrayFree(obj); +typedef struct { + int* s; +} NumArray; + +NumArray* numArrayCreate(int* nums, int n) { + int* s = malloc(sizeof(int) * (n + 1)); + s[0] = 0; + for (int i = 0; i < n; i++) { + s[i + 1] = s[i] + nums[i]; + } + NumArray* obj = malloc(sizeof(NumArray)); + obj->s = s; + return obj; +} + +int numArraySumRange(NumArray* obj, int left, int right) { + return obj->s[right + 1] - obj->s[left]; +} + +void numArrayFree(NumArray* obj) { + free(obj->s); + free(obj); +} + +/** + * Your NumArray struct will be instantiated and called as such: + * NumArray* obj = numArrayCreate(nums, numsSize); + * int param_1 = numArraySumRange(obj, left, right); + + * numArrayFree(obj); */ \ No newline at end of file diff --git a/solution/0300-0399/0303.Range Sum Query - Immutable/Solution.cpp b/solution/0300-0399/0303.Range Sum Query - Immutable/Solution.cpp index 6d43748b70011..d7f42a5432441 100644 --- a/solution/0300-0399/0303.Range Sum Query - Immutable/Solution.cpp +++ b/solution/0300-0399/0303.Range Sum Query - Immutable/Solution.cpp @@ -1,23 +1,23 @@ -class NumArray { -public: - NumArray(vector& nums) { - int n = nums.size(); - s.resize(n + 1); - for (int i = 0; i < n; ++i) { - s[i + 1] = s[i] + nums[i]; - } - } - - int sumRange(int left, int right) { - return s[right + 1] - s[left]; - } - -private: - vector s; -}; - -/** - * Your NumArray object will be instantiated and called as such: - * NumArray* obj = new NumArray(nums); - * int param_1 = obj->sumRange(left,right); +class NumArray { +public: + NumArray(vector& nums) { + int n = nums.size(); + s.resize(n + 1); + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + } + + int sumRange(int left, int right) { + return s[right + 1] - s[left]; + } + +private: + vector s; +}; + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray* obj = new NumArray(nums); + * int param_1 = obj->sumRange(left,right); */ \ No newline at end of file diff --git a/solution/0300-0399/0303.Range Sum Query - Immutable/Solution.php b/solution/0300-0399/0303.Range Sum Query - Immutable/Solution.php index ca25c0e8f5028..2cc6809cbf32d 100644 --- a/solution/0300-0399/0303.Range Sum Query - Immutable/Solution.php +++ b/solution/0300-0399/0303.Range Sum Query - Immutable/Solution.php @@ -23,4 +23,4 @@ function sumRange($left, $right) { * Your NumArray object will be instantiated and called as such: * $obj = NumArray($nums); * $ret_1 = $obj->sumRange($left, $right); - */ \ No newline at end of file + */ diff --git a/solution/0300-0399/0305.Number of Islands II/Solution.cpp b/solution/0300-0399/0305.Number of Islands II/Solution.cpp index 2175b71fe3448..09b6675f17037 100644 --- a/solution/0300-0399/0305.Number of Islands II/Solution.cpp +++ b/solution/0300-0399/0305.Number of Islands II/Solution.cpp @@ -1,62 +1,62 @@ -class UnionFind { -public: - UnionFind(int n) { - p = vector(n); - size = vector(n, 1); - iota(p.begin(), p.end(), 0); - } - - bool unite(int a, int b) { - int pa = find(a), pb = find(b); - if (pa == pb) { - return false; - } - if (size[pa] > size[pb]) { - p[pb] = pa; - size[pa] += size[pb]; - } else { - p[pa] = pb; - size[pb] += size[pa]; - } - return true; - } - - int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } - -private: - vector p, size; -}; - -class Solution { -public: - vector numIslands2(int m, int n, vector>& positions) { - int grid[m][n]; - memset(grid, 0, sizeof(grid)); - UnionFind uf(m * n); - int dirs[5] = {-1, 0, 1, 0, -1}; - int cnt = 0; - vector ans; - for (auto& p : positions) { - int i = p[0], j = p[1]; - if (grid[i][j]) { - ans.push_back(cnt); - continue; - } - grid[i][j] = 1; - ++cnt; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] && uf.union(i * n + j, x * n + y)) { - --cnt; - } - } - ans.push_back(cnt); - } - return ans; - } +class UnionFind { +public: + UnionFind(int n) { + p = vector(n); + size = vector(n, 1); + iota(p.begin(), p.end(), 0); + } + + bool unite(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) { + return false; + } + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + return true; + } + + int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + +private: + vector p, size; +}; + +class Solution { +public: + vector numIslands2(int m, int n, vector>& positions) { + int grid[m][n]; + memset(grid, 0, sizeof(grid)); + UnionFind uf(m * n); + int dirs[5] = {-1, 0, 1, 0, -1}; + int cnt = 0; + vector ans; + for (auto& p : positions) { + int i = p[0], j = p[1]; + if (grid[i][j]) { + ans.push_back(cnt); + continue; + } + grid[i][j] = 1; + ++cnt; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] && uf.unite(i * n + j, x * n + y)) { + --cnt; + } + } + ans.push_back(cnt); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0300-0399/0305.Number of Islands II/Solution.java b/solution/0300-0399/0305.Number of Islands II/Solution.java index e5808e8b70af7..04723bccd3b1b 100644 --- a/solution/0300-0399/0305.Number of Islands II/Solution.java +++ b/solution/0300-0399/0305.Number of Islands II/Solution.java @@ -1,63 +1,63 @@ -class UnionFind { - private final int[] p; - private final int[] size; - - public UnionFind(int n) { - p = new int[n]; - size = new int[n]; - for (int i = 0; i < n; ++i) { - p[i] = i; - size[i] = 1; - } - } - - public int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } - - public boolean union(int a, int b) { - int pa = find(a), pb = find(b); - if (pa == pb) { - return false; - } - if (size[pa] > size[pb]) { - p[pb] = pa; - size[pa] += size[pb]; - } else { - p[pa] = pb; - size[pb] += size[pa]; - } - return true; - } -} - -class Solution { - public List numIslands2(int m, int n, int[][] positions) { - int[][] grid = new int[m][n]; - UnionFind uf = new UnionFind(m * n); - int[] dirs = {-1, 0, 1, 0, -1}; - int cnt = 0; - List ans = new ArrayList<>(); - for (var p : positions) { - int i = p[0], j = p[1]; - if (grid[i][j] == 1) { - ans.add(cnt); - continue; - } - grid[i][j] = 1; - ++cnt; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1 - && uf.union(i * n + j, x * n + y)) { - --cnt; - } - } - ans.add(cnt); - } - return ans; - } +class UnionFind { + private final int[] p; + private final int[] size; + + public UnionFind(int n) { + p = new int[n]; + size = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + size[i] = 1; + } + } + + public int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + + public boolean union(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) { + return false; + } + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + return true; + } +} + +class Solution { + public List numIslands2(int m, int n, int[][] positions) { + int[][] grid = new int[m][n]; + UnionFind uf = new UnionFind(m * n); + int[] dirs = {-1, 0, 1, 0, -1}; + int cnt = 0; + List ans = new ArrayList<>(); + for (var p : positions) { + int i = p[0], j = p[1]; + if (grid[i][j] == 1) { + ans.add(cnt); + continue; + } + grid[i][j] = 1; + ++cnt; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1 + && uf.union(i * n + j, x * n + y)) { + --cnt; + } + } + ans.add(cnt); + } + return ans; + } } \ No newline at end of file diff --git a/solution/0300-0399/0305.Number of Islands II/Solution.py b/solution/0300-0399/0305.Number of Islands II/Solution.py index 738f6d2ccc4cc..9d3c651ca748e 100644 --- a/solution/0300-0399/0305.Number of Islands II/Solution.py +++ b/solution/0300-0399/0305.Number of Islands II/Solution.py @@ -1,47 +1,47 @@ -class UnionFind: - def __init__(self, n: int): - self.p = list(range(n)) - self.size = [1] * n - - def find(self, x: int): - if self.p[x] != x: - self.p[x] = self.find(self.p[x]) - return self.p[x] - - def union(self, a: int, b: int) -> bool: - pa, pb = self.find(a - 1), self.find(b - 1) - if pa == pb: - return False - if self.size[pa] > self.size[pb]: - self.p[pb] = pa - self.size[pa] += self.size[pb] - else: - self.p[pa] = pb - self.size[pb] += self.size[pa] - return True - - -class Solution: - def numIslands2(self, m: int, n: int, positions: List[List[int]]) -> List[int]: - uf = UnionFind(m * n) - grid = [[0] * n for _ in range(m)] - ans = [] - dirs = (-1, 0, 1, 0, -1) - cnt = 0 - for i, j in positions: - if grid[i][j]: - ans.append(cnt) - continue - grid[i][j] = 1 - cnt += 1 - for a, b in pairwise(dirs): - x, y = i + a, j + b - if ( - 0 <= x < m - and 0 <= y < n - and grid[x][y] - and uf.union(i * n + j, x * n + y) - ): - cnt -= 1 - ans.append(cnt) - return ans +class UnionFind: + def __init__(self, n: int): + self.p = list(range(n)) + self.size = [1] * n + + def find(self, x: int): + if self.p[x] != x: + self.p[x] = self.find(self.p[x]) + return self.p[x] + + def union(self, a: int, b: int) -> bool: + pa, pb = self.find(a - 1), self.find(b - 1) + if pa == pb: + return False + if self.size[pa] > self.size[pb]: + self.p[pb] = pa + self.size[pa] += self.size[pb] + else: + self.p[pa] = pb + self.size[pb] += self.size[pa] + return True + + +class Solution: + def numIslands2(self, m: int, n: int, positions: List[List[int]]) -> List[int]: + uf = UnionFind(m * n) + grid = [[0] * n for _ in range(m)] + ans = [] + dirs = (-1, 0, 1, 0, -1) + cnt = 0 + for i, j in positions: + if grid[i][j]: + ans.append(cnt) + continue + grid[i][j] = 1 + cnt += 1 + for a, b in pairwise(dirs): + x, y = i + a, j + b + if ( + 0 <= x < m + and 0 <= y < n + and grid[x][y] + and uf.union(i * n + j, x * n + y) + ): + cnt -= 1 + ans.append(cnt) + return ans diff --git a/solution/0300-0399/0307.Range Sum Query - Mutable/Solution.cpp b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution.cpp index cbc5b3e8cdc88..d27eb0d405f44 100644 --- a/solution/0300-0399/0307.Range Sum Query - Mutable/Solution.cpp +++ b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution.cpp @@ -1,52 +1,52 @@ -class BinaryIndexedTree { -public: - int n; - vector c; - - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += x & -x; - } - } - - int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= x & -x; - } - return s; - } -}; - -class NumArray { -public: - BinaryIndexedTree* tree; - - NumArray(vector& nums) { - int n = nums.size(); - tree = new BinaryIndexedTree(n); - for (int i = 0; i < n; ++i) tree->update(i + 1, nums[i]); - } - - void update(int index, int val) { - int prev = sumRange(index, index); - tree->update(index + 1, val - prev); - } - - int sumRange(int left, int right) { - return tree->query(right + 1) - tree->query(left); - } -}; - -/** - * Your NumArray object will be instantiated and called as such: - * NumArray* obj = new NumArray(nums); - * obj->update(index,val); - * int param_2 = obj->sumRange(left,right); +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +}; + +class NumArray { +public: + BinaryIndexedTree* tree; + + NumArray(vector& nums) { + int n = nums.size(); + tree = new BinaryIndexedTree(n); + for (int i = 0; i < n; ++i) tree->update(i + 1, nums[i]); + } + + void update(int index, int val) { + int prev = sumRange(index, index); + tree->update(index + 1, val - prev); + } + + int sumRange(int left, int right) { + return tree->query(right + 1) - tree->query(left); + } +}; + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray* obj = new NumArray(nums); + * obj->update(index,val); + * int param_2 = obj->sumRange(left,right); */ \ No newline at end of file diff --git a/solution/0300-0399/0307.Range Sum Query - Mutable/Solution.cs b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution.cs index d23451667b418..7b00c18d4fa6d 100644 --- a/solution/0300-0399/0307.Range Sum Query - Mutable/Solution.cs +++ b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution.cs @@ -1,53 +1,53 @@ -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void Update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += x & -x; - } - } - - public int Query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= x & -x; - } - return s; - } -} - -public class NumArray { - private BinaryIndexedTree tree; - - public NumArray(int[] nums) { - int n = nums.Length; - tree = new BinaryIndexedTree(n); - for (int i = 0; i < n; ++i) { - tree.Update(i + 1, nums[i]); - } - } - - public void Update(int index, int val) { - int prev = SumRange(index, index); - tree.Update(index + 1, val - prev); - } - - public int SumRange(int left, int right) { - return tree.Query(right + 1) - tree.Query(left); - } -} - -/** - * Your NumArray object will be instantiated and called as such: - * NumArray obj = new NumArray(nums); - * obj.Update(index,val); - * int param_2 = obj.SumRange(left,right); - */ \ No newline at end of file +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void Update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + public int Query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +} + +public class NumArray { + private BinaryIndexedTree tree; + + public NumArray(int[] nums) { + int n = nums.Length; + tree = new BinaryIndexedTree(n); + for (int i = 0; i < n; ++i) { + tree.Update(i + 1, nums[i]); + } + } + + public void Update(int index, int val) { + int prev = SumRange(index, index); + tree.Update(index + 1, val - prev); + } + + public int SumRange(int left, int right) { + return tree.Query(right + 1) - tree.Query(left); + } +} + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray obj = new NumArray(nums); + * obj.Update(index,val); + * int param_2 = obj.SumRange(left,right); + */ diff --git a/solution/0300-0399/0307.Range Sum Query - Mutable/Solution.java b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution.java index 719de552f47f8..05b6482c6585f 100644 --- a/solution/0300-0399/0307.Range Sum Query - Mutable/Solution.java +++ b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution.java @@ -1,53 +1,53 @@ -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += x & -x; - } - } - - public int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= x & -x; - } - return s; - } -} - -class NumArray { - private BinaryIndexedTree tree; - - public NumArray(int[] nums) { - int n = nums.length; - tree = new BinaryIndexedTree(n); - for (int i = 0; i < n; ++i) { - tree.update(i + 1, nums[i]); - } - } - - public void update(int index, int val) { - int prev = sumRange(index, index); - tree.update(index + 1, val - prev); - } - - public int sumRange(int left, int right) { - return tree.query(right + 1) - tree.query(left); - } -} - -/** - * Your NumArray object will be instantiated and called as such: - * NumArray obj = new NumArray(nums); - * obj.update(index,val); - * int param_2 = obj.sumRange(left,right); +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +} + +class NumArray { + private BinaryIndexedTree tree; + + public NumArray(int[] nums) { + int n = nums.length; + tree = new BinaryIndexedTree(n); + for (int i = 0; i < n; ++i) { + tree.update(i + 1, nums[i]); + } + } + + public void update(int index, int val) { + int prev = sumRange(index, index); + tree.update(index + 1, val - prev); + } + + public int sumRange(int left, int right) { + return tree.query(right + 1) - tree.query(left); + } +} + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray obj = new NumArray(nums); + * obj.update(index,val); + * int param_2 = obj.sumRange(left,right); */ \ No newline at end of file diff --git a/solution/0300-0399/0307.Range Sum Query - Mutable/Solution.py b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution.py index 125581a2f756c..694f987b7d368 100644 --- a/solution/0300-0399/0307.Range Sum Query - Mutable/Solution.py +++ b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution.py @@ -1,40 +1,40 @@ -class BinaryIndexedTree: - __slots__ = ["n", "c"] - - def __init__(self, n): - self.n = n - self.c = [0] * (n + 1) - - def update(self, x: int, delta: int): - while x <= self.n: - self.c[x] += delta - x += x & -x - - def query(self, x: int) -> int: - s = 0 - while x > 0: - s += self.c[x] - x -= x & -x - return s - - -class NumArray: - __slots__ = ["tree"] - - def __init__(self, nums: List[int]): - self.tree = BinaryIndexedTree(len(nums)) - for i, v in enumerate(nums, 1): - self.tree.update(i, v) - - def update(self, index: int, val: int) -> None: - prev = self.sumRange(index, index) - self.tree.update(index + 1, val - prev) - - def sumRange(self, left: int, right: int) -> int: - return self.tree.query(right + 1) - self.tree.query(left) - - -# Your NumArray object will be instantiated and called as such: -# obj = NumArray(nums) -# obj.update(index,val) -# param_2 = obj.sumRange(left,right) +class BinaryIndexedTree: + __slots__ = ["n", "c"] + + def __init__(self, n): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x: int, delta: int): + while x <= self.n: + self.c[x] += delta + x += x & -x + + def query(self, x: int) -> int: + s = 0 + while x > 0: + s += self.c[x] + x -= x & -x + return s + + +class NumArray: + __slots__ = ["tree"] + + def __init__(self, nums: List[int]): + self.tree = BinaryIndexedTree(len(nums)) + for i, v in enumerate(nums, 1): + self.tree.update(i, v) + + def update(self, index: int, val: int) -> None: + prev = self.sumRange(index, index) + self.tree.update(index + 1, val - prev) + + def sumRange(self, left: int, right: int) -> int: + return self.tree.query(right + 1) - self.tree.query(left) + + +# Your NumArray object will be instantiated and called as such: +# obj = NumArray(nums) +# obj.update(index,val) +# param_2 = obj.sumRange(left,right) diff --git a/solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.cpp b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.cpp new file mode 100644 index 0000000000000..55d89c7f4cc63 --- /dev/null +++ b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.cpp @@ -0,0 +1,83 @@ +class Node { +public: + int l; + int r; + int v; +}; + +class SegmentTree { +public: + vector tr; + vector nums; + + SegmentTree(vector& nums) { + this->nums = nums; + int n = nums.size(); + tr.resize(n << 2); + for (int i = 0; i < tr.size(); ++i) tr[i] = new Node(); + build(1, 1, n); + } + + void build(int u, int l, int r) { + tr[u]->l = l; + tr[u]->r = r; + if (l == r) { + tr[u]->v = nums[l - 1]; + return; + } + int mid = (l + r) >> 1; + build(u << 1, l, mid); + build(u << 1 | 1, mid + 1, r); + pushup(u); + } + + void modify(int u, int x, int v) { + if (tr[u]->l == x && tr[u]->r == x) { + tr[u]->v = v; + return; + } + int mid = (tr[u]->l + tr[u]->r) >> 1; + if (x <= mid) + modify(u << 1, x, v); + else + modify(u << 1 | 1, x, v); + pushup(u); + } + + int query(int u, int l, int r) { + if (tr[u]->l >= l && tr[u]->r <= r) return tr[u]->v; + int mid = (tr[u]->l + tr[u]->r) >> 1; + int v = 0; + if (l <= mid) v += query(u << 1, l, r); + if (r > mid) v += query(u << 1 | 1, l, r); + return v; + } + + void pushup(int u) { + tr[u]->v = tr[u << 1]->v + tr[u << 1 | 1]->v; + } +}; + +class NumArray { +public: + SegmentTree* tree; + + NumArray(vector& nums) { + tree = new SegmentTree(nums); + } + + void update(int index, int val) { + return tree->modify(1, index + 1, val); + } + + int sumRange(int left, int right) { + return tree->query(1, left + 1, right + 1); + } +}; + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray* obj = new NumArray(nums); + * obj->update(index,val); + * int param_2 = obj->sumRange(left,right); + */ \ No newline at end of file diff --git a/solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.cs b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.cs new file mode 100644 index 0000000000000..dce2fd0d559f5 --- /dev/null +++ b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.cs @@ -0,0 +1,89 @@ +public class Node { + public int l; + public int r; + public int v; +} + +public class SegmentTree { + private Node[] tr; + private int[] nums; + + public SegmentTree(int[] nums) { + this.nums = nums; + int n = nums.Length; + tr = new Node[n << 2]; + for (int i = 0; i < tr.Length; ++i) { + tr[i] = new Node(); + } + Build(1, 1, n); + } + + public void Build(int u, int l, int r) { + tr[u].l = l; + tr[u].r = r; + if (l == r) { + tr[u].v = nums[l - 1]; + return; + } + int mid = (l + r) >> 1; + Build(u << 1, l, mid); + Build(u << 1 | 1, mid + 1, r); + Pushup(u); + } + + public void Modify(int u, int x, int v) { + if (tr[u].l == x && tr[u].r == x) { + tr[u].v = v; + return; + } + int mid = (tr[u].l + tr[u].r) >> 1; + if (x <= mid) { + Modify(u << 1, x, v); + } else { + Modify(u << 1 | 1, x, v); + } + Pushup(u); + } + + public int Query(int u, int l, int r) { + if (tr[u].l >= l && tr[u].r <= r) { + return tr[u].v; + } + int mid = (tr[u].l + tr[u].r) >> 1; + int v = 0; + if (l <= mid) { + v += Query(u << 1, l, r); + } + if (r > mid) { + v += Query(u << 1 | 1, l, r); + } + return v; + } + + public void Pushup(int u) { + tr[u].v = tr[u << 1].v + tr[u << 1 | 1].v; + } +} + +public class NumArray { + private SegmentTree tree; + + public NumArray(int[] nums) { + tree = new SegmentTree(nums); + } + + public void Update(int index, int val) { + tree.Modify(1, index + 1, val); + } + + public int SumRange(int left, int right) { + return tree.Query(1, left + 1, right + 1); + } +} + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray obj = new NumArray(nums); + * obj.Update(index,val); + * int param_2 = obj.SumRange(left,right); + */ diff --git a/solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.go b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.go new file mode 100644 index 0000000000000..e1b46fbc5caf5 --- /dev/null +++ b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.go @@ -0,0 +1,91 @@ +type Node struct { + l, r, v int +} + +type SegmentTree struct { + tr []Node + nums []int +} + +func newSegmentTree(nums []int) *SegmentTree { + n := len(nums) + tr := make([]Node, n<<2) + for i := range tr { + tr[i] = Node{} + } + tree := &SegmentTree{ + tr: tr, + nums: nums, + } + tree.build(1, 1, n) + return tree +} + +func (tree *SegmentTree) build(u, l, r int) { + tree.tr[u].l, tree.tr[u].r = l, r + if l == r { + tree.tr[u].v = tree.nums[l-1] + return + } + mid := (l + r) >> 1 + tree.build(u<<1, l, mid) + tree.build(u<<1|1, mid+1, r) + tree.pushup(u) +} + +func (tree *SegmentTree) modify(u, x, v int) { + if tree.tr[u].l == x && tree.tr[u].r == x { + tree.tr[u].v = v + return + } + mid := (tree.tr[u].l + tree.tr[u].r) >> 1 + if x <= mid { + tree.modify(u<<1, x, v) + } else { + tree.modify(u<<1|1, x, v) + } + tree.pushup(u) +} + +func (tree *SegmentTree) query(u, l, r int) (v int) { + if tree.tr[u].l >= l && tree.tr[u].r <= r { + return tree.tr[u].v + } + mid := (tree.tr[u].l + tree.tr[u].r) >> 1 + if l <= mid { + v += tree.query(u<<1, l, r) + } + if r > mid { + v += tree.query(u<<1|1, l, r) + } + return v +} + +func (tree *SegmentTree) pushup(u int) { + tree.tr[u].v = tree.tr[u<<1].v + tree.tr[u<<1|1].v +} + +type NumArray struct { + tree *SegmentTree +} + +func Constructor(nums []int) NumArray { + return NumArray{ + tree: newSegmentTree(nums), + } +} + +func (this *NumArray) Update(index int, val int) { + this.tree.modify(1, index+1, val) +} + +func (this *NumArray) SumRange(left int, right int) int { + return this.tree.query(1, left+1, right+1) +} + +/** + * Your NumArray object will be instantiated and called as such: + * obj := Constructor(nums); + * obj.Update(index,val); + * param_2 := obj.SumRange(left,right); + */ \ No newline at end of file diff --git a/solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.java b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.java new file mode 100644 index 0000000000000..cbd49266f08c9 --- /dev/null +++ b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.java @@ -0,0 +1,89 @@ +class Node { + int l; + int r; + int v; +} + +class SegmentTree { + private Node[] tr; + private int[] nums; + + public SegmentTree(int[] nums) { + this.nums = nums; + int n = nums.length; + tr = new Node[n << 2]; + for (int i = 0; i < tr.length; ++i) { + tr[i] = new Node(); + } + build(1, 1, n); + } + + public void build(int u, int l, int r) { + tr[u].l = l; + tr[u].r = r; + if (l == r) { + tr[u].v = nums[l - 1]; + return; + } + int mid = (l + r) >> 1; + build(u << 1, l, mid); + build(u << 1 | 1, mid + 1, r); + pushup(u); + } + + public void modify(int u, int x, int v) { + if (tr[u].l == x && tr[u].r == x) { + tr[u].v = v; + return; + } + int mid = (tr[u].l + tr[u].r) >> 1; + if (x <= mid) { + modify(u << 1, x, v); + } else { + modify(u << 1 | 1, x, v); + } + pushup(u); + } + + public int query(int u, int l, int r) { + if (tr[u].l >= l && tr[u].r <= r) { + return tr[u].v; + } + int mid = (tr[u].l + tr[u].r) >> 1; + int v = 0; + if (l <= mid) { + v += query(u << 1, l, r); + } + if (r > mid) { + v += query(u << 1 | 1, l, r); + } + return v; + } + + public void pushup(int u) { + tr[u].v = tr[u << 1].v + tr[u << 1 | 1].v; + } +} + +class NumArray { + private SegmentTree tree; + + public NumArray(int[] nums) { + tree = new SegmentTree(nums); + } + + public void update(int index, int val) { + tree.modify(1, index + 1, val); + } + + public int sumRange(int left, int right) { + return tree.query(1, left + 1, right + 1); + } +} + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray obj = new NumArray(nums); + * obj.update(index,val); + * int param_2 = obj.sumRange(left,right); + */ \ No newline at end of file diff --git a/solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.py b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.py new file mode 100644 index 0000000000000..b019db7879256 --- /dev/null +++ b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.py @@ -0,0 +1,69 @@ +class Node: + __slots__ = ["l", "r", "v"] + + def __init__(self): + self.l = self.r = self.v = 0 + + +class SegmentTree: + __slots__ = ["nums", "tr"] + + def __init__(self, nums): + self.nums = nums + n = len(nums) + self.tr = [Node() for _ in range(n << 2)] + self.build(1, 1, n) + + def build(self, u, l, r): + self.tr[u].l, self.tr[u].r = l, r + if l == r: + self.tr[u].v = self.nums[l - 1] + return + mid = (l + r) >> 1 + self.build(u << 1, l, mid) + self.build(u << 1 | 1, mid + 1, r) + self.pushup(u) + + def modify(self, u, x, v): + if self.tr[u].l == x and self.tr[u].r == x: + self.tr[u].v = v + return + mid = (self.tr[u].l + self.tr[u].r) >> 1 + if x <= mid: + self.modify(u << 1, x, v) + else: + self.modify(u << 1 | 1, x, v) + self.pushup(u) + + def query(self, u, l, r): + if self.tr[u].l >= l and self.tr[u].r <= r: + return self.tr[u].v + mid = (self.tr[u].l + self.tr[u].r) >> 1 + result = 0 + if l <= mid: + result += self.query(u << 1, l, r) + if r > mid: + result += self.query(u << 1 | 1, l, r) + return result + + def pushup(self, u): + self.tr[u].v = self.tr[u << 1].v + self.tr[u << 1 | 1].v + + +class NumArray: + __slots__ = ["tree"] + + def __init__(self, nums: List[int]): + self.tree = SegmentTree(nums) + + def update(self, index: int, val: int) -> None: + self.tree.modify(1, index + 1, val) + + def sumRange(self, left: int, right: int) -> int: + return self.tree.query(1, left + 1, right + 1) + + +# Your NumArray object will be instantiated and called as such: +# obj = NumArray(nums) +# obj.update(index,val) +# param_2 = obj.sumRange(left,right) diff --git a/solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.ts b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.ts new file mode 100644 index 0000000000000..9cf6643c868ec --- /dev/null +++ b/solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.ts @@ -0,0 +1,89 @@ +class Node { + l: number; + r: number; + v: number; +} + +class SegmentTree { + private tr: Node[]; + private nums: number[]; + + constructor(nums: number[]) { + this.nums = nums; + const n = nums.length; + this.tr = new Array(n << 2); + for (let i = 0; i < this.tr.length; ++i) { + this.tr[i] = { l: 0, r: 0, v: 0 }; + } + this.build(1, 1, n); + } + + build(u: number, l: number, r: number): void { + this.tr[u].l = l; + this.tr[u].r = r; + if (l == r) { + this.tr[u].v = this.nums[l - 1]; + return; + } + const mid = (l + r) >> 1; + this.build(u << 1, l, mid); + this.build((u << 1) | 1, mid + 1, r); + this.pushup(u); + } + + modify(u: number, x: number, v: number): void { + if (this.tr[u].l == x && this.tr[u].r == x) { + this.tr[u].v = v; + return; + } + const mid = (this.tr[u].l + this.tr[u].r) >> 1; + if (x <= mid) { + this.modify(u << 1, x, v); + } else { + this.modify((u << 1) | 1, x, v); + } + this.pushup(u); + } + + query(u: number, l: number, r: number): number { + if (this.tr[u].l >= l && this.tr[u].r <= r) { + return this.tr[u].v; + } + const mid = (this.tr[u].l + this.tr[u].r) >> 1; + let v = 0; + if (l <= mid) { + v += this.query(u << 1, l, r); + } + if (r > mid) { + v += this.query((u << 1) | 1, l, r); + } + return v; + } + + pushup(u: number): void { + this.tr[u].v = this.tr[u << 1].v + this.tr[(u << 1) | 1].v; + } +} + +class NumArray { + private tree: SegmentTree; + + constructor(nums: number[]) { + this.tree = new SegmentTree(nums); + } + + update(index: number, val: number): void { + this.tree.modify(1, index + 1, val); + } + + sumRange(left: number, right: number): number { + return this.tree.query(1, left + 1, right + 1); + } +} + +/** + * Your NumArray object will be instantiated and called as such: + * var obj = new NumArray(nums) + * obj.update(index,val) + * var param_2 = obj.sumRange(left,right) + */ diff --git a/solution/0300-0399/0308.Range Sum Query 2D - Mutable/Solution2.cpp b/solution/0300-0399/0308.Range Sum Query 2D - Mutable/Solution2.cpp new file mode 100644 index 0000000000000..0fe906883d771 --- /dev/null +++ b/solution/0300-0399/0308.Range Sum Query 2D - Mutable/Solution2.cpp @@ -0,0 +1,88 @@ +class Node { +public: + int l; + int r; + int v; +}; + +class SegmentTree { +public: + vector tr; + vector nums; + + SegmentTree(vector& nums) { + int n = nums.size(); + tr.resize(n << 2); + this->nums = nums; + for (int i = 0; i < tr.size(); ++i) tr[i] = new Node(); + build(1, 1, n); + } + + void build(int u, int l, int r) { + tr[u]->l = l; + tr[u]->r = r; + if (l == r) { + tr[u]->v = nums[l - 1]; + return; + } + int mid = (l + r) >> 1; + build(u << 1, l, mid); + build(u << 1 | 1, mid + 1, r); + pushup(u); + } + + void modify(int u, int x, int v) { + if (tr[u]->l == x && tr[u]->r == x) { + tr[u]->v = v; + return; + } + int mid = (tr[u]->l + tr[u]->r) >> 1; + if (x <= mid) + modify(u << 1, x, v); + else + modify(u << 1 | 1, x, v); + pushup(u); + } + + int query(int u, int l, int r) { + if (tr[u]->l >= l && tr[u]->r <= r) return tr[u]->v; + int mid = (tr[u]->l + tr[u]->r) >> 1; + int v = 0; + if (l <= mid) v += query(u << 1, l, r); + if (r > mid) v += query(u << 1 | 1, l, r); + return v; + } + + void pushup(int u) { + tr[u]->v = tr[u << 1]->v + tr[u << 1 | 1]->v; + } +}; + +class NumMatrix { +public: + vector trees; + + NumMatrix(vector>& matrix) { + int m = matrix.size(); + trees.resize(m); + for (int i = 0; i < m; ++i) trees[i] = new SegmentTree(matrix[i]); + } + + void update(int row, int col, int val) { + SegmentTree* tree = trees[row]; + tree->modify(1, col + 1, val); + } + + int sumRegion(int row1, int col1, int row2, int col2) { + int s = 0; + for (int row = row1; row <= row2; ++row) s += trees[row]->query(1, col1 + 1, col2 + 1); + return s; + } +}; + +/** + * Your NumMatrix object will be instantiated and called as such: + * NumMatrix* obj = new NumMatrix(matrix); + * obj->update(row,col,val); + * int param_2 = obj->sumRegion(row1,col1,row2,col2); + */ \ No newline at end of file diff --git a/solution/0300-0399/0308.Range Sum Query 2D - Mutable/Solution2.java b/solution/0300-0399/0308.Range Sum Query 2D - Mutable/Solution2.java new file mode 100644 index 0000000000000..84ee36b15a320 --- /dev/null +++ b/solution/0300-0399/0308.Range Sum Query 2D - Mutable/Solution2.java @@ -0,0 +1,99 @@ +class Node { + int l; + int r; + int v; +} + +class SegmentTree { + private Node[] tr; + private int[] nums; + + public SegmentTree(int[] nums) { + int n = nums.length; + tr = new Node[n << 2]; + this.nums = nums; + for (int i = 0; i < tr.length; ++i) { + tr[i] = new Node(); + } + build(1, 1, n); + } + + public void build(int u, int l, int r) { + tr[u].l = l; + tr[u].r = r; + if (l == r) { + tr[u].v = nums[l - 1]; + return; + } + int mid = (l + r) >> 1; + build(u << 1, l, mid); + build(u << 1 | 1, mid + 1, r); + pushup(u); + } + + public void modify(int u, int x, int v) { + if (tr[u].l == x && tr[u].r == x) { + tr[u].v = v; + return; + } + int mid = (tr[u].l + tr[u].r) >> 1; + if (x <= mid) { + modify(u << 1, x, v); + } else { + modify(u << 1 | 1, x, v); + } + pushup(u); + } + + public void pushup(int u) { + tr[u].v = tr[u << 1].v + tr[u << 1 | 1].v; + } + + public int query(int u, int l, int r) { + if (tr[u].l >= l && tr[u].r <= r) { + return tr[u].v; + } + int mid = (tr[u].l + tr[u].r) >> 1; + int v = 0; + if (l <= mid) { + v += query(u << 1, l, r); + } + if (r > mid) { + v += query(u << 1 | 1, l, r); + } + return v; + } +} + +class NumMatrix { + private SegmentTree[] trees; + + public NumMatrix(int[][] matrix) { + int m = matrix.length; + trees = new SegmentTree[m]; + for (int i = 0; i < m; ++i) { + trees[i] = new SegmentTree(matrix[i]); + } + } + + public void update(int row, int col, int val) { + SegmentTree tree = trees[row]; + tree.modify(1, col + 1, val); + } + + public int sumRegion(int row1, int col1, int row2, int col2) { + int s = 0; + for (int row = row1; row <= row2; ++row) { + SegmentTree tree = trees[row]; + s += tree.query(1, col1 + 1, col2 + 1); + } + return s; + } +} + +/** + * Your NumMatrix object will be instantiated and called as such: + * NumMatrix obj = new NumMatrix(matrix); + * obj.update(row,col,val); + * int param_2 = obj.sumRegion(row1,col1,row2,col2); + */ \ No newline at end of file diff --git a/solution/0300-0399/0308.Range Sum Query 2D - Mutable/Solution2.py b/solution/0300-0399/0308.Range Sum Query 2D - Mutable/Solution2.py new file mode 100644 index 0000000000000..4621ee01b56de --- /dev/null +++ b/solution/0300-0399/0308.Range Sum Query 2D - Mutable/Solution2.py @@ -0,0 +1,70 @@ +class Node: + def __init__(self): + self.l = 0 + self.r = 0 + self.v = 0 + + +class SegmentTree: + def __init__(self, nums): + n = len(nums) + self.nums = nums + self.tr = [Node() for _ in range(4 * n)] + self.build(1, 1, n) + + def build(self, u, l, r): + self.tr[u].l = l + self.tr[u].r = r + if l == r: + self.tr[u].v = self.nums[l - 1] + return + mid = (l + r) >> 1 + self.build(u << 1, l, mid) + self.build(u << 1 | 1, mid + 1, r) + self.pushup(u) + + def modify(self, u, x, v): + if self.tr[u].l == x and self.tr[u].r == x: + self.tr[u].v = v + return + mid = (self.tr[u].l + self.tr[u].r) >> 1 + if x <= mid: + self.modify(u << 1, x, v) + else: + self.modify(u << 1 | 1, x, v) + self.pushup(u) + + def query(self, u, l, r): + if self.tr[u].l >= l and self.tr[u].r <= r: + return self.tr[u].v + mid = (self.tr[u].l + self.tr[u].r) >> 1 + v = 0 + if l <= mid: + v += self.query(u << 1, l, r) + if r > mid: + v += self.query(u << 1 | 1, l, r) + return v + + def pushup(self, u): + self.tr[u].v = self.tr[u << 1].v + self.tr[u << 1 | 1].v + + +class NumMatrix: + def __init__(self, matrix: List[List[int]]): + self.trees = [SegmentTree(row) for row in matrix] + + def update(self, row: int, col: int, val: int) -> None: + tree = self.trees[row] + tree.modify(1, col + 1, val) + + def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int: + return sum( + self.trees[row].query(1, col1 + 1, col2 + 1) + for row in range(row1, row2 + 1) + ) + + +# Your NumMatrix object will be instantiated and called as such: +# obj = NumMatrix(matrix) +# obj.update(row,col,val) +# param_2 = obj.sumRegion(row1,col1,row2,col2) diff --git a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.cpp b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.cpp index 5cdd9675cc446..b4d4863af3e8d 100644 --- a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.cpp +++ b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.cpp @@ -1,13 +1,24 @@ -class Solution { -public: - int maxProfit(vector& prices) { - int f = 0, f0 = 0, f1 = -prices[0]; - for (int i = 1; i < prices.size(); ++i) { - int g0 = max(f0, f1 + prices[i]); - f1 = max(f1, f - prices[i]); - f = f0; - f0 = g0; - } - return f0; - } +class Solution { +public: + int maxProfit(vector& prices) { + int n = prices.size(); + int f[n][2]; + memset(f, -1, sizeof(f)); + function dfs = [&](int i, int j) { + if (i >= n) { + return 0; + } + if (f[i][j] != -1) { + return f[i][j]; + } + int ans = dfs(i + 1, j); + if (j) { + ans = max(ans, prices[i] + dfs(i + 2, 0)); + } else { + ans = max(ans, -prices[i] + dfs(i + 1, 1)); + } + return f[i][j] = ans; + }; + return dfs(0, 0); + } }; \ No newline at end of file diff --git a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.go b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.go index bbaa1728f64ed..47e0989d996df 100644 --- a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.go +++ b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.go @@ -1,7 +1,25 @@ func maxProfit(prices []int) int { - f, f0, f1 := 0, 0, -prices[0] - for _, x := range prices[1:] { - f, f0, f1 = f0, max(f0, f1+x), max(f1, f-x) + n := len(prices) + f := make([][2]int, n) + for i := range f { + f[i] = [2]int{-1, -1} } - return f0 + var dfs func(i, j int) int + dfs = func(i, j int) int { + if i >= n { + return 0 + } + if f[i][j] != -1 { + return f[i][j] + } + ans := dfs(i+1, j) + if j > 0 { + ans = max(ans, prices[i]+dfs(i+2, 0)) + } else { + ans = max(ans, -prices[i]+dfs(i+1, 1)) + } + f[i][j] = ans + return ans + } + return dfs(0, 0) } \ No newline at end of file diff --git a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.java b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.java index c09dd13c214aa..0866002ad7af0 100644 --- a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.java +++ b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.java @@ -1,12 +1,26 @@ -class Solution { - public int maxProfit(int[] prices) { - int f = 0, f0 = 0, f1 = -prices[0]; - for (int i = 1; i < prices.length; ++i) { - int g0 = Math.max(f0, f1 + prices[i]); - f1 = Math.max(f1, f - prices[i]); - f = f0; - f0 = g0; - } - return f0; - } +class Solution { + private int[] prices; + private Integer[][] f; + + public int maxProfit(int[] prices) { + this.prices = prices; + f = new Integer[prices.length][2]; + return dfs(0, 0); + } + + private int dfs(int i, int j) { + if (i >= prices.length) { + return 0; + } + if (f[i][j] != null) { + return f[i][j]; + } + int ans = dfs(i + 1, j); + if (j > 0) { + ans = Math.max(ans, prices[i] + dfs(i + 2, 0)); + } else { + ans = Math.max(ans, -prices[i] + dfs(i + 1, 1)); + } + return f[i][j] = ans; + } } \ No newline at end of file diff --git a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.py b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.py index 8562ac66ec693..caf5973c61ca6 100644 --- a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.py +++ b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.py @@ -1,6 +1,14 @@ -class Solution: - def maxProfit(self, prices: List[int]) -> int: - f, f0, f1 = 0, 0, -prices[0] - for x in prices[1:]: - f, f0, f1 = f0, max(f0, f1 + x), max(f1, f - x) - return f0 +class Solution: + def maxProfit(self, prices: List[int]) -> int: + @cache + def dfs(i: int, j: int) -> int: + if i >= len(prices): + return 0 + ans = dfs(i + 1, j) + if j: + ans = max(ans, prices[i] + dfs(i + 2, 0)) + else: + ans = max(ans, -prices[i] + dfs(i + 1, 1)) + return ans + + return dfs(0, 0) diff --git a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.ts b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.ts index c694608146a5e..4b0c494051ffe 100644 --- a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.ts +++ b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.ts @@ -1,7 +1,20 @@ function maxProfit(prices: number[]): number { - let [f, f0, f1] = [0, 0, -prices[0]]; - for (const x of prices.slice(1)) { - [f, f0, f1] = [f0, Math.max(f0, f1 + x), Math.max(f1, f - x)]; - } - return f0; + const n = prices.length; + const f: number[][] = Array.from({ length: n }, () => Array.from({ length: 2 }, () => -1)); + const dfs = (i: number, j: number): number => { + if (i >= n) { + return 0; + } + if (f[i][j] !== -1) { + return f[i][j]; + } + let ans = dfs(i + 1, j); + if (j) { + ans = Math.max(ans, prices[i] + dfs(i + 2, 0)); + } else { + ans = Math.max(ans, -prices[i] + dfs(i + 1, 1)); + } + return (f[i][j] = ans); + }; + return dfs(0, 0); } diff --git a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution2.cpp b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution2.cpp new file mode 100644 index 0000000000000..4b9e30315a785 --- /dev/null +++ b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int maxProfit(vector& prices) { + int n = prices.size(); + int f[n][2]; + memset(f, 0, sizeof(f)); + f[0][1] = -prices[0]; + for (int i = 1; i < n; ++i) { + f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i]); + f[i][1] = max(f[i - 1][1], (i > 1 ? f[i - 2][0] : 0) - prices[i]); + } + return f[n - 1][0]; + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution2.go b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution2.go new file mode 100644 index 0000000000000..48a5147177dd1 --- /dev/null +++ b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution2.go @@ -0,0 +1,14 @@ +func maxProfit(prices []int) int { + n := len(prices) + f := make([][2]int, n) + f[0][1] = -prices[0] + for i := 1; i < n; i++ { + f[i][0] = max(f[i-1][0], f[i-1][1]+prices[i]) + if i > 1 { + f[i][1] = max(f[i-1][1], f[i-2][0]-prices[i]) + } else { + f[i][1] = max(f[i-1][1], -prices[i]) + } + } + return f[n-1][0] +} \ No newline at end of file diff --git a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution2.java b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution2.java new file mode 100644 index 0000000000000..8fca037021c96 --- /dev/null +++ b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution2.java @@ -0,0 +1,12 @@ +class Solution { + public int maxProfit(int[] prices) { + int n = prices.length; + int[][] f = new int[n][2]; + f[0][1] = -prices[0]; + for (int i = 1; i < n; i++) { + f[i][0] = Math.max(f[i - 1][0], f[i - 1][1] + prices[i]); + f[i][1] = Math.max(f[i - 1][1], (i > 1 ? f[i - 2][0] : 0) - prices[i]); + } + return f[n - 1][0]; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution2.py b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution2.py new file mode 100644 index 0000000000000..e19ab36585b94 --- /dev/null +++ b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + n = len(prices) + f = [[0] * 2 for _ in range(n)] + f[0][1] = -prices[0] + for i in range(1, n): + f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i]) + f[i][1] = max(f[i - 1][1], f[i - 2][0] - prices[i]) + return f[n - 1][0] diff --git a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution2.ts b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution2.ts new file mode 100644 index 0000000000000..e8d2290d05b37 --- /dev/null +++ b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution2.ts @@ -0,0 +1,10 @@ +function maxProfit(prices: number[]): number { + const n = prices.length; + const f: number[][] = Array.from({ length: n }, () => Array.from({ length: 2 }, () => 0)); + f[0][1] = -prices[0]; + for (let i = 1; i < n; ++i) { + f[i][0] = Math.max(f[i - 1][0], f[i - 1][1] + prices[i]); + f[i][1] = Math.max(f[i - 1][1], (i > 1 ? f[i - 2][0] : 0) - prices[i]); + } + return f[n - 1][0]; +} diff --git a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution3.cpp b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution3.cpp new file mode 100644 index 0000000000000..9ca2141b6cdc3 --- /dev/null +++ b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution3.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int maxProfit(vector& prices) { + int f = 0, f0 = 0, f1 = -prices[0]; + for (int i = 1; i < prices.size(); ++i) { + int g0 = max(f0, f1 + prices[i]); + f1 = max(f1, f - prices[i]); + f = f0; + f0 = g0; + } + return f0; + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution3.go b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution3.go new file mode 100644 index 0000000000000..bbaa1728f64ed --- /dev/null +++ b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution3.go @@ -0,0 +1,7 @@ +func maxProfit(prices []int) int { + f, f0, f1 := 0, 0, -prices[0] + for _, x := range prices[1:] { + f, f0, f1 = f0, max(f0, f1+x), max(f1, f-x) + } + return f0 +} \ No newline at end of file diff --git a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution3.java b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution3.java new file mode 100644 index 0000000000000..3566261f49302 --- /dev/null +++ b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution3.java @@ -0,0 +1,12 @@ +class Solution { + public int maxProfit(int[] prices) { + int f = 0, f0 = 0, f1 = -prices[0]; + for (int i = 1; i < prices.length; ++i) { + int g0 = Math.max(f0, f1 + prices[i]); + f1 = Math.max(f1, f - prices[i]); + f = f0; + f0 = g0; + } + return f0; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution3.py b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution3.py new file mode 100644 index 0000000000000..11676566baee5 --- /dev/null +++ b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution3.py @@ -0,0 +1,6 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + f, f0, f1 = 0, 0, -prices[0] + for x in prices[1:]: + f, f0, f1 = f0, max(f0, f1 + x), max(f1, f - x) + return f0 diff --git a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution3.ts b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution3.ts new file mode 100644 index 0000000000000..c694608146a5e --- /dev/null +++ b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution3.ts @@ -0,0 +1,7 @@ +function maxProfit(prices: number[]): number { + let [f, f0, f1] = [0, 0, -prices[0]]; + for (const x of prices.slice(1)) { + [f, f0, f1] = [f0, Math.max(f0, f1 + x), Math.max(f1, f - x)]; + } + return f0; +} diff --git a/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.cpp b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.cpp index 7a831eae1fdb9..7fc2b8b6f600a 100644 --- a/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.cpp +++ b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.cpp @@ -1,29 +1,15 @@ -class Solution { -public: - vector> multiply(vector>& mat1, vector>& mat2) { - int m = mat1.size(), n = mat2[0].size(); - vector> ans(m, vector(n)); - auto g1 = f(mat1), g2 = f(mat2); - for (int i = 0; i < m; ++i) { - for (auto& [k, x] : g1[i]) { - for (auto& [j, y] : g2[k]) { - ans[i][j] += x * y; - } - } - } - return ans; - } - - vector>> f(vector>& mat) { - int m = mat.size(), n = mat[0].size(); - vector>> g(m); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (mat[i][j]) { - g[i].emplace_back(j, mat[i][j]); - } - } - } - return g; - } +class Solution { +public: + vector> multiply(vector>& mat1, vector>& mat2) { + int m = mat1.size(), n = mat2[0].size(); + vector> ans(m, vector(n)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k < mat2.size(); ++k) { + ans[i][j] += mat1[i][k] * mat2[k][j]; + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.go b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.go index 93f83453bf0ce..b1d9ab6cbb712 100644 --- a/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.go +++ b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.go @@ -4,26 +4,10 @@ func multiply(mat1 [][]int, mat2 [][]int) [][]int { for i := range ans { ans[i] = make([]int, n) } - f := func(mat [][]int) [][][2]int { - m, n := len(mat), len(mat[0]) - g := make([][][2]int, m) - for i := range g { - g[i] = make([][2]int, 0, n) - for j := range mat[i] { - if mat[i][j] != 0 { - g[i] = append(g[i], [2]int{j, mat[i][j]}) - } - } - } - return g - } - g1, g2 := f(mat1), f(mat2) - for i := range g1 { - for _, p := range g1[i] { - k, x := p[0], p[1] - for _, q := range g2[k] { - j, y := q[0], q[1] - ans[i][j] += x * y + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + for k := 0; k < len(mat2); k++ { + ans[i][j] += mat1[i][k] * mat2[k][j] } } } diff --git a/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.java b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.java index 7e35b5e75ba81..dab0d2dd43f3b 100644 --- a/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.java +++ b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.java @@ -1,32 +1,14 @@ -class Solution { - public int[][] multiply(int[][] mat1, int[][] mat2) { - int m = mat1.length, n = mat2[0].length; - int[][] ans = new int[m][n]; - var g1 = f(mat1); - var g2 = f(mat2); - for (int i = 0; i < m; ++i) { - for (int[] p : g1[i]) { - int k = p[0], x = p[1]; - for (int[] q : g2[k]) { - int j = q[0], y = q[1]; - ans[i][j] += x * y; - } - } - } - return ans; - } - - private List[] f(int[][] mat) { - int m = mat.length, n = mat[0].length; - List[] g = new List[m]; - Arrays.setAll(g, i -> new ArrayList<>()); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (mat[i][j] != 0) { - g[i].add(new int[] {j, mat[i][j]}); - } - } - } - return g; - } +class Solution { + public int[][] multiply(int[][] mat1, int[][] mat2) { + int m = mat1.length, n = mat2[0].length; + int[][] ans = new int[m][n]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k < mat2.length; ++k) { + ans[i][j] += mat1[i][k] * mat2[k][j]; + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.py b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.py index a951328efec29..52cdd162da8f1 100644 --- a/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.py +++ b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.py @@ -1,19 +1,9 @@ -class Solution: - def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]: - def f(mat: List[List[int]]) -> List[List[int]]: - g = [[] for _ in range(len(mat))] - for i, row in enumerate(mat): - for j, x in enumerate(row): - if x: - g[i].append((j, x)) - return g - - g1 = f(mat1) - g2 = f(mat2) - m, n = len(mat1), len(mat2[0]) - ans = [[0] * n for _ in range(m)] - for i in range(m): - for k, x in g1[i]: - for j, y in g2[k]: - ans[i][j] += x * y - return ans +class Solution: + def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]: + m, n = len(mat1), len(mat2[0]) + ans = [[0] * n for _ in range(m)] + for i in range(m): + for j in range(n): + for k in range(len(mat2)): + ans[i][j] += mat1[i][k] * mat2[k][j] + return ans diff --git a/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.ts b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.ts index 5f9e7e487e014..45ce3b4e69060 100644 --- a/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.ts +++ b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.ts @@ -1,24 +1,10 @@ function multiply(mat1: number[][], mat2: number[][]): number[][] { const [m, n] = [mat1.length, mat2[0].length]; const ans: number[][] = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); - const f = (mat: number[][]): number[][][] => { - const [m, n] = [mat.length, mat[0].length]; - const ans: number[][][] = Array.from({ length: m }, () => []); - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - if (mat[i][j] !== 0) { - ans[i].push([j, mat[i][j]]); - } - } - } - return ans; - }; - const g1 = f(mat1); - const g2 = f(mat2); for (let i = 0; i < m; ++i) { - for (const [k, x] of g1[i]) { - for (const [j, y] of g2[k]) { - ans[i][j] += x * y; + for (let j = 0; j < n; ++j) { + for (let k = 0; k < mat2.length; ++k) { + ans[i][j] += mat1[i][k] * mat2[k][j]; } } } diff --git a/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution2.cpp b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution2.cpp new file mode 100644 index 0000000000000..87e15833b8783 --- /dev/null +++ b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution2.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + vector> multiply(vector>& mat1, vector>& mat2) { + int m = mat1.size(), n = mat2[0].size(); + vector> ans(m, vector(n)); + auto g1 = f(mat1), g2 = f(mat2); + for (int i = 0; i < m; ++i) { + for (auto& [k, x] : g1[i]) { + for (auto& [j, y] : g2[k]) { + ans[i][j] += x * y; + } + } + } + return ans; + } + + vector>> f(vector>& mat) { + int m = mat.size(), n = mat[0].size(); + vector>> g(m); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (mat[i][j]) { + g[i].emplace_back(j, mat[i][j]); + } + } + } + return g; + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution2.go b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution2.go new file mode 100644 index 0000000000000..93f83453bf0ce --- /dev/null +++ b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution2.go @@ -0,0 +1,31 @@ +func multiply(mat1 [][]int, mat2 [][]int) [][]int { + m, n := len(mat1), len(mat2[0]) + ans := make([][]int, m) + for i := range ans { + ans[i] = make([]int, n) + } + f := func(mat [][]int) [][][2]int { + m, n := len(mat), len(mat[0]) + g := make([][][2]int, m) + for i := range g { + g[i] = make([][2]int, 0, n) + for j := range mat[i] { + if mat[i][j] != 0 { + g[i] = append(g[i], [2]int{j, mat[i][j]}) + } + } + } + return g + } + g1, g2 := f(mat1), f(mat2) + for i := range g1 { + for _, p := range g1[i] { + k, x := p[0], p[1] + for _, q := range g2[k] { + j, y := q[0], q[1] + ans[i][j] += x * y + } + } + } + return ans +} \ No newline at end of file diff --git a/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution2.java b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution2.java new file mode 100644 index 0000000000000..515452058f168 --- /dev/null +++ b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution2.java @@ -0,0 +1,32 @@ +class Solution { + public int[][] multiply(int[][] mat1, int[][] mat2) { + int m = mat1.length, n = mat2[0].length; + int[][] ans = new int[m][n]; + var g1 = f(mat1); + var g2 = f(mat2); + for (int i = 0; i < m; ++i) { + for (int[] p : g1[i]) { + int k = p[0], x = p[1]; + for (int[] q : g2[k]) { + int j = q[0], y = q[1]; + ans[i][j] += x * y; + } + } + } + return ans; + } + + private List[] f(int[][] mat) { + int m = mat.length, n = mat[0].length; + List[] g = new List[m]; + Arrays.setAll(g, i -> new ArrayList<>()); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (mat[i][j] != 0) { + g[i].add(new int[] {j, mat[i][j]}); + } + } + } + return g; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution2.py b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution2.py new file mode 100644 index 0000000000000..d358e366ff43b --- /dev/null +++ b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution2.py @@ -0,0 +1,19 @@ +class Solution: + def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]: + def f(mat: List[List[int]]) -> List[List[int]]: + g = [[] for _ in range(len(mat))] + for i, row in enumerate(mat): + for j, x in enumerate(row): + if x: + g[i].append((j, x)) + return g + + g1 = f(mat1) + g2 = f(mat2) + m, n = len(mat1), len(mat2[0]) + ans = [[0] * n for _ in range(m)] + for i in range(m): + for k, x in g1[i]: + for j, y in g2[k]: + ans[i][j] += x * y + return ans diff --git a/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution2.ts b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution2.ts new file mode 100644 index 0000000000000..5f9e7e487e014 --- /dev/null +++ b/solution/0300-0399/0311.Sparse Matrix Multiplication/Solution2.ts @@ -0,0 +1,26 @@ +function multiply(mat1: number[][], mat2: number[][]): number[][] { + const [m, n] = [mat1.length, mat2[0].length]; + const ans: number[][] = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); + const f = (mat: number[][]): number[][][] => { + const [m, n] = [mat.length, mat[0].length]; + const ans: number[][][] = Array.from({ length: m }, () => []); + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (mat[i][j] !== 0) { + ans[i].push([j, mat[i][j]]); + } + } + } + return ans; + }; + const g1 = f(mat1); + const g2 = f(mat2); + for (let i = 0; i < m; ++i) { + for (const [k, x] of g1[i]) { + for (const [j, y] of g2[k]) { + ans[i][j] += x * y; + } + } + } + return ans; +} diff --git a/solution/0300-0399/0313.Super Ugly Number/Solution2.go b/solution/0300-0399/0313.Super Ugly Number/Solution2.go new file mode 100644 index 0000000000000..60c67e14bb882 --- /dev/null +++ b/solution/0300-0399/0313.Super Ugly Number/Solution2.go @@ -0,0 +1,30 @@ +type Ugly struct{ value, prime, index int } +type Queue []Ugly + +func (u Queue) Len() int { return len(u) } +func (u Queue) Swap(i, j int) { u[i], u[j] = u[j], u[i] } +func (u Queue) Less(i, j int) bool { return u[i].value < u[j].value } +func (u *Queue) Push(v any) { *u = append(*u, v.(Ugly)) } +func (u *Queue) Pop() any { + old, x := *u, (*u)[len(*u)-1] + *u = old[:len(old)-1] + return x +} + +func nthSuperUglyNumber(n int, primes []int) int { + ugly, pq, p := make([]int, n+1), &Queue{}, 2 + ugly[1] = 1 + heap.Init(pq) + for _, v := range primes { + heap.Push(pq, Ugly{value: v, prime: v, index: 2}) + } + for p <= n { + top := heap.Pop(pq).(Ugly) + if ugly[p-1] != top.value { + ugly[p], p = top.value, p+1 + } + top.value, top.index = ugly[top.index]*top.prime, top.index+1 + heap.Push(pq, top) + } + return ugly[n] +} \ No newline at end of file diff --git a/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution.cpp b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution.cpp index 36e3df181dcb3..9ef8e210f1fe9 100644 --- a/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution.cpp +++ b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution.cpp @@ -9,27 +9,32 @@ * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ +using pii = pair; + class Solution { public: + map> d; + vector> verticalOrder(TreeNode* root) { + dfs(root, 0, 0); vector> ans; - if (!root) return ans; - map> d; - queue> q{{{root, 0}}}; - while (!q.empty()) { - for (int n = q.size(); n; --n) { - auto p = q.front(); - q.pop(); - root = p.first; - int offset = p.second; - d[offset].push_back(root->val); - if (root->left) q.push({root->left, offset - 1}); - if (root->right) q.push({root->right, offset + 1}); - } - } for (auto& [_, v] : d) { - ans.push_back(v); + sort(v.begin(), v.end(), [&](pii& a, pii& b) { + return a.first < b.first; + }); + vector t; + for (auto& x : v) { + t.push_back(x.second); + } + ans.push_back(t); } return ans; } + + void dfs(TreeNode* root, int depth, int offset) { + if (!root) return; + d[offset].push_back({depth, root->val}); + dfs(root->left, depth + 1, offset - 1); + dfs(root->right, depth + 1, offset + 1); + } }; \ No newline at end of file diff --git a/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution.go b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution.go index 81b22b9f7b9db..fe39bfa3ff514 100644 --- a/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution.go +++ b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution.go @@ -7,39 +7,31 @@ * } */ func verticalOrder(root *TreeNode) [][]int { - ans := [][]int{} - if root == nil { - return ans - } - d := map[int][]int{} - q := []pair{pair{root, 0}} - for len(q) > 0 { - for n := len(q); n > 0; n-- { - p := q[0] - q = q[1:] - root = p.node - offset := p.offset - d[offset] = append(d[offset], root.Val) - if root.Left != nil { - q = append(q, pair{root.Left, offset - 1}) - } - if root.Right != nil { - q = append(q, pair{root.Right, offset + 1}) - } + d := map[int][][]int{} + var dfs func(*TreeNode, int, int) + dfs = func(root *TreeNode, depth, offset int) { + if root == nil { + return } + d[offset] = append(d[offset], []int{depth, root.Val}) + dfs(root.Left, depth+1, offset-1) + dfs(root.Right, depth+1, offset+1) } + dfs(root, 0, 0) idx := []int{} for i := range d { idx = append(idx, i) } sort.Ints(idx) + ans := [][]int{} for _, i := range idx { - ans = append(ans, d[i]) + v := d[i] + sort.SliceStable(v, func(i, j int) bool { return v[i][0] < v[j][0] }) + t := []int{} + for _, x := range v { + t = append(t, x[1]) + } + ans = append(ans, t) } return ans -} - -type pair struct { - node *TreeNode - offset int } \ No newline at end of file diff --git a/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution.java b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution.java index 08881308d70f7..9393a8befb830 100644 --- a/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution.java +++ b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution.java @@ -14,28 +14,28 @@ * } */ class Solution { + private TreeMap> d = new TreeMap<>(); + public List> verticalOrder(TreeNode root) { + dfs(root, 0, 0); List> ans = new ArrayList<>(); - if (root == null) { - return ans; - } - Deque> q = new ArrayDeque<>(); - q.offer(new Pair<>(root, 0)); - TreeMap> d = new TreeMap<>(); - while (!q.isEmpty()) { - for (int n = q.size(); n > 0; --n) { - var p = q.pollFirst(); - root = p.getKey(); - int offset = p.getValue(); - d.computeIfAbsent(offset, k -> new ArrayList()).add(root.val); - if (root.left != null) { - q.offer(new Pair<>(root.left, offset - 1)); - } - if (root.right != null) { - q.offer(new Pair<>(root.right, offset + 1)); - } + for (var v : d.values()) { + Collections.sort(v, (a, b) -> a[0] - b[0]); + List t = new ArrayList<>(); + for (var e : v) { + t.add(e[1]); } + ans.add(t); + } + return ans; + } + + private void dfs(TreeNode root, int depth, int offset) { + if (root == null) { + return; } - return new ArrayList<>(d.values()); + d.computeIfAbsent(offset, k -> new ArrayList<>()).add(new int[] {depth, root.val}); + dfs(root.left, depth + 1, offset - 1); + dfs(root.right, depth + 1, offset + 1); } } \ No newline at end of file diff --git a/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution.py b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution.py index 2130f3f24bb20..dd9247fbb9e05 100644 --- a/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution.py +++ b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution.py @@ -6,16 +6,17 @@ # self.right = right class Solution: def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]: - if root is None: - return [] - q = deque([(root, 0)]) + def dfs(root, depth, offset): + if root is None: + return + d[offset].append((depth, root.val)) + dfs(root.left, depth + 1, offset - 1) + dfs(root.right, depth + 1, offset + 1) + d = defaultdict(list) - while q: - for _ in range(len(q)): - root, offset = q.popleft() - d[offset].append(root.val) - if root.left: - q.append((root.left, offset - 1)) - if root.right: - q.append((root.right, offset + 1)) - return [v for _, v in sorted(d.items())] + dfs(root, 0, 0) + ans = [] + for _, v in sorted(d.items()): + v.sort(key=lambda x: x[0]) + ans.append([x[1] for x in v]) + return ans diff --git a/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution2.cpp b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution2.cpp new file mode 100644 index 0000000000000..36e3df181dcb3 --- /dev/null +++ b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution2.cpp @@ -0,0 +1,35 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> verticalOrder(TreeNode* root) { + vector> ans; + if (!root) return ans; + map> d; + queue> q{{{root, 0}}}; + while (!q.empty()) { + for (int n = q.size(); n; --n) { + auto p = q.front(); + q.pop(); + root = p.first; + int offset = p.second; + d[offset].push_back(root->val); + if (root->left) q.push({root->left, offset - 1}); + if (root->right) q.push({root->right, offset + 1}); + } + } + for (auto& [_, v] : d) { + ans.push_back(v); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution2.go b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution2.go new file mode 100644 index 0000000000000..81b22b9f7b9db --- /dev/null +++ b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution2.go @@ -0,0 +1,45 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func verticalOrder(root *TreeNode) [][]int { + ans := [][]int{} + if root == nil { + return ans + } + d := map[int][]int{} + q := []pair{pair{root, 0}} + for len(q) > 0 { + for n := len(q); n > 0; n-- { + p := q[0] + q = q[1:] + root = p.node + offset := p.offset + d[offset] = append(d[offset], root.Val) + if root.Left != nil { + q = append(q, pair{root.Left, offset - 1}) + } + if root.Right != nil { + q = append(q, pair{root.Right, offset + 1}) + } + } + } + idx := []int{} + for i := range d { + idx = append(idx, i) + } + sort.Ints(idx) + for _, i := range idx { + ans = append(ans, d[i]) + } + return ans +} + +type pair struct { + node *TreeNode + offset int +} \ No newline at end of file diff --git a/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution2.java b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution2.java new file mode 100644 index 0000000000000..08881308d70f7 --- /dev/null +++ b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution2.java @@ -0,0 +1,41 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List> verticalOrder(TreeNode root) { + List> ans = new ArrayList<>(); + if (root == null) { + return ans; + } + Deque> q = new ArrayDeque<>(); + q.offer(new Pair<>(root, 0)); + TreeMap> d = new TreeMap<>(); + while (!q.isEmpty()) { + for (int n = q.size(); n > 0; --n) { + var p = q.pollFirst(); + root = p.getKey(); + int offset = p.getValue(); + d.computeIfAbsent(offset, k -> new ArrayList()).add(root.val); + if (root.left != null) { + q.offer(new Pair<>(root.left, offset - 1)); + } + if (root.right != null) { + q.offer(new Pair<>(root.right, offset + 1)); + } + } + } + return new ArrayList<>(d.values()); + } +} \ No newline at end of file diff --git a/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution2.py b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution2.py new file mode 100644 index 0000000000000..2130f3f24bb20 --- /dev/null +++ b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/Solution2.py @@ -0,0 +1,21 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]: + if root is None: + return [] + q = deque([(root, 0)]) + d = defaultdict(list) + while q: + for _ in range(len(q)): + root, offset = q.popleft() + d[offset].append(root.val) + if root.left: + q.append((root.left, offset - 1)) + if root.right: + q.append((root.right, offset + 1)) + return [v for _, v in sorted(d.items())] diff --git a/solution/0300-0399/0315.Count of Smaller Numbers After Self/Solution2.cpp b/solution/0300-0399/0315.Count of Smaller Numbers After Self/Solution2.cpp new file mode 100644 index 0000000000000..891ced7567e0a --- /dev/null +++ b/solution/0300-0399/0315.Count of Smaller Numbers After Self/Solution2.cpp @@ -0,0 +1,72 @@ +class Node { +public: + int l; + int r; + int v; +}; + +class SegmentTree { +public: + vector tr; + + SegmentTree(int n) { + tr.resize(4 * n); + for (int i = 0; i < tr.size(); ++i) tr[i] = new Node(); + build(1, 1, n); + } + + void build(int u, int l, int r) { + tr[u]->l = l; + tr[u]->r = r; + if (l == r) return; + int mid = (l + r) >> 1; + build(u << 1, l, mid); + build(u << 1 | 1, mid + 1, r); + } + + void modify(int u, int x, int v) { + if (tr[u]->l == x && tr[u]->r == x) { + tr[u]->v += v; + return; + } + int mid = (tr[u]->l + tr[u]->r) >> 1; + if (x <= mid) + modify(u << 1, x, v); + else + modify(u << 1 | 1, x, v); + pushup(u); + } + + void pushup(int u) { + tr[u]->v = tr[u << 1]->v + tr[u << 1 | 1]->v; + } + + int query(int u, int l, int r) { + if (tr[u]->l >= l && tr[u]->r <= r) return tr[u]->v; + int mid = (tr[u]->l + tr[u]->r) >> 1; + int v = 0; + if (l <= mid) v += query(u << 1, l, r); + if (r > mid) v += query(u << 1 | 1, l, r); + return v; + } +}; + +class Solution { +public: + vector countSmaller(vector& nums) { + unordered_set s(nums.begin(), nums.end()); + vector alls(s.begin(), s.end()); + sort(alls.begin(), alls.end()); + unordered_map m; + int n = alls.size(); + for (int i = 0; i < n; ++i) m[alls[i]] = i + 1; + SegmentTree* tree = new SegmentTree(n); + vector ans(nums.size()); + for (int i = nums.size() - 1; i >= 0; --i) { + int x = m[nums[i]]; + tree->modify(1, x, 1); + ans[i] = tree->query(1, 1, x - 1); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0315.Count of Smaller Numbers After Self/Solution2.go b/solution/0300-0399/0315.Count of Smaller Numbers After Self/Solution2.go new file mode 100644 index 0000000000000..a0d7ad9d5fac9 --- /dev/null +++ b/solution/0300-0399/0315.Count of Smaller Numbers After Self/Solution2.go @@ -0,0 +1,56 @@ +type Pair struct { + val int + index int +} + +var ( + tmp []Pair + count []int +) + +func countSmaller(nums []int) []int { + tmp, count = make([]Pair, len(nums)), make([]int, len(nums)) + array := make([]Pair, len(nums)) + for i, v := range nums { + array[i] = Pair{val: v, index: i} + } + sorted(array, 0, len(array)-1) + return count +} + +func sorted(arr []Pair, low, high int) { + if low >= high { + return + } + mid := low + (high-low)/2 + sorted(arr, low, mid) + sorted(arr, mid+1, high) + merge(arr, low, mid, high) +} + +func merge(arr []Pair, low, mid, high int) { + left, right := low, mid+1 + idx := low + for left <= mid && right <= high { + if arr[left].val <= arr[right].val { + count[arr[left].index] += right - mid - 1 + tmp[idx], left = arr[left], left+1 + } else { + tmp[idx], right = arr[right], right+1 + } + idx++ + } + for left <= mid { + count[arr[left].index] += right - mid - 1 + tmp[idx] = arr[left] + idx, left = idx+1, left+1 + } + for right <= high { + tmp[idx] = arr[right] + idx, right = idx+1, right+1 + } + // 排序 + for i := low; i <= high; i++ { + arr[i] = tmp[i] + } +} \ No newline at end of file diff --git a/solution/0300-0399/0315.Count of Smaller Numbers After Self/Solution2.java b/solution/0300-0399/0315.Count of Smaller Numbers After Self/Solution2.java new file mode 100644 index 0000000000000..6977c5f6b1b1a --- /dev/null +++ b/solution/0300-0399/0315.Count of Smaller Numbers After Self/Solution2.java @@ -0,0 +1,85 @@ +class Solution { + public List countSmaller(int[] nums) { + Set s = new HashSet<>(); + for (int v : nums) { + s.add(v); + } + List alls = new ArrayList<>(s); + alls.sort(Comparator.comparingInt(a -> a)); + int n = alls.size(); + Map m = new HashMap<>(n); + for (int i = 0; i < n; ++i) { + m.put(alls.get(i), i + 1); + } + SegmentTree tree = new SegmentTree(n); + LinkedList ans = new LinkedList<>(); + for (int i = nums.length - 1; i >= 0; --i) { + int x = m.get(nums[i]); + tree.modify(1, x, 1); + ans.addFirst(tree.query(1, 1, x - 1)); + } + return ans; + } +} + +class Node { + int l; + int r; + int v; +} + +class SegmentTree { + private Node[] tr; + + public SegmentTree(int n) { + tr = new Node[4 * n]; + for (int i = 0; i < tr.length; ++i) { + tr[i] = new Node(); + } + build(1, 1, n); + } + + public void build(int u, int l, int r) { + tr[u].l = l; + tr[u].r = r; + if (l == r) { + return; + } + int mid = (l + r) >> 1; + build(u << 1, l, mid); + build(u << 1 | 1, mid + 1, r); + } + + public void modify(int u, int x, int v) { + if (tr[u].l == x && tr[u].r == x) { + tr[u].v += v; + return; + } + int mid = (tr[u].l + tr[u].r) >> 1; + if (x <= mid) { + modify(u << 1, x, v); + } else { + modify(u << 1 | 1, x, v); + } + pushup(u); + } + + public void pushup(int u) { + tr[u].v = tr[u << 1].v + tr[u << 1 | 1].v; + } + + public int query(int u, int l, int r) { + if (tr[u].l >= l && tr[u].r <= r) { + return tr[u].v; + } + int mid = (tr[u].l + tr[u].r) >> 1; + int v = 0; + if (l <= mid) { + v += query(u << 1, l, r); + } + if (r > mid) { + v += query(u << 1 | 1, l, r); + } + return v; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0315.Count of Smaller Numbers After Self/Solution2.py b/solution/0300-0399/0315.Count of Smaller Numbers After Self/Solution2.py new file mode 100644 index 0000000000000..5703cc8aef8d3 --- /dev/null +++ b/solution/0300-0399/0315.Count of Smaller Numbers After Self/Solution2.py @@ -0,0 +1,58 @@ +class Node: + def __init__(self): + self.l = 0 + self.r = 0 + self.v = 0 + + +class SegmentTree: + def __init__(self, n): + self.tr = [Node() for _ in range(n << 2)] + self.build(1, 1, n) + + def build(self, u, l, r): + self.tr[u].l = l + self.tr[u].r = r + if l == r: + return + mid = (l + r) >> 1 + self.build(u << 1, l, mid) + self.build(u << 1 | 1, mid + 1, r) + + def modify(self, u, x, v): + if self.tr[u].l == x and self.tr[u].r == x: + self.tr[u].v += v + return + mid = (self.tr[u].l + self.tr[u].r) >> 1 + if x <= mid: + self.modify(u << 1, x, v) + else: + self.modify(u << 1 | 1, x, v) + self.pushup(u) + + def query(self, u, l, r): + if self.tr[u].l >= l and self.tr[u].r <= r: + return self.tr[u].v + mid = (self.tr[u].l + self.tr[u].r) >> 1 + v = 0 + if l <= mid: + v += self.query(u << 1, l, r) + if r > mid: + v += self.query(u << 1 | 1, l, r) + return v + + def pushup(self, u): + self.tr[u].v = self.tr[u << 1].v + self.tr[u << 1 | 1].v + + +class Solution: + def countSmaller(self, nums: List[int]) -> List[int]: + s = sorted(set(nums)) + m = {v: i for i, v in enumerate(s, 1)} + tree = SegmentTree(len(s)) + ans = [] + for v in nums[::-1]: + x = m[v] + ans.append(tree.query(1, 1, x - 1)) + tree.modify(1, x, 1) + return ans[::-1] diff --git a/solution/0300-0399/0316.Remove Duplicate Letters/Solution2.go b/solution/0300-0399/0316.Remove Duplicate Letters/Solution2.go new file mode 100644 index 0000000000000..c6aac1de3d79e --- /dev/null +++ b/solution/0300-0399/0316.Remove Duplicate Letters/Solution2.go @@ -0,0 +1,21 @@ +func removeDuplicateLetters(s string) string { + count, in_stack, stack := make([]int, 128), make([]bool, 128), make([]rune, 0) + for _, c := range s { + count[c] += 1 + } + + for _, c := range s { + count[c] -= 1 + if in_stack[c] { + continue + } + for len(stack) > 0 && stack[len(stack)-1] > c && count[stack[len(stack)-1]] > 0 { + peek := stack[len(stack)-1] + stack = stack[0 : len(stack)-1] + in_stack[peek] = false + } + stack = append(stack, c) + in_stack[c] = true + } + return string(stack) +} \ No newline at end of file diff --git a/solution/0300-0399/0316.Remove Duplicate Letters/Solution2.py b/solution/0300-0399/0316.Remove Duplicate Letters/Solution2.py new file mode 100644 index 0000000000000..4786154c256c1 --- /dev/null +++ b/solution/0300-0399/0316.Remove Duplicate Letters/Solution2.py @@ -0,0 +1,19 @@ +class Solution: + def removeDuplicateLetters(self, s: str) -> str: + count, in_stack = [0] * 128, [False] * 128 + stack = [] + for c in s: + count[ord(c)] += 1 + for c in s: + count[ord(c)] -= 1 + if in_stack[ord(c)]: + continue + while len(stack) and stack[-1] > c: + peek = stack[-1] + if count[ord(peek)] < 1: + break + in_stack[ord(peek)] = False + stack.pop() + stack.append(c) + in_stack[ord(c)] = True + return ''.join(stack) diff --git a/solution/0300-0399/0317.Shortest Distance from All Buildings/Solution.py b/solution/0300-0399/0317.Shortest Distance from All Buildings/Solution.py index 7057ff2e4b5cc..e306e39d8300d 100644 --- a/solution/0300-0399/0317.Shortest Distance from All Buildings/Solution.py +++ b/solution/0300-0399/0317.Shortest Distance from All Buildings/Solution.py @@ -1,36 +1,36 @@ -class Solution: - def shortestDistance(self, grid: List[List[int]]) -> int: - m, n = len(grid), len(grid[0]) - q = deque() - total = 0 - cnt = [[0] * n for _ in range(m)] - dist = [[0] * n for _ in range(m)] - for i in range(m): - for j in range(n): - if grid[i][j] == 1: - total += 1 - q.append((i, j)) - d = 0 - vis = set() - while q: - d += 1 - for _ in range(len(q)): - r, c = q.popleft() - for a, b in [[0, 1], [0, -1], [1, 0], [-1, 0]]: - x, y = r + a, c + b - if ( - 0 <= x < m - and 0 <= y < n - and grid[x][y] == 0 - and (x, y) not in vis - ): - cnt[x][y] += 1 - dist[x][y] += d - q.append((x, y)) - vis.add((x, y)) - ans = inf - for i in range(m): - for j in range(n): - if grid[i][j] == 0 and cnt[i][j] == total: - ans = min(ans, dist[i][j]) - return -1 if ans == inf else ans +class Solution: + def shortestDistance(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + q = deque() + total = 0 + cnt = [[0] * n for _ in range(m)] + dist = [[0] * n for _ in range(m)] + for i in range(m): + for j in range(n): + if grid[i][j] == 1: + total += 1 + q.append((i, j)) + d = 0 + vis = set() + while q: + d += 1 + for _ in range(len(q)): + r, c = q.popleft() + for a, b in [[0, 1], [0, -1], [1, 0], [-1, 0]]: + x, y = r + a, c + b + if ( + 0 <= x < m + and 0 <= y < n + and grid[x][y] == 0 + and (x, y) not in vis + ): + cnt[x][y] += 1 + dist[x][y] += d + q.append((x, y)) + vis.add((x, y)) + ans = inf + for i in range(m): + for j in range(n): + if grid[i][j] == 0 and cnt[i][j] == total: + ans = min(ans, dist[i][j]) + return -1 if ans == inf else ans diff --git a/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution.cpp b/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution.cpp index 2e6fa7ba43129..eae6581b0da46 100644 --- a/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution.cpp +++ b/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - int maxProduct(vector& words) { - int n = words.size(); - int mask[n]; - memset(mask, 0, sizeof(mask)); - int ans = 0; - for (int i = 0; i < n; ++i) { - for (char& c : words[i]) { - mask[i] |= 1 << (c - 'a'); - } - for (int j = 0; j < i; ++j) { - if ((mask[i] & mask[j]) == 0) { - ans = max(ans, (int) (words[i].size() * words[j].size())); - } - } - } - return ans; - } +class Solution { +public: + int maxProduct(vector& words) { + int n = words.size(); + int mask[n]; + memset(mask, 0, sizeof(mask)); + int ans = 0; + for (int i = 0; i < n; ++i) { + for (char& c : words[i]) { + mask[i] |= 1 << (c - 'a'); + } + for (int j = 0; j < i; ++j) { + if ((mask[i] & mask[j]) == 0) { + ans = max(ans, (int) (words[i].size() * words[j].size())); + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution.java b/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution.java index b13b52a3aa207..3c304871adcbe 100644 --- a/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution.java +++ b/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution.java @@ -1,18 +1,18 @@ -class Solution { - public int maxProduct(String[] words) { - int n = words.length; - int[] mask = new int[n]; - int ans = 0; - for (int i = 0; i < n; ++i) { - for (char c : words[i].toCharArray()) { - mask[i] |= 1 << (c - 'a'); - } - for (int j = 0; j < i; ++j) { - if ((mask[i] & mask[j]) == 0) { - ans = Math.max(ans, words[i].length() * words[j].length()); - } - } - } - return ans; - } +class Solution { + public int maxProduct(String[] words) { + int n = words.length; + int[] mask = new int[n]; + int ans = 0; + for (int i = 0; i < n; ++i) { + for (char c : words[i].toCharArray()) { + mask[i] |= 1 << (c - 'a'); + } + for (int j = 0; j < i; ++j) { + if ((mask[i] & mask[j]) == 0) { + ans = Math.max(ans, words[i].length() * words[j].length()); + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution.py b/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution.py index 528613a76f6d1..fd5bf25730aa8 100644 --- a/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution.py +++ b/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def maxProduct(self, words: List[str]) -> int: - mask = [0] * len(words) - ans = 0 - for i, s in enumerate(words): - for c in s: - mask[i] |= 1 << (ord(c) - ord("a")) - for j, t in enumerate(words[:i]): - if (mask[i] & mask[j]) == 0: - ans = max(ans, len(s) * len(t)) - return ans +class Solution: + def maxProduct(self, words: List[str]) -> int: + mask = [0] * len(words) + ans = 0 + for i, s in enumerate(words): + for c in s: + mask[i] |= 1 << (ord(c) - ord("a")) + for j, t in enumerate(words[:i]): + if (mask[i] & mask[j]) == 0: + ans = max(ans, len(s) * len(t)) + return ans diff --git a/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution2.cpp b/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution2.cpp new file mode 100644 index 0000000000000..aa195071e411a --- /dev/null +++ b/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution2.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int maxProduct(vector& words) { + unordered_map mask; + int ans = 0; + for (auto& s : words) { + int a = s.size(); + int x = 0; + for (char& c : s) { + x |= 1 << (c - 'a'); + } + for (auto& [y, b] : mask) { + if ((x & y) == 0) { + ans = max(ans, a * b); + } + } + mask[x] = max(mask[x], a); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution2.go b/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution2.go new file mode 100644 index 0000000000000..254214ce562b3 --- /dev/null +++ b/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution2.go @@ -0,0 +1,17 @@ +func maxProduct(words []string) (ans int) { + mask := map[int]int{} + for _, s := range words { + a := len(s) + x := 0 + for _, c := range s { + x |= 1 << (c - 'a') + } + for y, b := range mask { + if x&y == 0 { + ans = max(ans, a*b) + } + } + mask[x] = max(mask[x], a) + } + return +} \ No newline at end of file diff --git a/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution2.java b/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution2.java new file mode 100644 index 0000000000000..c0fbb0f25c2cf --- /dev/null +++ b/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution2.java @@ -0,0 +1,21 @@ +class Solution { + public int maxProduct(String[] words) { + Map mask = new HashMap<>(); + int ans = 0; + for (var s : words) { + int a = s.length(); + int x = 0; + for (char c : s.toCharArray()) { + x |= 1 << (c - 'a'); + } + for (var e : mask.entrySet()) { + int y = e.getKey(), b = e.getValue(); + if ((x & y) == 0) { + ans = Math.max(ans, a * b); + } + } + mask.merge(x, a, Math::max); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution2.py b/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution2.py new file mode 100644 index 0000000000000..39944b4506a9e --- /dev/null +++ b/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def maxProduct(self, words: List[str]) -> int: + mask = defaultdict(int) + ans = 0 + for s in words: + a = len(s) + x = 0 + for c in s: + x |= 1 << (ord(c) - ord("a")) + for y, b in mask.items(): + if (x & y) == 0: + ans = max(ans, a * b) + mask[x] = max(mask[x], a) + return ans diff --git a/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution2.ts b/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution2.ts new file mode 100644 index 0000000000000..d3c0fb1fec888 --- /dev/null +++ b/solution/0300-0399/0318.Maximum Product of Word Lengths/Solution2.ts @@ -0,0 +1,18 @@ +function maxProduct(words: string[]): number { + const mask: Map = new Map(); + let ans = 0; + for (const s of words) { + const a = s.length; + let x = 0; + for (const c of s) { + x |= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0)); + } + for (const [y, b] of mask.entries()) { + if ((x & y) === 0) { + ans = Math.max(ans, a * b); + } + } + mask.set(x, Math.max(mask.get(x) || 0, a)); + } + return ans; +} diff --git a/solution/0300-0399/0320.Generalized Abbreviation/Solution.cpp b/solution/0300-0399/0320.Generalized Abbreviation/Solution.cpp index 080a647c6476b..46833a97ff85b 100644 --- a/solution/0300-0399/0320.Generalized Abbreviation/Solution.cpp +++ b/solution/0300-0399/0320.Generalized Abbreviation/Solution.cpp @@ -2,26 +2,23 @@ class Solution { public: vector generateAbbreviations(string word) { int n = word.size(); - vector ans; - for (int i = 0; i < 1 << n; ++i) { - string s; - int cnt = 0; - for (int j = 0; j < n; ++j) { - if (i >> j & 1) { - ++cnt; - } else { - if (cnt) { - s += to_string(cnt); - cnt = 0; - } - s.push_back(word[j]); - } + function(int)> dfs = [&](int i) -> vector { + if (i >= n) { + return {""}; + } + vector ans; + for (auto& s : dfs(i + 1)) { + string p(1, word[i]); + ans.emplace_back(p + s); } - if (cnt) { - s += to_string(cnt); + for (int j = i + 1; j <= n; ++j) { + for (auto& s : dfs(j + 1)) { + string p = j < n ? string(1, word[j]) : ""; + ans.emplace_back(to_string(j - i) + p + s); + } } - ans.push_back(s); - } - return ans; + return ans; + }; + return dfs(0); } }; \ No newline at end of file diff --git a/solution/0300-0399/0320.Generalized Abbreviation/Solution.go b/solution/0300-0399/0320.Generalized Abbreviation/Solution.go index 14fa5930f4d08..8524426f58ccb 100644 --- a/solution/0300-0399/0320.Generalized Abbreviation/Solution.go +++ b/solution/0300-0399/0320.Generalized Abbreviation/Solution.go @@ -1,23 +1,24 @@ -func generateAbbreviations(word string) (ans []string) { +func generateAbbreviations(word string) []string { n := len(word) - for i := 0; i < 1<>j&1 == 1 { - cnt++ - } else { - if cnt > 0 { - s.WriteString(strconv.Itoa(cnt)) - cnt = 0 + var dfs func(int) []string + dfs = func(i int) []string { + if i >= n { + return []string{""} + } + ans := []string{} + for _, s := range dfs(i + 1) { + ans = append(ans, word[i:i+1]+s) + } + for j := i + 1; j <= n; j++ { + for _, s := range dfs(j + 1) { + p := "" + if j < n { + p = word[j : j+1] } - s.WriteByte(word[j]) + ans = append(ans, strconv.Itoa(j-i)+p+s) } } - if cnt > 0 { - s.WriteString(strconv.Itoa(cnt)) - } - ans = append(ans, s.String()) + return ans } - return + return dfs(0) } \ No newline at end of file diff --git a/solution/0300-0399/0320.Generalized Abbreviation/Solution.java b/solution/0300-0399/0320.Generalized Abbreviation/Solution.java index bf7f45ba5ebfb..c11277e9ddddc 100644 --- a/solution/0300-0399/0320.Generalized Abbreviation/Solution.java +++ b/solution/0300-0399/0320.Generalized Abbreviation/Solution.java @@ -1,25 +1,25 @@ class Solution { + private String word; + private int n; + public List generateAbbreviations(String word) { - int n = word.length(); + this.word = word; + n = word.length(); + return dfs(0); + } + + private List dfs(int i) { + if (i >= n) { + return List.of(""); + } List ans = new ArrayList<>(); - for (int i = 0; i < 1 << n; ++i) { - StringBuilder s = new StringBuilder(); - int cnt = 0; - for (int j = 0; j < n; ++j) { - if ((i >> j & 1) == 1) { - ++cnt; - } else { - if (cnt > 0) { - s.append(cnt); - cnt = 0; - } - s.append(word.charAt(j)); - } - } - if (cnt > 0) { - s.append(cnt); + for (String s : dfs(i + 1)) { + ans.add(String.valueOf(word.charAt(i)) + s); + } + for (int j = i + 1; j <= n; ++j) { + for (String s : dfs(j + 1)) { + ans.add((j - i) + "" + (j < n ? String.valueOf(word.charAt(j)) : "") + s); } - ans.add(s.toString()); } return ans; } diff --git a/solution/0300-0399/0320.Generalized Abbreviation/Solution.py b/solution/0300-0399/0320.Generalized Abbreviation/Solution.py index 42422287eaaad..2781c7f794d4d 100644 --- a/solution/0300-0399/0320.Generalized Abbreviation/Solution.py +++ b/solution/0300-0399/0320.Generalized Abbreviation/Solution.py @@ -1,19 +1,13 @@ class Solution: def generateAbbreviations(self, word: str) -> List[str]: + def dfs(i: int) -> List[str]: + if i >= n: + return [""] + ans = [word[i] + s for s in dfs(i + 1)] + for j in range(i + 1, n + 1): + for s in dfs(j + 1): + ans.append(str(j - i) + (word[j] if j < n else "") + s) + return ans + n = len(word) - ans = [] - for i in range(1 << n): - cnt = 0 - s = [] - for j in range(n): - if i >> j & 1: - cnt += 1 - else: - if cnt: - s.append(str(cnt)) - cnt = 0 - s.append(word[j]) - if cnt: - s.append(str(cnt)) - ans.append("".join(s)) - return ans + return dfs(0) diff --git a/solution/0300-0399/0320.Generalized Abbreviation/Solution.ts b/solution/0300-0399/0320.Generalized Abbreviation/Solution.ts index 6d10d43b384a2..ef434bbeb8088 100644 --- a/solution/0300-0399/0320.Generalized Abbreviation/Solution.ts +++ b/solution/0300-0399/0320.Generalized Abbreviation/Solution.ts @@ -1,24 +1,19 @@ function generateAbbreviations(word: string): string[] { const n = word.length; - const ans: string[] = []; - for (let i = 0; i < 1 << n; ++i) { - const s: string[] = []; - let cnt = 0; - for (let j = 0; j < n; ++j) { - if ((i >> j) & 1) { - ++cnt; - } else { - if (cnt > 0) { - s.push(cnt.toString()); - cnt = 0; - } - s.push(word[j]); - } + const dfs = (i: number): string[] => { + if (i >= n) { + return ['']; + } + const ans: string[] = []; + for (const s of dfs(i + 1)) { + ans.push(word[i] + s); } - if (cnt > 0) { - s.push(cnt.toString()); + for (let j = i + 1; j <= n; ++j) { + for (const s of dfs(j + 1)) { + ans.push((j - i).toString() + (j < n ? word[j] : '') + s); + } } - ans.push(s.join('')); - } - return ans; + return ans; + }; + return dfs(0); } diff --git a/solution/0300-0399/0320.Generalized Abbreviation/Solution2.cpp b/solution/0300-0399/0320.Generalized Abbreviation/Solution2.cpp new file mode 100644 index 0000000000000..080a647c6476b --- /dev/null +++ b/solution/0300-0399/0320.Generalized Abbreviation/Solution2.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector generateAbbreviations(string word) { + int n = word.size(); + vector ans; + for (int i = 0; i < 1 << n; ++i) { + string s; + int cnt = 0; + for (int j = 0; j < n; ++j) { + if (i >> j & 1) { + ++cnt; + } else { + if (cnt) { + s += to_string(cnt); + cnt = 0; + } + s.push_back(word[j]); + } + } + if (cnt) { + s += to_string(cnt); + } + ans.push_back(s); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0320.Generalized Abbreviation/Solution2.go b/solution/0300-0399/0320.Generalized Abbreviation/Solution2.go new file mode 100644 index 0000000000000..14fa5930f4d08 --- /dev/null +++ b/solution/0300-0399/0320.Generalized Abbreviation/Solution2.go @@ -0,0 +1,23 @@ +func generateAbbreviations(word string) (ans []string) { + n := len(word) + for i := 0; i < 1<>j&1 == 1 { + cnt++ + } else { + if cnt > 0 { + s.WriteString(strconv.Itoa(cnt)) + cnt = 0 + } + s.WriteByte(word[j]) + } + } + if cnt > 0 { + s.WriteString(strconv.Itoa(cnt)) + } + ans = append(ans, s.String()) + } + return +} \ No newline at end of file diff --git a/solution/0300-0399/0320.Generalized Abbreviation/Solution2.java b/solution/0300-0399/0320.Generalized Abbreviation/Solution2.java new file mode 100644 index 0000000000000..bf7f45ba5ebfb --- /dev/null +++ b/solution/0300-0399/0320.Generalized Abbreviation/Solution2.java @@ -0,0 +1,26 @@ +class Solution { + public List generateAbbreviations(String word) { + int n = word.length(); + List ans = new ArrayList<>(); + for (int i = 0; i < 1 << n; ++i) { + StringBuilder s = new StringBuilder(); + int cnt = 0; + for (int j = 0; j < n; ++j) { + if ((i >> j & 1) == 1) { + ++cnt; + } else { + if (cnt > 0) { + s.append(cnt); + cnt = 0; + } + s.append(word.charAt(j)); + } + } + if (cnt > 0) { + s.append(cnt); + } + ans.add(s.toString()); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0320.Generalized Abbreviation/Solution2.py b/solution/0300-0399/0320.Generalized Abbreviation/Solution2.py new file mode 100644 index 0000000000000..42422287eaaad --- /dev/null +++ b/solution/0300-0399/0320.Generalized Abbreviation/Solution2.py @@ -0,0 +1,19 @@ +class Solution: + def generateAbbreviations(self, word: str) -> List[str]: + n = len(word) + ans = [] + for i in range(1 << n): + cnt = 0 + s = [] + for j in range(n): + if i >> j & 1: + cnt += 1 + else: + if cnt: + s.append(str(cnt)) + cnt = 0 + s.append(word[j]) + if cnt: + s.append(str(cnt)) + ans.append("".join(s)) + return ans diff --git a/solution/0300-0399/0321.Create Maximum Number/Solution.cpp b/solution/0300-0399/0321.Create Maximum Number/Solution.cpp index ac1ac9ee56950..ac8491c94bc29 100644 --- a/solution/0300-0399/0321.Create Maximum Number/Solution.cpp +++ b/solution/0300-0399/0321.Create Maximum Number/Solution.cpp @@ -1,65 +1,65 @@ -class Solution { -public: - vector maxNumber(vector& nums1, vector& nums2, int k) { - auto f = [](vector& nums, int k) { - int n = nums.size(); - vector stk(k); - int top = -1; - int remain = n - k; - for (int x : nums) { - while (top >= 0 && stk[top] < x && remain > 0) { - --top; - --remain; - } - if (top + 1 < k) { - stk[++top] = x; - } else { - --remain; - } - } - return stk; - }; - function&, vector&, int, int)> compare = [&](vector& nums1, vector& nums2, int i, int j) -> bool { - if (i >= nums1.size()) { - return false; - } - if (j >= nums2.size()) { - return true; - } - if (nums1[i] > nums2[j]) { - return true; - } - if (nums1[i] < nums2[j]) { - return false; - } - return compare(nums1, nums2, i + 1, j + 1); - }; - - auto merge = [&](vector& nums1, vector& nums2) { - int m = nums1.size(), n = nums2.size(); - int i = 0, j = 0; - vector ans(m + n); - for (int k = 0; k < m + n; ++k) { - if (compare(nums1, nums2, i, j)) { - ans[k] = nums1[i++]; - } else { - ans[k] = nums2[j++]; - } - } - return ans; - }; - - int m = nums1.size(), n = nums2.size(); - int l = max(0, k - n), r = min(k, m); - vector ans(k); - for (int x = l; x <= r; ++x) { - vector arr1 = f(nums1, x); - vector arr2 = f(nums2, k - x); - vector arr = merge(arr1, arr2); - if (ans < arr) { - ans = move(arr); - } - } - return ans; - } +class Solution { +public: + vector maxNumber(vector& nums1, vector& nums2, int k) { + auto f = [](vector& nums, int k) { + int n = nums.size(); + vector stk(k); + int top = -1; + int remain = n - k; + for (int x : nums) { + while (top >= 0 && stk[top] < x && remain > 0) { + --top; + --remain; + } + if (top + 1 < k) { + stk[++top] = x; + } else { + --remain; + } + } + return stk; + }; + function&, vector&, int, int)> compare = [&](vector& nums1, vector& nums2, int i, int j) -> bool { + if (i >= nums1.size()) { + return false; + } + if (j >= nums2.size()) { + return true; + } + if (nums1[i] > nums2[j]) { + return true; + } + if (nums1[i] < nums2[j]) { + return false; + } + return compare(nums1, nums2, i + 1, j + 1); + }; + + auto merge = [&](vector& nums1, vector& nums2) { + int m = nums1.size(), n = nums2.size(); + int i = 0, j = 0; + vector ans(m + n); + for (int k = 0; k < m + n; ++k) { + if (compare(nums1, nums2, i, j)) { + ans[k] = nums1[i++]; + } else { + ans[k] = nums2[j++]; + } + } + return ans; + }; + + int m = nums1.size(), n = nums2.size(); + int l = max(0, k - n), r = min(k, m); + vector ans(k); + for (int x = l; x <= r; ++x) { + vector arr1 = f(nums1, x); + vector arr2 = f(nums2, k - x); + vector arr = merge(arr1, arr2); + if (ans < arr) { + ans = move(arr); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0300-0399/0321.Create Maximum Number/Solution.java b/solution/0300-0399/0321.Create Maximum Number/Solution.java index a6aae9776b720..1b2252cf06137 100644 --- a/solution/0300-0399/0321.Create Maximum Number/Solution.java +++ b/solution/0300-0399/0321.Create Maximum Number/Solution.java @@ -1,65 +1,65 @@ -class Solution { - public int[] maxNumber(int[] nums1, int[] nums2, int k) { - int m = nums1.length, n = nums2.length; - int l = Math.max(0, k - n), r = Math.min(k, m); - int[] ans = new int[k]; - for (int x = l; x <= r; ++x) { - int[] arr1 = f(nums1, x); - int[] arr2 = f(nums2, k - x); - int[] arr = merge(arr1, arr2); - if (compare(arr, ans, 0, 0)) { - ans = arr; - } - } - return ans; - } - - private int[] f(int[] nums, int k) { - int n = nums.length; - int[] stk = new int[k]; - int top = -1; - int remain = n - k; - for (int x : nums) { - while (top >= 0 && stk[top] < x && remain > 0) { - --top; - --remain; - } - if (top + 1 < k) { - stk[++top] = x; - } else { - --remain; - } - } - return stk; - } - - private int[] merge(int[] nums1, int[] nums2) { - int m = nums1.length, n = nums2.length; - int i = 0, j = 0; - int[] ans = new int[m + n]; - for (int k = 0; k < m + n; ++k) { - if (compare(nums1, nums2, i, j)) { - ans[k] = nums1[i++]; - } else { - ans[k] = nums2[j++]; - } - } - return ans; - } - - private boolean compare(int[] nums1, int[] nums2, int i, int j) { - if (i >= nums1.length) { - return false; - } - if (j >= nums2.length) { - return true; - } - if (nums1[i] > nums2[j]) { - return true; - } - if (nums1[i] < nums2[j]) { - return false; - } - return compare(nums1, nums2, i + 1, j + 1); - } +class Solution { + public int[] maxNumber(int[] nums1, int[] nums2, int k) { + int m = nums1.length, n = nums2.length; + int l = Math.max(0, k - n), r = Math.min(k, m); + int[] ans = new int[k]; + for (int x = l; x <= r; ++x) { + int[] arr1 = f(nums1, x); + int[] arr2 = f(nums2, k - x); + int[] arr = merge(arr1, arr2); + if (compare(arr, ans, 0, 0)) { + ans = arr; + } + } + return ans; + } + + private int[] f(int[] nums, int k) { + int n = nums.length; + int[] stk = new int[k]; + int top = -1; + int remain = n - k; + for (int x : nums) { + while (top >= 0 && stk[top] < x && remain > 0) { + --top; + --remain; + } + if (top + 1 < k) { + stk[++top] = x; + } else { + --remain; + } + } + return stk; + } + + private int[] merge(int[] nums1, int[] nums2) { + int m = nums1.length, n = nums2.length; + int i = 0, j = 0; + int[] ans = new int[m + n]; + for (int k = 0; k < m + n; ++k) { + if (compare(nums1, nums2, i, j)) { + ans[k] = nums1[i++]; + } else { + ans[k] = nums2[j++]; + } + } + return ans; + } + + private boolean compare(int[] nums1, int[] nums2, int i, int j) { + if (i >= nums1.length) { + return false; + } + if (j >= nums2.length) { + return true; + } + if (nums1[i] > nums2[j]) { + return true; + } + if (nums1[i] < nums2[j]) { + return false; + } + return compare(nums1, nums2, i + 1, j + 1); + } } \ No newline at end of file diff --git a/solution/0300-0399/0321.Create Maximum Number/Solution.py b/solution/0300-0399/0321.Create Maximum Number/Solution.py index 991691ed60ca2..9b34907aa282a 100644 --- a/solution/0300-0399/0321.Create Maximum Number/Solution.py +++ b/solution/0300-0399/0321.Create Maximum Number/Solution.py @@ -1,52 +1,52 @@ -class Solution: - def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]: - def f(nums: List[int], k: int) -> List[int]: - n = len(nums) - stk = [0] * k - top = -1 - remain = n - k - for x in nums: - while top >= 0 and stk[top] < x and remain > 0: - top -= 1 - remain -= 1 - if top + 1 < k: - top += 1 - stk[top] = x - else: - remain -= 1 - return stk - - def compare(nums1: List[int], nums2: List[int], i: int, j: int) -> bool: - if i >= len(nums1): - return False - if j >= len(nums2): - return True - if nums1[i] > nums2[j]: - return True - if nums1[i] < nums2[j]: - return False - return compare(nums1, nums2, i + 1, j + 1) - - def merge(nums1: List[int], nums2: List[int]) -> List[int]: - m, n = len(nums1), len(nums2) - i = j = 0 - ans = [0] * (m + n) - for k in range(m + n): - if compare(nums1, nums2, i, j): - ans[k] = nums1[i] - i += 1 - else: - ans[k] = nums2[j] - j += 1 - return ans - - m, n = len(nums1), len(nums2) - l, r = max(0, k - n), min(k, m) - ans = [0] * k - for x in range(l, r + 1): - arr1 = f(nums1, x) - arr2 = f(nums2, k - x) - arr = merge(arr1, arr2) - if ans < arr: - ans = arr - return ans +class Solution: + def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]: + def f(nums: List[int], k: int) -> List[int]: + n = len(nums) + stk = [0] * k + top = -1 + remain = n - k + for x in nums: + while top >= 0 and stk[top] < x and remain > 0: + top -= 1 + remain -= 1 + if top + 1 < k: + top += 1 + stk[top] = x + else: + remain -= 1 + return stk + + def compare(nums1: List[int], nums2: List[int], i: int, j: int) -> bool: + if i >= len(nums1): + return False + if j >= len(nums2): + return True + if nums1[i] > nums2[j]: + return True + if nums1[i] < nums2[j]: + return False + return compare(nums1, nums2, i + 1, j + 1) + + def merge(nums1: List[int], nums2: List[int]) -> List[int]: + m, n = len(nums1), len(nums2) + i = j = 0 + ans = [0] * (m + n) + for k in range(m + n): + if compare(nums1, nums2, i, j): + ans[k] = nums1[i] + i += 1 + else: + ans[k] = nums2[j] + j += 1 + return ans + + m, n = len(nums1), len(nums2) + l, r = max(0, k - n), min(k, m) + ans = [0] * k + for x in range(l, r + 1): + arr1 = f(nums1, x) + arr2 = f(nums2, k - x) + arr = merge(arr1, arr2) + if ans < arr: + ans = arr + return ans diff --git a/solution/0300-0399/0322.Coin Change/Solution.cpp b/solution/0300-0399/0322.Coin Change/Solution.cpp index d2ce0b513051a..56163becd5daa 100644 --- a/solution/0300-0399/0322.Coin Change/Solution.cpp +++ b/solution/0300-0399/0322.Coin Change/Solution.cpp @@ -1,15 +1,18 @@ -class Solution { -public: - int coinChange(vector& coins, int amount) { - int n = amount; - int f[n + 1]; - memset(f, 0x3f, sizeof(f)); - f[0] = 0; - for (int x : coins) { - for (int j = x; j <= n; ++j) { - f[j] = min(f[j], f[j - x] + 1); - } - } - return f[n] > n ? -1 : f[n]; - } +class Solution { +public: + int coinChange(vector& coins, int amount) { + int m = coins.size(), n = amount; + int f[m + 1][n + 1]; + memset(f, 0x3f, sizeof(f)); + f[0][0] = 0; + for (int i = 1; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= coins[i - 1]) { + f[i][j] = min(f[i][j], f[i][j - coins[i - 1]] + 1); + } + } + } + return f[m][n] > n ? -1 : f[m][n]; + } }; \ No newline at end of file diff --git a/solution/0300-0399/0322.Coin Change/Solution.go b/solution/0300-0399/0322.Coin Change/Solution.go index bd7cd50453fe2..a64e5cce8a068 100644 --- a/solution/0300-0399/0322.Coin Change/Solution.go +++ b/solution/0300-0399/0322.Coin Change/Solution.go @@ -1,17 +1,24 @@ func coinChange(coins []int, amount int) int { - n := amount - f := make([]int, n+1) + m, n := len(coins), amount + f := make([][]int, m+1) + const inf = 1 << 30 for i := range f { - f[i] = 1 << 30 + f[i] = make([]int, n+1) + for j := range f[i] { + f[i][j] = inf + } } - f[0] = 0 - for _, x := range coins { - for j := x; j <= n; j++ { - f[j] = min(f[j], f[j-x]+1) + f[0][0] = 0 + for i := 1; i <= m; i++ { + for j := 0; j <= n; j++ { + f[i][j] = f[i-1][j] + if j >= coins[i-1] { + f[i][j] = min(f[i][j], f[i][j-coins[i-1]]+1) + } } } - if f[n] > n { + if f[m][n] > n { return -1 } - return f[n] + return f[m][n] } \ No newline at end of file diff --git a/solution/0300-0399/0322.Coin Change/Solution.java b/solution/0300-0399/0322.Coin Change/Solution.java index 49b70d6ddf207..a12100560a41c 100644 --- a/solution/0300-0399/0322.Coin Change/Solution.java +++ b/solution/0300-0399/0322.Coin Change/Solution.java @@ -1,15 +1,21 @@ -class Solution { - public int coinChange(int[] coins, int amount) { - final int inf = 1 << 30; - int n = amount; - int[] f = new int[n + 1]; - Arrays.fill(f, inf); - f[0] = 0; - for (int x : coins) { - for (int j = x; j <= n; ++j) { - f[j] = Math.min(f[j], f[j - x] + 1); - } - } - return f[n] >= inf ? -1 : f[n]; - } +class Solution { + public int coinChange(int[] coins, int amount) { + final int inf = 1 << 30; + int m = coins.length; + int n = amount; + int[][] f = new int[m + 1][n + 1]; + for (var g : f) { + Arrays.fill(g, inf); + } + f[0][0] = 0; + for (int i = 1; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= coins[i - 1]) { + f[i][j] = Math.min(f[i][j], f[i][j - coins[i - 1]] + 1); + } + } + } + return f[m][n] >= inf ? -1 : f[m][n]; + } } \ No newline at end of file diff --git a/solution/0300-0399/0322.Coin Change/Solution.js b/solution/0300-0399/0322.Coin Change/Solution.js index 138e84a045e45..5ddaa1b9b63fd 100644 --- a/solution/0300-0399/0322.Coin Change/Solution.js +++ b/solution/0300-0399/0322.Coin Change/Solution.js @@ -4,13 +4,19 @@ * @return {number} */ var coinChange = function (coins, amount) { + const m = coins.length; const n = amount; - const f = Array(n + 1).fill(1 << 30); - f[0] = 0; - for (const x of coins) { - for (let j = x; j <= n; ++j) { - f[j] = Math.min(f[j], f[j - x] + 1); + const f = Array(m + 1) + .fill(0) + .map(() => Array(n + 1).fill(1 << 30)); + f[0][0] = 0; + for (let i = 1; i <= m; ++i) { + for (let j = 0; j <= n; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= coins[i - 1]) { + f[i][j] = Math.min(f[i][j], f[i][j - coins[i - 1]] + 1); + } } } - return f[n] > n ? -1 : f[n]; + return f[m][n] > n ? -1 : f[m][n]; }; diff --git a/solution/0300-0399/0322.Coin Change/Solution.py b/solution/0300-0399/0322.Coin Change/Solution.py index d498b599a1173..165c36dee282d 100644 --- a/solution/0300-0399/0322.Coin Change/Solution.py +++ b/solution/0300-0399/0322.Coin Change/Solution.py @@ -1,8 +1,11 @@ -class Solution: - def coinChange(self, coins: List[int], amount: int) -> int: - n = amount - f = [0] + [inf] * n - for x in coins: - for j in range(x, n + 1): - f[j] = min(f[j], f[j - x] + 1) - return -1 if f[n] >= inf else f[n] +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + m, n = len(coins), amount + f = [[inf] * (n + 1) for _ in range(m + 1)] + f[0][0] = 0 + for i, x in enumerate(coins, 1): + for j in range(n + 1): + f[i][j] = f[i - 1][j] + if j >= x: + f[i][j] = min(f[i][j], f[i][j - x] + 1) + return -1 if f[m][n] >= inf else f[m][n] diff --git a/solution/0300-0399/0322.Coin Change/Solution.ts b/solution/0300-0399/0322.Coin Change/Solution.ts index b8c60eb2f8d7a..e96f658bceea7 100644 --- a/solution/0300-0399/0322.Coin Change/Solution.ts +++ b/solution/0300-0399/0322.Coin Change/Solution.ts @@ -1,11 +1,17 @@ function coinChange(coins: number[], amount: number): number { + const m = coins.length; const n = amount; - const f: number[] = Array(n + 1).fill(1 << 30); - f[0] = 0; - for (const x of coins) { - for (let j = x; j <= n; ++j) { - f[j] = Math.min(f[j], f[j - x] + 1); + const f: number[][] = Array(m + 1) + .fill(0) + .map(() => Array(n + 1).fill(1 << 30)); + f[0][0] = 0; + for (let i = 1; i <= m; ++i) { + for (let j = 0; j <= n; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= coins[i - 1]) { + f[i][j] = Math.min(f[i][j], f[i][j - coins[i - 1]] + 1); + } } } - return f[n] > n ? -1 : f[n]; + return f[m][n] > n ? -1 : f[m][n]; } diff --git a/solution/0300-0399/0322.Coin Change/Solution2.cpp b/solution/0300-0399/0322.Coin Change/Solution2.cpp new file mode 100644 index 0000000000000..f7aeb208c969c --- /dev/null +++ b/solution/0300-0399/0322.Coin Change/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int coinChange(vector& coins, int amount) { + int n = amount; + int f[n + 1]; + memset(f, 0x3f, sizeof(f)); + f[0] = 0; + for (int x : coins) { + for (int j = x; j <= n; ++j) { + f[j] = min(f[j], f[j - x] + 1); + } + } + return f[n] > n ? -1 : f[n]; + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0322.Coin Change/Solution2.go b/solution/0300-0399/0322.Coin Change/Solution2.go new file mode 100644 index 0000000000000..bd7cd50453fe2 --- /dev/null +++ b/solution/0300-0399/0322.Coin Change/Solution2.go @@ -0,0 +1,17 @@ +func coinChange(coins []int, amount int) int { + n := amount + f := make([]int, n+1) + for i := range f { + f[i] = 1 << 30 + } + f[0] = 0 + for _, x := range coins { + for j := x; j <= n; j++ { + f[j] = min(f[j], f[j-x]+1) + } + } + if f[n] > n { + return -1 + } + return f[n] +} \ No newline at end of file diff --git a/solution/0300-0399/0322.Coin Change/Solution2.java b/solution/0300-0399/0322.Coin Change/Solution2.java new file mode 100644 index 0000000000000..5d3cc51d1a177 --- /dev/null +++ b/solution/0300-0399/0322.Coin Change/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public int coinChange(int[] coins, int amount) { + final int inf = 1 << 30; + int n = amount; + int[] f = new int[n + 1]; + Arrays.fill(f, inf); + f[0] = 0; + for (int x : coins) { + for (int j = x; j <= n; ++j) { + f[j] = Math.min(f[j], f[j - x] + 1); + } + } + return f[n] >= inf ? -1 : f[n]; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0322.Coin Change/Solution2.js b/solution/0300-0399/0322.Coin Change/Solution2.js new file mode 100644 index 0000000000000..138e84a045e45 --- /dev/null +++ b/solution/0300-0399/0322.Coin Change/Solution2.js @@ -0,0 +1,16 @@ +/** + * @param {number[]} coins + * @param {number} amount + * @return {number} + */ +var coinChange = function (coins, amount) { + const n = amount; + const f = Array(n + 1).fill(1 << 30); + f[0] = 0; + for (const x of coins) { + for (let j = x; j <= n; ++j) { + f[j] = Math.min(f[j], f[j - x] + 1); + } + } + return f[n] > n ? -1 : f[n]; +}; diff --git a/solution/0300-0399/0322.Coin Change/Solution2.py b/solution/0300-0399/0322.Coin Change/Solution2.py new file mode 100644 index 0000000000000..6308d1ceda064 --- /dev/null +++ b/solution/0300-0399/0322.Coin Change/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + n = amount + f = [0] + [inf] * n + for x in coins: + for j in range(x, n + 1): + f[j] = min(f[j], f[j - x] + 1) + return -1 if f[n] >= inf else f[n] diff --git a/solution/0300-0399/0322.Coin Change/Solution2.ts b/solution/0300-0399/0322.Coin Change/Solution2.ts new file mode 100644 index 0000000000000..b8c60eb2f8d7a --- /dev/null +++ b/solution/0300-0399/0322.Coin Change/Solution2.ts @@ -0,0 +1,11 @@ +function coinChange(coins: number[], amount: number): number { + const n = amount; + const f: number[] = Array(n + 1).fill(1 << 30); + f[0] = 0; + for (const x of coins) { + for (let j = x; j <= n; ++j) { + f[j] = Math.min(f[j], f[j - x] + 1); + } + } + return f[n] > n ? -1 : f[n]; +} diff --git a/solution/0300-0399/0324.Wiggle Sort II/Solution2.cpp b/solution/0300-0399/0324.Wiggle Sort II/Solution2.cpp new file mode 100644 index 0000000000000..49b65e63f3bdf --- /dev/null +++ b/solution/0300-0399/0324.Wiggle Sort II/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + void wiggleSort(vector& nums) { + vector bucket(5001); + for (int& v : nums) ++bucket[v]; + int n = nums.size(); + int j = 5000; + for (int i = 1; i < n; i += 2) { + while (bucket[j] == 0) --j; + nums[i] = j; + --bucket[j]; + } + for (int i = 0; i < n; i += 2) { + while (bucket[j] == 0) --j; + nums[i] = j; + --bucket[j]; + } + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0324.Wiggle Sort II/Solution2.go b/solution/0300-0399/0324.Wiggle Sort II/Solution2.go new file mode 100644 index 0000000000000..50dabf7a68214 --- /dev/null +++ b/solution/0300-0399/0324.Wiggle Sort II/Solution2.go @@ -0,0 +1,21 @@ +func wiggleSort(nums []int) { + bucket := make([]int, 5001) + for _, v := range nums { + bucket[v]++ + } + n, j := len(nums), 5000 + for i := 1; i < n; i += 2 { + for bucket[j] == 0 { + j-- + } + nums[i] = j + bucket[j]-- + } + for i := 0; i < n; i += 2 { + for bucket[j] == 0 { + j-- + } + nums[i] = j + bucket[j]-- + } +} \ No newline at end of file diff --git a/solution/0300-0399/0324.Wiggle Sort II/Solution2.java b/solution/0300-0399/0324.Wiggle Sort II/Solution2.java new file mode 100644 index 0000000000000..45fb1210da7fe --- /dev/null +++ b/solution/0300-0399/0324.Wiggle Sort II/Solution2.java @@ -0,0 +1,24 @@ +class Solution { + public void wiggleSort(int[] nums) { + int[] bucket = new int[5001]; + for (int v : nums) { + ++bucket[v]; + } + int n = nums.length; + int j = 5000; + for (int i = 1; i < n; i += 2) { + while (bucket[j] == 0) { + --j; + } + nums[i] = j; + --bucket[j]; + } + for (int i = 0; i < n; i += 2) { + while (bucket[j] == 0) { + --j; + } + nums[i] = j; + --bucket[j]; + } + } +} \ No newline at end of file diff --git a/solution/0300-0399/0324.Wiggle Sort II/Solution2.py b/solution/0300-0399/0324.Wiggle Sort II/Solution2.py new file mode 100644 index 0000000000000..f42586c9e354c --- /dev/null +++ b/solution/0300-0399/0324.Wiggle Sort II/Solution2.py @@ -0,0 +1,20 @@ +class Solution: + def wiggleSort(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + bucket = [0] * 5001 + for v in nums: + bucket[v] += 1 + n = len(nums) + j = 5000 + for i in range(1, n, 2): + while bucket[j] == 0: + j -= 1 + nums[i] = j + bucket[j] -= 1 + for i in range(0, n, 2): + while bucket[j] == 0: + j -= 1 + nums[i] = j + bucket[j] -= 1 diff --git a/solution/0300-0399/0326.Power of Three/Solution.cpp b/solution/0300-0399/0326.Power of Three/Solution.cpp index 769e5884a2754..7a67bbc606755 100644 --- a/solution/0300-0399/0326.Power of Three/Solution.cpp +++ b/solution/0300-0399/0326.Power of Three/Solution.cpp @@ -1,6 +1,12 @@ class Solution { public: bool isPowerOfThree(int n) { - return n > 0 && 1162261467 % n == 0; + while (n > 2) { + if (n % 3) { + return false; + } + n /= 3; + } + return n == 1; } }; \ No newline at end of file diff --git a/solution/0300-0399/0326.Power of Three/Solution.go b/solution/0300-0399/0326.Power of Three/Solution.go index 96b26b56d2a23..94cd9d3fd5502 100644 --- a/solution/0300-0399/0326.Power of Three/Solution.go +++ b/solution/0300-0399/0326.Power of Three/Solution.go @@ -1,3 +1,9 @@ func isPowerOfThree(n int) bool { - return n > 0 && 1162261467%n == 0 + for n > 2 { + if n%3 != 0 { + return false + } + n /= 3 + } + return n == 1 } \ No newline at end of file diff --git a/solution/0300-0399/0326.Power of Three/Solution.java b/solution/0300-0399/0326.Power of Three/Solution.java index a7253a81d3959..aa6f1f49f2890 100644 --- a/solution/0300-0399/0326.Power of Three/Solution.java +++ b/solution/0300-0399/0326.Power of Three/Solution.java @@ -1,5 +1,11 @@ class Solution { public boolean isPowerOfThree(int n) { - return n > 0 && 1162261467 % n == 0; + while (n > 2) { + if (n % 3 != 0) { + return false; + } + n /= 3; + } + return n == 1; } } \ No newline at end of file diff --git a/solution/0300-0399/0326.Power of Three/Solution.py b/solution/0300-0399/0326.Power of Three/Solution.py index 9a757f215dcc8..4f9db31195b83 100644 --- a/solution/0300-0399/0326.Power of Three/Solution.py +++ b/solution/0300-0399/0326.Power of Three/Solution.py @@ -1,3 +1,7 @@ class Solution: def isPowerOfThree(self, n: int) -> bool: - return n > 0 and 1162261467 % n == 0 + while n > 2: + if n % 3: + return False + n //= 3 + return n == 1 diff --git a/solution/0300-0399/0326.Power of Three/Solution2.cpp b/solution/0300-0399/0326.Power of Three/Solution2.cpp new file mode 100644 index 0000000000000..769e5884a2754 --- /dev/null +++ b/solution/0300-0399/0326.Power of Three/Solution2.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + bool isPowerOfThree(int n) { + return n > 0 && 1162261467 % n == 0; + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0326.Power of Three/Solution2.go b/solution/0300-0399/0326.Power of Three/Solution2.go new file mode 100644 index 0000000000000..96b26b56d2a23 --- /dev/null +++ b/solution/0300-0399/0326.Power of Three/Solution2.go @@ -0,0 +1,3 @@ +func isPowerOfThree(n int) bool { + return n > 0 && 1162261467%n == 0 +} \ No newline at end of file diff --git a/solution/0300-0399/0326.Power of Three/Solution2.java b/solution/0300-0399/0326.Power of Three/Solution2.java new file mode 100644 index 0000000000000..a7253a81d3959 --- /dev/null +++ b/solution/0300-0399/0326.Power of Three/Solution2.java @@ -0,0 +1,5 @@ +class Solution { + public boolean isPowerOfThree(int n) { + return n > 0 && 1162261467 % n == 0; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0326.Power of Three/Solution2.py b/solution/0300-0399/0326.Power of Three/Solution2.py new file mode 100644 index 0000000000000..9a757f215dcc8 --- /dev/null +++ b/solution/0300-0399/0326.Power of Three/Solution2.py @@ -0,0 +1,3 @@ +class Solution: + def isPowerOfThree(self, n: int) -> bool: + return n > 0 and 1162261467 % n == 0 diff --git a/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/Solution.cpp b/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/Solution.cpp index 9ddd5721be207..00d3de413012c 100644 --- a/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/Solution.cpp +++ b/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/Solution.cpp @@ -1,18 +1,18 @@ -class Solution { -public: - bool isValidSerialization(string preorder) { - vector stk; - stringstream ss(preorder); - string s; - while (getline(ss, s, ',')) { - stk.push_back(s); - while (stk.size() >= 3 && stk[stk.size() - 1] == "#" && stk[stk.size() - 2] == "#" && stk[stk.size() - 3] != "#") { - stk.pop_back(); - stk.pop_back(); - stk.pop_back(); - stk.push_back("#"); - } - } - return stk.size() == 1 && stk[0] == "#"; - } +class Solution { +public: + bool isValidSerialization(string preorder) { + vector stk; + stringstream ss(preorder); + string s; + while (getline(ss, s, ',')) { + stk.push_back(s); + while (stk.size() >= 3 && stk[stk.size() - 1] == "#" && stk[stk.size() - 2] == "#" && stk[stk.size() - 3] != "#") { + stk.pop_back(); + stk.pop_back(); + stk.pop_back(); + stk.push_back("#"); + } + } + return stk.size() == 1 && stk[0] == "#"; + } }; \ No newline at end of file diff --git a/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/Solution.java b/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/Solution.java index 9e77f5818c405..926461f339fd6 100644 --- a/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/Solution.java +++ b/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/Solution.java @@ -1,16 +1,15 @@ -class Solution { - public boolean isValidSerialization(String preorder) { - List stk = new ArrayList<>(); - for (String s : preorder.split(",")) { - stk.add(s); - while (stk.size() >= 3 && stk.get(stk.size() - 1).equals("#") - && stk.get(stk.size() - 2).equals("#") && !stk.get(stk.size() - 3).equals("#")) { - stk.remove(stk.size() - 1); - stk.remove(stk.size() - 1); - stk.remove(stk.size() - 1); - stk.add("#"); - } - } - return stk.size() == 1 && stk.get(0).equals("#"); - } +class Solution { + public boolean isValidSerialization(String preorder) { + String[] strs = preorder.split(","); + int diff = 1; + for (String s : strs) { + if (--diff < 0) { + return false; + } + if (!s.equals("#")) { + diff += 2; + } + } + return diff == 0; + } } \ No newline at end of file diff --git a/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/Solution.py b/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/Solution.py index 957ae49481c8e..9207209a2a5d8 100644 --- a/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/Solution.py +++ b/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def isValidSerialization(self, preorder: str) -> bool: - stk = [] - for c in preorder.split(","): - stk.append(c) - while len(stk) > 2 and stk[-1] == stk[-2] == "#" and stk[-3] != "#": - stk = stk[:-3] - stk.append("#") - return len(stk) == 1 and stk[0] == "#" +class Solution: + def isValidSerialization(self, preorder: str) -> bool: + stk = [] + for c in preorder.split(","): + stk.append(c) + while len(stk) > 2 and stk[-1] == stk[-2] == "#" and stk[-3] != "#": + stk = stk[:-3] + stk.append("#") + return len(stk) == 1 and stk[0] == "#" diff --git a/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/Solution2.java b/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/Solution2.java new file mode 100644 index 0000000000000..070e61b980697 --- /dev/null +++ b/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public boolean isValidSerialization(String preorder) { + List stk = new ArrayList<>(); + for (String s : preorder.split(",")) { + stk.add(s); + while (stk.size() >= 3 && stk.get(stk.size() - 1).equals("#") + && stk.get(stk.size() - 2).equals("#") && !stk.get(stk.size() - 3).equals("#")) { + stk.remove(stk.size() - 1); + stk.remove(stk.size() - 1); + stk.remove(stk.size() - 1); + stk.add("#"); + } + } + return stk.size() == 1 && stk.get(0).equals("#"); + } +} \ No newline at end of file diff --git a/solution/0300-0399/0334.Increasing Triplet Subsequence/Solution.java b/solution/0300-0399/0334.Increasing Triplet Subsequence/Solution.java index 6fc1f4bf77b71..bb46c107370a8 100644 --- a/solution/0300-0399/0334.Increasing Triplet Subsequence/Solution.java +++ b/solution/0300-0399/0334.Increasing Triplet Subsequence/Solution.java @@ -1,15 +1,20 @@ class Solution { public boolean increasingTriplet(int[] nums) { - int min = Integer.MAX_VALUE, mid = Integer.MAX_VALUE; - for (int num : nums) { - if (num > mid) { + int n = nums.length; + int[] lmi = new int[n]; + int[] rmx = new int[n]; + lmi[0] = Integer.MAX_VALUE; + rmx[n - 1] = Integer.MIN_VALUE; + for (int i = 1; i < n; ++i) { + lmi[i] = Math.min(lmi[i - 1], nums[i - 1]); + } + for (int i = n - 2; i >= 0; --i) { + rmx[i] = Math.max(rmx[i + 1], nums[i + 1]); + } + for (int i = 0; i < n; ++i) { + if (lmi[i] < nums[i] && nums[i] < rmx[i]) { return true; } - if (num <= min) { - min = num; - } else { - mid = num; - } } return false; } diff --git a/solution/0300-0399/0334.Increasing Triplet Subsequence/Solution2.java b/solution/0300-0399/0334.Increasing Triplet Subsequence/Solution2.java new file mode 100644 index 0000000000000..6fc1f4bf77b71 --- /dev/null +++ b/solution/0300-0399/0334.Increasing Triplet Subsequence/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public boolean increasingTriplet(int[] nums) { + int min = Integer.MAX_VALUE, mid = Integer.MAX_VALUE; + for (int num : nums) { + if (num > mid) { + return true; + } + if (num <= min) { + min = num; + } else { + mid = num; + } + } + return false; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0336.Palindrome Pairs/Solution2.java b/solution/0300-0399/0336.Palindrome Pairs/Solution2.java new file mode 100644 index 0000000000000..4349d854ae7ad --- /dev/null +++ b/solution/0300-0399/0336.Palindrome Pairs/Solution2.java @@ -0,0 +1,78 @@ +class Trie { + Trie[] children = new Trie[26]; + Integer v; + + void insert(String w, int i) { + Trie node = this; + for (char c : w.toCharArray()) { + c -= 'a'; + if (node.children[c] == null) { + node.children[c] = new Trie(); + } + node = node.children[c]; + } + node.v = i; + } + + Integer search(String w, int i, int j) { + Trie node = this; + for (int k = j; k >= i; --k) { + int idx = w.charAt(k) - 'a'; + if (node.children[idx] == null) { + return null; + } + node = node.children[idx]; + } + return node.v; + } +} + +class Solution { + public List> palindromePairs(String[] words) { + Trie trie = new Trie(); + int n = words.length; + for (int i = 0; i < n; ++i) { + trie.insert(words[i], i); + } + List> ans = new ArrayList<>(); + for (int i = 0; i < n; ++i) { + String w = words[i]; + int m = w.length(); + for (int j = 0; j <= m; ++j) { + if (isPalindrome(w, j, m - 1)) { + Integer k = trie.search(w, 0, j - 1); + if (k != null && k != i) { + ans.add(Arrays.asList(i, k)); + } + } + if (j != 0 && isPalindrome(w, 0, j - 1)) { + Integer k = trie.search(w, j, m - 1); + if (k != null && k != i) { + ans.add(Arrays.asList(k, i)); + } + } + } + } + return ans; + } + + // TLE + // private boolean isPalindrome(String w, int i, int j) { + // for (; i < j; ++i, --j) { + // if (w.charAt(i) != w.charAt(j)) { + // return false; + // } + // } + // return true; + // } + + private boolean isPalindrome(String w, int start, int end) { + int i = start, j = end; + for (; i < j; ++i, --j) { + if (w.charAt(i) != w.charAt(j)) { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0337.House Robber III/Solution.cpp b/solution/0300-0399/0337.House Robber III/Solution.cpp index f1b4ba969cebf..006514a692ed7 100644 --- a/solution/0300-0399/0337.House Robber III/Solution.cpp +++ b/solution/0300-0399/0337.House Robber III/Solution.cpp @@ -1,26 +1,26 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int rob(TreeNode* root) { - function(TreeNode*)> dfs = [&](TreeNode* root) -> pair { - if (!root) { - return make_pair(0, 0); - } - auto [la, lb] = dfs(root->left); - auto [ra, rb] = dfs(root->right); - return make_pair(root->val + lb + rb, max(la, lb) + max(ra, rb)); - }; - auto [a, b] = dfs(root); - return max(a, b); - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int rob(TreeNode* root) { + function(TreeNode*)> dfs = [&](TreeNode* root) -> pair { + if (!root) { + return make_pair(0, 0); + } + auto [la, lb] = dfs(root->left); + auto [ra, rb] = dfs(root->right); + return make_pair(root->val + lb + rb, max(la, lb) + max(ra, rb)); + }; + auto [a, b] = dfs(root); + return max(a, b); + } }; \ No newline at end of file diff --git a/solution/0300-0399/0337.House Robber III/Solution.java b/solution/0300-0399/0337.House Robber III/Solution.java index 3d6c36eea2e78..01a7b778a55e7 100644 --- a/solution/0300-0399/0337.House Robber III/Solution.java +++ b/solution/0300-0399/0337.House Robber III/Solution.java @@ -1,30 +1,30 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public int rob(TreeNode root) { - int[] ans = dfs(root); - return Math.max(ans[0], ans[1]); - } - - private int[] dfs(TreeNode root) { - if (root == null) { - return new int[2]; - } - int[] l = dfs(root.left); - int[] r = dfs(root.right); - return new int[] {root.val + l[1] + r[1], Math.max(l[0], l[1]) + Math.max(r[0], r[1])}; - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int rob(TreeNode root) { + int[] ans = dfs(root); + return Math.max(ans[0], ans[1]); + } + + private int[] dfs(TreeNode root) { + if (root == null) { + return new int[2]; + } + int[] l = dfs(root.left); + int[] r = dfs(root.right); + return new int[] {root.val + l[1] + r[1], Math.max(l[0], l[1]) + Math.max(r[0], r[1])}; + } } \ No newline at end of file diff --git a/solution/0300-0399/0337.House Robber III/Solution.py b/solution/0300-0399/0337.House Robber III/Solution.py index 64520cae826ce..bea9ffe602ba1 100644 --- a/solution/0300-0399/0337.House Robber III/Solution.py +++ b/solution/0300-0399/0337.House Robber III/Solution.py @@ -1,16 +1,16 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def rob(self, root: Optional[TreeNode]) -> int: - def dfs(root: Optional[TreeNode]) -> (int, int): - if root is None: - return 0, 0 - la, lb = dfs(root.left) - ra, rb = dfs(root.right) - return root.val + lb + rb, max(la, lb) + max(ra, rb) - - return max(dfs(root)) +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def rob(self, root: Optional[TreeNode]) -> int: + def dfs(root: Optional[TreeNode]) -> (int, int): + if root is None: + return 0, 0 + la, lb = dfs(root.left) + ra, rb = dfs(root.right) + return root.val + lb + rb, max(la, lb) + max(ra, rb) + + return max(dfs(root)) diff --git a/solution/0300-0399/0338.Counting Bits/Solution.cpp b/solution/0300-0399/0338.Counting Bits/Solution.cpp index 67199c90eebdb..fd5f1bcda38fc 100644 --- a/solution/0300-0399/0338.Counting Bits/Solution.cpp +++ b/solution/0300-0399/0338.Counting Bits/Solution.cpp @@ -1,10 +1,10 @@ -class Solution { -public: - vector countBits(int n) { - vector ans(n + 1); - for (int i = 0; i <= n; ++i) { - ans[i] = __builtin_popcount(i); - } - return ans; - } +class Solution { +public: + vector countBits(int n) { + vector ans(n + 1); + for (int i = 0; i <= n; ++i) { + ans[i] = __builtin_popcount(i); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0300-0399/0338.Counting Bits/Solution.go b/solution/0300-0399/0338.Counting Bits/Solution.go index 1514dd2381b4f..3a014e4b87a64 100644 --- a/solution/0300-0399/0338.Counting Bits/Solution.go +++ b/solution/0300-0399/0338.Counting Bits/Solution.go @@ -1,7 +1,7 @@ func countBits(n int) []int { ans := make([]int, n+1) - for i := 1; i <= n; i++ { - ans[i] = ans[i&(i-1)] + 1 + for i := 0; i <= n; i++ { + ans[i] = bits.OnesCount(uint(i)) } return ans } \ No newline at end of file diff --git a/solution/0300-0399/0338.Counting Bits/Solution.java b/solution/0300-0399/0338.Counting Bits/Solution.java index d73eaca3a085d..71c96a52f190d 100644 --- a/solution/0300-0399/0338.Counting Bits/Solution.java +++ b/solution/0300-0399/0338.Counting Bits/Solution.java @@ -1,9 +1,9 @@ -class Solution { - public int[] countBits(int n) { - int[] ans = new int[n + 1]; - for (int i = 1; i <= n; ++i) { - ans[i] = ans[i & (i - 1)] + 1; - } - return ans; - } +class Solution { + public int[] countBits(int n) { + int[] ans = new int[n + 1]; + for (int i = 0; i <= n; ++i) { + ans[i] = Integer.bitCount(i); + } + return ans; + } } \ No newline at end of file diff --git a/solution/0300-0399/0338.Counting Bits/Solution.py b/solution/0300-0399/0338.Counting Bits/Solution.py index 371b46a1e521c..b156da9919f5b 100644 --- a/solution/0300-0399/0338.Counting Bits/Solution.py +++ b/solution/0300-0399/0338.Counting Bits/Solution.py @@ -1,6 +1,3 @@ -class Solution: - def countBits(self, n: int) -> List[int]: - ans = [0] * (n + 1) - for i in range(1, n + 1): - ans[i] = ans[i & (i - 1)] + 1 - return ans +class Solution: + def countBits(self, n: int) -> List[int]: + return [i.bit_count() for i in range(n + 1)] diff --git a/solution/0300-0399/0338.Counting Bits/Solution.ts b/solution/0300-0399/0338.Counting Bits/Solution.ts index 26e9a5229a73c..5ba4be020568f 100644 --- a/solution/0300-0399/0338.Counting Bits/Solution.ts +++ b/solution/0300-0399/0338.Counting Bits/Solution.ts @@ -1,7 +1,16 @@ function countBits(n: number): number[] { const ans: number[] = Array(n + 1).fill(0); - for (let i = 1; i <= n; ++i) { - ans[i] = ans[i & (i - 1)] + 1; + for (let i = 0; i <= n; ++i) { + ans[i] = bitCount(i); } return ans; } + +function bitCount(n: number): number { + let count = 0; + while (n) { + n &= n - 1; + ++count; + } + return count; +} diff --git a/solution/0300-0399/0338.Counting Bits/Solution2.cpp b/solution/0300-0399/0338.Counting Bits/Solution2.cpp new file mode 100644 index 0000000000000..38bd9851c9ef3 --- /dev/null +++ b/solution/0300-0399/0338.Counting Bits/Solution2.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + vector countBits(int n) { + vector ans(n + 1); + for (int i = 1; i <= n; ++i) { + ans[i] = ans[i & (i - 1)] + 1; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0338.Counting Bits/Solution2.go b/solution/0300-0399/0338.Counting Bits/Solution2.go new file mode 100644 index 0000000000000..1514dd2381b4f --- /dev/null +++ b/solution/0300-0399/0338.Counting Bits/Solution2.go @@ -0,0 +1,7 @@ +func countBits(n int) []int { + ans := make([]int, n+1) + for i := 1; i <= n; i++ { + ans[i] = ans[i&(i-1)] + 1 + } + return ans +} \ No newline at end of file diff --git a/solution/0300-0399/0338.Counting Bits/Solution2.java b/solution/0300-0399/0338.Counting Bits/Solution2.java new file mode 100644 index 0000000000000..b30086b6f45fb --- /dev/null +++ b/solution/0300-0399/0338.Counting Bits/Solution2.java @@ -0,0 +1,9 @@ +class Solution { + public int[] countBits(int n) { + int[] ans = new int[n + 1]; + for (int i = 1; i <= n; ++i) { + ans[i] = ans[i & (i - 1)] + 1; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0338.Counting Bits/Solution2.py b/solution/0300-0399/0338.Counting Bits/Solution2.py new file mode 100644 index 0000000000000..991b53e1d27ec --- /dev/null +++ b/solution/0300-0399/0338.Counting Bits/Solution2.py @@ -0,0 +1,6 @@ +class Solution: + def countBits(self, n: int) -> List[int]: + ans = [0] * (n + 1) + for i in range(1, n + 1): + ans[i] = ans[i & (i - 1)] + 1 + return ans diff --git a/solution/0300-0399/0338.Counting Bits/Solution2.ts b/solution/0300-0399/0338.Counting Bits/Solution2.ts new file mode 100644 index 0000000000000..26e9a5229a73c --- /dev/null +++ b/solution/0300-0399/0338.Counting Bits/Solution2.ts @@ -0,0 +1,7 @@ +function countBits(n: number): number[] { + const ans: number[] = Array(n + 1).fill(0); + for (let i = 1; i <= n; ++i) { + ans[i] = ans[i & (i - 1)] + 1; + } + return ans; +} diff --git a/solution/0300-0399/0341.Flatten Nested List Iterator/Solution.go b/solution/0300-0399/0341.Flatten Nested List Iterator/Solution.go index 0a7520dd9a266..231ed7a9e0f43 100644 --- a/solution/0300-0399/0341.Flatten Nested List Iterator/Solution.go +++ b/solution/0300-0399/0341.Flatten Nested List Iterator/Solution.go @@ -25,31 +25,32 @@ */ type NestedIterator struct { - nested *list.List + iterator []int + index, length int } func Constructor(nestedList []*NestedInteger) *NestedIterator { - nested := list.New() - for _, v := range nestedList { - nested.PushBack(v) + result := make([]int, 0) + var traversal func(nodes []*NestedInteger) + traversal = func(nodes []*NestedInteger) { + for _, child := range nodes { + if child.IsInteger() { + result = append(result, child.GetInteger()) + } else { + traversal(child.GetList()) + } + } } - return &NestedIterator{nested: nested} + traversal(nestedList) + return &NestedIterator{iterator: result, index: 0, length: len(result)} } func (this *NestedIterator) Next() int { - res := this.nested.Front().Value.(*NestedInteger) - this.nested.Remove(this.nested.Front()) - return res.GetInteger() + res := this.iterator[this.index] + this.index++ + return res } func (this *NestedIterator) HasNext() bool { - for this.nested.Len() > 0 && !this.nested.Front().Value.(*NestedInteger).IsInteger() { - front := this.nested.Front().Value.(*NestedInteger) - this.nested.Remove(this.nested.Front()) - nodes := front.GetList() - for i := len(nodes) - 1; i >= 0; i-- { - this.nested.PushFront(nodes[i]) - } - } - return this.nested.Len() > 0 + return this.index < this.length } \ No newline at end of file diff --git a/solution/0300-0399/0341.Flatten Nested List Iterator/Solution2.go b/solution/0300-0399/0341.Flatten Nested List Iterator/Solution2.go new file mode 100644 index 0000000000000..0a7520dd9a266 --- /dev/null +++ b/solution/0300-0399/0341.Flatten Nested List Iterator/Solution2.go @@ -0,0 +1,55 @@ +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * type NestedInteger struct { + * } + * + * // Return true if this NestedInteger holds a single integer, rather than a nested list. + * func (this NestedInteger) IsInteger() bool {} + * + * // Return the single integer that this NestedInteger holds, if it holds a single integer + * // The result is undefined if this NestedInteger holds a nested list + * // So before calling this method, you should have a check + * func (this NestedInteger) GetInteger() int {} + * + * // Set this NestedInteger to hold a single integer. + * func (n *NestedInteger) SetInteger(value int) {} + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * func (this *NestedInteger) Add(elem NestedInteger) {} + * + * // Return the nested list that this NestedInteger holds, if it holds a nested list + * // The list length is zero if this NestedInteger holds a single integer + * // You can access NestedInteger's List element directly if you want to modify it + * func (this NestedInteger) GetList() []*NestedInteger {} + */ + +type NestedIterator struct { + nested *list.List +} + +func Constructor(nestedList []*NestedInteger) *NestedIterator { + nested := list.New() + for _, v := range nestedList { + nested.PushBack(v) + } + return &NestedIterator{nested: nested} +} + +func (this *NestedIterator) Next() int { + res := this.nested.Front().Value.(*NestedInteger) + this.nested.Remove(this.nested.Front()) + return res.GetInteger() +} + +func (this *NestedIterator) HasNext() bool { + for this.nested.Len() > 0 && !this.nested.Front().Value.(*NestedInteger).IsInteger() { + front := this.nested.Front().Value.(*NestedInteger) + this.nested.Remove(this.nested.Front()) + nodes := front.GetList() + for i := len(nodes) - 1; i >= 0; i-- { + this.nested.PushFront(nodes[i]) + } + } + return this.nested.Len() > 0 +} \ No newline at end of file diff --git a/solution/0300-0399/0343.Integer Break/Solution.c b/solution/0300-0399/0343.Integer Break/Solution.c index bb625ffe04fa9..2cecd56a0f623 100644 --- a/solution/0300-0399/0343.Integer Break/Solution.c +++ b/solution/0300-0399/0343.Integer Break/Solution.c @@ -4,4 +4,4 @@ int integerBreak(int n) { } int count = (n - 2) / 3; return pow(3, count) * (n - count * 3); -} +} \ No newline at end of file diff --git a/solution/0300-0399/0343.Integer Break/Solution.cpp b/solution/0300-0399/0343.Integer Break/Solution.cpp index 0b0a3f32e8abe..6ceba393ee4fa 100644 --- a/solution/0300-0399/0343.Integer Break/Solution.cpp +++ b/solution/0300-0399/0343.Integer Break/Solution.cpp @@ -1,15 +1,13 @@ class Solution { public: int integerBreak(int n) { - if (n < 4) { - return n - 1; + vector dp(n + 1); + dp[1] = 1; + for (int i = 2; i <= n; ++i) { + for (int j = 1; j < i; ++j) { + dp[i] = max(max(dp[i], dp[i - j] * j), (i - j) * j); + } } - if (n % 3 == 0) { - return pow(3, n / 3); - } - if (n % 3 == 1) { - return pow(3, n / 3 - 1) * 4; - } - return pow(3, n / 3) * 2; + return dp[n]; } }; \ No newline at end of file diff --git a/solution/0300-0399/0343.Integer Break/Solution.go b/solution/0300-0399/0343.Integer Break/Solution.go index 9120221d8980d..c2de2799d04ed 100644 --- a/solution/0300-0399/0343.Integer Break/Solution.go +++ b/solution/0300-0399/0343.Integer Break/Solution.go @@ -1,12 +1,10 @@ func integerBreak(n int) int { - if n < 4 { - return n - 1 + dp := make([]int, n+1) + dp[1] = 1 + for i := 2; i <= n; i++ { + for j := 1; j < i; j++ { + dp[i] = max(max(dp[i], dp[i-j]*j), (i-j)*j) + } } - if n%3 == 0 { - return int(math.Pow(3, float64(n/3))) - } - if n%3 == 1 { - return int(math.Pow(3, float64(n/3-1))) * 4 - } - return int(math.Pow(3, float64(n/3))) * 2 + return dp[n] } \ No newline at end of file diff --git a/solution/0300-0399/0343.Integer Break/Solution.java b/solution/0300-0399/0343.Integer Break/Solution.java index c8464bebd7314..ebc48c40f0086 100644 --- a/solution/0300-0399/0343.Integer Break/Solution.java +++ b/solution/0300-0399/0343.Integer Break/Solution.java @@ -1,14 +1,12 @@ class Solution { public int integerBreak(int n) { - if (n < 4) { - return n - 1; + int[] dp = new int[n + 1]; + dp[1] = 1; + for (int i = 2; i <= n; ++i) { + for (int j = 1; j < i; ++j) { + dp[i] = Math.max(Math.max(dp[i], dp[i - j] * j), (i - j) * j); + } } - if (n % 3 == 0) { - return (int) Math.pow(3, n / 3); - } - if (n % 3 == 1) { - return (int) Math.pow(3, n / 3 - 1) * 4; - } - return (int) Math.pow(3, n / 3) * 2; + return dp[n]; } } \ No newline at end of file diff --git a/solution/0300-0399/0343.Integer Break/Solution.py b/solution/0300-0399/0343.Integer Break/Solution.py index 436a631dee93a..faebd81349904 100644 --- a/solution/0300-0399/0343.Integer Break/Solution.py +++ b/solution/0300-0399/0343.Integer Break/Solution.py @@ -1,9 +1,7 @@ class Solution: def integerBreak(self, n: int) -> int: - if n < 4: - return n - 1 - if n % 3 == 0: - return pow(3, n // 3) - if n % 3 == 1: - return pow(3, n // 3 - 1) * 4 - return pow(3, n // 3) * 2 + dp = [1] * (n + 1) + for i in range(2, n + 1): + for j in range(1, i): + dp[i] = max(dp[i], dp[i - j] * j, (i - j) * j) + return dp[n] diff --git a/solution/0300-0399/0343.Integer Break/Solution.ts b/solution/0300-0399/0343.Integer Break/Solution.ts index c7d27a11deb4e..bedef9889f279 100644 --- a/solution/0300-0399/0343.Integer Break/Solution.ts +++ b/solution/0300-0399/0343.Integer Break/Solution.ts @@ -1,13 +1,9 @@ function integerBreak(n: number): number { - if (n < 4) { - return n - 1; + let dp = new Array(n + 1).fill(1); + for (let i = 3; i <= n; i++) { + for (let j = 1; j < i; j++) { + dp[i] = Math.max(dp[i], j * (i - j), j * dp[i - j]); + } } - const m = Math.floor(n / 3); - if (n % 3 == 0) { - return 3 ** m; - } - if (n % 3 == 1) { - return 3 ** (m - 1) * 4; - } - return 3 ** m * 2; + return dp.pop(); } diff --git a/solution/0300-0399/0343.Integer Break/Solution2.cpp b/solution/0300-0399/0343.Integer Break/Solution2.cpp new file mode 100644 index 0000000000000..0b0a3f32e8abe --- /dev/null +++ b/solution/0300-0399/0343.Integer Break/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int integerBreak(int n) { + if (n < 4) { + return n - 1; + } + if (n % 3 == 0) { + return pow(3, n / 3); + } + if (n % 3 == 1) { + return pow(3, n / 3 - 1) * 4; + } + return pow(3, n / 3) * 2; + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0343.Integer Break/Solution2.go b/solution/0300-0399/0343.Integer Break/Solution2.go new file mode 100644 index 0000000000000..9120221d8980d --- /dev/null +++ b/solution/0300-0399/0343.Integer Break/Solution2.go @@ -0,0 +1,12 @@ +func integerBreak(n int) int { + if n < 4 { + return n - 1 + } + if n%3 == 0 { + return int(math.Pow(3, float64(n/3))) + } + if n%3 == 1 { + return int(math.Pow(3, float64(n/3-1))) * 4 + } + return int(math.Pow(3, float64(n/3))) * 2 +} \ No newline at end of file diff --git a/solution/0300-0399/0343.Integer Break/Solution2.java b/solution/0300-0399/0343.Integer Break/Solution2.java new file mode 100644 index 0000000000000..c8464bebd7314 --- /dev/null +++ b/solution/0300-0399/0343.Integer Break/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public int integerBreak(int n) { + if (n < 4) { + return n - 1; + } + if (n % 3 == 0) { + return (int) Math.pow(3, n / 3); + } + if (n % 3 == 1) { + return (int) Math.pow(3, n / 3 - 1) * 4; + } + return (int) Math.pow(3, n / 3) * 2; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0343.Integer Break/Solution2.py b/solution/0300-0399/0343.Integer Break/Solution2.py new file mode 100644 index 0000000000000..436a631dee93a --- /dev/null +++ b/solution/0300-0399/0343.Integer Break/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def integerBreak(self, n: int) -> int: + if n < 4: + return n - 1 + if n % 3 == 0: + return pow(3, n // 3) + if n % 3 == 1: + return pow(3, n // 3 - 1) * 4 + return pow(3, n // 3) * 2 diff --git a/solution/0300-0399/0343.Integer Break/Solution2.ts b/solution/0300-0399/0343.Integer Break/Solution2.ts new file mode 100644 index 0000000000000..c7d27a11deb4e --- /dev/null +++ b/solution/0300-0399/0343.Integer Break/Solution2.ts @@ -0,0 +1,13 @@ +function integerBreak(n: number): number { + if (n < 4) { + return n - 1; + } + const m = Math.floor(n / 3); + if (n % 3 == 0) { + return 3 ** m; + } + if (n % 3 == 1) { + return 3 ** (m - 1) * 4; + } + return 3 ** m * 2; +} diff --git a/solution/0300-0399/0344.Reverse String/Solution.cpp b/solution/0300-0399/0344.Reverse String/Solution.cpp index 7e401e2d65784..42baacbec5c6a 100644 --- a/solution/0300-0399/0344.Reverse String/Solution.cpp +++ b/solution/0300-0399/0344.Reverse String/Solution.cpp @@ -1,8 +1,8 @@ -class Solution { -public: - void reverseString(vector& s) { - for (int i = 0, j = s.size() - 1; i < j;) { - swap(s[i++], s[j--]); - } - } +class Solution { +public: + void reverseString(vector& s) { + for (int i = 0, j = s.size() - 1; i < j;) { + swap(s[i++], s[j--]); + } + } }; \ No newline at end of file diff --git a/solution/0300-0399/0344.Reverse String/Solution.py b/solution/0300-0399/0344.Reverse String/Solution.py index 18a47df1f4ed3..c89734b2e5d45 100644 --- a/solution/0300-0399/0344.Reverse String/Solution.py +++ b/solution/0300-0399/0344.Reverse String/Solution.py @@ -1,6 +1,6 @@ -class Solution: - def reverseString(self, s: List[str]) -> None: - i, j = 0, len(s) - 1 - while i < j: - s[i], s[j] = s[j], s[i] - i, j = i + 1, j - 1 +class Solution: + def reverseString(self, s: List[str]) -> None: + i, j = 0, len(s) - 1 + while i < j: + s[i], s[j] = s[j], s[i] + i, j = i + 1, j - 1 diff --git a/solution/0300-0399/0344.Reverse String/Solution2.py b/solution/0300-0399/0344.Reverse String/Solution2.py new file mode 100644 index 0000000000000..cbabe101ef861 --- /dev/null +++ b/solution/0300-0399/0344.Reverse String/Solution2.py @@ -0,0 +1,3 @@ +class Solution: + def reverseString(self, s: List[str]) -> None: + s[:] = s[::-1] diff --git a/solution/0300-0399/0344.Reverse String/Solution2.ts b/solution/0300-0399/0344.Reverse String/Solution2.ts new file mode 100644 index 0000000000000..fa5218608d9d4 --- /dev/null +++ b/solution/0300-0399/0344.Reverse String/Solution2.ts @@ -0,0 +1,6 @@ +/** + Do not return anything, modify s in-place instead. + */ +function reverseString(s: string[]): void { + s.reverse(); +} diff --git a/solution/0300-0399/0345.Reverse Vowels of a String/Solution.cpp b/solution/0300-0399/0345.Reverse Vowels of a String/Solution.cpp index aabf7b13ca1f3..31d4d52cf3d40 100644 --- a/solution/0300-0399/0345.Reverse Vowels of a String/Solution.cpp +++ b/solution/0300-0399/0345.Reverse Vowels of a String/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - string reverseVowels(string s) { - bool vowels[128]; - memset(vowels, false, sizeof(vowels)); - for (char c : "aeiouAEIOU") { - vowels[c] = true; - } - int i = 0, j = s.size() - 1; - while (i < j) { - while (i < j && !vowels[s[i]]) { - ++i; - } - while (i < j && !vowels[s[j]]) { - --j; - } - if (i < j) { - swap(s[i++], s[j--]); - } - } - return s; - } +class Solution { +public: + string reverseVowels(string s) { + bool vowels[128]; + memset(vowels, false, sizeof(vowels)); + for (char c : "aeiouAEIOU") { + vowels[c] = true; + } + int i = 0, j = s.size() - 1; + while (i < j) { + while (i < j && !vowels[s[i]]) { + ++i; + } + while (i < j && !vowels[s[j]]) { + --j; + } + if (i < j) { + swap(s[i++], s[j--]); + } + } + return s; + } }; \ No newline at end of file diff --git a/solution/0300-0399/0345.Reverse Vowels of a String/Solution.java b/solution/0300-0399/0345.Reverse Vowels of a String/Solution.java index 7ff1dc2d70ae1..fb33250153c72 100644 --- a/solution/0300-0399/0345.Reverse Vowels of a String/Solution.java +++ b/solution/0300-0399/0345.Reverse Vowels of a String/Solution.java @@ -1,26 +1,26 @@ -class Solution { - public String reverseVowels(String s) { - boolean[] vowels = new boolean[128]; - for (char c : "aeiouAEIOU".toCharArray()) { - vowels[c] = true; - } - char[] cs = s.toCharArray(); - int i = 0, j = cs.length - 1; - while (i < j) { - while (i < j && !vowels[cs[i]]) { - ++i; - } - while (i < j && !vowels[cs[j]]) { - --j; - } - if (i < j) { - char t = cs[i]; - cs[i] = cs[j]; - cs[j] = t; - ++i; - --j; - } - } - return String.valueOf(cs); - } +class Solution { + public String reverseVowels(String s) { + boolean[] vowels = new boolean[128]; + for (char c : "aeiouAEIOU".toCharArray()) { + vowels[c] = true; + } + char[] cs = s.toCharArray(); + int i = 0, j = cs.length - 1; + while (i < j) { + while (i < j && !vowels[cs[i]]) { + ++i; + } + while (i < j && !vowels[cs[j]]) { + --j; + } + if (i < j) { + char t = cs[i]; + cs[i] = cs[j]; + cs[j] = t; + ++i; + --j; + } + } + return String.valueOf(cs); + } } \ No newline at end of file diff --git a/solution/0300-0399/0345.Reverse Vowels of a String/Solution.py b/solution/0300-0399/0345.Reverse Vowels of a String/Solution.py index 073b1bc1ca326..04721158ac804 100644 --- a/solution/0300-0399/0345.Reverse Vowels of a String/Solution.py +++ b/solution/0300-0399/0345.Reverse Vowels of a String/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def reverseVowels(self, s: str) -> str: - vowels = "aeiouAEIOU" - i, j = 0, len(s) - 1 - cs = list(s) - while i < j: - while i < j and cs[i] not in vowels: - i += 1 - while i < j and cs[j] not in vowels: - j -= 1 - if i < j: - cs[i], cs[j] = cs[j], cs[i] - i, j = i + 1, j - 1 - return "".join(cs) +class Solution: + def reverseVowels(self, s: str) -> str: + vowels = "aeiouAEIOU" + i, j = 0, len(s) - 1 + cs = list(s) + while i < j: + while i < j and cs[i] not in vowels: + i += 1 + while i < j and cs[j] not in vowels: + j -= 1 + if i < j: + cs[i], cs[j] = cs[j], cs[i] + i, j = i + 1, j - 1 + return "".join(cs) diff --git a/solution/0300-0399/0346.Moving Average from Data Stream/Solution2.cpp b/solution/0300-0399/0346.Moving Average from Data Stream/Solution2.cpp new file mode 100644 index 0000000000000..123bfc20cd73b --- /dev/null +++ b/solution/0300-0399/0346.Moving Average from Data Stream/Solution2.cpp @@ -0,0 +1,27 @@ +class MovingAverage { +public: + MovingAverage(int size) { + n = size; + } + + double next(int val) { + if (q.size() == n) { + s -= q.front(); + q.pop(); + } + q.push(val); + s += val; + return (double) s / q.size(); + } + +private: + queue q; + int s = 0; + int n; +}; + +/** + * Your MovingAverage object will be instantiated and called as such: + * MovingAverage* obj = new MovingAverage(size); + * double param_1 = obj->next(val); + */ \ No newline at end of file diff --git a/solution/0300-0399/0346.Moving Average from Data Stream/Solution2.go b/solution/0300-0399/0346.Moving Average from Data Stream/Solution2.go new file mode 100644 index 0000000000000..a6e2255b7c187 --- /dev/null +++ b/solution/0300-0399/0346.Moving Average from Data Stream/Solution2.go @@ -0,0 +1,25 @@ +type MovingAverage struct { + q []int + s int + n int +} + +func Constructor(size int) MovingAverage { + return MovingAverage{n: size} +} + +func (this *MovingAverage) Next(val int) float64 { + if len(this.q) == this.n { + this.s -= this.q[0] + this.q = this.q[1:] + } + this.q = append(this.q, val) + this.s += val + return float64(this.s) / float64(len(this.q)) +} + +/** + * Your MovingAverage object will be instantiated and called as such: + * obj := Constructor(size); + * param_1 := obj.Next(val); + */ \ No newline at end of file diff --git a/solution/0300-0399/0346.Moving Average from Data Stream/Solution2.java b/solution/0300-0399/0346.Moving Average from Data Stream/Solution2.java new file mode 100644 index 0000000000000..32d2b1b3cafce --- /dev/null +++ b/solution/0300-0399/0346.Moving Average from Data Stream/Solution2.java @@ -0,0 +1,24 @@ +class MovingAverage { + private Deque q = new ArrayDeque<>(); + private int n; + private int s; + + public MovingAverage(int size) { + n = size; + } + + public double next(int val) { + if (q.size() == n) { + s -= q.pollFirst(); + } + q.offer(val); + s += val; + return s * 1.0 / q.size(); + } +} + +/** + * Your MovingAverage object will be instantiated and called as such: + * MovingAverage obj = new MovingAverage(size); + * double param_1 = obj.next(val); + */ \ No newline at end of file diff --git a/solution/0300-0399/0346.Moving Average from Data Stream/Solution2.py b/solution/0300-0399/0346.Moving Average from Data Stream/Solution2.py new file mode 100644 index 0000000000000..42684d122ee37 --- /dev/null +++ b/solution/0300-0399/0346.Moving Average from Data Stream/Solution2.py @@ -0,0 +1,17 @@ +class MovingAverage: + def __init__(self, size: int): + self.n = size + self.s = 0 + self.q = deque() + + def next(self, val: int) -> float: + if len(self.q) == self.n: + self.s -= self.q.popleft() + self.q.append(val) + self.s += val + return self.s / len(self.q) + + +# Your MovingAverage object will be instantiated and called as such: +# obj = MovingAverage(size) +# param_1 = obj.next(val) diff --git a/solution/0300-0399/0347.Top K Frequent Elements/Solution.java b/solution/0300-0399/0347.Top K Frequent Elements/Solution.java index 2c51bdcb0e84e..2dd78e1c6fdbc 100644 --- a/solution/0300-0399/0347.Top K Frequent Elements/Solution.java +++ b/solution/0300-0399/0347.Top K Frequent Elements/Solution.java @@ -11,4 +11,4 @@ public int[] topKFrequent(int[] nums, int k) { } return queue.stream().mapToInt(Map.Entry::getKey).toArray(); } -} +} \ No newline at end of file diff --git a/solution/0300-0399/0347.Top K Frequent Elements/Solution.py b/solution/0300-0399/0347.Top K Frequent Elements/Solution.py index 37e7fac77f36d..bb2e27754c5f0 100644 --- a/solution/0300-0399/0347.Top K Frequent Elements/Solution.py +++ b/solution/0300-0399/0347.Top K Frequent Elements/Solution.py @@ -1,9 +1,4 @@ class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: cnt = Counter(nums) - hp = [] - for num, freq in cnt.items(): - heappush(hp, (freq, num)) - if len(hp) > k: - heappop(hp) - return [v[1] for v in hp] + return [v[0] for v in cnt.most_common(k)] diff --git a/solution/0300-0399/0347.Top K Frequent Elements/Solution2.java b/solution/0300-0399/0347.Top K Frequent Elements/Solution2.java new file mode 100644 index 0000000000000..50579ba0ce6b6 --- /dev/null +++ b/solution/0300-0399/0347.Top K Frequent Elements/Solution2.java @@ -0,0 +1,20 @@ +class Solution { + public int[] topKFrequent(int[] nums, int k) { + Map cnt = new HashMap<>(); + for (int v : nums) { + cnt.put(v, cnt.getOrDefault(v, 0) + 1); + } + PriorityQueue pq = new PriorityQueue<>((a, b) -> a[1] - b[1]); + for (var e : cnt.entrySet()) { + pq.offer(new int[] {e.getKey(), e.getValue()}); + if (pq.size() > k) { + pq.poll(); + } + } + int[] ans = new int[k]; + for (int i = 0; i < k; ++i) { + ans[i] = pq.poll()[0]; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0347.Top K Frequent Elements/Solution2.py b/solution/0300-0399/0347.Top K Frequent Elements/Solution2.py new file mode 100644 index 0000000000000..37e7fac77f36d --- /dev/null +++ b/solution/0300-0399/0347.Top K Frequent Elements/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + cnt = Counter(nums) + hp = [] + for num, freq in cnt.items(): + heappush(hp, (freq, num)) + if len(hp) > k: + heappop(hp) + return [v[1] for v in hp] diff --git a/solution/0300-0399/0347.Top K Frequent Elements/Solution2.ts b/solution/0300-0399/0347.Top K Frequent Elements/Solution2.ts new file mode 100644 index 0000000000000..9001644391a42 --- /dev/null +++ b/solution/0300-0399/0347.Top K Frequent Elements/Solution2.ts @@ -0,0 +1,20 @@ +function topKFrequent(nums: number[], k: number): number[] { + const map = new Map(); + let maxCount = 0; + for (const num of nums) { + map.set(num, (map.get(num) ?? 0) + 1); + maxCount = Math.max(maxCount, map.get(num)); + } + + const res = []; + while (k > 0) { + for (const key of map.keys()) { + if (map.get(key) === maxCount) { + res.push(key); + k--; + } + } + maxCount--; + } + return res; +} diff --git a/solution/0300-0399/0349.Intersection of Two Arrays/Solution.cs b/solution/0300-0399/0349.Intersection of Two Arrays/Solution.cs new file mode 100644 index 0000000000000..f62d6b57dbf96 --- /dev/null +++ b/solution/0300-0399/0349.Intersection of Two Arrays/Solution.cs @@ -0,0 +1,13 @@ +public class Solution { + public int[] Intersection(int[] nums1, int[] nums2) { + List result = new List(); + HashSet arr1 = new(nums1); + HashSet arr2 = new(nums2); + foreach (int x in arr1) { + if (arr2.Contains(x)) { + result.Add(x); + } + } + return result.ToArray(); + } +} diff --git a/solution/0300-0399/0349.Intersection of Two Arrays/Solution.php b/solution/0300-0399/0349.Intersection of Two Arrays/Solution.php index 1a77c5715ba40..18775d08022c1 100644 --- a/solution/0300-0399/0349.Intersection of Two Arrays/Solution.php +++ b/solution/0300-0399/0349.Intersection of Two Arrays/Solution.php @@ -18,4 +18,4 @@ function intersection($nums1, $nums2) { } return $rs; } -} \ No newline at end of file +} diff --git a/solution/0300-0399/0349.Intersection of Two Arrays/Solution2.js b/solution/0300-0399/0349.Intersection of Two Arrays/Solution2.js new file mode 100644 index 0000000000000..c5d90bee0b32d --- /dev/null +++ b/solution/0300-0399/0349.Intersection of Two Arrays/Solution2.js @@ -0,0 +1,8 @@ +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var intersection = function (nums1, nums2) { + return Array.from(new Set(nums1)).filter(num => new Set(nums2).has(num)); +}; diff --git a/solution/0300-0399/0350.Intersection of Two Arrays II/Solution.php b/solution/0300-0399/0350.Intersection of Two Arrays II/Solution.php index fb73f75c413f9..30f3bc9fdcb73 100644 --- a/solution/0300-0399/0350.Intersection of Two Arrays II/Solution.php +++ b/solution/0300-0399/0350.Intersection of Two Arrays II/Solution.php @@ -17,4 +17,4 @@ function intersect($nums1, $nums2) { } return $rs; } -} \ No newline at end of file +} diff --git a/solution/0300-0399/0351.Android Unlock Patterns/Solution.cpp b/solution/0300-0399/0351.Android Unlock Patterns/Solution.cpp index 5a79ea54e2eb1..8243406981551 100644 --- a/solution/0300-0399/0351.Android Unlock Patterns/Solution.cpp +++ b/solution/0300-0399/0351.Android Unlock Patterns/Solution.cpp @@ -1,35 +1,35 @@ -class Solution { -public: - int numberOfPatterns(int m, int n) { - int cross[10][10]; - memset(cross, 0, sizeof(cross)); - bool vis[10]; - memset(vis, false, sizeof(vis)); - cross[1][3] = cross[3][1] = 2; - cross[1][7] = cross[7][1] = 4; - cross[1][9] = cross[9][1] = 5; - cross[2][8] = cross[8][2] = 5; - cross[3][7] = cross[7][3] = 5; - cross[3][9] = cross[9][3] = 6; - cross[4][6] = cross[6][4] = 5; - cross[7][9] = cross[9][7] = 8; - - function dfs = [&](int i, int cnt) { - if (cnt > n) { - return 0; - } - vis[i] = true; - int ans = cnt >= m ? 1 : 0; - for (int j = 1; j < 10; ++j) { - int x = cross[i][j]; - if (!vis[j] && (x == 0 || vis[x])) { - ans += dfs(j, cnt + 1); - } - } - vis[i] = false; - return ans; - }; - - return dfs(1, 1) * 4 + dfs(2, 1) * 4 + dfs(5, 1); - } +class Solution { +public: + int numberOfPatterns(int m, int n) { + int cross[10][10]; + memset(cross, 0, sizeof(cross)); + bool vis[10]; + memset(vis, false, sizeof(vis)); + cross[1][3] = cross[3][1] = 2; + cross[1][7] = cross[7][1] = 4; + cross[1][9] = cross[9][1] = 5; + cross[2][8] = cross[8][2] = 5; + cross[3][7] = cross[7][3] = 5; + cross[3][9] = cross[9][3] = 6; + cross[4][6] = cross[6][4] = 5; + cross[7][9] = cross[9][7] = 8; + + function dfs = [&](int i, int cnt) { + if (cnt > n) { + return 0; + } + vis[i] = true; + int ans = cnt >= m ? 1 : 0; + for (int j = 1; j < 10; ++j) { + int x = cross[i][j]; + if (!vis[j] && (x == 0 || vis[x])) { + ans += dfs(j, cnt + 1); + } + } + vis[i] = false; + return ans; + }; + + return dfs(1, 1) * 4 + dfs(2, 1) * 4 + dfs(5, 1); + } }; \ No newline at end of file diff --git a/solution/0300-0399/0351.Android Unlock Patterns/Solution.java b/solution/0300-0399/0351.Android Unlock Patterns/Solution.java index 0cb48c6607cbf..362425b0fa717 100644 --- a/solution/0300-0399/0351.Android Unlock Patterns/Solution.java +++ b/solution/0300-0399/0351.Android Unlock Patterns/Solution.java @@ -1,36 +1,36 @@ -class Solution { - private int m; - private int n; - private int[][] cross = new int[10][10]; - private boolean[] vis = new boolean[10]; - - public int numberOfPatterns(int m, int n) { - this.m = m; - this.n = n; - cross[1][3] = cross[3][1] = 2; - cross[1][7] = cross[7][1] = 4; - cross[1][9] = cross[9][1] = 5; - cross[2][8] = cross[8][2] = 5; - cross[3][7] = cross[7][3] = 5; - cross[3][9] = cross[9][3] = 6; - cross[4][6] = cross[6][4] = 5; - cross[7][9] = cross[9][7] = 8; - return dfs(1, 1) * 4 + dfs(2, 1) * 4 + dfs(5, 1); - } - - private int dfs(int i, int cnt) { - if (cnt > n) { - return 0; - } - vis[i] = true; - int ans = cnt >= m ? 1 : 0; - for (int j = 1; j < 10; ++j) { - int x = cross[i][j]; - if (!vis[j] && (x == 0 || vis[x])) { - ans += dfs(j, cnt + 1); - } - } - vis[i] = false; - return ans; - } +class Solution { + private int m; + private int n; + private int[][] cross = new int[10][10]; + private boolean[] vis = new boolean[10]; + + public int numberOfPatterns(int m, int n) { + this.m = m; + this.n = n; + cross[1][3] = cross[3][1] = 2; + cross[1][7] = cross[7][1] = 4; + cross[1][9] = cross[9][1] = 5; + cross[2][8] = cross[8][2] = 5; + cross[3][7] = cross[7][3] = 5; + cross[3][9] = cross[9][3] = 6; + cross[4][6] = cross[6][4] = 5; + cross[7][9] = cross[9][7] = 8; + return dfs(1, 1) * 4 + dfs(2, 1) * 4 + dfs(5, 1); + } + + private int dfs(int i, int cnt) { + if (cnt > n) { + return 0; + } + vis[i] = true; + int ans = cnt >= m ? 1 : 0; + for (int j = 1; j < 10; ++j) { + int x = cross[i][j]; + if (!vis[j] && (x == 0 || vis[x])) { + ans += dfs(j, cnt + 1); + } + } + vis[i] = false; + return ans; + } } \ No newline at end of file diff --git a/solution/0300-0399/0351.Android Unlock Patterns/Solution.py b/solution/0300-0399/0351.Android Unlock Patterns/Solution.py index f7d3af26d9b5d..d5f13d5301d4d 100644 --- a/solution/0300-0399/0351.Android Unlock Patterns/Solution.py +++ b/solution/0300-0399/0351.Android Unlock Patterns/Solution.py @@ -1,25 +1,25 @@ -class Solution: - def numberOfPatterns(self, m: int, n: int) -> int: - def dfs(i: int, cnt: int = 1) -> int: - if cnt > n: - return 0 - vis[i] = True - ans = int(cnt >= m) - for j in range(1, 10): - x = cross[i][j] - if not vis[j] and (x == 0 or vis[x]): - ans += dfs(j, cnt + 1) - vis[i] = False - return ans - - cross = [[0] * 10 for _ in range(10)] - cross[1][3] = cross[3][1] = 2 - cross[1][7] = cross[7][1] = 4 - cross[1][9] = cross[9][1] = 5 - cross[2][8] = cross[8][2] = 5 - cross[3][7] = cross[7][3] = 5 - cross[3][9] = cross[9][3] = 6 - cross[4][6] = cross[6][4] = 5 - cross[7][9] = cross[9][7] = 8 - vis = [False] * 10 - return dfs(1) * 4 + dfs(2) * 4 + dfs(5) +class Solution: + def numberOfPatterns(self, m: int, n: int) -> int: + def dfs(i: int, cnt: int = 1) -> int: + if cnt > n: + return 0 + vis[i] = True + ans = int(cnt >= m) + for j in range(1, 10): + x = cross[i][j] + if not vis[j] and (x == 0 or vis[x]): + ans += dfs(j, cnt + 1) + vis[i] = False + return ans + + cross = [[0] * 10 for _ in range(10)] + cross[1][3] = cross[3][1] = 2 + cross[1][7] = cross[7][1] = 4 + cross[1][9] = cross[9][1] = 5 + cross[2][8] = cross[8][2] = 5 + cross[3][7] = cross[7][3] = 5 + cross[3][9] = cross[9][3] = 6 + cross[4][6] = cross[6][4] = 5 + cross[7][9] = cross[9][7] = 8 + vis = [False] * 10 + return dfs(1) * 4 + dfs(2) * 4 + dfs(5) diff --git a/solution/0300-0399/0353.Design Snake Game/Solution.cpp b/solution/0300-0399/0353.Design Snake Game/Solution.cpp index dd699e5c6f175..df941cddcb183 100644 --- a/solution/0300-0399/0353.Design Snake Game/Solution.cpp +++ b/solution/0300-0399/0353.Design Snake Game/Solution.cpp @@ -1,64 +1,64 @@ -class SnakeGame { -public: - SnakeGame(int width, int height, vector>& food) { - m = height; - n = width; - this->food = food; - score = 0; - idx = 0; - q.push_back(0); - vis.insert(0); - } - - int move(string direction) { - int p = q.front(); - int i = p / n, j = p % n; - int x = i, y = j; - if (direction == "U") { - --x; - } else if (direction == "D") { - ++x; - } else if (direction == "L") { - --y; - } else { - ++y; - } - if (x < 0 || x >= m || y < 0 || y >= n) { - return -1; - } - if (idx < food.size() && x == food[idx][0] && y == food[idx][1]) { - ++score; - ++idx; - } else { - int tail = q.back(); - q.pop_back(); - vis.erase(tail); - } - int cur = f(x, y); - if (vis.count(cur)) { - return -1; - } - q.push_front(cur); - vis.insert(cur); - return score; - } - -private: - int m; - int n; - vector> food; - int score; - int idx; - deque q; - unordered_set vis; - - int f(int i, int j) { - return i * n + j; - } -}; - -/** - * Your SnakeGame object will be instantiated and called as such: - * SnakeGame* obj = new SnakeGame(width, height, food); - * int param_1 = obj->move(direction); +class SnakeGame { +public: + SnakeGame(int width, int height, vector>& food) { + m = height; + n = width; + this->food = food; + score = 0; + idx = 0; + q.push_back(0); + vis.insert(0); + } + + int move(string direction) { + int p = q.front(); + int i = p / n, j = p % n; + int x = i, y = j; + if (direction == "U") { + --x; + } else if (direction == "D") { + ++x; + } else if (direction == "L") { + --y; + } else { + ++y; + } + if (x < 0 || x >= m || y < 0 || y >= n) { + return -1; + } + if (idx < food.size() && x == food[idx][0] && y == food[idx][1]) { + ++score; + ++idx; + } else { + int tail = q.back(); + q.pop_back(); + vis.erase(tail); + } + int cur = f(x, y); + if (vis.count(cur)) { + return -1; + } + q.push_front(cur); + vis.insert(cur); + return score; + } + +private: + int m; + int n; + vector> food; + int score; + int idx; + deque q; + unordered_set vis; + + int f(int i, int j) { + return i * n + j; + } +}; + +/** + * Your SnakeGame object will be instantiated and called as such: + * SnakeGame* obj = new SnakeGame(width, height, food); + * int param_1 = obj->move(direction); */ \ No newline at end of file diff --git a/solution/0300-0399/0353.Design Snake Game/Solution.java b/solution/0300-0399/0353.Design Snake Game/Solution.java index 3c246368e177e..fdadf66735578 100644 --- a/solution/0300-0399/0353.Design Snake Game/Solution.java +++ b/solution/0300-0399/0353.Design Snake Game/Solution.java @@ -1,59 +1,59 @@ -class SnakeGame { - private int m; - private int n; - private int[][] food; - private int score; - private int idx; - private Deque q = new ArrayDeque<>(); - private Set vis = new HashSet<>(); - - public SnakeGame(int width, int height, int[][] food) { - m = height; - n = width; - this.food = food; - q.offer(0); - vis.add(0); - } - - public int move(String direction) { - int p = q.peekFirst(); - int i = p / n, j = p % n; - int x = i, y = j; - if ("U".equals(direction)) { - --x; - } else if ("D".equals(direction)) { - ++x; - } else if ("L".equals(direction)) { - --y; - } else { - ++y; - } - if (x < 0 || x >= m || y < 0 || y >= n) { - return -1; - } - if (idx < food.length && x == food[idx][0] && y == food[idx][1]) { - ++score; - ++idx; - } else { - int t = q.pollLast(); - vis.remove(t); - } - int cur = f(x, y); - if (vis.contains(cur)) { - return -1; - } - q.offerFirst(cur); - vis.add(cur); - return score; - } - - private int f(int i, int j) { - return i * n + j; - } -} - -/** - * Your SnakeGame object will be instantiated and called as such: - * SnakeGame obj = new SnakeGame(width, height, food); - * int param_1 = obj.move(direction); +class SnakeGame { + private int m; + private int n; + private int[][] food; + private int score; + private int idx; + private Deque q = new ArrayDeque<>(); + private Set vis = new HashSet<>(); + + public SnakeGame(int width, int height, int[][] food) { + m = height; + n = width; + this.food = food; + q.offer(0); + vis.add(0); + } + + public int move(String direction) { + int p = q.peekFirst(); + int i = p / n, j = p % n; + int x = i, y = j; + if ("U".equals(direction)) { + --x; + } else if ("D".equals(direction)) { + ++x; + } else if ("L".equals(direction)) { + --y; + } else { + ++y; + } + if (x < 0 || x >= m || y < 0 || y >= n) { + return -1; + } + if (idx < food.length && x == food[idx][0] && y == food[idx][1]) { + ++score; + ++idx; + } else { + int t = q.pollLast(); + vis.remove(t); + } + int cur = f(x, y); + if (vis.contains(cur)) { + return -1; + } + q.offerFirst(cur); + vis.add(cur); + return score; + } + + private int f(int i, int j) { + return i * n + j; + } +} + +/** + * Your SnakeGame object will be instantiated and called as such: + * SnakeGame obj = new SnakeGame(width, height, food); + * int param_1 = obj.move(direction); */ \ No newline at end of file diff --git a/solution/0300-0399/0353.Design Snake Game/Solution.py b/solution/0300-0399/0353.Design Snake Game/Solution.py index 340120e0163a6..e4835abc4fc8f 100644 --- a/solution/0300-0399/0353.Design Snake Game/Solution.py +++ b/solution/0300-0399/0353.Design Snake Game/Solution.py @@ -1,43 +1,43 @@ -class SnakeGame: - def __init__(self, width: int, height: int, food: List[List[int]]): - self.m = height - self.n = width - self.food = food - self.score = 0 - self.idx = 0 - self.q = deque([(0, 0)]) - self.vis = {(0, 0)} - - def move(self, direction: str) -> int: - i, j = self.q[0] - x, y = i, j - match direction: - case "U": - x -= 1 - case "D": - x += 1 - case "L": - y -= 1 - case "R": - y += 1 - if x < 0 or x >= self.m or y < 0 or y >= self.n: - return -1 - if ( - self.idx < len(self.food) - and x == self.food[self.idx][0] - and y == self.food[self.idx][1] - ): - self.score += 1 - self.idx += 1 - else: - self.vis.remove(self.q.pop()) - if (x, y) in self.vis: - return -1 - self.q.appendleft((x, y)) - self.vis.add((x, y)) - return self.score - - -# Your SnakeGame object will be instantiated and called as such: -# obj = SnakeGame(width, height, food) -# param_1 = obj.move(direction) +class SnakeGame: + def __init__(self, width: int, height: int, food: List[List[int]]): + self.m = height + self.n = width + self.food = food + self.score = 0 + self.idx = 0 + self.q = deque([(0, 0)]) + self.vis = {(0, 0)} + + def move(self, direction: str) -> int: + i, j = self.q[0] + x, y = i, j + match direction: + case "U": + x -= 1 + case "D": + x += 1 + case "L": + y -= 1 + case "R": + y += 1 + if x < 0 or x >= self.m or y < 0 or y >= self.n: + return -1 + if ( + self.idx < len(self.food) + and x == self.food[self.idx][0] + and y == self.food[self.idx][1] + ): + self.score += 1 + self.idx += 1 + else: + self.vis.remove(self.q.pop()) + if (x, y) in self.vis: + return -1 + self.q.appendleft((x, y)) + self.vis.add((x, y)) + return self.score + + +# Your SnakeGame object will be instantiated and called as such: +# obj = SnakeGame(width, height, food) +# param_1 = obj.move(direction) diff --git a/solution/0300-0399/0354.Russian Doll Envelopes/Solution.cpp b/solution/0300-0399/0354.Russian Doll Envelopes/Solution.cpp index a1ffeafdad822..8d20f6f11f34f 100644 --- a/solution/0300-0399/0354.Russian Doll Envelopes/Solution.cpp +++ b/solution/0300-0399/0354.Russian Doll Envelopes/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - int maxEnvelopes(vector>& envelopes) { - sort(envelopes.begin(), envelopes.end(), [](const auto& e1, const auto& e2) { - return e1[0] < e2[0] || (e1[0] == e2[0] && e1[1] > e2[1]); - }); - int n = envelopes.size(); - vector d{envelopes[0][1]}; - for (int i = 1; i < n; ++i) { - int x = envelopes[i][1]; - if (x > d[d.size() - 1]) - d.push_back(x); - else { - int idx = lower_bound(d.begin(), d.end(), x) - d.begin(); - if (idx == d.size()) idx = 0; - d[idx] = x; - } - } - return d.size(); - } +class Solution { +public: + int maxEnvelopes(vector>& envelopes) { + sort(envelopes.begin(), envelopes.end(), [](const auto& e1, const auto& e2) { + return e1[0] < e2[0] || (e1[0] == e2[0] && e1[1] > e2[1]); + }); + int n = envelopes.size(); + vector d{envelopes[0][1]}; + for (int i = 1; i < n; ++i) { + int x = envelopes[i][1]; + if (x > d[d.size() - 1]) + d.push_back(x); + else { + int idx = lower_bound(d.begin(), d.end(), x) - d.begin(); + if (idx == d.size()) idx = 0; + d[idx] = x; + } + } + return d.size(); + } }; \ No newline at end of file diff --git a/solution/0300-0399/0354.Russian Doll Envelopes/Solution.java b/solution/0300-0399/0354.Russian Doll Envelopes/Solution.java index 8b20d3e9eb4bd..b0509ab60467f 100644 --- a/solution/0300-0399/0354.Russian Doll Envelopes/Solution.java +++ b/solution/0300-0399/0354.Russian Doll Envelopes/Solution.java @@ -1,28 +1,28 @@ -class Solution { - public int maxEnvelopes(int[][] envelopes) { - Arrays.sort(envelopes, (a, b) -> { return a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]; }); - int n = envelopes.length; - int[] d = new int[n + 1]; - d[1] = envelopes[0][1]; - int size = 1; - for (int i = 1; i < n; ++i) { - int x = envelopes[i][1]; - if (x > d[size]) { - d[++size] = x; - } else { - int left = 1, right = size; - while (left < right) { - int mid = (left + right) >> 1; - if (d[mid] >= x) { - right = mid; - } else { - left = mid + 1; - } - } - int p = d[left] >= x ? left : 1; - d[p] = x; - } - } - return size; - } +class Solution { + public int maxEnvelopes(int[][] envelopes) { + Arrays.sort(envelopes, (a, b) -> { return a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]; }); + int n = envelopes.length; + int[] d = new int[n + 1]; + d[1] = envelopes[0][1]; + int size = 1; + for (int i = 1; i < n; ++i) { + int x = envelopes[i][1]; + if (x > d[size]) { + d[++size] = x; + } else { + int left = 1, right = size; + while (left < right) { + int mid = (left + right) >> 1; + if (d[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } + } + int p = d[left] >= x ? left : 1; + d[p] = x; + } + } + return size; + } } \ No newline at end of file diff --git a/solution/0300-0399/0354.Russian Doll Envelopes/Solution.py b/solution/0300-0399/0354.Russian Doll Envelopes/Solution.py index dbc56161ac09b..14a6b94494677 100644 --- a/solution/0300-0399/0354.Russian Doll Envelopes/Solution.py +++ b/solution/0300-0399/0354.Russian Doll Envelopes/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def maxEnvelopes(self, envelopes: List[List[int]]) -> int: - envelopes.sort(key=lambda x: (x[0], -x[1])) - d = [envelopes[0][1]] - for _, h in envelopes[1:]: - if h > d[-1]: - d.append(h) - else: - idx = bisect_left(d, h) - if idx == len(d): - idx = 0 - d[idx] = h - return len(d) +class Solution: + def maxEnvelopes(self, envelopes: List[List[int]]) -> int: + envelopes.sort(key=lambda x: (x[0], -x[1])) + d = [envelopes[0][1]] + for _, h in envelopes[1:]: + if h > d[-1]: + d.append(h) + else: + idx = bisect_left(d, h) + if idx == len(d): + idx = 0 + d[idx] = h + return len(d) diff --git a/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution.cpp b/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution.cpp index a3bd0498af51e..b0a07584d382c 100644 --- a/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution.cpp +++ b/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution.cpp @@ -1,13 +1,13 @@ -class Solution { -public: - int countNumbersWithUniqueDigits(int n) { - if (n == 0) return 1; - if (n == 1) return 10; - int ans = 10; - for (int i = 0, cur = 9; i < n - 1; ++i) { - cur *= (9 - i); - ans += cur; - } - return ans; - } +class Solution { +public: + int countNumbersWithUniqueDigits(int n) { + if (n == 0) return 1; + if (n == 1) return 10; + int ans = 10; + for (int i = 0, cur = 9; i < n - 1; ++i) { + cur *= (9 - i); + ans += cur; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution.java b/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution.java index e2260f20c229b..ccf5f3e08651c 100644 --- a/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution.java +++ b/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution.java @@ -1,16 +1,16 @@ -class Solution { - public int countNumbersWithUniqueDigits(int n) { - if (n == 0) { - return 1; - } - if (n == 1) { - return 10; - } - int ans = 10; - for (int i = 0, cur = 9; i < n - 1; ++i) { - cur *= (9 - i); - ans += cur; - } - return ans; - } +class Solution { + public int countNumbersWithUniqueDigits(int n) { + if (n == 0) { + return 1; + } + if (n == 1) { + return 10; + } + int ans = 10; + for (int i = 0, cur = 9; i < n - 1; ++i) { + cur *= (9 - i); + ans += cur; + } + return ans; + } } \ No newline at end of file diff --git a/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution.py b/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution.py index 39b6990639724..b2cfdae7f9b28 100644 --- a/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution.py +++ b/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def countNumbersWithUniqueDigits(self, n: int) -> int: - if n == 0: - return 1 - if n == 1: - return 10 - ans, cur = 10, 9 - for i in range(n - 1): - cur *= 9 - i - ans += cur - return ans +class Solution: + def countNumbersWithUniqueDigits(self, n: int) -> int: + if n == 0: + return 1 + if n == 1: + return 10 + ans, cur = 10, 9 + for i in range(n - 1): + cur *= 9 - i + ans += cur + return ans diff --git a/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution2.cpp b/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution2.cpp new file mode 100644 index 0000000000000..1b5eec267f1e1 --- /dev/null +++ b/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution2.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int dp[10][1 << 11]; + + int countNumbersWithUniqueDigits(int n) { + memset(dp, -1, sizeof dp); + return dfs(n, 0, true); + } + + int dfs(int pos, int mask, bool lead) { + if (pos <= 0) { + return 1; + } + if (!lead && dp[pos][mask] != -1) { + return dp[pos][mask]; + } + int ans = 0; + for (int i = 0; i < 10; ++i) { + if ((mask >> i) & 1) continue; + if (i == 0 && lead) { + ans += dfs(pos - 1, mask, lead); + } else { + ans += dfs(pos - 1, mask | 1 << i, false); + } + } + if (!lead) { + dp[pos][mask] = ans; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution2.go b/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution2.go new file mode 100644 index 0000000000000..106797551d9e4 --- /dev/null +++ b/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution2.go @@ -0,0 +1,35 @@ +func countNumbersWithUniqueDigits(n int) int { + dp := make([][]int, 10) + for i := range dp { + dp[i] = make([]int, 1<<11) + for j := range dp[i] { + dp[i][j] = -1 + } + } + var dfs func(int, int, bool) int + dfs = func(pos, mask int, lead bool) int { + if pos <= 0 { + return 1 + } + if !lead && dp[pos][mask] != -1 { + return dp[pos][mask] + } + ans := 0 + for i := 0; i < 10; i++ { + if ((mask >> i) & 1) == 1 { + continue + } + if i == 0 && lead { + ans += dfs(pos-1, mask, lead) + } else { + ans += dfs(pos-1, mask|1<> i) & 1) == 1) { + continue; + } + if (i == 0 && lead) { + ans += dfs(pos - 1, mask, lead); + } else { + ans += dfs(pos - 1, mask | (1 << i), false); + } + } + if (!lead) { + dp[pos][mask] = ans; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution2.py b/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution2.py new file mode 100644 index 0000000000000..3f88638764666 --- /dev/null +++ b/solution/0300-0399/0357.Count Numbers with Unique Digits/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def countNumbersWithUniqueDigits(self, n: int) -> int: + @cache + def dfs(pos, mask, lead): + if pos <= 0: + return 1 + ans = 0 + for i in range(10): + if (mask >> i) & 1: + continue + if i == 0 and lead: + ans += dfs(pos - 1, mask, lead) + else: + ans += dfs(pos - 1, mask | (1 << i), False) + return ans + + return dfs(n, 0, True) diff --git a/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/Solution.cpp b/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/Solution.cpp index d49547816777f..abc7b5ed7b6bc 100644 --- a/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/Solution.cpp +++ b/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/Solution.cpp @@ -1,28 +1,28 @@ -class Solution { -public: - int maxSumSubmatrix(vector>& matrix, int k) { - int m = matrix.size(), n = matrix[0].size(); - const int inf = 1 << 30; - int ans = -inf; - for (int i = 0; i < m; ++i) { - vector nums(n); - for (int j = i; j < m; ++j) { - for (int h = 0; h < n; ++h) { - nums[h] += matrix[j][h]; - } - set ts; - int s = 0; - ts.insert(0); - for (int x : nums) { - s += x; - auto it = ts.lower_bound(s - k); - if (it != ts.end()) { - ans = max(ans, s - *it); - } - ts.insert(s); - } - } - } - return ans; - } +class Solution { +public: + int maxSumSubmatrix(vector>& matrix, int k) { + int m = matrix.size(), n = matrix[0].size(); + const int inf = 1 << 30; + int ans = -inf; + for (int i = 0; i < m; ++i) { + vector nums(n); + for (int j = i; j < m; ++j) { + for (int h = 0; h < n; ++h) { + nums[h] += matrix[j][h]; + } + set ts; + int s = 0; + ts.insert(0); + for (int x : nums) { + s += x; + auto it = ts.lower_bound(s - k); + if (it != ts.end()) { + ans = max(ans, s - *it); + } + ts.insert(s); + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/Solution.java b/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/Solution.java index dfddc1ae6839c..868ebdea23b99 100644 --- a/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/Solution.java +++ b/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/Solution.java @@ -1,28 +1,28 @@ -class Solution { - public int maxSumSubmatrix(int[][] matrix, int k) { - int m = matrix.length; - int n = matrix[0].length; - final int inf = 1 << 30; - int ans = -inf; - for (int i = 0; i < m; ++i) { - int[] nums = new int[n]; - for (int j = i; j < m; ++j) { - for (int h = 0; h < n; ++h) { - nums[h] += matrix[j][h]; - } - int s = 0; - TreeSet ts = new TreeSet<>(); - ts.add(0); - for (int x : nums) { - s += x; - Integer y = ts.ceiling(s - k); - if (y != null) { - ans = Math.max(ans, s - y); - } - ts.add(s); - } - } - } - return ans; - } +class Solution { + public int maxSumSubmatrix(int[][] matrix, int k) { + int m = matrix.length; + int n = matrix[0].length; + final int inf = 1 << 30; + int ans = -inf; + for (int i = 0; i < m; ++i) { + int[] nums = new int[n]; + for (int j = i; j < m; ++j) { + for (int h = 0; h < n; ++h) { + nums[h] += matrix[j][h]; + } + int s = 0; + TreeSet ts = new TreeSet<>(); + ts.add(0); + for (int x : nums) { + s += x; + Integer y = ts.ceiling(s - k); + if (y != null) { + ans = Math.max(ans, s - y); + } + ts.add(s); + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/Solution.py b/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/Solution.py index ad66ae0b668a2..9e8e82b985567 100644 --- a/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/Solution.py +++ b/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/Solution.py @@ -1,21 +1,21 @@ -from sortedcontainers import SortedSet - - -class Solution: - def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int: - m, n = len(matrix), len(matrix[0]) - ans = -inf - for i in range(m): - nums = [0] * n - for j in range(i, m): - for h in range(n): - nums[h] += matrix[j][h] - s = 0 - ts = SortedSet([0]) - for x in nums: - s += x - p = ts.bisect_left(s - k) - if p != len(ts): - ans = max(ans, s - ts[p]) - ts.add(s) - return ans +from sortedcontainers import SortedSet + + +class Solution: + def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int: + m, n = len(matrix), len(matrix[0]) + ans = -inf + for i in range(m): + nums = [0] * n + for j in range(i, m): + for h in range(n): + nums[h] += matrix[j][h] + s = 0 + ts = SortedSet([0]) + for x in nums: + s += x + p = ts.bisect_left(s - k) + if p != len(ts): + ans = max(ans, s - ts[p]) + ts.add(s) + return ans diff --git a/solution/0300-0399/0365.Water and Jug Problem/Solution.java b/solution/0300-0399/0365.Water and Jug Problem/Solution.java index 189439e92e90e..fbcd88fd2ef52 100644 --- a/solution/0300-0399/0365.Water and Jug Problem/Solution.java +++ b/solution/0300-0399/0365.Water and Jug Problem/Solution.java @@ -1,15 +1,38 @@ class Solution { public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) { - if (jug1Capacity + jug2Capacity < targetCapacity) { - return false; + Deque stk = new ArrayDeque<>(); + stk.add(new int[] {0, 0}); + Set seen = new HashSet<>(); + while (!stk.isEmpty()) { + if (seen.contains(hash(stk.peek()))) { + stk.pop(); + continue; + } + int[] cur = stk.pop(); + seen.add(hash(cur)); + int cur1 = cur[0], cur2 = cur[1]; + if (cur1 == targetCapacity || cur2 == targetCapacity || cur1 + cur2 == targetCapacity) { + return true; + } + stk.offer(new int[] {jug1Capacity, cur2}); + stk.offer(new int[] {0, cur2}); + stk.offer(new int[] {cur1, jug1Capacity}); + stk.offer(new int[] {cur2, 0}); + if (cur1 + cur2 > jug1Capacity) { + stk.offer(new int[] {jug1Capacity, cur2 - jug1Capacity + cur1}); + } else { + stk.offer(new int[] {cur1 + cur2, 0}); + } + if (cur1 + cur2 > jug2Capacity) { + stk.offer(new int[] {cur1 - jug2Capacity + cur2, jug2Capacity}); + } else { + stk.offer(new int[] {0, cur1 + cur2}); + } } - if (jug1Capacity == 0 || jug2Capacity == 0) { - return targetCapacity == 0 || jug1Capacity + jug2Capacity == targetCapacity; - } - return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0; + return false; } - private int gcd(int a, int b) { - return b == 0 ? a : gcd(b, a % b); + public long hash(int[] nums) { + return nums[0] * 10000006L + nums[1]; } } \ No newline at end of file diff --git a/solution/0300-0399/0365.Water and Jug Problem/Solution.py b/solution/0300-0399/0365.Water and Jug Problem/Solution.py index 5e03008894b9a..beb4cc9fb8d6f 100644 --- a/solution/0300-0399/0365.Water and Jug Problem/Solution.py +++ b/solution/0300-0399/0365.Water and Jug Problem/Solution.py @@ -2,8 +2,35 @@ class Solution: def canMeasureWater( self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int ) -> bool: - if jug1Capacity + jug2Capacity < targetCapacity: - return False - if jug1Capacity == 0 or jug2Capacity == 0: - return targetCapacity == 0 or jug1Capacity + jug2Capacity == targetCapacity - return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0 + stk, seen = [], set() + stk.append([0, 0]) + + def get_hash(nums): + return nums[0] * 10000006 + nums[1] + + while stk: + if get_hash(stk[-1]) in seen: + stk.pop() + continue + seen.add(get_hash(stk[-1])) + cur = stk.pop() + cur1, cur2 = cur[0], cur[1] + if ( + cur1 == targetCapacity + or cur2 == targetCapacity + or cur1 + cur2 == targetCapacity + ): + return True + stk.append([jug1Capacity, cur2]) + stk.append([0, cur2]) + stk.append([cur1, jug2Capacity]) + stk.append([cur1, 0]) + if cur1 + cur2 > jug1Capacity: + stk.append([jug1Capacity, cur2 - jug1Capacity + cur1]) + else: + stk.append([cur1 + cur2, 0]) + if cur1 + cur2 > jug2Capacity: + stk.append([cur1 - jug2Capacity + cur2, jug2Capacity]) + else: + stk.append([0, cur1 + cur2]) + return False diff --git a/solution/0300-0399/0365.Water and Jug Problem/Solution2.java b/solution/0300-0399/0365.Water and Jug Problem/Solution2.java new file mode 100644 index 0000000000000..189439e92e90e --- /dev/null +++ b/solution/0300-0399/0365.Water and Jug Problem/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) { + if (jug1Capacity + jug2Capacity < targetCapacity) { + return false; + } + if (jug1Capacity == 0 || jug2Capacity == 0) { + return targetCapacity == 0 || jug1Capacity + jug2Capacity == targetCapacity; + } + return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} \ No newline at end of file diff --git a/solution/0300-0399/0365.Water and Jug Problem/Solution2.py b/solution/0300-0399/0365.Water and Jug Problem/Solution2.py new file mode 100644 index 0000000000000..5e03008894b9a --- /dev/null +++ b/solution/0300-0399/0365.Water and Jug Problem/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def canMeasureWater( + self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int + ) -> bool: + if jug1Capacity + jug2Capacity < targetCapacity: + return False + if jug1Capacity == 0 or jug2Capacity == 0: + return targetCapacity == 0 or jug1Capacity + jug2Capacity == targetCapacity + return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0 diff --git a/solution/0300-0399/0367.Valid Perfect Square/Solution2.cpp b/solution/0300-0399/0367.Valid Perfect Square/Solution2.cpp new file mode 100644 index 0000000000000..da03061abc243 --- /dev/null +++ b/solution/0300-0399/0367.Valid Perfect Square/Solution2.cpp @@ -0,0 +1,7 @@ +class Solution { +public: + bool isPerfectSquare(int num) { + for (int i = 1; num > 0; i += 2) num -= i; + return num == 0; + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0367.Valid Perfect Square/Solution2.go b/solution/0300-0399/0367.Valid Perfect Square/Solution2.go new file mode 100644 index 0000000000000..c4d755f0f06ad --- /dev/null +++ b/solution/0300-0399/0367.Valid Perfect Square/Solution2.go @@ -0,0 +1,6 @@ +func isPerfectSquare(num int) bool { + for i := 1; num > 0; i += 2 { + num -= i + } + return num == 0 +} \ No newline at end of file diff --git a/solution/0300-0399/0367.Valid Perfect Square/Solution2.java b/solution/0300-0399/0367.Valid Perfect Square/Solution2.java new file mode 100644 index 0000000000000..3e2f0fdc483fa --- /dev/null +++ b/solution/0300-0399/0367.Valid Perfect Square/Solution2.java @@ -0,0 +1,8 @@ +class Solution { + public boolean isPerfectSquare(int num) { + for (int i = 1; num > 0; i += 2) { + num -= i; + } + return num == 0; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0367.Valid Perfect Square/Solution2.py b/solution/0300-0399/0367.Valid Perfect Square/Solution2.py new file mode 100644 index 0000000000000..b0c41e6d996e8 --- /dev/null +++ b/solution/0300-0399/0367.Valid Perfect Square/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def isPerfectSquare(self, num: int) -> bool: + i = 1 + while num > 0: + num -= i + i += 2 + return num == 0 diff --git a/solution/0300-0399/0367.Valid Perfect Square/Solution2.rs b/solution/0300-0399/0367.Valid Perfect Square/Solution2.rs new file mode 100644 index 0000000000000..b36380213a351 --- /dev/null +++ b/solution/0300-0399/0367.Valid Perfect Square/Solution2.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn is_perfect_square(mut num: i32) -> bool { + let mut i = 1; + while num > 0 { + num -= i; + i += 2; + } + num == 0 + } +} diff --git a/solution/0300-0399/0367.Valid Perfect Square/Solution2.ts b/solution/0300-0399/0367.Valid Perfect Square/Solution2.ts new file mode 100644 index 0000000000000..0921161ec544f --- /dev/null +++ b/solution/0300-0399/0367.Valid Perfect Square/Solution2.ts @@ -0,0 +1,8 @@ +function isPerfectSquare(num: number): boolean { + let i = 1; + while (num > 0) { + num -= i; + i += 2; + } + return num === 0; +} diff --git a/solution/0300-0399/0370.Range Addition/Solution2.cpp b/solution/0300-0399/0370.Range Addition/Solution2.cpp new file mode 100644 index 0000000000000..4e661b4191c48 --- /dev/null +++ b/solution/0300-0399/0370.Range Addition/Solution2.cpp @@ -0,0 +1,44 @@ +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + int lowbit(int x) { + return x & -x; + } +}; + +class Solution { +public: + vector getModifiedArray(int length, vector>& updates) { + BinaryIndexedTree* tree = new BinaryIndexedTree(length); + for (auto& e : updates) { + int start = e[0], end = e[1], inc = e[2]; + tree->update(start + 1, inc); + tree->update(end + 2, -inc); + } + vector ans; + for (int i = 0; i < length; ++i) ans.push_back(tree->query(i + 1)); + return ans; + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0370.Range Addition/Solution2.go b/solution/0300-0399/0370.Range Addition/Solution2.go new file mode 100644 index 0000000000000..d5b3877030f7c --- /dev/null +++ b/solution/0300-0399/0370.Range Addition/Solution2.go @@ -0,0 +1,43 @@ +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) lowbit(x int) int { + return x & -x +} + +func (this *BinaryIndexedTree) update(x, delta int) { + for x <= this.n { + this.c[x] += delta + x += this.lowbit(x) + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= this.lowbit(x) + } + return s +} + +func getModifiedArray(length int, updates [][]int) []int { + tree := newBinaryIndexedTree(length) + for _, e := range updates { + start, end, inc := e[0], e[1], e[2] + tree.update(start+1, inc) + tree.update(end+2, -inc) + } + ans := make([]int, length) + for i := range ans { + ans[i] = tree.query(i + 1) + } + return ans +} \ No newline at end of file diff --git a/solution/0300-0399/0370.Range Addition/Solution2.java b/solution/0300-0399/0370.Range Addition/Solution2.java new file mode 100644 index 0000000000000..a7c3194be1fca --- /dev/null +++ b/solution/0300-0399/0370.Range Addition/Solution2.java @@ -0,0 +1,45 @@ +class Solution { + public int[] getModifiedArray(int length, int[][] updates) { + BinaryIndexedTree tree = new BinaryIndexedTree(length); + for (int[] e : updates) { + int start = e[0], end = e[1], inc = e[2]; + tree.update(start + 1, inc); + tree.update(end + 2, -inc); + } + int[] ans = new int[length]; + for (int i = 0; i < length; ++i) { + ans[i] = tree.query(i + 1); + } + return ans; + } +} + +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + public static int lowbit(int x) { + return x & -x; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0370.Range Addition/Solution2.py b/solution/0300-0399/0370.Range Addition/Solution2.py new file mode 100644 index 0000000000000..ffdd09fd6c50f --- /dev/null +++ b/solution/0300-0399/0370.Range Addition/Solution2.py @@ -0,0 +1,29 @@ +class BinaryIndexedTree: + def __init__(self, n): + self.n = n + self.c = [0] * (n + 1) + + @staticmethod + def lowbit(x): + return x & -x + + def update(self, x, delta): + while x <= self.n: + self.c[x] += delta + x += BinaryIndexedTree.lowbit(x) + + def query(self, x): + s = 0 + while x: + s += self.c[x] + x -= BinaryIndexedTree.lowbit(x) + return s + + +class Solution: + def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]: + tree = BinaryIndexedTree(length) + for start, end, inc in updates: + tree.update(start + 1, inc) + tree.update(end + 2, -inc) + return [tree.query(i + 1) for i in range(length)] diff --git a/solution/0300-0399/0372.Super Pow/Solution.cpp b/solution/0300-0399/0372.Super Pow/Solution.cpp index ff242a6524369..60d58ccfe9b32 100644 --- a/solution/0300-0399/0372.Super Pow/Solution.cpp +++ b/solution/0300-0399/0372.Super Pow/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - int superPow(int a, vector& b) { - using ll = long long; - const int mod = 1337; - ll ans = 1; - auto qpow = [&](ll a, int n) { - ll ans = 1; - for (; n; n >>= 1) { - if (n & 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return (int) ans; - }; - for (int i = b.size() - 1; ~i; --i) { - ans = ans * qpow(a, b[i]) % mod; - a = qpow(a, 10); - } - return ans; - } +class Solution { +public: + int superPow(int a, vector& b) { + using ll = long long; + const int mod = 1337; + ll ans = 1; + auto qpow = [&](ll a, int n) { + ll ans = 1; + for (; n; n >>= 1) { + if (n & 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return (int) ans; + }; + for (int i = b.size() - 1; ~i; --i) { + ans = ans * qpow(a, b[i]) % mod; + a = qpow(a, 10); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0300-0399/0372.Super Pow/Solution.java b/solution/0300-0399/0372.Super Pow/Solution.java index f60e79df11487..15433d914173b 100644 --- a/solution/0300-0399/0372.Super Pow/Solution.java +++ b/solution/0300-0399/0372.Super Pow/Solution.java @@ -1,23 +1,23 @@ -class Solution { - private final int mod = 1337; - - public int superPow(int a, int[] b) { - long ans = 1; - for (int i = b.length - 1; i >= 0; --i) { - ans = ans * qpow(a, b[i]) % mod; - a = qpow(a, 10); - } - return (int) ans; - } - - private long qpow(long a, int n) { - long ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return ans; - } +class Solution { + private final int mod = 1337; + + public int superPow(int a, int[] b) { + long ans = 1; + for (int i = b.length - 1; i >= 0; --i) { + ans = ans * qpow(a, b[i]) % mod; + a = qpow(a, 10); + } + return (int) ans; + } + + private long qpow(long a, int n) { + long ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return ans; + } } \ No newline at end of file diff --git a/solution/0300-0399/0372.Super Pow/Solution.py b/solution/0300-0399/0372.Super Pow/Solution.py index 60817aa149048..d26d967688302 100644 --- a/solution/0300-0399/0372.Super Pow/Solution.py +++ b/solution/0300-0399/0372.Super Pow/Solution.py @@ -1,8 +1,8 @@ -class Solution: - def superPow(self, a: int, b: List[int]) -> int: - mod = 1337 - ans = 1 - for e in b[::-1]: - ans = ans * pow(a, e, mod) % mod - a = pow(a, 10, mod) - return ans +class Solution: + def superPow(self, a: int, b: List[int]) -> int: + mod = 1337 + ans = 1 + for e in b[::-1]: + ans = ans * pow(a, e, mod) % mod + a = pow(a, 10, mod) + return ans diff --git a/solution/0300-0399/0374.Guess Number Higher or Lower/Solution.cs b/solution/0300-0399/0374.Guess Number Higher or Lower/Solution.cs index 0b9b2001403d6..b923260c8cf3e 100644 --- a/solution/0300-0399/0374.Guess Number Higher or Lower/Solution.cs +++ b/solution/0300-0399/0374.Guess Number Higher or Lower/Solution.cs @@ -1,4 +1,4 @@ -/** +/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number @@ -20,4 +20,4 @@ public int GuessNumber(int n) { } return left; } -} \ No newline at end of file +} diff --git a/solution/0300-0399/0374.Guess Number Higher or Lower/Solution.go b/solution/0300-0399/0374.Guess Number Higher or Lower/Solution.go index 8b26fb475b79b..cd74f3d51626a 100644 --- a/solution/0300-0399/0374.Guess Number Higher or Lower/Solution.go +++ b/solution/0300-0399/0374.Guess Number Higher or Lower/Solution.go @@ -1,15 +1,21 @@ /** * Forward declaration of guess API. * @param num your guess - * @return -1 if num is higher than the picked number - * 1 if num is lower than the picked number + * @return -1 if num is lower than the guess number + * 1 if num is higher than the guess number * otherwise return 0 * func guess(num int) int; */ func guessNumber(n int) int { - return sort.Search(n, func(i int) bool { - i++ - return guess(i) <= 0 - }) + 1 + left, right := 1, n + for left < right { + mid := (left + right) >> 1 + if guess(mid) <= 0 { + right = mid + } else { + left = mid + 1 + } + } + return left } \ No newline at end of file diff --git a/solution/0300-0399/0374.Guess Number Higher or Lower/Solution.py b/solution/0300-0399/0374.Guess Number Higher or Lower/Solution.py index 944c89c9f4e22..3ec7dfc825b46 100644 --- a/solution/0300-0399/0374.Guess Number Higher or Lower/Solution.py +++ b/solution/0300-0399/0374.Guess Number Higher or Lower/Solution.py @@ -1,11 +1,16 @@ # The guess API is already defined for you. # @param num, your guess -# @return -1 if num is higher than the picked number -# 1 if num is lower than the picked number -# otherwise return 0 +# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num: int) -> int: class Solution: def guessNumber(self, n: int) -> int: - return bisect.bisect(range(1, n + 1), 0, key=lambda x: -guess(x)) + left, right = 1, n + while left < right: + mid = (left + right) >> 1 + if guess(mid) <= 0: + right = mid + else: + left = mid + 1 + return left diff --git a/solution/0300-0399/0374.Guess Number Higher or Lower/Solution2.go b/solution/0300-0399/0374.Guess Number Higher or Lower/Solution2.go new file mode 100644 index 0000000000000..8b26fb475b79b --- /dev/null +++ b/solution/0300-0399/0374.Guess Number Higher or Lower/Solution2.go @@ -0,0 +1,15 @@ +/** + * Forward declaration of guess API. + * @param num your guess + * @return -1 if num is higher than the picked number + * 1 if num is lower than the picked number + * otherwise return 0 + * func guess(num int) int; + */ + +func guessNumber(n int) int { + return sort.Search(n, func(i int) bool { + i++ + return guess(i) <= 0 + }) + 1 +} \ No newline at end of file diff --git a/solution/0300-0399/0374.Guess Number Higher or Lower/Solution2.py b/solution/0300-0399/0374.Guess Number Higher or Lower/Solution2.py new file mode 100644 index 0000000000000..944c89c9f4e22 --- /dev/null +++ b/solution/0300-0399/0374.Guess Number Higher or Lower/Solution2.py @@ -0,0 +1,11 @@ +# The guess API is already defined for you. +# @param num, your guess +# @return -1 if num is higher than the picked number +# 1 if num is lower than the picked number +# otherwise return 0 +# def guess(num: int) -> int: + + +class Solution: + def guessNumber(self, n: int) -> int: + return bisect.bisect(range(1, n + 1), 0, key=lambda x: -guess(x)) diff --git a/solution/0300-0399/0377.Combination Sum IV/Solution.cs b/solution/0300-0399/0377.Combination Sum IV/Solution.cs index f0167a9baa43d..2bd7a2af28fc4 100644 --- a/solution/0300-0399/0377.Combination Sum IV/Solution.cs +++ b/solution/0300-0399/0377.Combination Sum IV/Solution.cs @@ -11,4 +11,4 @@ public int CombinationSum4(int[] nums, int target) { } return f[target]; } -} \ No newline at end of file +} diff --git a/solution/0300-0399/0380.Insert Delete GetRandom O(1)/Solution.cpp b/solution/0300-0399/0380.Insert Delete GetRandom O(1)/Solution.cpp index 00e2447f48338..1274394a5f392 100644 --- a/solution/0300-0399/0380.Insert Delete GetRandom O(1)/Solution.cpp +++ b/solution/0300-0399/0380.Insert Delete GetRandom O(1)/Solution.cpp @@ -1,42 +1,42 @@ -class RandomizedSet { -public: - RandomizedSet() { - } - - bool insert(int val) { - if (d.count(val)) { - return false; - } - d[val] = q.size(); - q.push_back(val); - return true; - } - - bool remove(int val) { - if (!d.count(val)) { - return false; - } - int i = d[val]; - d[q.back()] = i; - q[i] = q.back(); - q.pop_back(); - d.erase(val); - return true; - } - - int getRandom() { - return q[rand() % q.size()]; - } - -private: - unordered_map d; - vector q; -}; - -/** - * Your RandomizedSet object will be instantiated and called as such: - * RandomizedSet* obj = new RandomizedSet(); - * bool param_1 = obj->insert(val); - * bool param_2 = obj->remove(val); - * int param_3 = obj->getRandom(); +class RandomizedSet { +public: + RandomizedSet() { + } + + bool insert(int val) { + if (d.count(val)) { + return false; + } + d[val] = q.size(); + q.push_back(val); + return true; + } + + bool remove(int val) { + if (!d.count(val)) { + return false; + } + int i = d[val]; + d[q.back()] = i; + q[i] = q.back(); + q.pop_back(); + d.erase(val); + return true; + } + + int getRandom() { + return q[rand() % q.size()]; + } + +private: + unordered_map d; + vector q; +}; + +/** + * Your RandomizedSet object will be instantiated and called as such: + * RandomizedSet* obj = new RandomizedSet(); + * bool param_1 = obj->insert(val); + * bool param_2 = obj->remove(val); + * int param_3 = obj->getRandom(); */ \ No newline at end of file diff --git a/solution/0300-0399/0380.Insert Delete GetRandom O(1)/Solution.cs b/solution/0300-0399/0380.Insert Delete GetRandom O(1)/Solution.cs index 32f3b59e30eef..27db9ad285683 100644 --- a/solution/0300-0399/0380.Insert Delete GetRandom O(1)/Solution.cs +++ b/solution/0300-0399/0380.Insert Delete GetRandom O(1)/Solution.cs @@ -5,7 +5,7 @@ public class RandomizedSet { public RandomizedSet() { } - + public bool Insert(int val) { if (d.ContainsKey(val)) { return false; @@ -14,7 +14,7 @@ public bool Insert(int val) { q.Add(val); return true; } - + public bool Remove(int val) { if (!d.ContainsKey(val)) { return false; @@ -26,7 +26,7 @@ public bool Remove(int val) { d.Remove(val); return true; } - + public int GetRandom() { return q[new Random().Next(0, q.Count)]; } @@ -38,4 +38,4 @@ public int GetRandom() { * bool param_1 = obj.Insert(val); * bool param_2 = obj.Remove(val); * int param_3 = obj.GetRandom(); - */ \ No newline at end of file + */ diff --git a/solution/0300-0399/0380.Insert Delete GetRandom O(1)/Solution.java b/solution/0300-0399/0380.Insert Delete GetRandom O(1)/Solution.java index 5ac01b4c6805c..46b263d80632a 100644 --- a/solution/0300-0399/0380.Insert Delete GetRandom O(1)/Solution.java +++ b/solution/0300-0399/0380.Insert Delete GetRandom O(1)/Solution.java @@ -1,41 +1,41 @@ -class RandomizedSet { - private Map d = new HashMap<>(); - private List q = new ArrayList<>(); - private Random rnd = new Random(); - - public RandomizedSet() { - } - - public boolean insert(int val) { - if (d.containsKey(val)) { - return false; - } - d.put(val, q.size()); - q.add(val); - return true; - } - - public boolean remove(int val) { - if (!d.containsKey(val)) { - return false; - } - int i = d.get(val); - d.put(q.get(q.size() - 1), i); - q.set(i, q.get(q.size() - 1)); - q.remove(q.size() - 1); - d.remove(val); - return true; - } - - public int getRandom() { - return q.get(rnd.nextInt(q.size())); - } -} - -/** - * Your RandomizedSet object will be instantiated and called as such: - * RandomizedSet obj = new RandomizedSet(); - * boolean param_1 = obj.insert(val); - * boolean param_2 = obj.remove(val); - * int param_3 = obj.getRandom(); +class RandomizedSet { + private Map d = new HashMap<>(); + private List q = new ArrayList<>(); + private Random rnd = new Random(); + + public RandomizedSet() { + } + + public boolean insert(int val) { + if (d.containsKey(val)) { + return false; + } + d.put(val, q.size()); + q.add(val); + return true; + } + + public boolean remove(int val) { + if (!d.containsKey(val)) { + return false; + } + int i = d.get(val); + d.put(q.get(q.size() - 1), i); + q.set(i, q.get(q.size() - 1)); + q.remove(q.size() - 1); + d.remove(val); + return true; + } + + public int getRandom() { + return q.get(rnd.nextInt(q.size())); + } +} + +/** + * Your RandomizedSet object will be instantiated and called as such: + * RandomizedSet obj = new RandomizedSet(); + * boolean param_1 = obj.insert(val); + * boolean param_2 = obj.remove(val); + * int param_3 = obj.getRandom(); */ \ No newline at end of file diff --git a/solution/0300-0399/0380.Insert Delete GetRandom O(1)/Solution.py b/solution/0300-0399/0380.Insert Delete GetRandom O(1)/Solution.py index 340c04c391876..6550326c28829 100644 --- a/solution/0300-0399/0380.Insert Delete GetRandom O(1)/Solution.py +++ b/solution/0300-0399/0380.Insert Delete GetRandom O(1)/Solution.py @@ -1,31 +1,31 @@ -class RandomizedSet: - def __init__(self): - self.d = {} - self.q = [] - - def insert(self, val: int) -> bool: - if val in self.d: - return False - self.d[val] = len(self.q) - self.q.append(val) - return True - - def remove(self, val: int) -> bool: - if val not in self.d: - return False - i = self.d[val] - self.d[self.q[-1]] = i - self.q[i] = self.q[-1] - self.q.pop() - self.d.pop(val) - return True - - def getRandom(self) -> int: - return choice(self.q) - - -# Your RandomizedSet object will be instantiated and called as such: -# obj = RandomizedSet() -# param_1 = obj.insert(val) -# param_2 = obj.remove(val) -# param_3 = obj.getRandom() +class RandomizedSet: + def __init__(self): + self.d = {} + self.q = [] + + def insert(self, val: int) -> bool: + if val in self.d: + return False + self.d[val] = len(self.q) + self.q.append(val) + return True + + def remove(self, val: int) -> bool: + if val not in self.d: + return False + i = self.d[val] + self.d[self.q[-1]] = i + self.q[i] = self.q[-1] + self.q.pop() + self.d.pop(val) + return True + + def getRandom(self) -> int: + return choice(self.q) + + +# Your RandomizedSet object will be instantiated and called as such: +# obj = RandomizedSet() +# param_1 = obj.insert(val) +# param_2 = obj.remove(val) +# param_3 = obj.getRandom() diff --git a/solution/0300-0399/0383.Ransom Note/Solution.cs b/solution/0300-0399/0383.Ransom Note/Solution.cs index 4736ef1e7d8f9..257d386b0d165 100644 --- a/solution/0300-0399/0383.Ransom Note/Solution.cs +++ b/solution/0300-0399/0383.Ransom Note/Solution.cs @@ -11,4 +11,4 @@ public bool CanConstruct(string ransomNote, string magazine) { } return true; } -} \ No newline at end of file +} diff --git a/solution/0300-0399/0383.Ransom Note/Solution.php b/solution/0300-0399/0383.Ransom Note/Solution.php index c3cc280db9ce3..44f20f1088a90 100644 --- a/solution/0300-0399/0383.Ransom Note/Solution.php +++ b/solution/0300-0399/0383.Ransom Note/Solution.php @@ -18,4 +18,4 @@ function canConstruct($ransomNote, $magazine) { } return true; } -} \ No newline at end of file +} diff --git a/solution/0300-0399/0385.Mini Parser/Solution.cpp b/solution/0300-0399/0385.Mini Parser/Solution.cpp index 8a3505a9b4472..3f6362493c4d8 100644 --- a/solution/0300-0399/0385.Mini Parser/Solution.cpp +++ b/solution/0300-0399/0385.Mini Parser/Solution.cpp @@ -1,64 +1,53 @@ -/** - * // This is the interface that allows for creating nested lists. - * // You should not implement it, or speculate about its implementation - * class NestedInteger { - * public: - * // Constructor initializes an empty nested list. - * NestedInteger(); - * - * // Constructor initializes a single integer. - * NestedInteger(int value); - * - * // Return true if this NestedInteger holds a single integer, rather than a nested list. - * bool isInteger() const; - * - * // Return the single integer that this NestedInteger holds, if it holds a single integer - * // The result is undefined if this NestedInteger holds a nested list - * int getInteger() const; - * - * // Set this NestedInteger to hold a single integer. - * void setInteger(int value); - * - * // Set this NestedInteger to hold a nested list and adds a nested integer to it. - * void add(const NestedInteger &ni); - * - * // Return the nested list that this NestedInteger holds, if it holds a nested list - * // The result is undefined if this NestedInteger holds a single integer - * const vector &getList() const; - * }; - */ -class Solution { -public: - NestedInteger deserialize(string s) { - if (s[0] != '[') { - return NestedInteger(stoi(s)); - } - stack stk; - int x = 0; - bool neg = false; - for (int i = 0; i < s.size(); ++i) { - if (s[i] == '-') { - neg = true; - } else if (isdigit(s[i])) { - x = x * 10 + s[i] - '0'; - } else if (s[i] == '[') { - stk.push(NestedInteger()); - } else if (s[i] == ',' || s[i] == ']') { - if (isdigit(s[i - 1])) { - if (neg) { - x = -x; - } - stk.top().add(NestedInteger(x)); - } - x = 0; - neg = false; - if (s[i] == ']' && stk.size() > 1) { - auto t = stk.top(); - stk.pop(); - stk.top().add(t); - } - } - } - return stk.top(); - } +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * class NestedInteger { + * public: + * // Constructor initializes an empty nested list. + * NestedInteger(); + * + * // Constructor initializes a single integer. + * NestedInteger(int value); + * + * // Return true if this NestedInteger holds a single integer, rather than a nested list. + * bool isInteger() const; + * + * // Return the single integer that this NestedInteger holds, if it holds a single integer + * // The result is undefined if this NestedInteger holds a nested list + * int getInteger() const; + * + * // Set this NestedInteger to hold a single integer. + * void setInteger(int value); + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * void add(const NestedInteger &ni); + * + * // Return the nested list that this NestedInteger holds, if it holds a nested list + * // The result is undefined if this NestedInteger holds a single integer + * const vector &getList() const; + * }; + */ +class Solution { +public: + NestedInteger deserialize(string s) { + if (s == "" || s == "[]") { + return NestedInteger(); + } + if (s[0] != '[') { + return NestedInteger(stoi(s)); + } + NestedInteger ans; + int depth = 0; + for (int i = 1, j = 1; i < s.size(); ++i) { + if (depth == 0 && (s[i] == ',' || i == s.size() - 1)) { + ans.add(deserialize(s.substr(j, i - j))); + j = i + 1; + } else if (s[i] == '[') { + ++depth; + } else if (s[i] == ']') { + --depth; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0300-0399/0385.Mini Parser/Solution.go b/solution/0300-0399/0385.Mini Parser/Solution.go index 0862e8c125c0e..e934a63e91b19 100644 --- a/solution/0300-0399/0385.Mini Parser/Solution.go +++ b/solution/0300-0399/0385.Mini Parser/Solution.go @@ -24,39 +24,25 @@ * func (n NestedInteger) GetList() []*NestedInteger {} */ func deserialize(s string) *NestedInteger { + ans := &NestedInteger{} + if s == "" || s == "[]" { + return ans + } if s[0] != '[' { v, _ := strconv.Atoi(s) - ans := NestedInteger{} ans.SetInteger(v) - return &ans + return ans } - stk := []*NestedInteger{} - x := 0 - neg := false - for i, c := range s { - if c == '-' { - neg = true - } else if c >= '0' && c <= '9' { - x = x*10 + int(c-'0') - } else if c == '[' { - stk = append(stk, &NestedInteger{}) - } else if c == ',' || c == ']' { - if s[i-1] >= '0' && s[i-1] <= '9' { - if neg { - x = -x - } - t := NestedInteger{} - t.SetInteger(x) - stk[len(stk)-1].Add(t) - } - x = 0 - neg = false - if c == ']' && len(stk) > 1 { - t := stk[len(stk)-1] - stk = stk[:len(stk)-1] - stk[len(stk)-1].Add(*t) - } + depth := 0 + for i, j := 1, 1; i < len(s); i++ { + if depth == 0 && (s[i] == ',' || i == len(s)-1) { + (*ans).Add(*deserialize(s[j:i])) + j = i + 1 + } else if s[i] == '[' { + depth++ + } else if s[i] == ']' { + depth-- } } - return stk[0] + return ans } \ No newline at end of file diff --git a/solution/0300-0399/0385.Mini Parser/Solution.java b/solution/0300-0399/0385.Mini Parser/Solution.java index 70666380f277c..dbda99a9ced11 100644 --- a/solution/0300-0399/0385.Mini Parser/Solution.java +++ b/solution/0300-0399/0385.Mini Parser/Solution.java @@ -1,62 +1,51 @@ -/** - * // This is the interface that allows for creating nested lists. - * // You should not implement it, or speculate about its implementation - * public interface NestedInteger { - * // Constructor initializes an empty nested list. - * public NestedInteger(); - * - * // Constructor initializes a single integer. - * public NestedInteger(int value); - * - * // @return true if this NestedInteger holds a single integer, rather than a nested list. - * public boolean isInteger(); - * - * // @return the single integer that this NestedInteger holds, if it holds a single integer - * // Return null if this NestedInteger holds a nested list - * public Integer getInteger(); - * - * // Set this NestedInteger to hold a single integer. - * public void setInteger(int value); - * - * // Set this NestedInteger to hold a nested list and adds a nested integer to it. - * public void add(NestedInteger ni); - * - * // @return the nested list that this NestedInteger holds, if it holds a nested list - * // Return empty list if this NestedInteger holds a single integer - * public List getList(); - * } - */ -class Solution { - public NestedInteger deserialize(String s) { - if (s.charAt(0) != '[') { - return new NestedInteger(Integer.parseInt(s)); - } - Deque stk = new ArrayDeque<>(); - int x = 0; - boolean neg = false; - for (int i = 0; i < s.length(); ++i) { - char c = s.charAt(i); - if (c == '-') { - neg = true; - } else if (Character.isDigit(c)) { - x = x * 10 + c - '0'; - } else if (c == '[') { - stk.push(new NestedInteger()); - } else if (c == ',' || c == ']') { - if (Character.isDigit(s.charAt(i - 1))) { - if (neg) { - x = -x; - } - stk.peek().add(new NestedInteger(x)); - } - x = 0; - neg = false; - if (c == ']' && stk.size() > 1) { - NestedInteger t = stk.pop(); - stk.peek().add(t); - } - } - } - return stk.peek(); - } +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * public interface NestedInteger { + * // Constructor initializes an empty nested list. + * public NestedInteger(); + * + * // Constructor initializes a single integer. + * public NestedInteger(int value); + * + * // @return true if this NestedInteger holds a single integer, rather than a nested list. + * public boolean isInteger(); + * + * // @return the single integer that this NestedInteger holds, if it holds a single integer + * // Return null if this NestedInteger holds a nested list + * public Integer getInteger(); + * + * // Set this NestedInteger to hold a single integer. + * public void setInteger(int value); + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * public void add(NestedInteger ni); + * + * // @return the nested list that this NestedInteger holds, if it holds a nested list + * // Return empty list if this NestedInteger holds a single integer + * public List getList(); + * } + */ +class Solution { + public NestedInteger deserialize(String s) { + if ("".equals(s) || "[]".equals(s)) { + return new NestedInteger(); + } + if (s.charAt(0) != '[') { + return new NestedInteger(Integer.parseInt(s)); + } + NestedInteger ans = new NestedInteger(); + int depth = 0; + for (int i = 1, j = 1; i < s.length(); ++i) { + if (depth == 0 && (s.charAt(i) == ',' || i == s.length() - 1)) { + ans.add(deserialize(s.substring(j, i))); + j = i + 1; + } else if (s.charAt(i) == '[') { + ++depth; + } else if (s.charAt(i) == ']') { + --depth; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0300-0399/0385.Mini Parser/Solution.py b/solution/0300-0399/0385.Mini Parser/Solution.py index 11e33cc658b1d..d4c28894f1875 100644 --- a/solution/0300-0399/0385.Mini Parser/Solution.py +++ b/solution/0300-0399/0385.Mini Parser/Solution.py @@ -1,64 +1,59 @@ -# """ -# This is the interface that allows for creating nested lists. -# You should not implement it, or speculate about its implementation -# """ -# class NestedInteger: -# def __init__(self, value=None): -# """ -# If value is not specified, initializes an empty list. -# Otherwise initializes a single integer equal to value. -# """ -# -# def isInteger(self): -# """ -# @return True if this NestedInteger holds a single integer, rather than a nested list. -# :rtype bool -# """ -# -# def add(self, elem): -# """ -# Set this NestedInteger to hold a nested list and adds a nested integer elem to it. -# :rtype void -# """ -# -# def setInteger(self, value): -# """ -# Set this NestedInteger to hold a single integer equal to value. -# :rtype void -# """ -# -# def getInteger(self): -# """ -# @return the single integer that this NestedInteger holds, if it holds a single integer -# Return None if this NestedInteger holds a nested list -# :rtype int -# """ -# -# def getList(self): -# """ -# @return the nested list that this NestedInteger holds, if it holds a nested list -# Return None if this NestedInteger holds a single integer -# :rtype List[NestedInteger] -# """ -class Solution: - def deserialize(self, s: str) -> NestedInteger: - if s[0] != '[': - return NestedInteger(int(s)) - stk, x, neg = [], 0, False - for i, c in enumerate(s): - if c == '-': - neg = True - elif c.isdigit(): - x = x * 10 + int(c) - elif c == '[': - stk.append(NestedInteger()) - elif c in ',]': - if s[i - 1].isdigit(): - if neg: - x = -x - stk[-1].add(NestedInteger(x)) - x, neg = 0, False - if c == ']' and len(stk) > 1: - t = stk.pop() - stk[-1].add(t) - return stk.pop() +# """ +# This is the interface that allows for creating nested lists. +# You should not implement it, or speculate about its implementation +# """ +# class NestedInteger: +# def __init__(self, value=None): +# """ +# If value is not specified, initializes an empty list. +# Otherwise initializes a single integer equal to value. +# """ +# +# def isInteger(self): +# """ +# @return True if this NestedInteger holds a single integer, rather than a nested list. +# :rtype bool +# """ +# +# def add(self, elem): +# """ +# Set this NestedInteger to hold a nested list and adds a nested integer elem to it. +# :rtype void +# """ +# +# def setInteger(self, value): +# """ +# Set this NestedInteger to hold a single integer equal to value. +# :rtype void +# """ +# +# def getInteger(self): +# """ +# @return the single integer that this NestedInteger holds, if it holds a single integer +# Return None if this NestedInteger holds a nested list +# :rtype int +# """ +# +# def getList(self): +# """ +# @return the nested list that this NestedInteger holds, if it holds a nested list +# Return None if this NestedInteger holds a single integer +# :rtype List[NestedInteger] +# """ +class Solution: + def deserialize(self, s: str) -> NestedInteger: + if not s or s == '[]': + return NestedInteger() + if s[0] != '[': + return NestedInteger(int(s)) + ans = NestedInteger() + depth, j = 0, 1 + for i in range(1, len(s)): + if depth == 0 and (s[i] == ',' or i == len(s) - 1): + ans.add(self.deserialize(s[j:i])) + j = i + 1 + elif s[i] == '[': + depth += 1 + elif s[i] == ']': + depth -= 1 + return ans diff --git a/solution/0300-0399/0385.Mini Parser/Solution.ts b/solution/0300-0399/0385.Mini Parser/Solution.ts index 9d0a0186e740f..c40a16e1300f9 100644 --- a/solution/0300-0399/0385.Mini Parser/Solution.ts +++ b/solution/0300-0399/0385.Mini Parser/Solution.ts @@ -38,30 +38,23 @@ */ function deserialize(s: string): NestedInteger { + if (s === '' || s === '[]') { + return new NestedInteger(); + } if (s[0] !== '[') { return new NestedInteger(+s); } - const stk: NestedInteger[] = []; - let x = 0; - let neg = false; - for (let i = 0; i < s.length; ++i) { - if (s[i] === '-') { - neg = true; + const ans: NestedInteger = new NestedInteger(); + let depth = 0; + for (let i = 1, j = 1; i < s.length; ++i) { + if (depth === 0 && (s[i] === ',' || i === s.length - 1)) { + ans.add(deserialize(s.slice(j, i))); + j = i + 1; } else if (s[i] === '[') { - stk.push(new NestedInteger()); - } else if (s[i] >= '0' && s[i] <= '9') { - x = x * 10 + s[i].charCodeAt(0) - '0'.charCodeAt(0); - } else if (s[i] === ',' || s[i] === ']') { - if (s[i - 1] >= '0' && s[i - 1] <= '9') { - stk[stk.length - 1].add(new NestedInteger(neg ? -x : x)); - } - x = 0; - neg = false; - if (s[i] === ']' && stk.length > 1) { - const t = stk.pop()!; - stk[stk.length - 1].add(t); - } + ++depth; + } else if (s[i] === ']') { + --depth; } } - return stk[0]; + return ans; } diff --git a/solution/0300-0399/0385.Mini Parser/Solution2.cpp b/solution/0300-0399/0385.Mini Parser/Solution2.cpp new file mode 100644 index 0000000000000..24dd96c4e97a3 --- /dev/null +++ b/solution/0300-0399/0385.Mini Parser/Solution2.cpp @@ -0,0 +1,64 @@ +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * class NestedInteger { + * public: + * // Constructor initializes an empty nested list. + * NestedInteger(); + * + * // Constructor initializes a single integer. + * NestedInteger(int value); + * + * // Return true if this NestedInteger holds a single integer, rather than a nested list. + * bool isInteger() const; + * + * // Return the single integer that this NestedInteger holds, if it holds a single integer + * // The result is undefined if this NestedInteger holds a nested list + * int getInteger() const; + * + * // Set this NestedInteger to hold a single integer. + * void setInteger(int value); + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * void add(const NestedInteger &ni); + * + * // Return the nested list that this NestedInteger holds, if it holds a nested list + * // The result is undefined if this NestedInteger holds a single integer + * const vector &getList() const; + * }; + */ +class Solution { +public: + NestedInteger deserialize(string s) { + if (s[0] != '[') { + return NestedInteger(stoi(s)); + } + stack stk; + int x = 0; + bool neg = false; + for (int i = 0; i < s.size(); ++i) { + if (s[i] == '-') { + neg = true; + } else if (isdigit(s[i])) { + x = x * 10 + s[i] - '0'; + } else if (s[i] == '[') { + stk.push(NestedInteger()); + } else if (s[i] == ',' || s[i] == ']') { + if (isdigit(s[i - 1])) { + if (neg) { + x = -x; + } + stk.top().add(NestedInteger(x)); + } + x = 0; + neg = false; + if (s[i] == ']' && stk.size() > 1) { + auto t = stk.top(); + stk.pop(); + stk.top().add(t); + } + } + } + return stk.top(); + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0385.Mini Parser/Solution2.go b/solution/0300-0399/0385.Mini Parser/Solution2.go new file mode 100644 index 0000000000000..0862e8c125c0e --- /dev/null +++ b/solution/0300-0399/0385.Mini Parser/Solution2.go @@ -0,0 +1,62 @@ +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * type NestedInteger struct { + * } + * + * // Return true if this NestedInteger holds a single integer, rather than a nested list. + * func (n NestedInteger) IsInteger() bool {} + * + * // Return the single integer that this NestedInteger holds, if it holds a single integer + * // The result is undefined if this NestedInteger holds a nested list + * // So before calling this method, you should have a check + * func (n NestedInteger) GetInteger() int {} + * + * // Set this NestedInteger to hold a single integer. + * func (n *NestedInteger) SetInteger(value int) {} + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * func (n *NestedInteger) Add(elem NestedInteger) {} + * + * // Return the nested list that this NestedInteger holds, if it holds a nested list + * // The list length is zero if this NestedInteger holds a single integer + * // You can access NestedInteger's List element directly if you want to modify it + * func (n NestedInteger) GetList() []*NestedInteger {} + */ +func deserialize(s string) *NestedInteger { + if s[0] != '[' { + v, _ := strconv.Atoi(s) + ans := NestedInteger{} + ans.SetInteger(v) + return &ans + } + stk := []*NestedInteger{} + x := 0 + neg := false + for i, c := range s { + if c == '-' { + neg = true + } else if c >= '0' && c <= '9' { + x = x*10 + int(c-'0') + } else if c == '[' { + stk = append(stk, &NestedInteger{}) + } else if c == ',' || c == ']' { + if s[i-1] >= '0' && s[i-1] <= '9' { + if neg { + x = -x + } + t := NestedInteger{} + t.SetInteger(x) + stk[len(stk)-1].Add(t) + } + x = 0 + neg = false + if c == ']' && len(stk) > 1 { + t := stk[len(stk)-1] + stk = stk[:len(stk)-1] + stk[len(stk)-1].Add(*t) + } + } + } + return stk[0] +} \ No newline at end of file diff --git a/solution/0300-0399/0385.Mini Parser/Solution2.java b/solution/0300-0399/0385.Mini Parser/Solution2.java new file mode 100644 index 0000000000000..929a6da984bc2 --- /dev/null +++ b/solution/0300-0399/0385.Mini Parser/Solution2.java @@ -0,0 +1,62 @@ +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * public interface NestedInteger { + * // Constructor initializes an empty nested list. + * public NestedInteger(); + * + * // Constructor initializes a single integer. + * public NestedInteger(int value); + * + * // @return true if this NestedInteger holds a single integer, rather than a nested list. + * public boolean isInteger(); + * + * // @return the single integer that this NestedInteger holds, if it holds a single integer + * // Return null if this NestedInteger holds a nested list + * public Integer getInteger(); + * + * // Set this NestedInteger to hold a single integer. + * public void setInteger(int value); + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * public void add(NestedInteger ni); + * + * // @return the nested list that this NestedInteger holds, if it holds a nested list + * // Return empty list if this NestedInteger holds a single integer + * public List getList(); + * } + */ +class Solution { + public NestedInteger deserialize(String s) { + if (s.charAt(0) != '[') { + return new NestedInteger(Integer.parseInt(s)); + } + Deque stk = new ArrayDeque<>(); + int x = 0; + boolean neg = false; + for (int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if (c == '-') { + neg = true; + } else if (Character.isDigit(c)) { + x = x * 10 + c - '0'; + } else if (c == '[') { + stk.push(new NestedInteger()); + } else if (c == ',' || c == ']') { + if (Character.isDigit(s.charAt(i - 1))) { + if (neg) { + x = -x; + } + stk.peek().add(new NestedInteger(x)); + } + x = 0; + neg = false; + if (c == ']' && stk.size() > 1) { + NestedInteger t = stk.pop(); + stk.peek().add(t); + } + } + } + return stk.peek(); + } +} \ No newline at end of file diff --git a/solution/0300-0399/0385.Mini Parser/Solution2.py b/solution/0300-0399/0385.Mini Parser/Solution2.py new file mode 100644 index 0000000000000..8c78d6ec8462c --- /dev/null +++ b/solution/0300-0399/0385.Mini Parser/Solution2.py @@ -0,0 +1,64 @@ +# """ +# This is the interface that allows for creating nested lists. +# You should not implement it, or speculate about its implementation +# """ +# class NestedInteger: +# def __init__(self, value=None): +# """ +# If value is not specified, initializes an empty list. +# Otherwise initializes a single integer equal to value. +# """ +# +# def isInteger(self): +# """ +# @return True if this NestedInteger holds a single integer, rather than a nested list. +# :rtype bool +# """ +# +# def add(self, elem): +# """ +# Set this NestedInteger to hold a nested list and adds a nested integer elem to it. +# :rtype void +# """ +# +# def setInteger(self, value): +# """ +# Set this NestedInteger to hold a single integer equal to value. +# :rtype void +# """ +# +# def getInteger(self): +# """ +# @return the single integer that this NestedInteger holds, if it holds a single integer +# Return None if this NestedInteger holds a nested list +# :rtype int +# """ +# +# def getList(self): +# """ +# @return the nested list that this NestedInteger holds, if it holds a nested list +# Return None if this NestedInteger holds a single integer +# :rtype List[NestedInteger] +# """ +class Solution: + def deserialize(self, s: str) -> NestedInteger: + if s[0] != '[': + return NestedInteger(int(s)) + stk, x, neg = [], 0, False + for i, c in enumerate(s): + if c == '-': + neg = True + elif c.isdigit(): + x = x * 10 + int(c) + elif c == '[': + stk.append(NestedInteger()) + elif c in ',]': + if s[i - 1].isdigit(): + if neg: + x = -x + stk[-1].add(NestedInteger(x)) + x, neg = 0, False + if c == ']' and len(stk) > 1: + t = stk.pop() + stk[-1].add(t) + return stk.pop() diff --git a/solution/0300-0399/0385.Mini Parser/Solution2.ts b/solution/0300-0399/0385.Mini Parser/Solution2.ts new file mode 100644 index 0000000000000..9d0a0186e740f --- /dev/null +++ b/solution/0300-0399/0385.Mini Parser/Solution2.ts @@ -0,0 +1,67 @@ +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * class NestedInteger { + * If value is provided, then it holds a single integer + * Otherwise it holds an empty nested list + * constructor(value?: number) { + * ... + * }; + * + * Return true if this NestedInteger holds a single integer, rather than a nested list. + * isInteger(): boolean { + * ... + * }; + * + * Return the single integer that this NestedInteger holds, if it holds a single integer + * Return null if this NestedInteger holds a nested list + * getInteger(): number | null { + * ... + * }; + * + * Set this NestedInteger to hold a single integer equal to value. + * setInteger(value: number) { + * ... + * }; + * + * Set this NestedInteger to hold a nested list and adds a nested integer elem to it. + * add(elem: NestedInteger) { + * ... + * }; + * + * Return the nested list that this NestedInteger holds, + * or an empty list if this NestedInteger holds a single integer + * getList(): NestedInteger[] { + * ... + * }; + * }; + */ + +function deserialize(s: string): NestedInteger { + if (s[0] !== '[') { + return new NestedInteger(+s); + } + const stk: NestedInteger[] = []; + let x = 0; + let neg = false; + for (let i = 0; i < s.length; ++i) { + if (s[i] === '-') { + neg = true; + } else if (s[i] === '[') { + stk.push(new NestedInteger()); + } else if (s[i] >= '0' && s[i] <= '9') { + x = x * 10 + s[i].charCodeAt(0) - '0'.charCodeAt(0); + } else if (s[i] === ',' || s[i] === ']') { + if (s[i - 1] >= '0' && s[i - 1] <= '9') { + stk[stk.length - 1].add(new NestedInteger(neg ? -x : x)); + } + x = 0; + neg = false; + if (s[i] === ']' && stk.length > 1) { + const t = stk.pop()!; + stk[stk.length - 1].add(t); + } + } + } + return stk[0]; +} diff --git a/solution/0300-0399/0386.Lexicographical Numbers/Solution.cpp b/solution/0300-0399/0386.Lexicographical Numbers/Solution.cpp index f7f95eba0f4b8..ccf7ec79db4fa 100644 --- a/solution/0300-0399/0386.Lexicographical Numbers/Solution.cpp +++ b/solution/0300-0399/0386.Lexicographical Numbers/Solution.cpp @@ -1,17 +1,14 @@ -class Solution { -public: - vector lexicalOrder(int n) { - vector ans; - int v = 1; - for (int i = 0; i < n; ++i) { - ans.push_back(v); - if (v * 10 <= n) - v *= 10; - else { - while (v % 10 == 9 || v + 1 > n) v /= 10; - ++v; - } - } - return ans; - } +class Solution { +public: + vector lexicalOrder(int n) { + vector ans; + for (int i = 1; i < 10; ++i) dfs(i, n, ans); + return ans; + } + + void dfs(int u, int n, vector& ans) { + if (u > n) return; + ans.push_back(u); + for (int i = 0; i < 10; ++i) dfs(u * 10 + i, n, ans); + } }; \ No newline at end of file diff --git a/solution/0300-0399/0386.Lexicographical Numbers/Solution.go b/solution/0300-0399/0386.Lexicographical Numbers/Solution.go index 1cb885b1567a7..dd0622ffa1e67 100644 --- a/solution/0300-0399/0386.Lexicographical Numbers/Solution.go +++ b/solution/0300-0399/0386.Lexicographical Numbers/Solution.go @@ -1,16 +1,17 @@ func lexicalOrder(n int) []int { var ans []int - v := 1 - for i := 0; i < n; i++ { - ans = append(ans, v) - if v*10 <= n { - v *= 10 - } else { - for v%10 == 9 || v+1 > n { - v /= 10 - } - v++ + var dfs func(u int) + dfs = func(u int) { + if u > n { + return } + ans = append(ans, u) + for i := 0; i < 10; i++ { + dfs(u*10 + i) + } + } + for i := 1; i < 10; i++ { + dfs(i) } return ans } \ No newline at end of file diff --git a/solution/0300-0399/0386.Lexicographical Numbers/Solution.java b/solution/0300-0399/0386.Lexicographical Numbers/Solution.java index 5f648bf91247f..6716bacebda33 100644 --- a/solution/0300-0399/0386.Lexicographical Numbers/Solution.java +++ b/solution/0300-0399/0386.Lexicographical Numbers/Solution.java @@ -1,18 +1,19 @@ -class Solution { - public List lexicalOrder(int n) { - List ans = new ArrayList<>(); - int v = 1; - for (int i = 0; i < n; ++i) { - ans.add(v); - if (v * 10 <= n) { - v *= 10; - } else { - while (v % 10 == 9 || v + 1 > n) { - v /= 10; - } - ++v; - } - } - return ans; - } +class Solution { + public List lexicalOrder(int n) { + List ans = new ArrayList<>(); + for (int i = 1; i < 10; ++i) { + dfs(i, n, ans); + } + return ans; + } + + private void dfs(int u, int n, List ans) { + if (u > n) { + return; + } + ans.add(u); + for (int i = 0; i < 10; ++i) { + dfs(u * 10 + i, n, ans); + } + } } \ No newline at end of file diff --git a/solution/0300-0399/0386.Lexicographical Numbers/Solution.py b/solution/0300-0399/0386.Lexicographical Numbers/Solution.py index 8ae6cba281838..1109325ba1b89 100644 --- a/solution/0300-0399/0386.Lexicographical Numbers/Solution.py +++ b/solution/0300-0399/0386.Lexicographical Numbers/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def lexicalOrder(self, n: int) -> List[int]: - v = 1 - ans = [] - for i in range(n): - ans.append(v) - if v * 10 <= n: - v *= 10 - else: - while v % 10 == 9 or v + 1 > n: - v //= 10 - v += 1 - return ans +class Solution: + def lexicalOrder(self, n: int) -> List[int]: + def dfs(u): + if u > n: + return + ans.append(u) + for i in range(10): + dfs(u * 10 + i) + + ans = [] + for i in range(1, 10): + dfs(i) + return ans diff --git a/solution/0300-0399/0386.Lexicographical Numbers/Solution2.cpp b/solution/0300-0399/0386.Lexicographical Numbers/Solution2.cpp new file mode 100644 index 0000000000000..1e2746fd3e240 --- /dev/null +++ b/solution/0300-0399/0386.Lexicographical Numbers/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector lexicalOrder(int n) { + vector ans; + int v = 1; + for (int i = 0; i < n; ++i) { + ans.push_back(v); + if (v * 10 <= n) + v *= 10; + else { + while (v % 10 == 9 || v + 1 > n) v /= 10; + ++v; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0386.Lexicographical Numbers/Solution2.go b/solution/0300-0399/0386.Lexicographical Numbers/Solution2.go new file mode 100644 index 0000000000000..1cb885b1567a7 --- /dev/null +++ b/solution/0300-0399/0386.Lexicographical Numbers/Solution2.go @@ -0,0 +1,16 @@ +func lexicalOrder(n int) []int { + var ans []int + v := 1 + for i := 0; i < n; i++ { + ans = append(ans, v) + if v*10 <= n { + v *= 10 + } else { + for v%10 == 9 || v+1 > n { + v /= 10 + } + v++ + } + } + return ans +} \ No newline at end of file diff --git a/solution/0300-0399/0386.Lexicographical Numbers/Solution2.java b/solution/0300-0399/0386.Lexicographical Numbers/Solution2.java new file mode 100644 index 0000000000000..a7cf5b1b9dccb --- /dev/null +++ b/solution/0300-0399/0386.Lexicographical Numbers/Solution2.java @@ -0,0 +1,18 @@ +class Solution { + public List lexicalOrder(int n) { + List ans = new ArrayList<>(); + int v = 1; + for (int i = 0; i < n; ++i) { + ans.add(v); + if (v * 10 <= n) { + v *= 10; + } else { + while (v % 10 == 9 || v + 1 > n) { + v /= 10; + } + ++v; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0387.First Unique Character in a String/Solution.cpp b/solution/0300-0399/0387.First Unique Character in a String/Solution.cpp index 301958b7f860b..681799682a0a0 100644 --- a/solution/0300-0399/0387.First Unique Character in a String/Solution.cpp +++ b/solution/0300-0399/0387.First Unique Character in a String/Solution.cpp @@ -1,4 +1,4 @@ -class Solution { +class Solution { public: int firstUniqChar(string s) { int cnt[26]{}; diff --git a/solution/0300-0399/0387.First Unique Character in a String/Solution.php b/solution/0300-0399/0387.First Unique Character in a String/Solution.php index 50961919d117c..965a189fc07f7 100644 --- a/solution/0300-0399/0387.First Unique Character in a String/Solution.php +++ b/solution/0300-0399/0387.First Unique Character in a String/Solution.php @@ -14,4 +14,4 @@ function firstUniqChar($s) { } return -1; } -} \ No newline at end of file +} diff --git a/solution/0300-0399/0388.Longest Absolute File Path/Solution.cpp b/solution/0300-0399/0388.Longest Absolute File Path/Solution.cpp index 5a6655738a62c..11cf41e4a3aa3 100644 --- a/solution/0300-0399/0388.Longest Absolute File Path/Solution.cpp +++ b/solution/0300-0399/0388.Longest Absolute File Path/Solution.cpp @@ -39,4 +39,4 @@ class Solution { } return ans; } -}; +}; \ No newline at end of file diff --git a/solution/0300-0399/0388.Longest Absolute File Path/Solution.java b/solution/0300-0399/0388.Longest Absolute File Path/Solution.java index 9e2c3bec54c9f..642836180b012 100644 --- a/solution/0300-0399/0388.Longest Absolute File Path/Solution.java +++ b/solution/0300-0399/0388.Longest Absolute File Path/Solution.java @@ -39,4 +39,4 @@ public int lengthLongestPath(String input) { } return ans; } -} +} \ No newline at end of file diff --git a/solution/0300-0399/0389.Find the Difference/Solution.c b/solution/0300-0399/0389.Find the Difference/Solution.c index cf683a231a5e0..ce5885b2b8e6f 100644 --- a/solution/0300-0399/0389.Find the Difference/Solution.c +++ b/solution/0300-0399/0389.Find the Difference/Solution.c @@ -1,10 +1,14 @@ char findTheDifference(char* s, char* t) { int n = strlen(s); - char ans = 0; + int cnt[26] = {0}; for (int i = 0; i < n; i++) { - ans ^= s[i]; - ans ^= t[i]; + cnt[s[i] - 'a']++; + cnt[t[i] - 'a']--; } - ans ^= t[n]; - return ans; -} + cnt[t[n] - 'a']--; + for (int i = 0;; i++) { + if (cnt[i]) { + return 'a' + i; + } + } +} \ No newline at end of file diff --git a/solution/0300-0399/0389.Find the Difference/Solution.cpp b/solution/0300-0399/0389.Find the Difference/Solution.cpp index e0c3b8f7b9f99..42e449845df72 100644 --- a/solution/0300-0399/0389.Find the Difference/Solution.cpp +++ b/solution/0300-0399/0389.Find the Difference/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - char findTheDifference(string s, string t) { - int cnt[26]{}; - for (char& c : s) { - ++cnt[c - 'a']; - } - for (char& c : t) { - if (--cnt[c - 'a'] < 0) { - return c; - } - } - return ' '; - } +class Solution { +public: + char findTheDifference(string s, string t) { + int cnt[26]{}; + for (char& c : s) { + ++cnt[c - 'a']; + } + for (char& c : t) { + if (--cnt[c - 'a'] < 0) { + return c; + } + } + return ' '; + } }; \ No newline at end of file diff --git a/solution/0300-0399/0389.Find the Difference/Solution.rs b/solution/0300-0399/0389.Find the Difference/Solution.rs index 0cfdf39c3469c..37fb6da5f3df8 100644 --- a/solution/0300-0399/0389.Find the Difference/Solution.rs +++ b/solution/0300-0399/0389.Find the Difference/Solution.rs @@ -1,12 +1,22 @@ impl Solution { pub fn find_the_difference(s: String, t: String) -> char { - let mut ans = 0; - for c in s.as_bytes() { - ans ^= c; + let s = s.as_bytes(); + let t = t.as_bytes(); + let n = s.len(); + let mut count = [0; 26]; + for i in 0..n { + count[(s[i] - b'a') as usize] += 1; + count[(t[i] - b'a') as usize] -= 1; } - for c in t.as_bytes() { - ans ^= c; - } - char::from(ans) + count[(t[n] - b'a') as usize] -= 1; + char::from( + b'a' + + ( + count + .iter() + .position(|&v| v != 0) + .unwrap() as u8 + ) + ) } } diff --git a/solution/0300-0399/0389.Find the Difference/Solution2.c b/solution/0300-0399/0389.Find the Difference/Solution2.c new file mode 100644 index 0000000000000..77959091c185c --- /dev/null +++ b/solution/0300-0399/0389.Find the Difference/Solution2.c @@ -0,0 +1,10 @@ +char findTheDifference(char* s, char* t) { + int n = strlen(s); + char ans = 0; + for (int i = 0; i < n; i++) { + ans ^= s[i]; + ans ^= t[i]; + } + ans ^= t[n]; + return ans; +} \ No newline at end of file diff --git a/solution/0300-0399/0389.Find the Difference/Solution2.cpp b/solution/0300-0399/0389.Find the Difference/Solution2.cpp new file mode 100644 index 0000000000000..5e30504343b33 --- /dev/null +++ b/solution/0300-0399/0389.Find the Difference/Solution2.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + char findTheDifference(string s, string t) { + int a = 0, b = 0; + for (char& c : s) { + a += c; + } + for (char& c : t) { + b += c; + } + return b - a; + } +}; \ No newline at end of file diff --git a/solution/0300-0399/0389.Find the Difference/Solution2.go b/solution/0300-0399/0389.Find the Difference/Solution2.go new file mode 100644 index 0000000000000..9f498032f6335 --- /dev/null +++ b/solution/0300-0399/0389.Find the Difference/Solution2.go @@ -0,0 +1,10 @@ +func findTheDifference(s string, t string) byte { + ss := 0 + for _, c := range s { + ss -= int(c) + } + for _, c := range t { + ss += int(c) + } + return byte(ss) +} \ No newline at end of file diff --git a/solution/0300-0399/0389.Find the Difference/Solution2.java b/solution/0300-0399/0389.Find the Difference/Solution2.java new file mode 100644 index 0000000000000..ca0343d3acfdb --- /dev/null +++ b/solution/0300-0399/0389.Find the Difference/Solution2.java @@ -0,0 +1,12 @@ +class Solution { + public char findTheDifference(String s, String t) { + int ss = 0; + for (int i = 0; i < t.length(); ++i) { + ss += t.charAt(i); + } + for (int i = 0; i < s.length(); ++i) { + ss -= s.charAt(i); + } + return (char) ss; + } +} \ No newline at end of file diff --git a/solution/0300-0399/0389.Find the Difference/Solution2.py b/solution/0300-0399/0389.Find the Difference/Solution2.py new file mode 100644 index 0000000000000..216574541d94c --- /dev/null +++ b/solution/0300-0399/0389.Find the Difference/Solution2.py @@ -0,0 +1,5 @@ +class Solution: + def findTheDifference(self, s: str, t: str) -> str: + a = sum(ord(c) for c in s) + b = sum(ord(c) for c in t) + return chr(b - a) diff --git a/solution/0300-0399/0389.Find the Difference/Solution2.rs b/solution/0300-0399/0389.Find the Difference/Solution2.rs new file mode 100644 index 0000000000000..0cfdf39c3469c --- /dev/null +++ b/solution/0300-0399/0389.Find the Difference/Solution2.rs @@ -0,0 +1,12 @@ +impl Solution { + pub fn find_the_difference(s: String, t: String) -> char { + let mut ans = 0; + for c in s.as_bytes() { + ans ^= c; + } + for c in t.as_bytes() { + ans ^= c; + } + char::from(ans) + } +} diff --git a/solution/0300-0399/0389.Find the Difference/Solution2.ts b/solution/0300-0399/0389.Find the Difference/Solution2.ts new file mode 100644 index 0000000000000..38407053ac895 --- /dev/null +++ b/solution/0300-0399/0389.Find the Difference/Solution2.ts @@ -0,0 +1,6 @@ +function findTheDifference(s: string, t: string): string { + return String.fromCharCode( + [...t].reduce((r, v) => r + v.charCodeAt(0), 0) - + [...s].reduce((r, v) => r + v.charCodeAt(0), 0), + ); +} diff --git a/solution/0300-0399/0391.Perfect Rectangle/Solution.cpp b/solution/0300-0399/0391.Perfect Rectangle/Solution.cpp index 4a0f495ef2e02..4475dac088c4f 100644 --- a/solution/0300-0399/0391.Perfect Rectangle/Solution.cpp +++ b/solution/0300-0399/0391.Perfect Rectangle/Solution.cpp @@ -38,4 +38,4 @@ class Solution { return e.second == 2 || e.second == 4; }); } -}; +}; \ No newline at end of file diff --git a/solution/0300-0399/0391.Perfect Rectangle/Solution.java b/solution/0300-0399/0391.Perfect Rectangle/Solution.java index dd3e767b0ad57..a6d96406f7669 100644 --- a/solution/0300-0399/0391.Perfect Rectangle/Solution.java +++ b/solution/0300-0399/0391.Perfect Rectangle/Solution.java @@ -61,4 +61,4 @@ public int hashCode() { return Objects.hash(first, second); } } -} +} \ No newline at end of file diff --git a/solution/0300-0399/0392.Is Subsequence/Solution.cs b/solution/0300-0399/0392.Is Subsequence/Solution.cs index 47aff1691467c..02d1c1b881b8c 100644 --- a/solution/0300-0399/0392.Is Subsequence/Solution.cs +++ b/solution/0300-0399/0392.Is Subsequence/Solution.cs @@ -9,4 +9,4 @@ public bool IsSubsequence(string s, string t) { } return i == m; } -} \ No newline at end of file +} diff --git a/solution/0300-0399/0393.UTF-8 Validation/Solution.cpp b/solution/0300-0399/0393.UTF-8 Validation/Solution.cpp index 44113d11a652d..551f0e4879ef6 100644 --- a/solution/0300-0399/0393.UTF-8 Validation/Solution.cpp +++ b/solution/0300-0399/0393.UTF-8 Validation/Solution.cpp @@ -1,4 +1,4 @@ -class Solution { +class Solution { public: bool validUtf8(vector& data) { int n = 0; diff --git a/solution/0300-0399/0396.Rotate Function/Solution.cpp b/solution/0300-0399/0396.Rotate Function/Solution.cpp index 7b921b9dbc37f..d5dc24a193f9f 100644 --- a/solution/0300-0399/0396.Rotate Function/Solution.cpp +++ b/solution/0300-0399/0396.Rotate Function/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - int maxRotateFunction(vector& nums) { - int f = 0, s = 0, n = nums.size(); - for (int i = 0; i < n; ++i) { - f += i * nums[i]; - s += nums[i]; - } - int ans = f; - for (int i = 1; i < n; ++i) { - f = f + s - n * nums[n - i]; - ans = max(ans, f); - } - return ans; - } +class Solution { +public: + int maxRotateFunction(vector& nums) { + int f = 0, s = 0, n = nums.size(); + for (int i = 0; i < n; ++i) { + f += i * nums[i]; + s += nums[i]; + } + int ans = f; + for (int i = 1; i < n; ++i) { + f = f + s - n * nums[n - i]; + ans = max(ans, f); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0300-0399/0396.Rotate Function/Solution.java b/solution/0300-0399/0396.Rotate Function/Solution.java index 0c1dec2b049b9..37052e2d6de98 100644 --- a/solution/0300-0399/0396.Rotate Function/Solution.java +++ b/solution/0300-0399/0396.Rotate Function/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public int maxRotateFunction(int[] nums) { - int f = 0; - int s = 0; - int n = nums.length; - for (int i = 0; i < n; ++i) { - f += i * nums[i]; - s += nums[i]; - } - int ans = f; - for (int i = 1; i < n; ++i) { - f = f + s - n * nums[n - i]; - ans = Math.max(ans, f); - } - return ans; - } +class Solution { + public int maxRotateFunction(int[] nums) { + int f = 0; + int s = 0; + int n = nums.length; + for (int i = 0; i < n; ++i) { + f += i * nums[i]; + s += nums[i]; + } + int ans = f; + for (int i = 1; i < n; ++i) { + f = f + s - n * nums[n - i]; + ans = Math.max(ans, f); + } + return ans; + } } \ No newline at end of file diff --git a/solution/0300-0399/0396.Rotate Function/Solution.py b/solution/0300-0399/0396.Rotate Function/Solution.py index 034f616cc42a4..b316405e108af 100644 --- a/solution/0300-0399/0396.Rotate Function/Solution.py +++ b/solution/0300-0399/0396.Rotate Function/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def maxRotateFunction(self, nums: List[int]) -> int: - f = sum(i * v for i, v in enumerate(nums)) - n, s = len(nums), sum(nums) - ans = f - for i in range(1, n): - f = f + s - n * nums[n - i] - ans = max(ans, f) - return ans +class Solution: + def maxRotateFunction(self, nums: List[int]) -> int: + f = sum(i * v for i, v in enumerate(nums)) + n, s = len(nums), sum(nums) + ans = f + for i in range(1, n): + f = f + s - n * nums[n - i] + ans = max(ans, f) + return ans diff --git a/solution/0400-0499/0400.Nth Digit/Solution.cs b/solution/0400-0499/0400.Nth Digit/Solution.cs index 22ef8ee8ee259..483966882445d 100644 --- a/solution/0400-0499/0400.Nth Digit/Solution.cs +++ b/solution/0400-0499/0400.Nth Digit/Solution.cs @@ -10,4 +10,4 @@ public int FindNthDigit(int n) { int idx = (n - 1) % k; return num.ToString()[idx] - '0'; } -} \ No newline at end of file +} diff --git a/solution/0400-0499/0401.Binary Watch/Solution2.cpp b/solution/0400-0499/0401.Binary Watch/Solution2.cpp new file mode 100644 index 0000000000000..7e8d8124f7f23 --- /dev/null +++ b/solution/0400-0499/0401.Binary Watch/Solution2.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + vector readBinaryWatch(int turnedOn) { + vector ans; + for (int i = 0; i < 1 << 10; ++i) { + int h = i >> 6, m = i & 0b111111; + if (h < 12 && m < 60 && __builtin_popcount(i) == turnedOn) { + ans.push_back(to_string(h) + ":" + (m < 10 ? "0" : "") + to_string(m)); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0401.Binary Watch/Solution2.go b/solution/0400-0499/0401.Binary Watch/Solution2.go new file mode 100644 index 0000000000000..cc020f1010a39 --- /dev/null +++ b/solution/0400-0499/0401.Binary Watch/Solution2.go @@ -0,0 +1,10 @@ +func readBinaryWatch(turnedOn int) []string { + var ans []string + for i := 0; i < 1<<10; i++ { + h, m := i>>6, i&0b111111 + if h < 12 && m < 60 && bits.OnesCount(uint(i)) == turnedOn { + ans = append(ans, fmt.Sprintf("%d:%02d", h, m)) + } + } + return ans +} \ No newline at end of file diff --git a/solution/0400-0499/0401.Binary Watch/Solution2.java b/solution/0400-0499/0401.Binary Watch/Solution2.java new file mode 100644 index 0000000000000..98b8acd910293 --- /dev/null +++ b/solution/0400-0499/0401.Binary Watch/Solution2.java @@ -0,0 +1,12 @@ +class Solution { + public List readBinaryWatch(int turnedOn) { + List ans = new ArrayList<>(); + for (int i = 0; i < 1 << 10; ++i) { + int h = i >> 6, m = i & 0b111111; + if (h < 12 && m < 60 && Integer.bitCount(i) == turnedOn) { + ans.add(String.format("%d:%02d", h, m)); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0401.Binary Watch/Solution2.py b/solution/0400-0499/0401.Binary Watch/Solution2.py new file mode 100644 index 0000000000000..2f3a2e05d8fab --- /dev/null +++ b/solution/0400-0499/0401.Binary Watch/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def readBinaryWatch(self, turnedOn: int) -> List[str]: + ans = [] + for i in range(1 << 10): + h, m = i >> 6, i & 0b111111 + if h < 12 and m < 60 and i.bit_count() == turnedOn: + ans.append('{:d}:{:02d}'.format(h, m)) + return ans diff --git a/solution/0400-0499/0403.Frog Jump/Solution.rs b/solution/0400-0499/0403.Frog Jump/Solution.rs index 202892da3c328..70c33b696963e 100644 --- a/solution/0400-0499/0403.Frog Jump/Solution.rs +++ b/solution/0400-0499/0403.Frog Jump/Solution.rs @@ -1,26 +1,48 @@ +use std::collections::HashMap; + impl Solution { #[allow(dead_code)] pub fn can_cross(stones: Vec) -> bool { let n = stones.len(); - let mut dp = vec![vec![false; n]; n]; + let mut record = vec![vec![-1; n]; n]; + let mut pos = HashMap::new(); + for (i, &s) in stones.iter().enumerate() { + pos.insert(s, i); + } + + Self::dfs(&mut record, 0, 0, n, &pos, &stones) + } - // Initialize the dp vector - dp[0][0] = true; + #[allow(dead_code)] + fn dfs( + record: &mut Vec>, + i: usize, + k: usize, + n: usize, + pos: &HashMap, + stones: &Vec + ) -> bool { + if i == n - 1 { + return true; + } + + if record[i][k] != -1 { + return record[i][k] == 1; + } - // Begin the actual dp process - for i in 1..n { - for j in (0..=i - 1).rev() { - let k = (stones[i] - stones[j]) as usize; - if k - 1 > j { - break; - } - dp[i][k] = dp[j][k - 1] || dp[j][k] || dp[j][k + 1]; - if i == n - 1 && dp[i][k] { - return true; - } + let k = k as i32; + for j in k - 1..=k + 1 { + if + j > 0 && + pos.contains_key(&(stones[i] + j)) && + Self::dfs(record, pos[&(stones[i] + j)], j as usize, n, pos, stones) + { + record[i][k as usize] = 1; + return true; } } + record[i][k as usize] = 0; false } } diff --git a/solution/0400-0499/0403.Frog Jump/Solution2.cpp b/solution/0400-0499/0403.Frog Jump/Solution2.cpp new file mode 100644 index 0000000000000..eec6bb09a4062 --- /dev/null +++ b/solution/0400-0499/0403.Frog Jump/Solution2.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + bool canCross(vector& stones) { + int n = stones.size(); + bool f[n][n]; + memset(f, false, sizeof(f)); + f[0][0] = true; + for (int i = 1; i < n; ++i) { + for (int j = i - 1; j >= 0; --j) { + int k = stones[i] - stones[j]; + if (k - 1 > j) { + break; + } + f[i][k] = f[j][k - 1] || f[j][k] || f[j][k + 1]; + if (i == n - 1 && f[i][k]) { + return true; + } + } + } + return false; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0403.Frog Jump/Solution2.go b/solution/0400-0499/0403.Frog Jump/Solution2.go new file mode 100644 index 0000000000000..58e73c498c04c --- /dev/null +++ b/solution/0400-0499/0403.Frog Jump/Solution2.go @@ -0,0 +1,21 @@ +func canCross(stones []int) bool { + n := len(stones) + f := make([][]bool, n) + for i := range f { + f[i] = make([]bool, n) + } + f[0][0] = true + for i := 1; i < n; i++ { + for j := i - 1; j >= 0; j-- { + k := stones[i] - stones[j] + if k-1 > j { + break + } + f[i][k] = f[j][k-1] || f[j][k] || f[j][k+1] + if i == n-1 && f[i][k] { + return true + } + } + } + return false +} \ No newline at end of file diff --git a/solution/0400-0499/0403.Frog Jump/Solution2.java b/solution/0400-0499/0403.Frog Jump/Solution2.java new file mode 100644 index 0000000000000..0dd30d18c1f6c --- /dev/null +++ b/solution/0400-0499/0403.Frog Jump/Solution2.java @@ -0,0 +1,20 @@ +class Solution { + public boolean canCross(int[] stones) { + int n = stones.length; + boolean[][] f = new boolean[n][n]; + f[0][0] = true; + for (int i = 1; i < n; ++i) { + for (int j = i - 1; j >= 0; --j) { + int k = stones[i] - stones[j]; + if (k - 1 > j) { + break; + } + f[i][k] = f[j][k - 1] || f[j][k] || f[j][k + 1]; + if (i == n - 1 && f[i][k]) { + return true; + } + } + } + return false; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0403.Frog Jump/Solution2.py b/solution/0400-0499/0403.Frog Jump/Solution2.py new file mode 100644 index 0000000000000..3ee7a3a2a6f0b --- /dev/null +++ b/solution/0400-0499/0403.Frog Jump/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def canCross(self, stones: List[int]) -> bool: + n = len(stones) + f = [[False] * n for _ in range(n)] + f[0][0] = True + for i in range(1, n): + for j in range(i - 1, -1, -1): + k = stones[i] - stones[j] + if k - 1 > j: + break + f[i][k] = f[j][k - 1] or f[j][k] or f[j][k + 1] + if i == n - 1 and f[i][k]: + return True + return False diff --git a/solution/0400-0499/0403.Frog Jump/Solution2.rs b/solution/0400-0499/0403.Frog Jump/Solution2.rs new file mode 100644 index 0000000000000..202892da3c328 --- /dev/null +++ b/solution/0400-0499/0403.Frog Jump/Solution2.rs @@ -0,0 +1,26 @@ +impl Solution { + #[allow(dead_code)] + pub fn can_cross(stones: Vec) -> bool { + let n = stones.len(); + let mut dp = vec![vec![false; n]; n]; + + // Initialize the dp vector + dp[0][0] = true; + + // Begin the actual dp process + for i in 1..n { + for j in (0..=i - 1).rev() { + let k = (stones[i] - stones[j]) as usize; + if k - 1 > j { + break; + } + dp[i][k] = dp[j][k - 1] || dp[j][k] || dp[j][k + 1]; + if i == n - 1 && dp[i][k] { + return true; + } + } + } + + false + } +} diff --git a/solution/0400-0499/0403.Frog Jump/Solution2.ts b/solution/0400-0499/0403.Frog Jump/Solution2.ts new file mode 100644 index 0000000000000..c04f27591b628 --- /dev/null +++ b/solution/0400-0499/0403.Frog Jump/Solution2.ts @@ -0,0 +1,18 @@ +function canCross(stones: number[]): boolean { + const n = stones.length; + const f: boolean[][] = new Array(n).fill(0).map(() => new Array(n).fill(false)); + f[0][0] = true; + for (let i = 1; i < n; ++i) { + for (let j = i - 1; j >= 0; --j) { + const k = stones[i] - stones[j]; + if (k - 1 > j) { + break; + } + f[i][k] = f[j][k - 1] || f[j][k] || f[j][k + 1]; + if (i == n - 1 && f[i][k]) { + return true; + } + } + } + return false; +} diff --git a/solution/0400-0499/0404.Sum of Left Leaves/Solution.c b/solution/0400-0499/0404.Sum of Left Leaves/Solution.c index a8fa9f3e5a842..f1a41a6977810 100644 --- a/solution/0400-0499/0404.Sum of Left Leaves/Solution.c +++ b/solution/0400-0499/0404.Sum of Left Leaves/Solution.c @@ -19,4 +19,4 @@ int dfs(struct TreeNode* root, int isLeft) { int sumOfLeftLeaves(struct TreeNode* root) { return dfs(root, 0); -} +} \ No newline at end of file diff --git a/solution/0400-0499/0405.Convert a Number to Hexadecimal/Solution.java b/solution/0400-0499/0405.Convert a Number to Hexadecimal/Solution.java index 018f13826071b..c026adf780ed0 100644 --- a/solution/0400-0499/0405.Convert a Number to Hexadecimal/Solution.java +++ b/solution/0400-0499/0405.Convert a Number to Hexadecimal/Solution.java @@ -15,4 +15,4 @@ public String toHex(int num) { } return sb.reverse().toString(); } -} +} \ No newline at end of file diff --git a/solution/0400-0499/0405.Convert a Number to Hexadecimal/Solution2.java b/solution/0400-0499/0405.Convert a Number to Hexadecimal/Solution2.java new file mode 100644 index 0000000000000..3fdca46d2fef9 --- /dev/null +++ b/solution/0400-0499/0405.Convert a Number to Hexadecimal/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public String toHex(int num) { + if (num == 0) { + return "0"; + } + StringBuilder sb = new StringBuilder(); + for (int i = 7; i >= 0; --i) { + int x = (num >> (4 * i)) & 0xf; + if (sb.length() > 0 || x != 0) { + char c = x < 10 ? (char) (x + '0') : (char) (x - 10 + 'a'); + sb.append(c); + } + } + return sb.toString(); + } +} \ No newline at end of file diff --git a/solution/0400-0499/0408.Valid Word Abbreviation/Solution.cpp b/solution/0400-0499/0408.Valid Word Abbreviation/Solution.cpp index f0c29d1e8366c..efade23706125 100644 --- a/solution/0400-0499/0408.Valid Word Abbreviation/Solution.cpp +++ b/solution/0400-0499/0408.Valid Word Abbreviation/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - bool validWordAbbreviation(string word, string abbr) { - int m = word.size(), n = abbr.size(); - int i = 0, j = 0, x = 0; - for (; i < m && j < n; ++j) { - if (isdigit(abbr[j])) { - if (abbr[j] == '0' && x == 0) { - return false; - } - x = x * 10 + (abbr[j] - '0'); - } else { - i += x; - x = 0; - if (i >= m || word[i] != abbr[j]) { - return false; - } - ++i; - } - } - return i + x == m && j == n; - } +class Solution { +public: + bool validWordAbbreviation(string word, string abbr) { + int m = word.size(), n = abbr.size(); + int i = 0, j = 0, x = 0; + for (; i < m && j < n; ++j) { + if (isdigit(abbr[j])) { + if (abbr[j] == '0' && x == 0) { + return false; + } + x = x * 10 + (abbr[j] - '0'); + } else { + i += x; + x = 0; + if (i >= m || word[i] != abbr[j]) { + return false; + } + ++i; + } + } + return i + x == m && j == n; + } }; \ No newline at end of file diff --git a/solution/0400-0499/0408.Valid Word Abbreviation/Solution.java b/solution/0400-0499/0408.Valid Word Abbreviation/Solution.java index f74cd5bf78eea..61ddb0f29635d 100644 --- a/solution/0400-0499/0408.Valid Word Abbreviation/Solution.java +++ b/solution/0400-0499/0408.Valid Word Abbreviation/Solution.java @@ -1,23 +1,23 @@ -class Solution { - public boolean validWordAbbreviation(String word, String abbr) { - int m = word.length(), n = abbr.length(); - int i = 0, j = 0, x = 0; - for (; i < m && j < n; ++j) { - char c = abbr.charAt(j); - if (Character.isDigit(c)) { - if (c == '0' && x == 0) { - return false; - } - x = x * 10 + (c - '0'); - } else { - i += x; - x = 0; - if (i >= m || word.charAt(i) != c) { - return false; - } - ++i; - } - } - return i + x == m && j == n; - } +class Solution { + public boolean validWordAbbreviation(String word, String abbr) { + int m = word.length(), n = abbr.length(); + int i = 0, j = 0, x = 0; + for (; i < m && j < n; ++j) { + char c = abbr.charAt(j); + if (Character.isDigit(c)) { + if (c == '0' && x == 0) { + return false; + } + x = x * 10 + (c - '0'); + } else { + i += x; + x = 0; + if (i >= m || word.charAt(i) != c) { + return false; + } + ++i; + } + } + return i + x == m && j == n; + } } \ No newline at end of file diff --git a/solution/0400-0499/0408.Valid Word Abbreviation/Solution.py b/solution/0400-0499/0408.Valid Word Abbreviation/Solution.py index c25bdc3088837..9fde0287be1a4 100644 --- a/solution/0400-0499/0408.Valid Word Abbreviation/Solution.py +++ b/solution/0400-0499/0408.Valid Word Abbreviation/Solution.py @@ -1,17 +1,17 @@ -class Solution: - def validWordAbbreviation(self, word: str, abbr: str) -> bool: - m, n = len(word), len(abbr) - i = j = x = 0 - while i < m and j < n: - if abbr[j].isdigit(): - if abbr[j] == "0" and x == 0: - return False - x = x * 10 + int(abbr[j]) - else: - i += x - x = 0 - if i >= m or word[i] != abbr[j]: - return False - i += 1 - j += 1 - return i + x == m and j == n +class Solution: + def validWordAbbreviation(self, word: str, abbr: str) -> bool: + m, n = len(word), len(abbr) + i = j = x = 0 + while i < m and j < n: + if abbr[j].isdigit(): + if abbr[j] == "0" and x == 0: + return False + x = x * 10 + int(abbr[j]) + else: + i += x + x = 0 + if i >= m or word[i] != abbr[j]: + return False + i += 1 + j += 1 + return i + x == m and j == n diff --git a/solution/0400-0499/0409.Longest Palindrome/Solution2.ts b/solution/0400-0499/0409.Longest Palindrome/Solution2.ts new file mode 100644 index 0000000000000..8f223668bcefa --- /dev/null +++ b/solution/0400-0499/0409.Longest Palindrome/Solution2.ts @@ -0,0 +1,16 @@ +function longestPalindrome(s: string): number { + const map = new Map(); + for (const c of s) { + map.set(c, (map.get(c) ?? 0) + 1); + } + let hasOdd = false; + let res = 0; + for (const v of map.values()) { + res += v; + if (v & 1) { + hasOdd = true; + res--; + } + } + return res + (hasOdd ? 1 : 0); +} diff --git a/solution/0400-0499/0412.Fizz Buzz/Solution.php b/solution/0400-0499/0412.Fizz Buzz/Solution.php index 97cdf66d4fb2e..9e8e63c3202f2 100644 --- a/solution/0400-0499/0412.Fizz Buzz/Solution.php +++ b/solution/0400-0499/0412.Fizz Buzz/Solution.php @@ -18,4 +18,4 @@ function fizzBuzz($n) { } return $rs; } -} \ No newline at end of file +} diff --git a/solution/0400-0499/0413.Arithmetic Slices/Solution.py b/solution/0400-0499/0413.Arithmetic Slices/Solution.py index 23e3f897c6bc2..9b59a018148de 100644 --- a/solution/0400-0499/0413.Arithmetic Slices/Solution.py +++ b/solution/0400-0499/0413.Arithmetic Slices/Solution.py @@ -1,12 +1,12 @@ class Solution: def numberOfArithmeticSlices(self, nums: List[int]) -> int: - ans = cnt = 0 + ans, cnt = 0, 2 d = 3000 for a, b in pairwise(nums): if b - a == d: cnt += 1 else: d = b - a - cnt = 0 - ans += cnt + cnt = 2 + ans += max(0, cnt - 2) return ans diff --git a/solution/0400-0499/0413.Arithmetic Slices/Solution2.py b/solution/0400-0499/0413.Arithmetic Slices/Solution2.py new file mode 100644 index 0000000000000..23e3f897c6bc2 --- /dev/null +++ b/solution/0400-0499/0413.Arithmetic Slices/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def numberOfArithmeticSlices(self, nums: List[int]) -> int: + ans = cnt = 0 + d = 3000 + for a, b in pairwise(nums): + if b - a == d: + cnt += 1 + else: + d = b - a + cnt = 0 + ans += cnt + return ans diff --git a/solution/0400-0499/0415.Add Strings/Solution.py b/solution/0400-0499/0415.Add Strings/Solution.py index 2f69709f5949f..04bf0b4a3bb54 100644 --- a/solution/0400-0499/0415.Add Strings/Solution.py +++ b/solution/0400-0499/0415.Add Strings/Solution.py @@ -24,8 +24,8 @@ def subStrings(self, num1: str, num2: str) -> str: ans.append(str((c + 10) % 10)) c = 1 if c < 0 else 0 i, j = i - 1, j - 1 - while len(ans) > 1 and ans[-1] == "0": + while len(ans) > 1 and ans[-1] == '0': ans.pop() if neg: - ans.append("-") - return "".join(ans[::-1]) + ans.append('-') + return ''.join(ans[::-1]) diff --git a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.cpp b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.cpp index 4c6d6ee65d353..31be259dba54d 100644 --- a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.cpp +++ b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.cpp @@ -1,19 +1,21 @@ -class Solution { -public: - bool canPartition(vector& nums) { - int s = accumulate(nums.begin(), nums.end(), 0); - if (s % 2 == 1) { - return false; - } - int m = s >> 1; - bool f[m + 1]; - memset(f, false, sizeof(f)); - f[0] = true; - for (int& x : nums) { - for (int j = m; j >= x; --j) { - f[j] |= f[j - x]; - } - } - return f[m]; - } +class Solution { +public: + bool canPartition(vector& nums) { + int s = accumulate(nums.begin(), nums.end(), 0); + if (s % 2 == 1) { + return false; + } + int n = nums.size(); + int m = s >> 1; + bool f[n + 1][m + 1]; + memset(f, false, sizeof(f)); + f[0][0] = true; + for (int i = 1; i <= n; ++i) { + int x = nums[i - 1]; + for (int j = 0; j <= m; ++j) { + f[i][j] = f[i - 1][j] || (j >= x && f[i - 1][j - x]); + } + } + return f[n][m]; + } }; \ No newline at end of file diff --git a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.go b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.go index a65a877e067a5..db6c0f3823701 100644 --- a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.go +++ b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.go @@ -6,13 +6,17 @@ func canPartition(nums []int) bool { if s%2 == 1 { return false } - m := s >> 1 - f := make([]bool, m+1) - f[0] = true - for _, x := range nums { - for j := m; j >= x; j-- { - f[j] = f[j] || f[j-x] + n, m := len(nums), s>>1 + f := make([][]bool, n+1) + for i := range f { + f[i] = make([]bool, m+1) + } + f[0][0] = true + for i := 1; i <= n; i++ { + x := nums[i-1] + for j := 0; j <= m; j++ { + f[i][j] = f[i-1][j] || (j >= x && f[i-1][j-x]) } } - return f[m] + return f[n][m] } \ No newline at end of file diff --git a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.java b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.java index e32f2281ff14f..60cd442778ba8 100644 --- a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.java +++ b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.java @@ -1,21 +1,23 @@ -class Solution { - public boolean canPartition(int[] nums) { - // int s = Arrays.stream(nums).sum(); - int s = 0; - for (int x : nums) { - s += x; - } - if (s % 2 == 1) { - return false; - } - int m = s >> 1; - boolean[] f = new boolean[m + 1]; - f[0] = true; - for (int x : nums) { - for (int j = m; j >= x; --j) { - f[j] |= f[j - x]; - } - } - return f[m]; - } +class Solution { + public boolean canPartition(int[] nums) { + // int s = Arrays.stream(nums).sum(); + int s = 0; + for (int x : nums) { + s += x; + } + if (s % 2 == 1) { + return false; + } + int n = nums.length; + int m = s >> 1; + boolean[][] f = new boolean[n + 1][m + 1]; + f[0][0] = true; + for (int i = 1; i <= n; ++i) { + int x = nums[i - 1]; + for (int j = 0; j <= m; ++j) { + f[i][j] = f[i - 1][j] || (j >= x && f[i - 1][j - x]); + } + } + return f[n][m]; + } } \ No newline at end of file diff --git a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.js b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.js index 30f9f82ea363f..8bed0fdbce431 100644 --- a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.js +++ b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.js @@ -7,13 +7,17 @@ var canPartition = function (nums) { if (s % 2 === 1) { return false; } + const n = nums.length; const m = s >> 1; - const f = Array(m + 1).fill(false); - f[0] = true; - for (const x of nums) { - for (let j = m; j >= x; --j) { - f[j] = f[j] || f[j - x]; + const f = Array(n + 1) + .fill(0) + .map(() => Array(m + 1).fill(false)); + f[0][0] = true; + for (let i = 1; i <= n; ++i) { + const x = nums[i - 1]; + for (let j = 0; j <= m; ++j) { + f[i][j] = f[i - 1][j] || (j >= x && f[i - 1][j - x]); } } - return f[m]; + return f[n][m]; }; diff --git a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.py b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.py index 71bf5fe08a4f7..bef7951ace4bd 100644 --- a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.py +++ b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.py @@ -1,10 +1,12 @@ -class Solution: - def canPartition(self, nums: List[int]) -> bool: - m, mod = divmod(sum(nums), 2) - if mod: - return False - f = [True] + [False] * m - for x in nums: - for j in range(m, x - 1, -1): - f[j] = f[j] or f[j - x] - return f[m] +class Solution: + def canPartition(self, nums: List[int]) -> bool: + m, mod = divmod(sum(nums), 2) + if mod: + return False + n = len(nums) + f = [[False] * (m + 1) for _ in range(n + 1)] + f[0][0] = True + for i, x in enumerate(nums, 1): + for j in range(m + 1): + f[i][j] = f[i - 1][j] or (j >= x and f[i - 1][j - x]) + return f[n][m] diff --git a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.ts b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.ts index db6aec13da9a2..2a447d27d5503 100644 --- a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.ts +++ b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution.ts @@ -3,13 +3,17 @@ function canPartition(nums: number[]): boolean { if (s % 2 === 1) { return false; } + const n = nums.length; const m = s >> 1; - const f: boolean[] = Array(m + 1).fill(false); - f[0] = true; - for (const x of nums) { - for (let j = m; j >= x; --j) { - f[j] = f[j] || f[j - x]; + const f: boolean[][] = Array(n + 1) + .fill(0) + .map(() => Array(m + 1).fill(false)); + f[0][0] = true; + for (let i = 1; i <= n; ++i) { + const x = nums[i - 1]; + for (let j = 0; j <= m; ++j) { + f[i][j] = f[i - 1][j] || (j >= x && f[i - 1][j - x]); } } - return f[m]; + return f[n][m]; } diff --git a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.cpp b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.cpp new file mode 100644 index 0000000000000..0a139cbdf2f72 --- /dev/null +++ b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + bool canPartition(vector& nums) { + int s = accumulate(nums.begin(), nums.end(), 0); + if (s % 2 == 1) { + return false; + } + int m = s >> 1; + bool f[m + 1]; + memset(f, false, sizeof(f)); + f[0] = true; + for (int& x : nums) { + for (int j = m; j >= x; --j) { + f[j] |= f[j - x]; + } + } + return f[m]; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.go b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.go new file mode 100644 index 0000000000000..a65a877e067a5 --- /dev/null +++ b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.go @@ -0,0 +1,18 @@ +func canPartition(nums []int) bool { + s := 0 + for _, x := range nums { + s += x + } + if s%2 == 1 { + return false + } + m := s >> 1 + f := make([]bool, m+1) + f[0] = true + for _, x := range nums { + for j := m; j >= x; j-- { + f[j] = f[j] || f[j-x] + } + } + return f[m] +} \ No newline at end of file diff --git a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.java b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.java new file mode 100644 index 0000000000000..46a68d3d098d5 --- /dev/null +++ b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.java @@ -0,0 +1,21 @@ +class Solution { + public boolean canPartition(int[] nums) { + // int s = Arrays.stream(nums).sum(); + int s = 0; + for (int x : nums) { + s += x; + } + if (s % 2 == 1) { + return false; + } + int m = s >> 1; + boolean[] f = new boolean[m + 1]; + f[0] = true; + for (int x : nums) { + for (int j = m; j >= x; --j) { + f[j] |= f[j - x]; + } + } + return f[m]; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.js b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.js new file mode 100644 index 0000000000000..30f9f82ea363f --- /dev/null +++ b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.js @@ -0,0 +1,19 @@ +/** + * @param {number[]} nums + * @return {boolean} + */ +var canPartition = function (nums) { + const s = nums.reduce((a, b) => a + b, 0); + if (s % 2 === 1) { + return false; + } + const m = s >> 1; + const f = Array(m + 1).fill(false); + f[0] = true; + for (const x of nums) { + for (let j = m; j >= x; --j) { + f[j] = f[j] || f[j - x]; + } + } + return f[m]; +}; diff --git a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.py b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.py new file mode 100644 index 0000000000000..a8442064c4091 --- /dev/null +++ b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def canPartition(self, nums: List[int]) -> bool: + m, mod = divmod(sum(nums), 2) + if mod: + return False + f = [True] + [False] * m + for x in nums: + for j in range(m, x - 1, -1): + f[j] = f[j] or f[j - x] + return f[m] diff --git a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.rs b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.rs new file mode 100644 index 0000000000000..b5e1dfb2d9357 --- /dev/null +++ b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.rs @@ -0,0 +1,33 @@ +impl Solution { + #[allow(dead_code)] + pub fn can_partition(nums: Vec) -> bool { + let mut sum = 0; + for e in &nums { + sum += *e; + } + + if sum % 2 != 0 { + return false; + } + + let m = (sum >> 1) as usize; + + // Here dp[i] means if it can be sum up to `i` for all the number we've traversed through so far + // Which is actually compressing the 2-D dp vector to 1-D + let mut dp: Vec = vec![false; m + 1]; + + // Initialize the dp vector + dp[0] = true; + + // Begin the actual dp process + for e in &nums { + // For every num in nums vector + for i in (*e as usize..=m).rev() { + // Update the current status + dp[i] |= dp[i - (*e as usize)]; + } + } + + dp[m] + } +} diff --git a/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.ts b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.ts new file mode 100644 index 0000000000000..db6aec13da9a2 --- /dev/null +++ b/solution/0400-0499/0416.Partition Equal Subset Sum/Solution2.ts @@ -0,0 +1,15 @@ +function canPartition(nums: number[]): boolean { + const s = nums.reduce((a, b) => a + b, 0); + if (s % 2 === 1) { + return false; + } + const m = s >> 1; + const f: boolean[] = Array(m + 1).fill(false); + f[0] = true; + for (const x of nums) { + for (let j = m; j >= x; --j) { + f[j] = f[j] || f[j - x]; + } + } + return f[m]; +} diff --git a/solution/0400-0499/0417.Pacific Atlantic Water Flow/Solution.py b/solution/0400-0499/0417.Pacific Atlantic Water Flow/Solution.py index a9fb689504dc9..364f0b0d1ac8b 100644 --- a/solution/0400-0499/0417.Pacific Atlantic Water Flow/Solution.py +++ b/solution/0400-0499/0417.Pacific Atlantic Water Flow/Solution.py @@ -1,37 +1,37 @@ -class Solution: - def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: - def bfs(q, vis): - while q: - for _ in range(len(q)): - i, j = q.popleft() - for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]: - x, y = i + a, j + b - if ( - 0 <= x < m - and 0 <= y < n - and (x, y) not in vis - and heights[x][y] >= heights[i][j] - ): - vis.add((x, y)) - q.append((x, y)) - - m, n = len(heights), len(heights[0]) - vis1, vis2 = set(), set() - q1 = deque() - q2 = deque() - for i in range(m): - for j in range(n): - if i == 0 or j == 0: - vis1.add((i, j)) - q1.append((i, j)) - if i == m - 1 or j == n - 1: - vis2.add((i, j)) - q2.append((i, j)) - bfs(q1, vis1) - bfs(q2, vis2) - return [ - (i, j) - for i in range(m) - for j in range(n) - if (i, j) in vis1 and (i, j) in vis2 - ] +class Solution: + def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: + def bfs(q, vis): + while q: + for _ in range(len(q)): + i, j = q.popleft() + for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]: + x, y = i + a, j + b + if ( + 0 <= x < m + and 0 <= y < n + and (x, y) not in vis + and heights[x][y] >= heights[i][j] + ): + vis.add((x, y)) + q.append((x, y)) + + m, n = len(heights), len(heights[0]) + vis1, vis2 = set(), set() + q1 = deque() + q2 = deque() + for i in range(m): + for j in range(n): + if i == 0 or j == 0: + vis1.add((i, j)) + q1.append((i, j)) + if i == m - 1 or j == n - 1: + vis2.add((i, j)) + q2.append((i, j)) + bfs(q1, vis1) + bfs(q2, vis2) + return [ + (i, j) + for i in range(m) + for j in range(n) + if (i, j) in vis1 and (i, j) in vis2 + ] diff --git a/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/Solution.cpp b/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/Solution.cpp index d5deae45089be..533076df6166f 100644 --- a/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/Solution.cpp +++ b/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/Solution.cpp @@ -1,46 +1,46 @@ -class Trie { -public: - Trie* children[2]; - - Trie() - : children{nullptr, nullptr} {} - - void insert(int x) { - Trie* node = this; - for (int i = 30; ~i; --i) { - int v = x >> i & 1; - if (!node->children[v]) { - node->children[v] = new Trie(); - } - node = node->children[v]; - } - } - - int search(int x) { - Trie* node = this; - int ans = 0; - for (int i = 30; ~i; --i) { - int v = x >> i & 1; - if (node->children[v ^ 1]) { - ans |= 1 << i; - node = node->children[v ^ 1]; - } else { - node = node->children[v]; - } - } - return ans; - } -}; - -class Solution { -public: - int findMaximumXOR(vector& nums) { - Trie* trie = new Trie(); - int ans = 0; - for (int x : nums) { - trie->insert(x); - ans = max(ans, trie->search(x)); - } - return ans; - } -}; +class Trie { +public: + Trie* children[2]; + + Trie() + : children{nullptr, nullptr} {} + + void insert(int x) { + Trie* node = this; + for (int i = 30; ~i; --i) { + int v = x >> i & 1; + if (!node->children[v]) { + node->children[v] = new Trie(); + } + node = node->children[v]; + } + } + + int search(int x) { + Trie* node = this; + int ans = 0; + for (int i = 30; ~i; --i) { + int v = x >> i & 1; + if (node->children[v ^ 1]) { + ans |= 1 << i; + node = node->children[v ^ 1]; + } else { + node = node->children[v]; + } + } + return ans; + } +}; + +class Solution { +public: + int findMaximumXOR(vector& nums) { + Trie* trie = new Trie(); + int ans = 0; + for (int x : nums) { + trie->insert(x); + ans = max(ans, trie->search(x)); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/Solution.java b/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/Solution.java index b8cdd79995b12..a3389ce29724a 100644 --- a/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/Solution.java +++ b/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/Solution.java @@ -1,44 +1,44 @@ -class Trie { - private Trie[] children = new Trie[2]; - - public Trie() { - } - - public void insert(int x) { - Trie node = this; - for (int i = 30; i >= 0; --i) { - int v = x >> i & 1; - if (node.children[v] == null) { - node.children[v] = new Trie(); - } - node = node.children[v]; - } - } - - public int search(int x) { - Trie node = this; - int ans = 0; - for (int i = 30; i >= 0; --i) { - int v = x >> i & 1; - if (node.children[v ^ 1] != null) { - ans |= 1 << i; - node = node.children[v ^ 1]; - } else { - node = node.children[v]; - } - } - return ans; - } -} - -class Solution { - public int findMaximumXOR(int[] nums) { - Trie trie = new Trie(); - int ans = 0; - for (int x : nums) { - trie.insert(x); - ans = Math.max(ans, trie.search(x)); - } - return ans; - } +class Trie { + private Trie[] children = new Trie[2]; + + public Trie() { + } + + public void insert(int x) { + Trie node = this; + for (int i = 30; i >= 0; --i) { + int v = x >> i & 1; + if (node.children[v] == null) { + node.children[v] = new Trie(); + } + node = node.children[v]; + } + } + + public int search(int x) { + Trie node = this; + int ans = 0; + for (int i = 30; i >= 0; --i) { + int v = x >> i & 1; + if (node.children[v ^ 1] != null) { + ans |= 1 << i; + node = node.children[v ^ 1]; + } else { + node = node.children[v]; + } + } + return ans; + } +} + +class Solution { + public int findMaximumXOR(int[] nums) { + Trie trie = new Trie(); + int ans = 0; + for (int x : nums) { + trie.insert(x); + ans = Math.max(ans, trie.search(x)); + } + return ans; + } } \ No newline at end of file diff --git a/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/Solution.py b/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/Solution.py index a8ab524ced0f9..50426b31656f0 100644 --- a/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/Solution.py +++ b/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/Solution.py @@ -1,33 +1,33 @@ -class Trie: - __slots__ = ("children",) - - def __init__(self): - self.children: List[Trie | None] = [None, None] - - def insert(self, x: int): - node = self - for i in range(30, -1, -1): - v = x >> i & 1 - if node.children[v] is None: - node.children[v] = Trie() - node = node.children[v] - - def search(self, x: int) -> int: - node = self - ans = 0 - for i in range(30, -1, -1): - v = x >> i & 1 - if node.children[v ^ 1]: - ans |= 1 << i - node = node.children[v ^ 1] - else: - node = node.children[v] - return ans - - -class Solution: - def findMaximumXOR(self, nums: List[int]) -> int: - trie = Trie() - for x in nums: - trie.insert(x) - return max(trie.search(x) for x in nums) +class Trie: + __slots__ = ("children",) + + def __init__(self): + self.children: List[Trie | None] = [None, None] + + def insert(self, x: int): + node = self + for i in range(30, -1, -1): + v = x >> i & 1 + if node.children[v] is None: + node.children[v] = Trie() + node = node.children[v] + + def search(self, x: int) -> int: + node = self + ans = 0 + for i in range(30, -1, -1): + v = x >> i & 1 + if node.children[v ^ 1]: + ans |= 1 << i + node = node.children[v ^ 1] + else: + node = node.children[v] + return ans + + +class Solution: + def findMaximumXOR(self, nums: List[int]) -> int: + trie = Trie() + for x in nums: + trie.insert(x) + return max(trie.search(x) for x in nums) diff --git a/solution/0400-0499/0422.Valid Word Square/Solution.cpp b/solution/0400-0499/0422.Valid Word Square/Solution.cpp index 18ce30165b3d6..a1cff147a643a 100644 --- a/solution/0400-0499/0422.Valid Word Square/Solution.cpp +++ b/solution/0400-0499/0422.Valid Word Square/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - bool validWordSquare(vector& words) { - int m = words.size(); - for (int i = 0; i < m; ++i) { - int n = words[i].size(); - for (int j = 0; j < n; ++j) { - if (j >= m || i >= words[j].size() || words[i][j] != words[j][i]) { - return false; - } - } - } - return true; - } +class Solution { +public: + bool validWordSquare(vector& words) { + int m = words.size(); + for (int i = 0; i < m; ++i) { + int n = words[i].size(); + for (int j = 0; j < n; ++j) { + if (j >= m || i >= words[j].size() || words[i][j] != words[j][i]) { + return false; + } + } + } + return true; + } }; \ No newline at end of file diff --git a/solution/0400-0499/0422.Valid Word Square/Solution.java b/solution/0400-0499/0422.Valid Word Square/Solution.java index 76ab9c4c8f7ea..ec3d2753cf256 100644 --- a/solution/0400-0499/0422.Valid Word Square/Solution.java +++ b/solution/0400-0499/0422.Valid Word Square/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public boolean validWordSquare(List words) { - int m = words.size(); - for (int i = 0; i < m; ++i) { - int n = words.get(i).length(); - for (int j = 0; j < n; ++j) { - if (j >= m || i >= words.get(j).length()) { - return false; - } - if (words.get(i).charAt(j) != words.get(j).charAt(i)) { - return false; - } - } - } - return true; - } +class Solution { + public boolean validWordSquare(List words) { + int m = words.size(); + for (int i = 0; i < m; ++i) { + int n = words.get(i).length(); + for (int j = 0; j < n; ++j) { + if (j >= m || i >= words.get(j).length()) { + return false; + } + if (words.get(i).charAt(j) != words.get(j).charAt(i)) { + return false; + } + } + } + return true; + } } \ No newline at end of file diff --git a/solution/0400-0499/0422.Valid Word Square/Solution.py b/solution/0400-0499/0422.Valid Word Square/Solution.py index 5402ec93fd53e..c2cb805b3ec05 100644 --- a/solution/0400-0499/0422.Valid Word Square/Solution.py +++ b/solution/0400-0499/0422.Valid Word Square/Solution.py @@ -1,8 +1,10 @@ -class Solution: - def validWordSquare(self, words: List[str]) -> bool: - m = len(words) - for i, w in enumerate(words): - for j, c in enumerate(w): - if j >= m or i >= len(words[j]) or c != words[j][i]: - return False - return True +class Solution: + def validWordSquare(self, words: List[str]) -> bool: + m = len(words) + n = max(len(w) for w in words) + if m != n: + return False + for j in range(n): + if words[j] != "".join(w[j] for w in words if j < len(w)): + return False + return True diff --git a/solution/0400-0499/0422.Valid Word Square/Solution2.py b/solution/0400-0499/0422.Valid Word Square/Solution2.py new file mode 100644 index 0000000000000..99c6e2ea27175 --- /dev/null +++ b/solution/0400-0499/0422.Valid Word Square/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def validWordSquare(self, words: List[str]) -> bool: + m = len(words) + for i, w in enumerate(words): + for j, c in enumerate(w): + if j >= m or i >= len(words[j]) or c != words[j][i]: + return False + return True diff --git a/solution/0400-0499/0427.Construct Quad Tree/Solution.cpp b/solution/0400-0499/0427.Construct Quad Tree/Solution.cpp index 2d2a30ba26fa8..f9c1d9f004406 100644 --- a/solution/0400-0499/0427.Construct Quad Tree/Solution.cpp +++ b/solution/0400-0499/0427.Construct Quad Tree/Solution.cpp @@ -1,4 +1,4 @@ -/* +/* // Definition for a QuadTree node. class Node { public: diff --git a/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution.py b/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution.py index f8476bdca97a8..c9e2d68b7cd64 100644 --- a/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution.py +++ b/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution.py @@ -1,23 +1,23 @@ -""" -# Definition for a Node. -class Node: - def __init__(self, val=None, children=None): - self.val = val - self.children = children -""" - - -class Solution: - def levelOrder(self, root: 'Node') -> List[List[int]]: - ans = [] - if root is None: - return ans - q = deque([root]) - while q: - t = [] - for _ in range(len(q)): - root = q.popleft() - t.append(root.val) - q.extend(root.children) - ans.append(t) - return ans +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" + + +class Solution: + def levelOrder(self, root: 'Node') -> List[List[int]]: + ans = [] + if root is None: + return ans + q = deque([root]) + while q: + t = [] + for _ in range(len(q)): + root = q.popleft() + t.append(root.val) + q.extend(root.children) + ans.append(t) + return ans diff --git a/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution2.cpp b/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution2.cpp new file mode 100644 index 0000000000000..e0924bb6f0831 --- /dev/null +++ b/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution2.cpp @@ -0,0 +1,35 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { +public: + vector> levelOrder(Node* root) { + vector> ans; + dfs(root, 0, ans); + return ans; + } + + void dfs(Node* root, int i, vector>& ans) { + if (!root) return; + if (ans.size() <= i) ans.push_back({}); + ans[i++].push_back(root->val); + for (Node* child : root->children) dfs(child, i, ans); + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution2.go b/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution2.go new file mode 100644 index 0000000000000..bc6d7de0607d7 --- /dev/null +++ b/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution2.go @@ -0,0 +1,26 @@ +/** + * Definition for a Node. + * type Node struct { + * Val int + * Children []*Node + * } + */ + +func levelOrder(root *Node) [][]int { + var ans [][]int + var dfs func(root *Node, i int) + dfs = func(root *Node, i int) { + if root == nil { + return + } + if len(ans) <= i { + ans = append(ans, []int{}) + } + ans[i] = append(ans[i], root.Val) + for _, child := range root.Children { + dfs(child, i+1) + } + } + dfs(root, 0) + return ans +} \ No newline at end of file diff --git a/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution2.java b/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution2.java new file mode 100644 index 0000000000000..6b4bbc7de02a8 --- /dev/null +++ b/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution2.java @@ -0,0 +1,39 @@ +/* +// Definition for a Node. +class Node { + public int val; + public List children; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, List _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { + public List> levelOrder(Node root) { + List> ans = new ArrayList<>(); + dfs(root, 0, ans); + return ans; + } + + private void dfs(Node root, int i, List> ans) { + if (root == null) { + return; + } + if (ans.size() <= i) { + ans.add(new ArrayList<>()); + } + ans.get(i++).add(root.val); + for (Node child : root.children) { + dfs(child, i, ans); + } + } +} \ No newline at end of file diff --git a/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution2.py b/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution2.py new file mode 100644 index 0000000000000..1ce285876da5d --- /dev/null +++ b/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution2.py @@ -0,0 +1,23 @@ +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" + + +class Solution: + def levelOrder(self, root: 'Node') -> List[List[int]]: + def dfs(root, i): + if root is None: + return + if len(ans) <= i: + ans.append([]) + ans[i].append(root.val) + for child in root.children: + dfs(child, i + 1) + + ans = [] + dfs(root, 0) + return ans diff --git a/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution2.ts b/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution2.ts new file mode 100644 index 0000000000000..e23489af4f796 --- /dev/null +++ b/solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution2.ts @@ -0,0 +1,28 @@ +/** + * Definition for node. + * class Node { + * val: number + * children: Node[] + * constructor(val?: number) { + * this.val = (val===undefined ? 0 : val) + * this.children = [] + * } + * } + */ + +function levelOrder(root: Node | null): number[][] { + const res = []; + const dfs = (root: Node | null, depth: number) => { + if (root == null) { + return; + } + if (res.length <= depth) { + res.push([]); + } + const { val, children } = root; + res[depth].push(val); + children.forEach(node => dfs(node, depth + 1)); + }; + dfs(root, 0); + return res; +} diff --git a/solution/0400-0499/0430.Flatten a Multilevel Doubly Linked List/Solution.cpp b/solution/0400-0499/0430.Flatten a Multilevel Doubly Linked List/Solution.cpp index 7bc299f974c6c..67018df648616 100644 --- a/solution/0400-0499/0430.Flatten a Multilevel Doubly Linked List/Solution.cpp +++ b/solution/0400-0499/0430.Flatten a Multilevel Doubly Linked List/Solution.cpp @@ -1,47 +1,47 @@ -/* -// Definition for a Node. -class Node { -public: - int val; - Node* prev; - Node* next; - Node* child; -}; -*/ - -class Solution { -public: - Node* flatten(Node* head) { - flattenGetTail(head); - return head; - } - - Node* flattenGetTail(Node* head) { - Node* cur = head; - Node* tail = nullptr; - - while (cur) { - Node* next = cur->next; - if (cur->child) { - Node* child = cur->child; - Node* childTail = flattenGetTail(cur->child); - - cur->child = nullptr; - cur->next = child; - child->prev = cur; - childTail->next = next; - - if (next) - next->prev = childTail; - - tail = childTail; - } else { - tail = cur; - } - - cur = next; - } - - return tail; - } +/* +// Definition for a Node. +class Node { +public: + int val; + Node* prev; + Node* next; + Node* child; +}; +*/ + +class Solution { +public: + Node* flatten(Node* head) { + flattenGetTail(head); + return head; + } + + Node* flattenGetTail(Node* head) { + Node* cur = head; + Node* tail = nullptr; + + while (cur) { + Node* next = cur->next; + if (cur->child) { + Node* child = cur->child; + Node* childTail = flattenGetTail(cur->child); + + cur->child = nullptr; + cur->next = child; + child->prev = cur; + childTail->next = next; + + if (next) + next->prev = childTail; + + tail = childTail; + } else { + tail = cur; + } + + cur = next; + } + + return tail; + } }; \ No newline at end of file diff --git a/solution/0400-0499/0432.All O`one Data Structure/Solution.py b/solution/0400-0499/0432.All O`one Data Structure/Solution.py index 05a8618dd4958..f14c9244a119a 100644 --- a/solution/0400-0499/0432.All O`one Data Structure/Solution.py +++ b/solution/0400-0499/0432.All O`one Data Structure/Solution.py @@ -1,75 +1,75 @@ -class Node: - def __init__(self, key='', cnt=0): - self.prev = None - self.next = None - self.cnt = cnt - self.keys = {key} - - def insert(self, node): - node.prev = self - node.next = self.next - node.prev.next = node - node.next.prev = node - return node - - def remove(self): - self.prev.next = self.next - self.next.prev = self.prev - - -class AllOne: - def __init__(self): - self.root = Node() - self.root.next = self.root - self.root.prev = self.root - self.nodes = {} - - def inc(self, key: str) -> None: - root, nodes = self.root, self.nodes - if key not in nodes: - if root.next == root or root.next.cnt > 1: - nodes[key] = root.insert(Node(key, 1)) - else: - root.next.keys.add(key) - nodes[key] = root.next - else: - curr = nodes[key] - next = curr.next - if next == root or next.cnt > curr.cnt + 1: - nodes[key] = curr.insert(Node(key, curr.cnt + 1)) - else: - next.keys.add(key) - nodes[key] = next - curr.keys.discard(key) - if not curr.keys: - curr.remove() - - def dec(self, key: str) -> None: - root, nodes = self.root, self.nodes - curr = nodes[key] - if curr.cnt == 1: - nodes.pop(key) - else: - prev = curr.prev - if prev == root or prev.cnt < curr.cnt - 1: - nodes[key] = prev.insert(Node(key, curr.cnt - 1)) - else: - prev.keys.add(key) - nodes[key] = prev - curr.keys.discard(key) - if not curr.keys: - curr.remove() - - def getMaxKey(self) -> str: - return next(iter(self.root.prev.keys)) - - def getMinKey(self) -> str: - return next(iter(self.root.next.keys)) - - -# Your AllOne object will be instantiated and called as such: -# obj = AllOne() -# obj.inc(key) -# obj.dec(key) -# param_3 = obj.getMaxKey() -# param_4 = obj.getMinKey() +class Node: + def __init__(self, key='', cnt=0): + self.prev = None + self.next = None + self.cnt = cnt + self.keys = {key} + + def insert(self, node): + node.prev = self + node.next = self.next + node.prev.next = node + node.next.prev = node + return node + + def remove(self): + self.prev.next = self.next + self.next.prev = self.prev + + +class AllOne: + def __init__(self): + self.root = Node() + self.root.next = self.root + self.root.prev = self.root + self.nodes = {} + + def inc(self, key: str) -> None: + root, nodes = self.root, self.nodes + if key not in nodes: + if root.next == root or root.next.cnt > 1: + nodes[key] = root.insert(Node(key, 1)) + else: + root.next.keys.add(key) + nodes[key] = root.next + else: + curr = nodes[key] + next = curr.next + if next == root or next.cnt > curr.cnt + 1: + nodes[key] = curr.insert(Node(key, curr.cnt + 1)) + else: + next.keys.add(key) + nodes[key] = next + curr.keys.discard(key) + if not curr.keys: + curr.remove() + + def dec(self, key: str) -> None: + root, nodes = self.root, self.nodes + curr = nodes[key] + if curr.cnt == 1: + nodes.pop(key) + else: + prev = curr.prev + if prev == root or prev.cnt < curr.cnt - 1: + nodes[key] = prev.insert(Node(key, curr.cnt - 1)) + else: + prev.keys.add(key) + nodes[key] = prev + curr.keys.discard(key) + if not curr.keys: + curr.remove() + + def getMaxKey(self) -> str: + return next(iter(self.root.prev.keys)) + + def getMinKey(self) -> str: + return next(iter(self.root.next.keys)) + + +# Your AllOne object will be instantiated and called as such: +# obj = AllOne() +# obj.inc(key) +# obj.dec(key) +# param_3 = obj.getMaxKey() +# param_4 = obj.getMinKey() diff --git a/solution/0400-0499/0433.Minimum Genetic Mutation/Solution2.cpp b/solution/0400-0499/0433.Minimum Genetic Mutation/Solution2.cpp new file mode 100644 index 0000000000000..3e5eece847361 --- /dev/null +++ b/solution/0400-0499/0433.Minimum Genetic Mutation/Solution2.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int ans; + string seq = "ACGT"; + + int minMutation(string start, string end, vector& bank) { + unordered_set s; + for (auto& b : bank) s.insert(b); + ans = INT_MAX; + s.erase(start); + dfs(start, end, s, 0); + return ans == INT_MAX ? -1 : ans; + } + + void dfs(string& start, string& end, unordered_set& s, int t) { + if (start == end) { + ans = min(ans, t); + return; + } + for (int i = 0; i < start.size(); ++i) { + for (char& c : seq) { + if (start[i] == c) continue; + string nxt = start.substr(0, i) + c + start.substr(i + 1, start.size() - i - 1); + if (s.count(nxt)) { + s.erase(nxt); + dfs(nxt, end, s, t + 1); + } + } + } + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0433.Minimum Genetic Mutation/Solution2.go b/solution/0400-0499/0433.Minimum Genetic Mutation/Solution2.go new file mode 100644 index 0000000000000..a5f5ae5d60ad4 --- /dev/null +++ b/solution/0400-0499/0433.Minimum Genetic Mutation/Solution2.go @@ -0,0 +1,35 @@ +func minMutation(start string, end string, bank []string) int { + s := make(map[string]bool) + for _, b := range bank { + s[b] = true + } + ans := math.MaxInt32 + s[start] = false + seq := []rune{'A', 'C', 'G', 'T'} + var dfs func(start string, t int) + dfs = func(start string, t int) { + if start == end { + if ans > t { + ans = t + } + return + } + for i, x := range start { + for _, y := range seq { + if x == y { + continue + } + nxt := start[:i] + string(y) + start[i+1:] + if s[nxt] { + s[nxt] = false + dfs(nxt, t+1) + } + } + } + } + dfs(start, 0) + if ans == math.MaxInt32 { + return -1 + } + return ans +} \ No newline at end of file diff --git a/solution/0400-0499/0433.Minimum Genetic Mutation/Solution2.java b/solution/0400-0499/0433.Minimum Genetic Mutation/Solution2.java new file mode 100644 index 0000000000000..e7196592d8561 --- /dev/null +++ b/solution/0400-0499/0433.Minimum Genetic Mutation/Solution2.java @@ -0,0 +1,35 @@ +class Solution { + private int ans; + private Set s; + private static final char[] seq = {'A', 'C', 'G', 'T'}; + + public int minMutation(String start, String end, String[] bank) { + s = new HashSet<>(); + for (String b : bank) { + s.add(b); + } + ans = Integer.MAX_VALUE; + dfs(start, end, 0); + s.remove(start); + return ans == Integer.MAX_VALUE ? -1 : ans; + } + + private void dfs(String start, String end, int t) { + if (start.equals(end)) { + ans = Math.min(ans, t); + return; + } + for (int i = 0; i < start.length(); ++i) { + for (char c : seq) { + if (start.charAt(i) == c) { + continue; + } + String nxt = start.substring(0, i) + c + start.substring(i + 1); + if (s.contains(nxt)) { + s.remove(nxt); + dfs(nxt, end, t + 1); + } + } + } + } +} \ No newline at end of file diff --git a/solution/0400-0499/0433.Minimum Genetic Mutation/Solution2.py b/solution/0400-0499/0433.Minimum Genetic Mutation/Solution2.py new file mode 100644 index 0000000000000..6c971f3def542 --- /dev/null +++ b/solution/0400-0499/0433.Minimum Genetic Mutation/Solution2.py @@ -0,0 +1,19 @@ +class Solution: + def minMutation(self, start: str, end: str, bank: List[str]) -> int: + def dfs(start, t): + if start == end: + nonlocal ans + ans = min(ans, t) + return + for i, x in enumerate(start): + for y in 'ACGT': + if x != y: + nxt = start[:i] + y + start[i + 1 :] + if nxt in s: + s.remove(nxt) + dfs(nxt, t + 1) + + s = set(bank) + ans = inf + dfs(start, 0) + return -1 if ans == inf else ans diff --git a/solution/0400-0499/0434.Number of Segments in a String/Solution.cpp b/solution/0400-0499/0434.Number of Segments in a String/Solution.cpp index 0319baf0474f2..0ce694012e9cd 100644 --- a/solution/0400-0499/0434.Number of Segments in a String/Solution.cpp +++ b/solution/0400-0499/0434.Number of Segments in a String/Solution.cpp @@ -1,12 +1,9 @@ -class Solution { +class Solution { public: int countSegments(string s) { int ans = 0; - for (int i = 0; i < s.size(); ++i) { - if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) { - ++ans; - } - } + istringstream ss(s); + while (ss >> s) ++ans; return ans; } }; \ No newline at end of file diff --git a/solution/0400-0499/0434.Number of Segments in a String/Solution.go b/solution/0400-0499/0434.Number of Segments in a String/Solution.go index 410670850f28c..103c5df7a3a48 100644 --- a/solution/0400-0499/0434.Number of Segments in a String/Solution.go +++ b/solution/0400-0499/0434.Number of Segments in a String/Solution.go @@ -1,7 +1,7 @@ func countSegments(s string) int { ans := 0 - for i, c := range s { - if c != ' ' && (i == 0 || s[i-1] == ' ') { + for _, t := range strings.Split(s, " ") { + if len(t) > 0 { ans++ } } diff --git a/solution/0400-0499/0434.Number of Segments in a String/Solution.java b/solution/0400-0499/0434.Number of Segments in a String/Solution.java index 82fc95f3adcbb..f381bce3a057a 100644 --- a/solution/0400-0499/0434.Number of Segments in a String/Solution.java +++ b/solution/0400-0499/0434.Number of Segments in a String/Solution.java @@ -1,8 +1,8 @@ class Solution { public int countSegments(String s) { int ans = 0; - for (int i = 0; i < s.length(); ++i) { - if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) { + for (String t : s.split(" ")) { + if (!"".equals(t)) { ++ans; } } diff --git a/solution/0400-0499/0434.Number of Segments in a String/Solution.php b/solution/0400-0499/0434.Number of Segments in a String/Solution.php index 3b7b8fae96255..ef7b584f63f0d 100644 --- a/solution/0400-0499/0434.Number of Segments in a String/Solution.php +++ b/solution/0400-0499/0434.Number of Segments in a String/Solution.php @@ -13,4 +13,4 @@ function countSegments($s) { } return $cnt; } -} \ No newline at end of file +} diff --git a/solution/0400-0499/0434.Number of Segments in a String/Solution.py b/solution/0400-0499/0434.Number of Segments in a String/Solution.py index 1356a2146c682..8b9b6ce070aa1 100644 --- a/solution/0400-0499/0434.Number of Segments in a String/Solution.py +++ b/solution/0400-0499/0434.Number of Segments in a String/Solution.py @@ -1,7 +1,3 @@ class Solution: def countSegments(self, s: str) -> int: - ans = 0 - for i, c in enumerate(s): - if c != ' ' and (i == 0 or s[i - 1] == ' '): - ans += 1 - return ans + return len(s.split()) diff --git a/solution/0400-0499/0434.Number of Segments in a String/Solution2.cpp b/solution/0400-0499/0434.Number of Segments in a String/Solution2.cpp new file mode 100644 index 0000000000000..8b6905e4aa32f --- /dev/null +++ b/solution/0400-0499/0434.Number of Segments in a String/Solution2.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int countSegments(string s) { + int ans = 0; + for (int i = 0; i < s.size(); ++i) { + if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) { + ++ans; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0434.Number of Segments in a String/Solution2.go b/solution/0400-0499/0434.Number of Segments in a String/Solution2.go new file mode 100644 index 0000000000000..410670850f28c --- /dev/null +++ b/solution/0400-0499/0434.Number of Segments in a String/Solution2.go @@ -0,0 +1,9 @@ +func countSegments(s string) int { + ans := 0 + for i, c := range s { + if c != ' ' && (i == 0 || s[i-1] == ' ') { + ans++ + } + } + return ans +} \ No newline at end of file diff --git a/solution/0400-0499/0434.Number of Segments in a String/Solution2.java b/solution/0400-0499/0434.Number of Segments in a String/Solution2.java new file mode 100644 index 0000000000000..82fc95f3adcbb --- /dev/null +++ b/solution/0400-0499/0434.Number of Segments in a String/Solution2.java @@ -0,0 +1,11 @@ +class Solution { + public int countSegments(String s) { + int ans = 0; + for (int i = 0; i < s.length(); ++i) { + if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) { + ++ans; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0434.Number of Segments in a String/Solution2.py b/solution/0400-0499/0434.Number of Segments in a String/Solution2.py new file mode 100644 index 0000000000000..1356a2146c682 --- /dev/null +++ b/solution/0400-0499/0434.Number of Segments in a String/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def countSegments(self, s: str) -> int: + ans = 0 + for i, c in enumerate(s): + if c != ' ' and (i == 0 or s[i - 1] == ' '): + ans += 1 + return ans diff --git a/solution/0400-0499/0435.Non-overlapping Intervals/Solution.cpp b/solution/0400-0499/0435.Non-overlapping Intervals/Solution.cpp index 4bab38c48b5cd..e754f1db36a3a 100644 --- a/solution/0400-0499/0435.Non-overlapping Intervals/Solution.cpp +++ b/solution/0400-0499/0435.Non-overlapping Intervals/Solution.cpp @@ -1,14 +1,14 @@ -class Solution { -public: - int eraseOverlapIntervals(vector>& intervals) { - sort(intervals.begin(), intervals.end(), [](const auto& a, const auto& b) { return a[1] < b[1]; }); - int ans = 0, t = intervals[0][1]; - for (int i = 1; i < intervals.size(); ++i) { - if (t <= intervals[i][0]) - t = intervals[i][1]; - else - ++ans; - } - return ans; - } +class Solution { +public: + int eraseOverlapIntervals(vector>& intervals) { + sort(intervals.begin(), intervals.end(), [](const auto& a, const auto& b) { return a[1] < b[1]; }); + int ans = 0, t = intervals[0][1]; + for (int i = 1; i < intervals.size(); ++i) { + if (t <= intervals[i][0]) + t = intervals[i][1]; + else + ++ans; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0400-0499/0435.Non-overlapping Intervals/Solution.java b/solution/0400-0499/0435.Non-overlapping Intervals/Solution.java index 480ded3eef40a..06940f1be5f62 100644 --- a/solution/0400-0499/0435.Non-overlapping Intervals/Solution.java +++ b/solution/0400-0499/0435.Non-overlapping Intervals/Solution.java @@ -1,14 +1,14 @@ -class Solution { - public int eraseOverlapIntervals(int[][] intervals) { - Arrays.sort(intervals, Comparator.comparingInt(a -> a[1])); - int t = intervals[0][1], ans = 0; - for (int i = 1; i < intervals.length; ++i) { - if (intervals[i][0] >= t) { - t = intervals[i][1]; - } else { - ++ans; - } - } - return ans; - } +class Solution { + public int eraseOverlapIntervals(int[][] intervals) { + Arrays.sort(intervals, Comparator.comparingInt(a -> a[1])); + int t = intervals[0][1], ans = 0; + for (int i = 1; i < intervals.length; ++i) { + if (intervals[i][0] >= t) { + t = intervals[i][1]; + } else { + ++ans; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0400-0499/0435.Non-overlapping Intervals/Solution.py b/solution/0400-0499/0435.Non-overlapping Intervals/Solution.py index 6c33a91120653..d599421163958 100644 --- a/solution/0400-0499/0435.Non-overlapping Intervals/Solution.py +++ b/solution/0400-0499/0435.Non-overlapping Intervals/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: - intervals.sort(key=lambda x: x[1]) - ans, t = 0, intervals[0][1] - for s, e in intervals[1:]: - if s >= t: - t = e - else: - ans += 1 - return ans +class Solution: + def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: + intervals.sort(key=lambda x: x[1]) + ans, t = 0, intervals[0][1] + for s, e in intervals[1:]: + if s >= t: + t = e + else: + ans += 1 + return ans diff --git a/solution/0400-0499/0435.Non-overlapping Intervals/Solution2.java b/solution/0400-0499/0435.Non-overlapping Intervals/Solution2.java new file mode 100644 index 0000000000000..3db74098111b5 --- /dev/null +++ b/solution/0400-0499/0435.Non-overlapping Intervals/Solution2.java @@ -0,0 +1,32 @@ +class Solution { + public int eraseOverlapIntervals(int[][] intervals) { + Arrays.sort(intervals, (a, b) -> { + if (a[0] != b[0]) { + return a[0] - b[0]; + } + return a[1] - b[1]; + }); + int n = intervals.length; + int[] d = new int[n + 1]; + d[1] = intervals[0][1]; + int size = 1; + for (int i = 1; i < n; ++i) { + int s = intervals[i][0], e = intervals[i][1]; + if (s >= d[size]) { + d[++size] = e; + } else { + int left = 1, right = size; + while (left < right) { + int mid = (left + right) >> 1; + if (d[mid] >= s) { + right = mid; + } else { + left = mid + 1; + } + } + d[left] = Math.min(d[left], e); + } + } + return n - size; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0435.Non-overlapping Intervals/Solution2.py b/solution/0400-0499/0435.Non-overlapping Intervals/Solution2.py new file mode 100644 index 0000000000000..8b41845673b4f --- /dev/null +++ b/solution/0400-0499/0435.Non-overlapping Intervals/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: + intervals.sort() + d = [intervals[0][1]] + for s, e in intervals[1:]: + if s >= d[-1]: + d.append(e) + else: + idx = bisect_left(d, s) + d[idx] = min(d[idx], e) + return len(intervals) - len(d) diff --git a/solution/0400-0499/0438.Find All Anagrams in a String/Solution.cpp b/solution/0400-0499/0438.Find All Anagrams in a String/Solution.cpp index 4bde1ddb9ff31..de58b9525fad4 100644 --- a/solution/0400-0499/0438.Find All Anagrams in a String/Solution.cpp +++ b/solution/0400-0499/0438.Find All Anagrams in a String/Solution.cpp @@ -1,26 +1,26 @@ -class Solution { -public: - vector findAnagrams(string s, string p) { - int m = s.size(), n = p.size(); - vector ans; - if (m < n) { - return ans; - } - vector cnt1(26); - for (char& c : p) { - ++cnt1[c - 'a']; - } - vector cnt2(26); - for (int i = 0; i < n - 1; ++i) { - ++cnt2[s[i] - 'a']; - } - for (int i = n - 1; i < m; ++i) { - ++cnt2[s[i] - 'a']; - if (cnt1 == cnt2) { - ans.push_back(i - n + 1); - } - --cnt2[s[i - n + 1] - 'a']; - } - return ans; - } +class Solution { +public: + vector findAnagrams(string s, string p) { + int m = s.size(), n = p.size(); + vector ans; + if (m < n) { + return ans; + } + vector cnt1(26); + for (char& c : p) { + ++cnt1[c - 'a']; + } + vector cnt2(26); + for (int i = 0; i < n - 1; ++i) { + ++cnt2[s[i] - 'a']; + } + for (int i = n - 1; i < m; ++i) { + ++cnt2[s[i] - 'a']; + if (cnt1 == cnt2) { + ans.push_back(i - n + 1); + } + --cnt2[s[i - n + 1] - 'a']; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0400-0499/0438.Find All Anagrams in a String/Solution.cs b/solution/0400-0499/0438.Find All Anagrams in a String/Solution.cs index 234156321a416..3efb4a25ec937 100644 --- a/solution/0400-0499/0438.Find All Anagrams in a String/Solution.cs +++ b/solution/0400-0499/0438.Find All Anagrams in a String/Solution.cs @@ -1,25 +1,25 @@ -public class Solution { - public IList FindAnagrams(string s, string p) { - int m = s.Length, n = p.Length; - IList ans = new List(); - if (m < n) { - return ans; - } - int[] cnt1 = new int[26]; - int[] cnt2 = new int[26]; - for (int i = 0; i < n; ++i) { - ++cnt1[p[i] - 'a']; - } - for (int i = 0, j = 0; i < m; ++i) { - int k = s[i] - 'a'; - ++cnt2[k]; - while (cnt2[k] > cnt1[k]) { - --cnt2[s[j++] - 'a']; - } - if (i - j + 1 == n) { - ans.Add(j); - } - } - return ans; - } -} \ No newline at end of file +public class Solution { + public IList FindAnagrams(string s, string p) { + int m = s.Length, n = p.Length; + IList ans = new List(); + if (m < n) { + return ans; + } + int[] cnt1 = new int[26]; + int[] cnt2 = new int[26]; + for (int i = 0; i < n; ++i) { + ++cnt1[p[i] - 'a']; + } + for (int i = 0, j = 0; i < m; ++i) { + int k = s[i] - 'a'; + ++cnt2[k]; + while (cnt2[k] > cnt1[k]) { + --cnt2[s[j++] - 'a']; + } + if (i - j + 1 == n) { + ans.Add(j); + } + } + return ans; + } +} diff --git a/solution/0400-0499/0438.Find All Anagrams in a String/Solution.java b/solution/0400-0499/0438.Find All Anagrams in a String/Solution.java index 9a075ffe5e377..44bcf95dc95d2 100644 --- a/solution/0400-0499/0438.Find All Anagrams in a String/Solution.java +++ b/solution/0400-0499/0438.Find All Anagrams in a String/Solution.java @@ -1,25 +1,25 @@ -class Solution { - public List findAnagrams(String s, String p) { - int m = s.length(), n = p.length(); - List ans = new ArrayList<>(); - if (m < n) { - return ans; - } - int[] cnt1 = new int[26]; - for (int i = 0; i < n; ++i) { - ++cnt1[p.charAt(i) - 'a']; - } - int[] cnt2 = new int[26]; - for (int i = 0; i < n - 1; ++i) { - ++cnt2[s.charAt(i) - 'a']; - } - for (int i = n - 1; i < m; ++i) { - ++cnt2[s.charAt(i) - 'a']; - if (Arrays.equals(cnt1, cnt2)) { - ans.add(i - n + 1); - } - --cnt2[s.charAt(i - n + 1) - 'a']; - } - return ans; - } +class Solution { + public List findAnagrams(String s, String p) { + int m = s.length(), n = p.length(); + List ans = new ArrayList<>(); + if (m < n) { + return ans; + } + int[] cnt1 = new int[26]; + for (int i = 0; i < n; ++i) { + ++cnt1[p.charAt(i) - 'a']; + } + int[] cnt2 = new int[26]; + for (int i = 0; i < n - 1; ++i) { + ++cnt2[s.charAt(i) - 'a']; + } + for (int i = n - 1; i < m; ++i) { + ++cnt2[s.charAt(i) - 'a']; + if (Arrays.equals(cnt1, cnt2)) { + ans.add(i - n + 1); + } + --cnt2[s.charAt(i - n + 1) - 'a']; + } + return ans; + } } \ No newline at end of file diff --git a/solution/0400-0499/0438.Find All Anagrams in a String/Solution.py b/solution/0400-0499/0438.Find All Anagrams in a String/Solution.py index 25f9fea7dabf7..760208449bf50 100644 --- a/solution/0400-0499/0438.Find All Anagrams in a String/Solution.py +++ b/solution/0400-0499/0438.Find All Anagrams in a String/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def findAnagrams(self, s: str, p: str) -> List[int]: - m, n = len(s), len(p) - ans = [] - if m < n: - return ans - cnt1 = Counter(p) - cnt2 = Counter(s[: n - 1]) - for i in range(n - 1, m): - cnt2[s[i]] += 1 - if cnt1 == cnt2: - ans.append(i - n + 1) - cnt2[s[i - n + 1]] -= 1 - return ans +class Solution: + def findAnagrams(self, s: str, p: str) -> List[int]: + m, n = len(s), len(p) + ans = [] + if m < n: + return ans + cnt1 = Counter(p) + cnt2 = Counter(s[: n - 1]) + for i in range(n - 1, m): + cnt2[s[i]] += 1 + if cnt1 == cnt2: + ans.append(i - n + 1) + cnt2[s[i - n + 1]] -= 1 + return ans diff --git a/solution/0400-0499/0438.Find All Anagrams in a String/Solution2.cpp b/solution/0400-0499/0438.Find All Anagrams in a String/Solution2.cpp new file mode 100644 index 0000000000000..28c54ec8bc62a --- /dev/null +++ b/solution/0400-0499/0438.Find All Anagrams in a String/Solution2.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + vector findAnagrams(string s, string p) { + int m = s.size(), n = p.size(); + vector ans; + if (m < n) { + return ans; + } + vector cnt1(26); + for (char& c : p) { + ++cnt1[c - 'a']; + } + vector cnt2(26); + for (int i = 0, j = 0; i < m; ++i) { + int k = s[i] - 'a'; + ++cnt2[k]; + while (cnt2[k] > cnt1[k]) { + --cnt2[s[j++] - 'a']; + } + if (i - j + 1 == n) { + ans.push_back(j); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0438.Find All Anagrams in a String/Solution2.go b/solution/0400-0499/0438.Find All Anagrams in a String/Solution2.go new file mode 100644 index 0000000000000..6eb88e98375f9 --- /dev/null +++ b/solution/0400-0499/0438.Find All Anagrams in a String/Solution2.go @@ -0,0 +1,23 @@ +func findAnagrams(s string, p string) (ans []int) { + m, n := len(s), len(p) + if m < n { + return + } + cnt1 := [26]int{} + cnt2 := [26]int{} + for _, c := range p { + cnt1[c-'a']++ + } + j := 0 + for i, c := range s { + cnt2[c-'a']++ + for cnt2[c-'a'] > cnt1[c-'a'] { + cnt2[s[j]-'a']-- + j++ + } + if i-j+1 == n { + ans = append(ans, j) + } + } + return +} \ No newline at end of file diff --git a/solution/0400-0499/0438.Find All Anagrams in a String/Solution2.java b/solution/0400-0499/0438.Find All Anagrams in a String/Solution2.java new file mode 100644 index 0000000000000..d0e898699e86d --- /dev/null +++ b/solution/0400-0499/0438.Find All Anagrams in a String/Solution2.java @@ -0,0 +1,25 @@ +class Solution { + public List findAnagrams(String s, String p) { + int m = s.length(), n = p.length(); + List ans = new ArrayList<>(); + if (m < n) { + return ans; + } + int[] cnt1 = new int[26]; + for (int i = 0; i < n; ++i) { + ++cnt1[p.charAt(i) - 'a']; + } + int[] cnt2 = new int[26]; + for (int i = 0, j = 0; i < m; ++i) { + int k = s.charAt(i) - 'a'; + ++cnt2[k]; + while (cnt2[k] > cnt1[k]) { + --cnt2[s.charAt(j++) - 'a']; + } + if (i - j + 1 == n) { + ans.add(j); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0438.Find All Anagrams in a String/Solution2.py b/solution/0400-0499/0438.Find All Anagrams in a String/Solution2.py new file mode 100644 index 0000000000000..56cc3e8c3ff51 --- /dev/null +++ b/solution/0400-0499/0438.Find All Anagrams in a String/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def findAnagrams(self, s: str, p: str) -> List[int]: + m, n = len(s), len(p) + ans = [] + if m < n: + return ans + cnt1 = Counter(p) + cnt2 = Counter() + j = 0 + for i, c in enumerate(s): + cnt2[c] += 1 + while cnt2[c] > cnt1[c]: + cnt2[s[j]] -= 1 + j += 1 + if i - j + 1 == n: + ans.append(j) + return ans diff --git a/solution/0400-0499/0438.Find All Anagrams in a String/Solution2.ts b/solution/0400-0499/0438.Find All Anagrams in a String/Solution2.ts new file mode 100644 index 0000000000000..2b6a34763541a --- /dev/null +++ b/solution/0400-0499/0438.Find All Anagrams in a String/Solution2.ts @@ -0,0 +1,25 @@ +function findAnagrams(s: string, p: string): number[] { + const m = s.length; + const n = p.length; + const ans: number[] = []; + if (m < n) { + return ans; + } + const cnt1: number[] = new Array(26).fill(0); + const cnt2: number[] = new Array(26).fill(0); + const idx = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); + for (const c of p) { + ++cnt1[idx(c)]; + } + for (let i = 0, j = 0; i < m; ++i) { + const k = idx(s[i]); + ++cnt2[k]; + while (cnt2[k] > cnt1[k]) { + --cnt2[idx(s[j++])]; + } + if (i - j + 1 === n) { + ans.push(j); + } + } + return ans; +} diff --git a/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/Solution.cpp b/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/Solution.cpp index 27c94a4caa883..8ff2da4406189 100644 --- a/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/Solution.cpp +++ b/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/Solution.cpp @@ -1,32 +1,32 @@ -class Solution { -public: - int n; - - int findKthNumber(int n, int k) { - this->n = n; - --k; - long long curr = 1; - while (k) { - int cnt = count(curr); - if (k >= cnt) { - k -= cnt; - ++curr; - } else { - --k; - curr *= 10; - } - } - return (int) curr; - } - - int count(long long curr) { - long long next = curr + 1; - int cnt = 0; - while (curr <= n) { - cnt += min(n - curr + 1, next - curr); - next *= 10; - curr *= 10; - } - return cnt; - } +class Solution { +public: + int n; + + int findKthNumber(int n, int k) { + this->n = n; + --k; + long long curr = 1; + while (k) { + int cnt = count(curr); + if (k >= cnt) { + k -= cnt; + ++curr; + } else { + --k; + curr *= 10; + } + } + return (int) curr; + } + + int count(long long curr) { + long long next = curr + 1; + int cnt = 0; + while (curr <= n) { + cnt += min(n - curr + 1, next - curr); + next *= 10; + curr *= 10; + } + return cnt; + } }; \ No newline at end of file diff --git a/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/Solution.java b/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/Solution.java index 43f72d24ebc89..5ccb769abdb91 100644 --- a/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/Solution.java +++ b/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/Solution.java @@ -1,31 +1,31 @@ -class Solution { - private int n; - - public int findKthNumber(int n, int k) { - this.n = n; - long curr = 1; - --k; - while (k > 0) { - int cnt = count(curr); - if (k >= cnt) { - k -= cnt; - ++curr; - } else { - --k; - curr *= 10; - } - } - return (int) curr; - } - - public int count(long curr) { - long next = curr + 1; - long cnt = 0; - while (curr <= n) { - cnt += Math.min(n - curr + 1, next - curr); - next *= 10; - curr *= 10; - } - return (int) cnt; - } +class Solution { + private int n; + + public int findKthNumber(int n, int k) { + this.n = n; + long curr = 1; + --k; + while (k > 0) { + int cnt = count(curr); + if (k >= cnt) { + k -= cnt; + ++curr; + } else { + --k; + curr *= 10; + } + } + return (int) curr; + } + + public int count(long curr) { + long next = curr + 1; + long cnt = 0; + while (curr <= n) { + cnt += Math.min(n - curr + 1, next - curr); + next *= 10; + curr *= 10; + } + return (int) cnt; + } } \ No newline at end of file diff --git a/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/Solution.py b/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/Solution.py index b443e8b810270..2f60cf07797da 100644 --- a/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/Solution.py +++ b/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/Solution.py @@ -1,20 +1,20 @@ -class Solution: - def findKthNumber(self, n: int, k: int) -> int: - def count(curr): - next, cnt = curr + 1, 0 - while curr <= n: - cnt += min(n - curr + 1, next - curr) - next, curr = next * 10, curr * 10 - return cnt - - curr = 1 - k -= 1 - while k: - cnt = count(curr) - if k >= cnt: - k -= cnt - curr += 1 - else: - k -= 1 - curr *= 10 - return curr +class Solution: + def findKthNumber(self, n: int, k: int) -> int: + def count(curr): + next, cnt = curr + 1, 0 + while curr <= n: + cnt += min(n - curr + 1, next - curr) + next, curr = next * 10, curr * 10 + return cnt + + curr = 1 + k -= 1 + while k: + cnt = count(curr) + if k >= cnt: + k -= cnt + curr += 1 + else: + k -= 1 + curr *= 10 + return curr diff --git a/solution/0400-0499/0441.Arranging Coins/Solution2.java b/solution/0400-0499/0441.Arranging Coins/Solution2.java new file mode 100644 index 0000000000000..d92b34577e836 --- /dev/null +++ b/solution/0400-0499/0441.Arranging Coins/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public int arrangeCoins(int n) { + long left = 1, right = n; + while (left < right) { + long mid = (left + right + 1) >>> 1; + if ((1 + mid) * mid / 2 <= n) { + left = mid; + } else { + right = mid - 1; + } + } + return (int) left; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0441.Arranging Coins/Solution2.py b/solution/0400-0499/0441.Arranging Coins/Solution2.py new file mode 100644 index 0000000000000..3fd14619e2d6c --- /dev/null +++ b/solution/0400-0499/0441.Arranging Coins/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def arrangeCoins(self, n: int) -> int: + left, right = 1, n + while left < right: + mid = (left + right + 1) >> 1 + if (1 + mid) * mid // 2 <= n: + left = mid + else: + right = mid - 1 + return left diff --git a/solution/0400-0499/0443.String Compression/Solution.cpp b/solution/0400-0499/0443.String Compression/Solution.cpp index 9213ee71a1f4b..81d45fdb56cca 100644 --- a/solution/0400-0499/0443.String Compression/Solution.cpp +++ b/solution/0400-0499/0443.String Compression/Solution.cpp @@ -1,4 +1,4 @@ -class Solution { +class Solution { public: int compress(vector& chars) { int k = 0, n = chars.size(); diff --git a/solution/0400-0499/0445.Add Two Numbers II/Solution.rs b/solution/0400-0499/0445.Add Two Numbers II/Solution.rs index 836b4f22bd12a..d9f94f76b6aaa 100644 --- a/solution/0400-0499/0445.Add Two Numbers II/Solution.rs +++ b/solution/0400-0499/0445.Add Two Numbers II/Solution.rs @@ -15,39 +15,39 @@ // } // } impl Solution { - fn create_stack(mut head: Option>) -> Vec { - let mut res = vec![]; - while let Some(node) = head { - res.push(node.val); - head = node.next; + fn reverse(mut head: Option>) -> Option> { + let mut pre = None; + while let Some(mut node) = head { + let next = node.next.take(); + node.next = pre.take(); + pre = Some(node); + head = next; } - res + pre } pub fn add_two_numbers( - l1: Option>, - l2: Option> + mut l1: Option>, + mut l2: Option> ) -> Option> { - let mut s1 = Self::create_stack(l1); - let mut s2 = Self::create_stack(l2); - - let mut dummy = Box::new(ListNode::new(0)); - let mut carry = 0; - while !s1.is_empty() || !s2.is_empty() || carry != 0 { - if let Some(val) = s1.pop() { - carry += val; + l1 = Self::reverse(l1); + l2 = Self::reverse(l2); + let mut dummy = Some(Box::new(ListNode::new(0))); + let mut cur = &mut dummy; + let mut sum = 0; + while l1.is_some() || l2.is_some() || sum != 0 { + if let Some(node) = l1 { + sum += node.val; + l1 = node.next; } - if let Some(val) = s2.pop() { - carry += val; + if let Some(node) = l2 { + sum += node.val; + l2 = node.next; } - dummy.next = Some( - Box::new(ListNode { - val: carry % 10, - next: dummy.next.take(), - }) - ); - carry /= 10; + cur.as_mut().unwrap().next = Some(Box::new(ListNode::new(sum % 10))); + cur = &mut cur.as_mut().unwrap().next; + sum /= 10; } - dummy.next.take() + Self::reverse(dummy.unwrap().next.take()) } } diff --git a/solution/0400-0499/0445.Add Two Numbers II/Solution2.rs b/solution/0400-0499/0445.Add Two Numbers II/Solution2.rs new file mode 100644 index 0000000000000..836b4f22bd12a --- /dev/null +++ b/solution/0400-0499/0445.Add Two Numbers II/Solution2.rs @@ -0,0 +1,53 @@ +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + fn create_stack(mut head: Option>) -> Vec { + let mut res = vec![]; + while let Some(node) = head { + res.push(node.val); + head = node.next; + } + res + } + + pub fn add_two_numbers( + l1: Option>, + l2: Option> + ) -> Option> { + let mut s1 = Self::create_stack(l1); + let mut s2 = Self::create_stack(l2); + + let mut dummy = Box::new(ListNode::new(0)); + let mut carry = 0; + while !s1.is_empty() || !s2.is_empty() || carry != 0 { + if let Some(val) = s1.pop() { + carry += val; + } + if let Some(val) = s2.pop() { + carry += val; + } + dummy.next = Some( + Box::new(ListNode { + val: carry % 10, + next: dummy.next.take(), + }) + ); + carry /= 10; + } + dummy.next.take() + } +} diff --git a/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/Solution.cpp b/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/Solution.cpp index 33aaea9736a19..1c1bc203cf068 100644 --- a/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/Solution.cpp +++ b/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/Solution.cpp @@ -1,17 +1,17 @@ -class Solution { -public: - int numberOfArithmeticSlices(vector& nums) { - int n = nums.size(); - unordered_map f[n]; - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - long long d = 1LL * nums[i] - nums[j]; - int cnt = f[j][d]; - ans += cnt; - f[i][d] += cnt + 1; - } - } - return ans; - } +class Solution { +public: + int numberOfArithmeticSlices(vector& nums) { + int n = nums.size(); + unordered_map f[n]; + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + long long d = 1LL * nums[i] - nums[j]; + int cnt = f[j][d]; + ans += cnt; + f[i][d] += cnt + 1; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/Solution.java b/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/Solution.java index 6ed2e16576427..780731745bbfd 100644 --- a/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/Solution.java +++ b/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public int numberOfArithmeticSlices(int[] nums) { - int n = nums.length; - Map[] f = new Map[n]; - Arrays.setAll(f, k -> new HashMap<>()); - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - Long d = 1L * nums[i] - nums[j]; - int cnt = f[j].getOrDefault(d, 0); - ans += cnt; - f[i].merge(d, cnt + 1, Integer::sum); - } - } - return ans; - } +class Solution { + public int numberOfArithmeticSlices(int[] nums) { + int n = nums.length; + Map[] f = new Map[n]; + Arrays.setAll(f, k -> new HashMap<>()); + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + Long d = 1L * nums[i] - nums[j]; + int cnt = f[j].getOrDefault(d, 0); + ans += cnt; + f[i].merge(d, cnt + 1, Integer::sum); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/Solution.py b/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/Solution.py index bb701992cb2b2..1453762b451f7 100644 --- a/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/Solution.py +++ b/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def numberOfArithmeticSlices(self, nums: List[int]) -> int: - f = [defaultdict(int) for _ in nums] - ans = 0 - for i, x in enumerate(nums): - for j, y in enumerate(nums[:i]): - d = x - y - ans += f[j][d] - f[i][d] += f[j][d] + 1 - return ans +class Solution: + def numberOfArithmeticSlices(self, nums: List[int]) -> int: + f = [defaultdict(int) for _ in nums] + ans = 0 + for i, x in enumerate(nums): + for j, y in enumerate(nums[:i]): + d = x - y + ans += f[j][d] + f[i][d] += f[j][d] + 1 + return ans diff --git a/solution/0400-0499/0447.Number of Boomerangs/Solution.cpp b/solution/0400-0499/0447.Number of Boomerangs/Solution.cpp index 4bb88388639f6..ef02d850af5d0 100644 --- a/solution/0400-0499/0447.Number of Boomerangs/Solution.cpp +++ b/solution/0400-0499/0447.Number of Boomerangs/Solution.cpp @@ -1,17 +1,15 @@ -class Solution { -public: - int numberOfBoomerangs(vector>& points) { - int ans = 0; - for (auto& p1 : points) { - unordered_map cnt; - for (auto& p2 : points) { - int d = (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); - cnt[d]++; - } - for (auto& [_, x] : cnt) { - ans += x * (x - 1); - } - } - return ans; - } +class Solution { +public: + int numberOfBoomerangs(vector>& points) { + int ans = 0; + for (auto& p1 : points) { + unordered_map cnt; + for (auto& p2 : points) { + int d = (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); + ans += cnt[d]; + cnt[d]++; + } + } + return ans << 1; + } }; \ No newline at end of file diff --git a/solution/0400-0499/0447.Number of Boomerangs/Solution.go b/solution/0400-0499/0447.Number of Boomerangs/Solution.go index 7ce75d48352ac..afcb248ee2c8f 100644 --- a/solution/0400-0499/0447.Number of Boomerangs/Solution.go +++ b/solution/0400-0499/0447.Number of Boomerangs/Solution.go @@ -3,11 +3,10 @@ func numberOfBoomerangs(points [][]int) (ans int) { cnt := map[int]int{} for _, p2 := range points { d := (p1[0]-p2[0])*(p1[0]-p2[0]) + (p1[1]-p2[1])*(p1[1]-p2[1]) + ans += cnt[d] cnt[d]++ } - for _, x := range cnt { - ans += x * (x - 1) - } } + ans <<= 1 return } \ No newline at end of file diff --git a/solution/0400-0499/0447.Number of Boomerangs/Solution.java b/solution/0400-0499/0447.Number of Boomerangs/Solution.java index eb6e8377486c7..b3f737e5d30e3 100644 --- a/solution/0400-0499/0447.Number of Boomerangs/Solution.java +++ b/solution/0400-0499/0447.Number of Boomerangs/Solution.java @@ -1,16 +1,14 @@ -class Solution { - public int numberOfBoomerangs(int[][] points) { - int ans = 0; - for (int[] p1 : points) { - Map cnt = new HashMap<>(); - for (int[] p2 : points) { - int d = (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); - cnt.merge(d, 1, Integer::sum); - } - for (int x : cnt.values()) { - ans += x * (x - 1); - } - } - return ans; - } +class Solution { + public int numberOfBoomerangs(int[][] points) { + int ans = 0; + for (int[] p1 : points) { + Map cnt = new HashMap<>(); + for (int[] p2 : points) { + int d = (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); + ans += cnt.getOrDefault(d, 0); + cnt.merge(d, 1, Integer::sum); + } + } + return ans << 1; + } } \ No newline at end of file diff --git a/solution/0400-0499/0447.Number of Boomerangs/Solution.py b/solution/0400-0499/0447.Number of Boomerangs/Solution.py index 44ab8946074cc..e8a84a28e9141 100644 --- a/solution/0400-0499/0447.Number of Boomerangs/Solution.py +++ b/solution/0400-0499/0447.Number of Boomerangs/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def numberOfBoomerangs(self, points: List[List[int]]) -> int: - ans = 0 - for p1 in points: - cnt = Counter() - for p2 in points: - d = dist(p1, p2) - cnt[d] += 1 - ans += sum(x * (x - 1) for x in cnt.values()) - return ans +class Solution: + def numberOfBoomerangs(self, points: List[List[int]]) -> int: + ans = 0 + for p1 in points: + cnt = Counter() + for p2 in points: + d = dist(p1, p2) + ans += cnt[d] + cnt[d] += 1 + return ans << 1 diff --git a/solution/0400-0499/0447.Number of Boomerangs/Solution.ts b/solution/0400-0499/0447.Number of Boomerangs/Solution.ts index 6c45ef22118e4..edd15009d2ec0 100644 --- a/solution/0400-0499/0447.Number of Boomerangs/Solution.ts +++ b/solution/0400-0499/0447.Number of Boomerangs/Solution.ts @@ -4,11 +4,9 @@ function numberOfBoomerangs(points: number[][]): number { const cnt: Map = new Map(); for (const [x2, y2] of points) { const d = (x1 - x2) ** 2 + (y1 - y2) ** 2; + ans += cnt.get(d) || 0; cnt.set(d, (cnt.get(d) || 0) + 1); } - for (const [_, x] of cnt) { - ans += x * (x - 1); - } } - return ans; + return ans << 1; } diff --git a/solution/0400-0499/0447.Number of Boomerangs/Solution2.cpp b/solution/0400-0499/0447.Number of Boomerangs/Solution2.cpp new file mode 100644 index 0000000000000..7cfad9b6c59d2 --- /dev/null +++ b/solution/0400-0499/0447.Number of Boomerangs/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int numberOfBoomerangs(vector>& points) { + int ans = 0; + for (auto& p1 : points) { + unordered_map cnt; + for (auto& p2 : points) { + int d = (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); + cnt[d]++; + } + for (auto& [_, x] : cnt) { + ans += x * (x - 1); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0447.Number of Boomerangs/Solution2.go b/solution/0400-0499/0447.Number of Boomerangs/Solution2.go new file mode 100644 index 0000000000000..7ce75d48352ac --- /dev/null +++ b/solution/0400-0499/0447.Number of Boomerangs/Solution2.go @@ -0,0 +1,13 @@ +func numberOfBoomerangs(points [][]int) (ans int) { + for _, p1 := range points { + cnt := map[int]int{} + for _, p2 := range points { + d := (p1[0]-p2[0])*(p1[0]-p2[0]) + (p1[1]-p2[1])*(p1[1]-p2[1]) + cnt[d]++ + } + for _, x := range cnt { + ans += x * (x - 1) + } + } + return +} \ No newline at end of file diff --git a/solution/0400-0499/0447.Number of Boomerangs/Solution2.java b/solution/0400-0499/0447.Number of Boomerangs/Solution2.java new file mode 100644 index 0000000000000..9aa3d898870cb --- /dev/null +++ b/solution/0400-0499/0447.Number of Boomerangs/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public int numberOfBoomerangs(int[][] points) { + int ans = 0; + for (int[] p1 : points) { + Map cnt = new HashMap<>(); + for (int[] p2 : points) { + int d = (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); + cnt.merge(d, 1, Integer::sum); + } + for (int x : cnt.values()) { + ans += x * (x - 1); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0447.Number of Boomerangs/Solution2.py b/solution/0400-0499/0447.Number of Boomerangs/Solution2.py new file mode 100644 index 0000000000000..df4de63f2bb50 --- /dev/null +++ b/solution/0400-0499/0447.Number of Boomerangs/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def numberOfBoomerangs(self, points: List[List[int]]) -> int: + ans = 0 + for p1 in points: + cnt = Counter() + for p2 in points: + d = dist(p1, p2) + cnt[d] += 1 + ans += sum(x * (x - 1) for x in cnt.values()) + return ans diff --git a/solution/0400-0499/0447.Number of Boomerangs/Solution2.ts b/solution/0400-0499/0447.Number of Boomerangs/Solution2.ts new file mode 100644 index 0000000000000..6c45ef22118e4 --- /dev/null +++ b/solution/0400-0499/0447.Number of Boomerangs/Solution2.ts @@ -0,0 +1,14 @@ +function numberOfBoomerangs(points: number[][]): number { + let ans = 0; + for (const [x1, y1] of points) { + const cnt: Map = new Map(); + for (const [x2, y2] of points) { + const d = (x1 - x2) ** 2 + (y1 - y2) ** 2; + cnt.set(d, (cnt.get(d) || 0) + 1); + } + for (const [_, x] of cnt) { + ans += x * (x - 1); + } + } + return ans; +} diff --git a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.cpp b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.cpp index 49668098f7fb0..611af9e84d4e3 100644 --- a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.cpp +++ b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.cpp @@ -2,16 +2,15 @@ class Solution { public: vector findDisappearedNumbers(vector& nums) { int n = nums.size(); + bool s[n + 1]; + memset(s, false, sizeof(s)); for (int& x : nums) { - int i = abs(x) - 1; - if (nums[i] > 0) { - nums[i] = -nums[i]; - } + s[x] = true; } vector ans; - for (int i = 0; i < n; ++i) { - if (nums[i] > 0) { - ans.push_back(i + 1); + for (int i = 1; i <= n; ++i) { + if (!s[i]) { + ans.push_back(i); } } return ans; diff --git a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.go b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.go index 3a890a357e02e..1ed7fb86b8110 100644 --- a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.go +++ b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.go @@ -1,22 +1,13 @@ func findDisappearedNumbers(nums []int) (ans []int) { n := len(nums) + s := make([]bool, n+1) for _, x := range nums { - i := abs(x) - 1 - if nums[i] > 0 { - nums[i] = -nums[i] - } + s[x] = true } - for i := 0; i < n; i++ { - if nums[i] > 0 { - ans = append(ans, i+1) + for i := 1; i <= n; i++ { + if !s[i] { + ans = append(ans, i) } } return -} - -func abs(x int) int { - if x < 0 { - return -x - } - return x } \ No newline at end of file diff --git a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.java b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.java index 8968bcf7eb5d0..6b62f5dc64eb7 100644 --- a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.java +++ b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.java @@ -1,16 +1,14 @@ class Solution { public List findDisappearedNumbers(int[] nums) { int n = nums.length; + boolean[] s = new boolean[n + 1]; for (int x : nums) { - int i = Math.abs(x) - 1; - if (nums[i] > 0) { - nums[i] *= -1; - } + s[x] = true; } List ans = new ArrayList<>(); - for (int i = 0; i < n; i++) { - if (nums[i] > 0) { - ans.add(i + 1); + for (int i = 1; i <= n; i++) { + if (!s[i]) { + ans.add(i); } } return ans; diff --git a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.py b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.py index f9abaa2bb264b..5df7d7aa0b30e 100644 --- a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.py +++ b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.py @@ -1,7 +1,4 @@ class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: - for x in nums: - i = abs(x) - 1 - if nums[i] > 0: - nums[i] *= -1 - return [i + 1 for i in range(len(nums)) if nums[i] > 0] + s = set(nums) + return [x for x in range(1, len(nums) + 1) if x not in s] diff --git a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.ts b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.ts index d47efb47a4c51..4b9b463de11af 100644 --- a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.ts +++ b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.ts @@ -1,15 +1,13 @@ function findDisappearedNumbers(nums: number[]): number[] { const n = nums.length; + const s: boolean[] = new Array(n + 1).fill(false); for (const x of nums) { - const i = Math.abs(x) - 1; - if (nums[i] > 0) { - nums[i] *= -1; - } + s[x] = true; } const ans: number[] = []; - for (let i = 0; i < n; ++i) { - if (nums[i] > 0) { - ans.push(i + 1); + for (let i = 1; i <= n; ++i) { + if (!s[i]) { + ans.push(i); } } return ans; diff --git a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution2.cpp b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution2.cpp new file mode 100644 index 0000000000000..49668098f7fb0 --- /dev/null +++ b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + vector findDisappearedNumbers(vector& nums) { + int n = nums.size(); + for (int& x : nums) { + int i = abs(x) - 1; + if (nums[i] > 0) { + nums[i] = -nums[i]; + } + } + vector ans; + for (int i = 0; i < n; ++i) { + if (nums[i] > 0) { + ans.push_back(i + 1); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution2.go b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution2.go new file mode 100644 index 0000000000000..3a890a357e02e --- /dev/null +++ b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution2.go @@ -0,0 +1,22 @@ +func findDisappearedNumbers(nums []int) (ans []int) { + n := len(nums) + for _, x := range nums { + i := abs(x) - 1 + if nums[i] > 0 { + nums[i] = -nums[i] + } + } + for i := 0; i < n; i++ { + if nums[i] > 0 { + ans = append(ans, i+1) + } + } + return +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} \ No newline at end of file diff --git a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution2.java b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution2.java new file mode 100644 index 0000000000000..8968bcf7eb5d0 --- /dev/null +++ b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution2.java @@ -0,0 +1,18 @@ +class Solution { + public List findDisappearedNumbers(int[] nums) { + int n = nums.length; + for (int x : nums) { + int i = Math.abs(x) - 1; + if (nums[i] > 0) { + nums[i] *= -1; + } + } + List ans = new ArrayList<>(); + for (int i = 0; i < n; i++) { + if (nums[i] > 0) { + ans.add(i + 1); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution2.py b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution2.py new file mode 100644 index 0000000000000..f9abaa2bb264b --- /dev/null +++ b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def findDisappearedNumbers(self, nums: List[int]) -> List[int]: + for x in nums: + i = abs(x) - 1 + if nums[i] > 0: + nums[i] *= -1 + return [i + 1 for i in range(len(nums)) if nums[i] > 0] diff --git a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution2.ts b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution2.ts new file mode 100644 index 0000000000000..d47efb47a4c51 --- /dev/null +++ b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution2.ts @@ -0,0 +1,16 @@ +function findDisappearedNumbers(nums: number[]): number[] { + const n = nums.length; + for (const x of nums) { + const i = Math.abs(x) - 1; + if (nums[i] > 0) { + nums[i] *= -1; + } + } + const ans: number[] = []; + for (let i = 0; i < n; ++i) { + if (nums[i] > 0) { + ans.push(i + 1); + } + } + return ans; +} diff --git a/solution/0400-0499/0449.Serialize and Deserialize BST/Solution.cpp b/solution/0400-0499/0449.Serialize and Deserialize BST/Solution.cpp index 7c22f45ed5920..de036ef8ba104 100644 --- a/solution/0400-0499/0449.Serialize and Deserialize BST/Solution.cpp +++ b/solution/0400-0499/0449.Serialize and Deserialize BST/Solution.cpp @@ -1,67 +1,67 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Codec { -public: - // Encodes a tree to a single string. - string serialize(TreeNode* root) { - if (!root) { - return ""; - } - string data = ""; - function dfs = [&](TreeNode* root) { - if (!root) { - return; - } - data += to_string(root->val) + " "; - dfs(root->left); - dfs(root->right); - }; - dfs(root); - data.pop_back(); - return data; - } - - // Decodes your encoded data to tree. - TreeNode* deserialize(string data) { - if (data.empty()) { - return nullptr; - } - vector nums = split(data, ' '); - int i = 0; - function dfs = [&](int mi, int mx) -> TreeNode* { - if (i == nums.size() || nums[i] < mi || nums[i] > mx) { - return nullptr; - } - int x = nums[i++]; - TreeNode* root = new TreeNode(x); - root->left = dfs(mi, x); - root->right = dfs(x, mx); - return root; - }; - return dfs(INT_MIN, INT_MAX); - } - - vector split(const string& s, char delim) { - vector tokens; - stringstream ss(s); - string token; - while (getline(ss, token, delim)) { - tokens.push_back(stoi(token)); - } - return tokens; - } -}; - -// Your Codec object will be instantiated and called as such: -// Codec* ser = new Codec(); -// Codec* deser = new Codec(); -// string tree = ser->serialize(root); -// TreeNode* ans = deser->deserialize(tree); +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Codec { +public: + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + if (!root) { + return ""; + } + string data = ""; + function dfs = [&](TreeNode* root) { + if (!root) { + return; + } + data += to_string(root->val) + " "; + dfs(root->left); + dfs(root->right); + }; + dfs(root); + data.pop_back(); + return data; + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + if (data.empty()) { + return nullptr; + } + vector nums = split(data, ' '); + int i = 0; + function dfs = [&](int mi, int mx) -> TreeNode* { + if (i == nums.size() || nums[i] < mi || nums[i] > mx) { + return nullptr; + } + int x = nums[i++]; + TreeNode* root = new TreeNode(x); + root->left = dfs(mi, x); + root->right = dfs(x, mx); + return root; + }; + return dfs(INT_MIN, INT_MAX); + } + + vector split(const string& s, char delim) { + vector tokens; + stringstream ss(s); + string token; + while (getline(ss, token, delim)) { + tokens.push_back(stoi(token)); + } + return tokens; + } +}; + +// Your Codec object will be instantiated and called as such: +// Codec* ser = new Codec(); +// Codec* deser = new Codec(); +// string tree = ser->serialize(root); +// TreeNode* ans = deser->deserialize(tree); // return ans; \ No newline at end of file diff --git a/solution/0400-0499/0449.Serialize and Deserialize BST/Solution.java b/solution/0400-0499/0449.Serialize and Deserialize BST/Solution.java index 027519c6b91b5..8fbfec0190294 100644 --- a/solution/0400-0499/0449.Serialize and Deserialize BST/Solution.java +++ b/solution/0400-0499/0449.Serialize and Deserialize BST/Solution.java @@ -1,62 +1,62 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Codec { - private int i; - private List nums; - private final int inf = 1 << 30; - - // Encodes a tree to a single string. - public String serialize(TreeNode root) { - nums = new ArrayList<>(); - dfs(root); - return String.join(" ", nums); - } - - // Decodes your encoded data to tree. - public TreeNode deserialize(String data) { - if (data == null || "".equals(data)) { - return null; - } - i = 0; - nums = Arrays.asList(data.split(" ")); - return dfs(-inf, inf); - } - - private void dfs(TreeNode root) { - if (root == null) { - return; - } - nums.add(String.valueOf(root.val)); - dfs(root.left); - dfs(root.right); - } - - private TreeNode dfs(int mi, int mx) { - if (i == nums.size()) { - return null; - } - int x = Integer.parseInt(nums.get(i)); - if (x < mi || x > mx) { - return null; - } - TreeNode root = new TreeNode(x); - ++i; - root.left = dfs(mi, x); - root.right = dfs(x, mx); - return root; - } -} - -// Your Codec object will be instantiated and called as such: -// Codec ser = new Codec(); -// Codec deser = new Codec(); -// String tree = ser.serialize(root); -// TreeNode ans = deser.deserialize(tree); +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Codec { + private int i; + private List nums; + private final int inf = 1 << 30; + + // Encodes a tree to a single string. + public String serialize(TreeNode root) { + nums = new ArrayList<>(); + dfs(root); + return String.join(" ", nums); + } + + // Decodes your encoded data to tree. + public TreeNode deserialize(String data) { + if (data == null || "".equals(data)) { + return null; + } + i = 0; + nums = Arrays.asList(data.split(" ")); + return dfs(-inf, inf); + } + + private void dfs(TreeNode root) { + if (root == null) { + return; + } + nums.add(String.valueOf(root.val)); + dfs(root.left); + dfs(root.right); + } + + private TreeNode dfs(int mi, int mx) { + if (i == nums.size()) { + return null; + } + int x = Integer.parseInt(nums.get(i)); + if (x < mi || x > mx) { + return null; + } + TreeNode root = new TreeNode(x); + ++i; + root.left = dfs(mi, x); + root.right = dfs(x, mx); + return root; + } +} + +// Your Codec object will be instantiated and called as such: +// Codec ser = new Codec(); +// Codec deser = new Codec(); +// String tree = ser.serialize(root); +// TreeNode ans = deser.deserialize(tree); // return ans; \ No newline at end of file diff --git a/solution/0400-0499/0449.Serialize and Deserialize BST/Solution.py b/solution/0400-0499/0449.Serialize and Deserialize BST/Solution.py index 0173812f58a2a..45d481cbb355d 100644 --- a/solution/0400-0499/0449.Serialize and Deserialize BST/Solution.py +++ b/solution/0400-0499/0449.Serialize and Deserialize BST/Solution.py @@ -1,49 +1,49 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None - - -class Codec: - def serialize(self, root: Optional[TreeNode]) -> str: - """Encodes a tree to a single string.""" - - def dfs(root: Optional[TreeNode]): - if root is None: - return - nums.append(root.val) - dfs(root.left) - dfs(root.right) - - nums = [] - dfs(root) - return " ".join(map(str, nums)) - - def deserialize(self, data: str) -> Optional[TreeNode]: - """Decodes your encoded data to tree.""" - - def dfs(mi: int, mx: int) -> Optional[TreeNode]: - nonlocal i - if i == len(nums) or not mi <= nums[i] <= mx: - return None - x = nums[i] - root = TreeNode(x) - i += 1 - root.left = dfs(mi, x) - root.right = dfs(x, mx) - return root - - nums = list(map(int, data.split())) - i = 0 - return dfs(-inf, inf) - - -# Your Codec object will be instantiated and called as such: -# Your Codec object will be instantiated and called as such: -# ser = Codec() -# deser = Codec() -# tree = ser.serialize(root) -# ans = deser.deserialize(tree) -# return ans +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Codec: + def serialize(self, root: Optional[TreeNode]) -> str: + """Encodes a tree to a single string.""" + + def dfs(root: Optional[TreeNode]): + if root is None: + return + nums.append(root.val) + dfs(root.left) + dfs(root.right) + + nums = [] + dfs(root) + return " ".join(map(str, nums)) + + def deserialize(self, data: str) -> Optional[TreeNode]: + """Decodes your encoded data to tree.""" + + def dfs(mi: int, mx: int) -> Optional[TreeNode]: + nonlocal i + if i == len(nums) or not mi <= nums[i] <= mx: + return None + x = nums[i] + root = TreeNode(x) + i += 1 + root.left = dfs(mi, x) + root.right = dfs(x, mx) + return root + + nums = list(map(int, data.split())) + i = 0 + return dfs(-inf, inf) + + +# Your Codec object will be instantiated and called as such: +# Your Codec object will be instantiated and called as such: +# ser = Codec() +# deser = Codec() +# tree = ser.serialize(root) +# ans = deser.deserialize(tree) +# return ans diff --git a/solution/0400-0499/0451.Sort Characters By Frequency/Solution.php b/solution/0400-0499/0451.Sort Characters By Frequency/Solution.php index d59f212daef41..b807fc7e2152e 100644 --- a/solution/0400-0499/0451.Sort Characters By Frequency/Solution.php +++ b/solution/0400-0499/0451.Sort Characters By Frequency/Solution.php @@ -14,4 +14,4 @@ function frequencySort($s) { } return $rs; } -} \ No newline at end of file +} diff --git a/solution/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/Solution.cs b/solution/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/Solution.cs index d4976499862cd..129cb4d3d58aa 100644 --- a/solution/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/Solution.cs +++ b/solution/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/Solution.cs @@ -11,4 +11,4 @@ public int FindMinArrowShots(int[][] points) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/Solution.java b/solution/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/Solution.java index 10dd55092984b..e210000607e83 100644 --- a/solution/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/Solution.java +++ b/solution/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/Solution.java @@ -1,5 +1,6 @@ class Solution { public int findMinArrowShots(int[][] points) { + // 直接 a[1] - b[1] 可能会溢出 Arrays.sort(points, Comparator.comparingInt(a -> a[1])); int ans = 0; long last = -(1L << 60); diff --git a/solution/0400-0499/0453.Minimum Moves to Equal Array Elements/Solution.java b/solution/0400-0499/0453.Minimum Moves to Equal Array Elements/Solution.java index 6d4f0f3df655a..2b3e65cba52fc 100644 --- a/solution/0400-0499/0453.Minimum Moves to Equal Array Elements/Solution.java +++ b/solution/0400-0499/0453.Minimum Moves to Equal Array Elements/Solution.java @@ -2,4 +2,4 @@ class Solution { public int minMoves(int[] nums) { return Arrays.stream(nums).sum() - Arrays.stream(nums).min().getAsInt() * nums.length; } -} +} \ No newline at end of file diff --git a/solution/0400-0499/0453.Minimum Moves to Equal Array Elements/Solution2.java b/solution/0400-0499/0453.Minimum Moves to Equal Array Elements/Solution2.java new file mode 100644 index 0000000000000..5842dd023cbb9 --- /dev/null +++ b/solution/0400-0499/0453.Minimum Moves to Equal Array Elements/Solution2.java @@ -0,0 +1,11 @@ +class Solution { + public int minMoves(int[] nums) { + int s = 0; + int mi = 1 << 30; + for (int x : nums) { + s += x; + mi = Math.min(mi, x); + } + return s - mi * nums.length; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0456.132 Pattern/Solution2.cpp b/solution/0400-0499/0456.132 Pattern/Solution2.cpp new file mode 100644 index 0000000000000..16e0ae85e0c7a --- /dev/null +++ b/solution/0400-0499/0456.132 Pattern/Solution2.cpp @@ -0,0 +1,52 @@ +class BinaryIndexedTree { +public: + BinaryIndexedTree(int n) { + this->n = n; + this->c = vector(n + 1, 0); + } + + void update(int x, int val) { + while (x <= n) { + c[x] += val; + x += x & -x; + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } + +private: + int n; + vector c; +}; + +class Solution { +public: + bool find132pattern(vector& nums) { + vector s = nums; + sort(s.begin(), s.end()); + s.erase(unique(s.begin(), s.end()), s.end()); + BinaryIndexedTree tree(s.size()); + int n = nums.size(); + int left[n + 1]; + memset(left, 63, sizeof(left)); + for (int i = 0; i < n; ++i) { + left[i + 1] = min(left[i], nums[i]); + } + for (int i = nums.size() - 1; ~i; --i) { + int x = lower_bound(s.begin(), s.end(), nums[i]) - s.begin() + 1; + int y = lower_bound(s.begin(), s.end(), left[i]) - s.begin() + 1; + if (x > y && tree.query(x - 1) > tree.query(y)) { + return true; + } + tree.update(x, 1); + } + return false; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0456.132 Pattern/Solution2.go b/solution/0400-0499/0456.132 Pattern/Solution2.go new file mode 100644 index 0000000000000..c266563dcc483 --- /dev/null +++ b/solution/0400-0499/0456.132 Pattern/Solution2.go @@ -0,0 +1,53 @@ +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) update(x, val int) { + for x <= this.n { + this.c[x] += val + x += x & -x + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= x & -x + } + return s +} + +func find132pattern(nums []int) bool { + n := len(nums) + s := make([]int, n) + left := make([]int, n+1) + left[0] = 1 << 30 + copy(s, nums) + sort.Ints(s) + m := 0 + for i := 0; i < n; i++ { + left[i+1] = min(left[i], nums[i]) + if i == 0 || s[i] != s[i-1] { + s[m] = s[i] + m++ + } + } + s = s[:m] + tree := newBinaryIndexedTree(m) + for i := n - 1; i >= 0; i-- { + x := sort.SearchInts(s, nums[i]) + 1 + y := sort.SearchInts(s, left[i]) + 1 + if x > y && tree.query(x-1) > tree.query(y) { + return true + } + tree.update(x, 1) + } + return false +} \ No newline at end of file diff --git a/solution/0400-0499/0456.132 Pattern/Solution2.java b/solution/0400-0499/0456.132 Pattern/Solution2.java new file mode 100644 index 0000000000000..963f678e596ca --- /dev/null +++ b/solution/0400-0499/0456.132 Pattern/Solution2.java @@ -0,0 +1,65 @@ +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int v) { + while (x <= n) { + c[x] += v; + x += x & -x; + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +} + +class Solution { + public boolean find132pattern(int[] nums) { + int[] s = nums.clone(); + Arrays.sort(s); + int n = nums.length; + int m = 0; + int[] left = new int[n + 1]; + left[0] = 1 << 30; + for (int i = 0; i < n; ++i) { + left[i + 1] = Math.min(left[i], nums[i]); + if (i == 0 || s[i] != s[i - 1]) { + s[m++] = s[i]; + } + } + BinaryIndexedTree tree = new BinaryIndexedTree(m); + for (int i = n - 1; i >= 0; --i) { + int x = search(s, m, nums[i]); + int y = search(s, m, left[i]); + if (x > y && tree.query(x - 1) > tree.query(y)) { + return true; + } + tree.update(x, 1); + } + return false; + } + + private int search(int[] nums, int r, int x) { + int l = 0; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l + 1; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0456.132 Pattern/Solution2.py b/solution/0400-0499/0456.132 Pattern/Solution2.py new file mode 100644 index 0000000000000..ddc0b96bbeb7c --- /dev/null +++ b/solution/0400-0499/0456.132 Pattern/Solution2.py @@ -0,0 +1,33 @@ +class BinaryIndexedTree: + def __init__(self, n): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x, delta): + while x <= self.n: + self.c[x] += delta + x += x & -x + + def query(self, x): + s = 0 + while x: + s += self.c[x] + x -= x & -x + return s + + +class Solution: + def find132pattern(self, nums: List[int]) -> bool: + s = sorted(set(nums)) + n = len(nums) + left = [inf] * (n + 1) + for i, x in enumerate(nums): + left[i + 1] = min(left[i], x) + tree = BinaryIndexedTree(len(s)) + for i in range(n - 1, -1, -1): + x = bisect_left(s, nums[i]) + 1 + y = bisect_left(s, left[i]) + 1 + if x > y and tree.query(x - 1) > tree.query(y): + return True + tree.update(x, 1) + return False diff --git a/solution/0400-0499/0456.132 Pattern/Solution2.ts b/solution/0400-0499/0456.132 Pattern/Solution2.ts new file mode 100644 index 0000000000000..3fbda2e409d13 --- /dev/null +++ b/solution/0400-0499/0456.132 Pattern/Solution2.ts @@ -0,0 +1,64 @@ +class BinaryIndextedTree { + n: number; + c: number[]; + + constructor(n: number) { + this.n = n; + this.c = new Array(n + 1).fill(0); + } + + update(x: number, val: number): void { + while (x <= this.n) { + this.c[x] += val; + x += x & -x; + } + } + + query(x: number): number { + let s = 0; + while (x) { + s += this.c[x]; + x -= x & -x; + } + return s; + } +} + +function find132pattern(nums: number[]): boolean { + let s: number[] = [...nums]; + s.sort((a, b) => a - b); + const n = nums.length; + const left: number[] = new Array(n + 1).fill(1 << 30); + let m = 0; + for (let i = 0; i < n; ++i) { + left[i + 1] = Math.min(left[i], nums[i]); + if (i == 0 || s[i] != s[i - 1]) { + s[m++] = s[i]; + } + } + s = s.slice(0, m); + const tree = new BinaryIndextedTree(m); + for (let i = n - 1; i >= 0; --i) { + const x = search(s, nums[i]); + const y = search(s, left[i]); + if (x > y && tree.query(x - 1) > tree.query(y)) { + return true; + } + tree.update(x, 1); + } + return false; +} + +function search(nums: number[], x: number): number { + let l = 0, + r = nums.length - 1; + while (l < r) { + const mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l + 1; +} diff --git a/solution/0400-0499/0459.Repeated Substring Pattern/Solution.java b/solution/0400-0499/0459.Repeated Substring Pattern/Solution.java index 7d700a4130491..98f517f221c69 100644 --- a/solution/0400-0499/0459.Repeated Substring Pattern/Solution.java +++ b/solution/0400-0499/0459.Repeated Substring Pattern/Solution.java @@ -3,4 +3,4 @@ public boolean repeatedSubstringPattern(String s) { String str = s + s; return str.substring(1, str.length() - 1).contains(s); } -} +} \ No newline at end of file diff --git a/solution/0400-0499/0459.Repeated Substring Pattern/Solution2.ts b/solution/0400-0499/0459.Repeated Substring Pattern/Solution2.ts new file mode 100644 index 0000000000000..04bb2475a988e --- /dev/null +++ b/solution/0400-0499/0459.Repeated Substring Pattern/Solution2.ts @@ -0,0 +1,20 @@ +function repeatedSubstringPattern(s: string): boolean { + const n = s.length; + for (let i = 0; i < n >> 1; i++) { + const len = i + 1; + if (n % len !== 0) { + continue; + } + const t = s.slice(0, len); + let j: number; + for (j = len; j < n; j += len) { + if (s.slice(j, j + len) !== t) { + break; + } + } + if (j === n) { + return true; + } + } + return false; +} diff --git a/solution/0400-0499/0460.LFU Cache/Solution.cpp b/solution/0400-0499/0460.LFU Cache/Solution.cpp index 49e2a6ad760cc..f9a8efdfb5dcd 100644 --- a/solution/0400-0499/0460.LFU Cache/Solution.cpp +++ b/solution/0400-0499/0460.LFU Cache/Solution.cpp @@ -1,121 +1,121 @@ -class Node { -public: - int key; - int value; - int freq; - Node* prev; - Node* next; - Node(int key, int value) { - this->key = key; - this->value = value; - this->freq = 1; - this->prev = nullptr; - this->next = nullptr; - } -}; - -class DoublyLinkedList { -public: - Node* head; - Node* tail; - DoublyLinkedList() { - this->head = new Node(-1, -1); - this->tail = new Node(-1, -1); - this->head->next = this->tail; - this->tail->prev = this->head; - } - void addFirst(Node* node) { - node->prev = this->head; - node->next = this->head->next; - this->head->next->prev = node; - this->head->next = node; - } - Node* remove(Node* node) { - node->next->prev = node->prev; - node->prev->next = node->next; - node->next = nullptr; - node->prev = nullptr; - return node; - } - Node* removeLast() { - return remove(this->tail->prev); - } - bool isEmpty() { - return this->head->next == this->tail; - } -}; - -class LFUCache { -public: - LFUCache(int capacity) { - this->capacity = capacity; - this->minFreq = 0; - } - - int get(int key) { - if (capacity == 0 || map.find(key) == map.end()) { - return -1; - } - Node* node = map[key]; - incrFreq(node); - return node->value; - } - - void put(int key, int value) { - if (capacity == 0) { - return; - } - if (map.find(key) != map.end()) { - Node* node = map[key]; - node->value = value; - incrFreq(node); - return; - } - if (map.size() == capacity) { - DoublyLinkedList* list = freqMap[minFreq]; - Node* node = list->removeLast(); - map.erase(node->key); - } - Node* node = new Node(key, value); - addNode(node); - map[key] = node; - minFreq = 1; - } - -private: - int capacity; - int minFreq; - unordered_map map; - unordered_map freqMap; - - void incrFreq(Node* node) { - int freq = node->freq; - DoublyLinkedList* list = freqMap[freq]; - list->remove(node); - if (list->isEmpty()) { - freqMap.erase(freq); - if (freq == minFreq) { - minFreq++; - } - } - node->freq++; - addNode(node); - } - - void addNode(Node* node) { - int freq = node->freq; - if (freqMap.find(freq) == freqMap.end()) { - freqMap[freq] = new DoublyLinkedList(); - } - DoublyLinkedList* list = freqMap[freq]; - list->addFirst(node); - freqMap[freq] = list; - } -}; - -/** - * Your LFUCache object will be instantiated and called as such: - * LFUCache* obj = new LFUCache(capacity); - * int param_1 = obj->get(key); - * obj->put(key,value); +class Node { +public: + int key; + int value; + int freq; + Node* prev; + Node* next; + Node(int key, int value) { + this->key = key; + this->value = value; + this->freq = 1; + this->prev = nullptr; + this->next = nullptr; + } +}; + +class DoublyLinkedList { +public: + Node* head; + Node* tail; + DoublyLinkedList() { + this->head = new Node(-1, -1); + this->tail = new Node(-1, -1); + this->head->next = this->tail; + this->tail->prev = this->head; + } + void addFirst(Node* node) { + node->prev = this->head; + node->next = this->head->next; + this->head->next->prev = node; + this->head->next = node; + } + Node* remove(Node* node) { + node->next->prev = node->prev; + node->prev->next = node->next; + node->next = nullptr; + node->prev = nullptr; + return node; + } + Node* removeLast() { + return remove(this->tail->prev); + } + bool isEmpty() { + return this->head->next == this->tail; + } +}; + +class LFUCache { +public: + LFUCache(int capacity) { + this->capacity = capacity; + this->minFreq = 0; + } + + int get(int key) { + if (capacity == 0 || map.find(key) == map.end()) { + return -1; + } + Node* node = map[key]; + incrFreq(node); + return node->value; + } + + void put(int key, int value) { + if (capacity == 0) { + return; + } + if (map.find(key) != map.end()) { + Node* node = map[key]; + node->value = value; + incrFreq(node); + return; + } + if (map.size() == capacity) { + DoublyLinkedList* list = freqMap[minFreq]; + Node* node = list->removeLast(); + map.erase(node->key); + } + Node* node = new Node(key, value); + addNode(node); + map[key] = node; + minFreq = 1; + } + +private: + int capacity; + int minFreq; + unordered_map map; + unordered_map freqMap; + + void incrFreq(Node* node) { + int freq = node->freq; + DoublyLinkedList* list = freqMap[freq]; + list->remove(node); + if (list->isEmpty()) { + freqMap.erase(freq); + if (freq == minFreq) { + minFreq++; + } + } + node->freq++; + addNode(node); + } + + void addNode(Node* node) { + int freq = node->freq; + if (freqMap.find(freq) == freqMap.end()) { + freqMap[freq] = new DoublyLinkedList(); + } + DoublyLinkedList* list = freqMap[freq]; + list->addFirst(node); + freqMap[freq] = list; + } +}; + +/** + * Your LFUCache object will be instantiated and called as such: + * LFUCache* obj = new LFUCache(capacity); + * int param_1 = obj->get(key); + * obj->put(key,value); */ \ No newline at end of file diff --git a/solution/0400-0499/0460.LFU Cache/Solution.java b/solution/0400-0499/0460.LFU Cache/Solution.java index b975df6e0daa0..0dc846641e1b5 100644 --- a/solution/0400-0499/0460.LFU Cache/Solution.java +++ b/solution/0400-0499/0460.LFU Cache/Solution.java @@ -113,4 +113,4 @@ public boolean isEmpty() { return head.next == tail; } } -} +} \ No newline at end of file diff --git a/solution/0400-0499/0460.LFU Cache/Solution.py b/solution/0400-0499/0460.LFU Cache/Solution.py index 8a4dcc852307f..06fb5185dfcb9 100644 --- a/solution/0400-0499/0460.LFU Cache/Solution.py +++ b/solution/0400-0499/0460.LFU Cache/Solution.py @@ -1,88 +1,88 @@ -class Node: - def __init__(self, key: int, value: int) -> None: - self.key = key - self.value = value - self.freq = 1 - self.prev = None - self.next = None - - -class DoublyLinkedList: - def __init__(self) -> None: - self.head = Node(-1, -1) - self.tail = Node(-1, -1) - self.head.next = self.tail - self.tail.prev = self.head - - def add_first(self, node: Node) -> None: - node.prev = self.head - node.next = self.head.next - self.head.next.prev = node - self.head.next = node - - def remove(self, node: Node) -> Node: - node.next.prev = node.prev - node.prev.next = node.next - node.next, node.prev = None, None - return node - - def remove_last(self) -> Node: - return self.remove(self.tail.prev) - - def is_empty(self) -> bool: - return self.head.next == self.tail - - -class LFUCache: - def __init__(self, capacity: int): - self.capacity = capacity - self.min_freq = 0 - self.map = defaultdict(Node) - self.freq_map = defaultdict(DoublyLinkedList) - - def get(self, key: int) -> int: - if self.capacity == 0 or key not in self.map: - return -1 - node = self.map[key] - self.incr_freq(node) - return node.value - - def put(self, key: int, value: int) -> None: - if self.capacity == 0: - return - if key in self.map: - node = self.map[key] - node.value = value - self.incr_freq(node) - return - if len(self.map) == self.capacity: - ls = self.freq_map[self.min_freq] - node = ls.remove_last() - self.map.pop(node.key) - node = Node(key, value) - self.add_node(node) - self.map[key] = node - self.min_freq = 1 - - def incr_freq(self, node: Node) -> None: - freq = node.freq - ls = self.freq_map[freq] - ls.remove(node) - if ls.is_empty(): - self.freq_map.pop(freq) - if freq == self.min_freq: - self.min_freq += 1 - node.freq += 1 - self.add_node(node) - - def add_node(self, node: Node) -> None: - freq = node.freq - ls = self.freq_map[freq] - ls.add_first(node) - self.freq_map[freq] = ls - - -# Your LFUCache object will be instantiated and called as such: -# obj = LFUCache(capacity) -# param_1 = obj.get(key) -# obj.put(key,value) +class Node: + def __init__(self, key: int, value: int) -> None: + self.key = key + self.value = value + self.freq = 1 + self.prev = None + self.next = None + + +class DoublyLinkedList: + def __init__(self) -> None: + self.head = Node(-1, -1) + self.tail = Node(-1, -1) + self.head.next = self.tail + self.tail.prev = self.head + + def add_first(self, node: Node) -> None: + node.prev = self.head + node.next = self.head.next + self.head.next.prev = node + self.head.next = node + + def remove(self, node: Node) -> Node: + node.next.prev = node.prev + node.prev.next = node.next + node.next, node.prev = None, None + return node + + def remove_last(self) -> Node: + return self.remove(self.tail.prev) + + def is_empty(self) -> bool: + return self.head.next == self.tail + + +class LFUCache: + def __init__(self, capacity: int): + self.capacity = capacity + self.min_freq = 0 + self.map = defaultdict(Node) + self.freq_map = defaultdict(DoublyLinkedList) + + def get(self, key: int) -> int: + if self.capacity == 0 or key not in self.map: + return -1 + node = self.map[key] + self.incr_freq(node) + return node.value + + def put(self, key: int, value: int) -> None: + if self.capacity == 0: + return + if key in self.map: + node = self.map[key] + node.value = value + self.incr_freq(node) + return + if len(self.map) == self.capacity: + ls = self.freq_map[self.min_freq] + node = ls.remove_last() + self.map.pop(node.key) + node = Node(key, value) + self.add_node(node) + self.map[key] = node + self.min_freq = 1 + + def incr_freq(self, node: Node) -> None: + freq = node.freq + ls = self.freq_map[freq] + ls.remove(node) + if ls.is_empty(): + self.freq_map.pop(freq) + if freq == self.min_freq: + self.min_freq += 1 + node.freq += 1 + self.add_node(node) + + def add_node(self, node: Node) -> None: + freq = node.freq + ls = self.freq_map[freq] + ls.add_first(node) + self.freq_map[freq] = ls + + +# Your LFUCache object will be instantiated and called as such: +# obj = LFUCache(capacity) +# param_1 = obj.get(key) +# obj.put(key,value) diff --git a/solution/0400-0499/0462.Minimum Moves to Equal Array Elements II/Solution2.py b/solution/0400-0499/0462.Minimum Moves to Equal Array Elements II/Solution2.py new file mode 100644 index 0000000000000..f099225ea8553 --- /dev/null +++ b/solution/0400-0499/0462.Minimum Moves to Equal Array Elements II/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def minMoves2(self, nums: List[int]) -> int: + def move(i): + v = nums[i] + a = v * i - s[i] + b = s[-1] - s[i + 1] - v * (n - i - 1) + return a + b + + nums.sort() + s = [0] + list(accumulate(nums)) + n = len(nums) + return min(move(i) for i in range(n)) diff --git a/solution/0400-0499/0466.Count The Repetitions/Solution.cpp b/solution/0400-0499/0466.Count The Repetitions/Solution.cpp index 7e808b4a118b3..cb8e428f197e4 100644 --- a/solution/0400-0499/0466.Count The Repetitions/Solution.cpp +++ b/solution/0400-0499/0466.Count The Repetitions/Solution.cpp @@ -1,26 +1,26 @@ -class Solution { -public: - int getMaxRepetitions(string s1, int n1, string s2, int n2) { - int m = s1.size(), n = s2.size(); - vector> d; - for (int i = 0; i < n; ++i) { - int j = i; - int cnt = 0; - for (int k = 0; k < m; ++k) { - if (s1[k] == s2[j]) { - if (++j == n) { - ++cnt; - j = 0; - } - } - } - d.emplace_back(cnt, j); - } - int ans = 0; - for (int j = 0; n1; --n1) { - ans += d[j].first; - j = d[j].second; - } - return ans / n2; - } +class Solution { +public: + int getMaxRepetitions(string s1, int n1, string s2, int n2) { + int m = s1.size(), n = s2.size(); + vector> d; + for (int i = 0; i < n; ++i) { + int j = i; + int cnt = 0; + for (int k = 0; k < m; ++k) { + if (s1[k] == s2[j]) { + if (++j == n) { + ++cnt; + j = 0; + } + } + } + d.emplace_back(cnt, j); + } + int ans = 0; + for (int j = 0; n1; --n1) { + ans += d[j].first; + j = d[j].second; + } + return ans / n2; + } }; \ No newline at end of file diff --git a/solution/0400-0499/0466.Count The Repetitions/Solution.java b/solution/0400-0499/0466.Count The Repetitions/Solution.java index 54fefc776192d..ed19419de0929 100644 --- a/solution/0400-0499/0466.Count The Repetitions/Solution.java +++ b/solution/0400-0499/0466.Count The Repetitions/Solution.java @@ -1,25 +1,25 @@ -class Solution { - public int getMaxRepetitions(String s1, int n1, String s2, int n2) { - int m = s1.length(), n = s2.length(); - int[][] d = new int[n][0]; - for (int i = 0; i < n; ++i) { - int j = i; - int cnt = 0; - for (int k = 0; k < m; ++k) { - if (s1.charAt(k) == s2.charAt(j)) { - if (++j == n) { - j = 0; - ++cnt; - } - } - } - d[i] = new int[] {cnt, j}; - } - int ans = 0; - for (int j = 0; n1 > 0; --n1) { - ans += d[j][0]; - j = d[j][1]; - } - return ans / n2; - } +class Solution { + public int getMaxRepetitions(String s1, int n1, String s2, int n2) { + int m = s1.length(), n = s2.length(); + int[][] d = new int[n][0]; + for (int i = 0; i < n; ++i) { + int j = i; + int cnt = 0; + for (int k = 0; k < m; ++k) { + if (s1.charAt(k) == s2.charAt(j)) { + if (++j == n) { + j = 0; + ++cnt; + } + } + } + d[i] = new int[] {cnt, j}; + } + int ans = 0; + for (int j = 0; n1 > 0; --n1) { + ans += d[j][0]; + j = d[j][1]; + } + return ans / n2; + } } \ No newline at end of file diff --git a/solution/0400-0499/0466.Count The Repetitions/Solution.py b/solution/0400-0499/0466.Count The Repetitions/Solution.py index cf68783617198..16c1c1d1ac76a 100644 --- a/solution/0400-0499/0466.Count The Repetitions/Solution.py +++ b/solution/0400-0499/0466.Count The Repetitions/Solution.py @@ -1,21 +1,21 @@ -class Solution: - def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int: - n = len(s2) - d = {} - for i in range(n): - cnt = 0 - j = i - for c in s1: - if c == s2[j]: - j += 1 - if j == n: - cnt += 1 - j = 0 - d[i] = (cnt, j) - - ans = 0 - j = 0 - for _ in range(n1): - cnt, j = d[j] - ans += cnt - return ans // n2 +class Solution: + def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int: + n = len(s2) + d = {} + for i in range(n): + cnt = 0 + j = i + for c in s1: + if c == s2[j]: + j += 1 + if j == n: + cnt += 1 + j = 0 + d[i] = (cnt, j) + + ans = 0 + j = 0 + for _ in range(n1): + cnt, j = d[j] + ans += cnt + return ans // n2 diff --git a/solution/0400-0499/0469.Convex Polygon/Solution.cpp b/solution/0400-0499/0469.Convex Polygon/Solution.cpp index fffa6bd1fe8cd..2462aed2da7c1 100644 --- a/solution/0400-0499/0469.Convex Polygon/Solution.cpp +++ b/solution/0400-0499/0469.Convex Polygon/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - bool isConvex(vector>& points) { - int n = points.size(); - long long pre = 0, cur = 0; - for (int i = 0; i < n; ++i) { - int x1 = points[(i + 1) % n][0] - points[i][0]; - int y1 = points[(i + 1) % n][1] - points[i][1]; - int x2 = points[(i + 2) % n][0] - points[i][0]; - int y2 = points[(i + 2) % n][1] - points[i][1]; - cur = 1L * x1 * y2 - x2 * y1; - if (cur != 0) { - if (cur * pre < 0) { - return false; - } - pre = cur; - } - } - return true; - } +class Solution { +public: + bool isConvex(vector>& points) { + int n = points.size(); + long long pre = 0, cur = 0; + for (int i = 0; i < n; ++i) { + int x1 = points[(i + 1) % n][0] - points[i][0]; + int y1 = points[(i + 1) % n][1] - points[i][1]; + int x2 = points[(i + 2) % n][0] - points[i][0]; + int y2 = points[(i + 2) % n][1] - points[i][1]; + cur = 1L * x1 * y2 - x2 * y1; + if (cur != 0) { + if (cur * pre < 0) { + return false; + } + pre = cur; + } + } + return true; + } }; \ No newline at end of file diff --git a/solution/0400-0499/0469.Convex Polygon/Solution.java b/solution/0400-0499/0469.Convex Polygon/Solution.java index 988fbb325fe81..47ac18b7c43c7 100644 --- a/solution/0400-0499/0469.Convex Polygon/Solution.java +++ b/solution/0400-0499/0469.Convex Polygon/Solution.java @@ -1,23 +1,23 @@ -class Solution { - public boolean isConvex(List> points) { - int n = points.size(); - long pre = 0, cur = 0; - for (int i = 0; i < n; ++i) { - var p1 = points.get(i); - var p2 = points.get((i + 1) % n); - var p3 = points.get((i + 2) % n); - int x1 = p2.get(0) - p1.get(0); - int y1 = p2.get(1) - p1.get(1); - int x2 = p3.get(0) - p1.get(0); - int y2 = p3.get(1) - p1.get(1); - cur = x1 * y2 - x2 * y1; - if (cur != 0) { - if (cur * pre < 0) { - return false; - } - pre = cur; - } - } - return true; - } +class Solution { + public boolean isConvex(List> points) { + int n = points.size(); + long pre = 0, cur = 0; + for (int i = 0; i < n; ++i) { + var p1 = points.get(i); + var p2 = points.get((i + 1) % n); + var p3 = points.get((i + 2) % n); + int x1 = p2.get(0) - p1.get(0); + int y1 = p2.get(1) - p1.get(1); + int x2 = p3.get(0) - p1.get(0); + int y2 = p3.get(1) - p1.get(1); + cur = x1 * y2 - x2 * y1; + if (cur != 0) { + if (cur * pre < 0) { + return false; + } + pre = cur; + } + } + return true; + } } \ No newline at end of file diff --git a/solution/0400-0499/0469.Convex Polygon/Solution.py b/solution/0400-0499/0469.Convex Polygon/Solution.py index addf509c5ad84..0b88ce34c8024 100644 --- a/solution/0400-0499/0469.Convex Polygon/Solution.py +++ b/solution/0400-0499/0469.Convex Polygon/Solution.py @@ -1,15 +1,15 @@ -class Solution: - def isConvex(self, points: List[List[int]]) -> bool: - n = len(points) - pre = cur = 0 - for i in range(n): - x1 = points[(i + 1) % n][0] - points[i][0] - y1 = points[(i + 1) % n][1] - points[i][1] - x2 = points[(i + 2) % n][0] - points[i][0] - y2 = points[(i + 2) % n][1] - points[i][1] - cur = x1 * y2 - x2 * y1 - if cur != 0: - if cur * pre < 0: - return False - pre = cur - return True +class Solution: + def isConvex(self, points: List[List[int]]) -> bool: + n = len(points) + pre = cur = 0 + for i in range(n): + x1 = points[(i + 1) % n][0] - points[i][0] + y1 = points[(i + 1) % n][1] - points[i][1] + x2 = points[(i + 2) % n][0] - points[i][0] + y2 = points[(i + 2) % n][1] - points[i][1] + cur = x1 * y2 - x2 * y1 + if cur != 0: + if cur * pre < 0: + return False + pre = cur + return True diff --git a/solution/0400-0499/0470.Implement Rand10() Using Rand7()/Solution.cpp b/solution/0400-0499/0470.Implement Rand10() Using Rand7()/Solution.cpp index a3cff95440ef1..395cda954d0b1 100644 --- a/solution/0400-0499/0470.Implement Rand10() Using Rand7()/Solution.cpp +++ b/solution/0400-0499/0470.Implement Rand10() Using Rand7()/Solution.cpp @@ -1,17 +1,17 @@ -// The rand7() API is already defined for you. -// int rand7(); -// @return a random integer in the range 1 to 7 - -class Solution { -public: - int rand10() { - while (1) { - int i = rand7() - 1; - int j = rand7(); - int x = i * 7 + j; - if (x <= 40) { - return x % 10 + 1; - } - } - } +// The rand7() API is already defined for you. +// int rand7(); +// @return a random integer in the range 1 to 7 + +class Solution { +public: + int rand10() { + while (1) { + int i = rand7() - 1; + int j = rand7(); + int x = i * 7 + j; + if (x <= 40) { + return x % 10 + 1; + } + } + } }; \ No newline at end of file diff --git a/solution/0400-0499/0470.Implement Rand10() Using Rand7()/Solution.java b/solution/0400-0499/0470.Implement Rand10() Using Rand7()/Solution.java index 48b57b22b6c4d..a7ec34011d52a 100644 --- a/solution/0400-0499/0470.Implement Rand10() Using Rand7()/Solution.java +++ b/solution/0400-0499/0470.Implement Rand10() Using Rand7()/Solution.java @@ -1,17 +1,17 @@ -/** - * The rand7() API is already defined in the parent class SolBase. - * public int rand7(); - * @return a random integer in the range 1 to 7 - */ -class Solution extends SolBase { - public int rand10() { - while (true) { - int i = rand7() - 1; - int j = rand7(); - int x = i * 7 + j; - if (x <= 40) { - return x % 10 + 1; - } - } - } +/** + * The rand7() API is already defined in the parent class SolBase. + * public int rand7(); + * @return a random integer in the range 1 to 7 + */ +class Solution extends SolBase { + public int rand10() { + while (true) { + int i = rand7() - 1; + int j = rand7(); + int x = i * 7 + j; + if (x <= 40) { + return x % 10 + 1; + } + } + } } \ No newline at end of file diff --git a/solution/0400-0499/0470.Implement Rand10() Using Rand7()/Solution.py b/solution/0400-0499/0470.Implement Rand10() Using Rand7()/Solution.py index 5653c935976df..9dc30dcf3b441 100644 --- a/solution/0400-0499/0470.Implement Rand10() Using Rand7()/Solution.py +++ b/solution/0400-0499/0470.Implement Rand10() Using Rand7()/Solution.py @@ -1,16 +1,16 @@ -# The rand7() API is already defined for you. -# def rand7(): -# @return a random integer in the range 1 to 7 - - -class Solution: - def rand10(self): - """ - :rtype: int - """ - while 1: - i = rand7() - 1 - j = rand7() - x = i * 7 + j - if x <= 40: - return x % 10 + 1 +# The rand7() API is already defined for you. +# def rand7(): +# @return a random integer in the range 1 to 7 + + +class Solution: + def rand10(self): + """ + :rtype: int + """ + while 1: + i = rand7() - 1 + j = rand7() + x = i * 7 + j + if x <= 40: + return x % 10 + 1 diff --git a/solution/0400-0499/0471.Encode String with Shortest Length/Solution.cpp b/solution/0400-0499/0471.Encode String with Shortest Length/Solution.cpp index 86ca88596407a..7700deb7199ce 100644 --- a/solution/0400-0499/0471.Encode String with Shortest Length/Solution.cpp +++ b/solution/0400-0499/0471.Encode String with Shortest Length/Solution.cpp @@ -1,35 +1,35 @@ -class Solution { -public: - string encode(string s) { - int n = s.size(); - vector> f(n, vector(n)); - - auto g = [&](int i, int j) { - string t = s.substr(i, j - i + 1); - if (t.size() < 5) { - return t; - } - int k = (t + t).find(t, 1); - if (k < t.size()) { - int cnt = t.size() / k; - return to_string(cnt) + "[" + f[i][i + k - 1] + "]"; - } - return t; - }; - - for (int i = n - 1; ~i; --i) { - for (int j = i; j < n; ++j) { - f[i][j] = g(i, j); - if (j - i + 1 > 4) { - for (int k = i; k < j; ++k) { - string t = f[i][k] + f[k + 1][j]; - if (t.size() < f[i][j].size()) { - f[i][j] = t; - } - } - } - } - } - return f[0][n - 1]; - } +class Solution { +public: + string encode(string s) { + int n = s.size(); + vector> f(n, vector(n)); + + auto g = [&](int i, int j) { + string t = s.substr(i, j - i + 1); + if (t.size() < 5) { + return t; + } + int k = (t + t).find(t, 1); + if (k < t.size()) { + int cnt = t.size() / k; + return to_string(cnt) + "[" + f[i][i + k - 1] + "]"; + } + return t; + }; + + for (int i = n - 1; ~i; --i) { + for (int j = i; j < n; ++j) { + f[i][j] = g(i, j); + if (j - i + 1 > 4) { + for (int k = i; k < j; ++k) { + string t = f[i][k] + f[k + 1][j]; + if (t.size() < f[i][j].size()) { + f[i][j] = t; + } + } + } + } + } + return f[0][n - 1]; + } }; \ No newline at end of file diff --git a/solution/0400-0499/0471.Encode String with Shortest Length/Solution.java b/solution/0400-0499/0471.Encode String with Shortest Length/Solution.java index efed7108ec52d..068f99391b123 100644 --- a/solution/0400-0499/0471.Encode String with Shortest Length/Solution.java +++ b/solution/0400-0499/0471.Encode String with Shortest Length/Solution.java @@ -1,37 +1,37 @@ -class Solution { - private String s; - private String[][] f; - - public String encode(String s) { - this.s = s; - int n = s.length(); - f = new String[n][n]; - for (int i = n - 1; i >= 0; --i) { - for (int j = i; j < n; ++j) { - f[i][j] = g(i, j); - if (j - i + 1 > 4) { - for (int k = i; k < j; ++k) { - String t = f[i][k] + f[k + 1][j]; - if (f[i][j].length() > t.length()) { - f[i][j] = t; - } - } - } - } - } - return f[0][n - 1]; - } - - private String g(int i, int j) { - String t = s.substring(i, j + 1); - if (t.length() < 5) { - return t; - } - int k = (t + t).indexOf(t, 1); - if (k < t.length()) { - int cnt = t.length() / k; - return String.format("%d[%s]", cnt, f[i][i + k - 1]); - } - return t; - } +class Solution { + private String s; + private String[][] f; + + public String encode(String s) { + this.s = s; + int n = s.length(); + f = new String[n][n]; + for (int i = n - 1; i >= 0; --i) { + for (int j = i; j < n; ++j) { + f[i][j] = g(i, j); + if (j - i + 1 > 4) { + for (int k = i; k < j; ++k) { + String t = f[i][k] + f[k + 1][j]; + if (f[i][j].length() > t.length()) { + f[i][j] = t; + } + } + } + } + } + return f[0][n - 1]; + } + + private String g(int i, int j) { + String t = s.substring(i, j + 1); + if (t.length() < 5) { + return t; + } + int k = (t + t).indexOf(t, 1); + if (k < t.length()) { + int cnt = t.length() / k; + return String.format("%d[%s]", cnt, f[i][i + k - 1]); + } + return t; + } } \ No newline at end of file diff --git a/solution/0400-0499/0471.Encode String with Shortest Length/Solution.py b/solution/0400-0499/0471.Encode String with Shortest Length/Solution.py index 83990232037f2..e2c5b20b0ca6f 100644 --- a/solution/0400-0499/0471.Encode String with Shortest Length/Solution.py +++ b/solution/0400-0499/0471.Encode String with Shortest Length/Solution.py @@ -1,23 +1,23 @@ -class Solution: - def encode(self, s: str) -> str: - def g(i: int, j: int) -> str: - t = s[i : j + 1] - if len(t) < 5: - return t - k = (t + t).index(t, 1) - if k < len(t): - cnt = len(t) // k - return f"{cnt}[{f[i][i + k - 1]}]" - return t - - n = len(s) - f = [[None] * n for _ in range(n)] - for i in range(n - 1, -1, -1): - for j in range(i, n): - f[i][j] = g(i, j) - if j - i + 1 > 4: - for k in range(i, j): - t = f[i][k] + f[k + 1][j] - if len(f[i][j]) > len(t): - f[i][j] = t - return f[0][-1] +class Solution: + def encode(self, s: str) -> str: + def g(i: int, j: int) -> str: + t = s[i : j + 1] + if len(t) < 5: + return t + k = (t + t).index(t, 1) + if k < len(t): + cnt = len(t) // k + return f"{cnt}[{f[i][i + k - 1]}]" + return t + + n = len(s) + f = [[None] * n for _ in range(n)] + for i in range(n - 1, -1, -1): + for j in range(i, n): + f[i][j] = g(i, j) + if j - i + 1 > 4: + for k in range(i, j): + t = f[i][k] + f[k + 1][j] + if len(f[i][j]) > len(t): + f[i][j] = t + return f[0][-1] diff --git a/solution/0400-0499/0473.Matchsticks to Square/Solution.cpp b/solution/0400-0499/0473.Matchsticks to Square/Solution.cpp index eb4bbe81a935c..eebe519f25bb4 100644 --- a/solution/0400-0499/0473.Matchsticks to Square/Solution.cpp +++ b/solution/0400-0499/0473.Matchsticks to Square/Solution.cpp @@ -23,4 +23,4 @@ class Solution { } return false; } -}; +}; \ No newline at end of file diff --git a/solution/0400-0499/0473.Matchsticks to Square/Solution.java b/solution/0400-0499/0473.Matchsticks to Square/Solution.java index 13e3f654a7d47..35bf6753bb828 100644 --- a/solution/0400-0499/0473.Matchsticks to Square/Solution.java +++ b/solution/0400-0499/0473.Matchsticks to Square/Solution.java @@ -30,4 +30,4 @@ private boolean dfs(int u, int x, int[] matchsticks, int[] edges) { } return false; } -} +} \ No newline at end of file diff --git a/solution/0400-0499/0473.Matchsticks to Square/Solution2.py b/solution/0400-0499/0473.Matchsticks to Square/Solution2.py new file mode 100644 index 0000000000000..b11d0450465ed --- /dev/null +++ b/solution/0400-0499/0473.Matchsticks to Square/Solution2.py @@ -0,0 +1,20 @@ +class Solution: + def makesquare(self, matchsticks: List[int]) -> bool: + @cache + def dfs(state, t): + if state == (1 << len(matchsticks)) - 1: + return True + for i, v in enumerate(matchsticks): + if state & (1 << i): + continue + if t + v > s: + break + if dfs(state | (1 << i), (t + v) % s): + return True + return False + + s, mod = divmod(sum(matchsticks), 4) + matchsticks.sort() + if mod: + return False + return dfs(0, 0) diff --git a/solution/0400-0499/0474.Ones and Zeroes/Solution.cpp b/solution/0400-0499/0474.Ones and Zeroes/Solution.cpp index 675be9ed73eaa..30f3df8e08ea6 100644 --- a/solution/0400-0499/0474.Ones and Zeroes/Solution.cpp +++ b/solution/0400-0499/0474.Ones and Zeroes/Solution.cpp @@ -1,21 +1,25 @@ -class Solution { -public: - int findMaxForm(vector& strs, int m, int n) { - int f[m + 1][n + 1]; - memset(f, 0, sizeof(f)); - for (auto& s : strs) { - auto [a, b] = count(s); - for (int i = m; i >= a; --i) { - for (int j = n; j >= b; --j) { - f[i][j] = max(f[i][j], f[i - a][j - b] + 1); - } - } - } - return f[m][n]; - } - - pair count(string& s) { - int a = count_if(s.begin(), s.end(), [](char c) { return c == '0'; }); - return {a, s.size() - a}; - } +class Solution { +public: + int findMaxForm(vector& strs, int m, int n) { + int sz = strs.size(); + int f[sz + 1][m + 1][n + 1]; + memset(f, 0, sizeof(f)); + for (int i = 1; i <= sz; ++i) { + auto [a, b] = count(strs[i - 1]); + for (int j = 0; j <= m; ++j) { + for (int k = 0; k <= n; ++k) { + f[i][j][k] = f[i - 1][j][k]; + if (j >= a && k >= b) { + f[i][j][k] = max(f[i][j][k], f[i - 1][j - a][k - b] + 1); + } + } + } + } + return f[sz][m][n]; + } + + pair count(string& s) { + int a = count_if(s.begin(), s.end(), [](char c) { return c == '0'; }); + return {a, s.size() - a}; + } }; \ No newline at end of file diff --git a/solution/0400-0499/0474.Ones and Zeroes/Solution.go b/solution/0400-0499/0474.Ones and Zeroes/Solution.go index c1ba32a3dd8ac..d0823936ee46f 100644 --- a/solution/0400-0499/0474.Ones and Zeroes/Solution.go +++ b/solution/0400-0499/0474.Ones and Zeroes/Solution.go @@ -1,17 +1,24 @@ func findMaxForm(strs []string, m int, n int) int { - f := make([][]int, m+1) + sz := len(strs) + f := make([][][]int, sz+1) for i := range f { - f[i] = make([]int, n+1) + f[i] = make([][]int, m+1) + for j := range f[i] { + f[i][j] = make([]int, n+1) + } } - for _, s := range strs { - a, b := count(s) - for j := m; j >= a; j-- { - for k := n; k >= b; k-- { - f[j][k] = max(f[j][k], f[j-a][k-b]+1) + for i := 1; i <= sz; i++ { + a, b := count(strs[i-1]) + for j := 0; j <= m; j++ { + for k := 0; k <= n; k++ { + f[i][j][k] = f[i-1][j][k] + if j >= a && k >= b { + f[i][j][k] = max(f[i][j][k], f[i-1][j-a][k-b]+1) + } } } } - return f[m][n] + return f[sz][m][n] } func count(s string) (int, int) { diff --git a/solution/0400-0499/0474.Ones and Zeroes/Solution.java b/solution/0400-0499/0474.Ones and Zeroes/Solution.java index c2551778f1957..7b06797d91f83 100644 --- a/solution/0400-0499/0474.Ones and Zeroes/Solution.java +++ b/solution/0400-0499/0474.Ones and Zeroes/Solution.java @@ -1,22 +1,26 @@ -class Solution { - public int findMaxForm(String[] strs, int m, int n) { - int[][] f = new int[m + 1][n + 1]; - for (String s : strs) { - int[] cnt = count(s); - for (int i = m; i >= cnt[0]; --i) { - for (int j = n; j >= cnt[1]; --j) { - f[i][j] = Math.max(f[i][j], f[i - cnt[0]][j - cnt[1]] + 1); - } - } - } - return f[m][n]; - } - - private int[] count(String s) { - int[] cnt = new int[2]; - for (int i = 0; i < s.length(); ++i) { - ++cnt[s.charAt(i) - '0']; - } - return cnt; - } +class Solution { + public int findMaxForm(String[] strs, int m, int n) { + int sz = strs.length; + int[][][] f = new int[sz + 1][m + 1][n + 1]; + for (int i = 1; i <= sz; ++i) { + int[] cnt = count(strs[i - 1]); + for (int j = 0; j <= m; ++j) { + for (int k = 0; k <= n; ++k) { + f[i][j][k] = f[i - 1][j][k]; + if (j >= cnt[0] && k >= cnt[1]) { + f[i][j][k] = Math.max(f[i][j][k], f[i - 1][j - cnt[0]][k - cnt[1]] + 1); + } + } + } + } + return f[sz][m][n]; + } + + private int[] count(String s) { + int[] cnt = new int[2]; + for (int i = 0; i < s.length(); ++i) { + ++cnt[s.charAt(i) - '0']; + } + return cnt; + } } \ No newline at end of file diff --git a/solution/0400-0499/0474.Ones and Zeroes/Solution.py b/solution/0400-0499/0474.Ones and Zeroes/Solution.py index 7a410696daad9..010c66fa685c0 100644 --- a/solution/0400-0499/0474.Ones and Zeroes/Solution.py +++ b/solution/0400-0499/0474.Ones and Zeroes/Solution.py @@ -1,9 +1,12 @@ -class Solution: - def findMaxForm(self, strs: List[str], m: int, n: int) -> int: - f = [[0] * (n + 1) for _ in range(m + 1)] - for s in strs: - a, b = s.count("0"), s.count("1") - for i in range(m, a - 1, -1): - for j in range(n, b - 1, -1): - f[i][j] = max(f[i][j], f[i - a][j - b] + 1) - return f[m][n] +class Solution: + def findMaxForm(self, strs: List[str], m: int, n: int) -> int: + sz = len(strs) + f = [[[0] * (n + 1) for _ in range(m + 1)] for _ in range(sz + 1)] + for i, s in enumerate(strs, 1): + a, b = s.count("0"), s.count("1") + for j in range(m + 1): + for k in range(n + 1): + f[i][j][k] = f[i - 1][j][k] + if j >= a and k >= b: + f[i][j][k] = max(f[i][j][k], f[i - 1][j - a][k - b] + 1) + return f[sz][m][n] diff --git a/solution/0400-0499/0474.Ones and Zeroes/Solution.ts b/solution/0400-0499/0474.Ones and Zeroes/Solution.ts index dc1324af65a3b..ca45d6a67a24b 100644 --- a/solution/0400-0499/0474.Ones and Zeroes/Solution.ts +++ b/solution/0400-0499/0474.Ones and Zeroes/Solution.ts @@ -1,5 +1,8 @@ function findMaxForm(strs: string[], m: number, n: number): number { - const f = Array.from({ length: m + 1 }, () => Array.from({ length: n + 1 }, () => 0)); + const sz = strs.length; + const f = Array.from({ length: sz + 1 }, () => + Array.from({ length: m + 1 }, () => Array.from({ length: n + 1 }, () => 0)), + ); const count = (s: string): [number, number] => { let a = 0; for (const c of s) { @@ -7,13 +10,16 @@ function findMaxForm(strs: string[], m: number, n: number): number { } return [a, s.length - a]; }; - for (const s of strs) { - const [a, b] = count(s); - for (let i = m; i >= a; --i) { - for (let j = n; j >= b; --j) { - f[i][j] = Math.max(f[i][j], f[i - a][j - b] + 1); + for (let i = 1; i <= sz; ++i) { + const [a, b] = count(strs[i - 1]); + for (let j = 0; j <= m; ++j) { + for (let k = 0; k <= n; ++k) { + f[i][j][k] = f[i - 1][j][k]; + if (j >= a && k >= b) { + f[i][j][k] = Math.max(f[i][j][k], f[i - 1][j - a][k - b] + 1); + } } } } - return f[m][n]; + return f[sz][m][n]; } diff --git a/solution/0400-0499/0474.Ones and Zeroes/Solution2.cpp b/solution/0400-0499/0474.Ones and Zeroes/Solution2.cpp new file mode 100644 index 0000000000000..b3cf0b76e9587 --- /dev/null +++ b/solution/0400-0499/0474.Ones and Zeroes/Solution2.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int findMaxForm(vector& strs, int m, int n) { + int f[m + 1][n + 1]; + memset(f, 0, sizeof(f)); + for (auto& s : strs) { + auto [a, b] = count(s); + for (int i = m; i >= a; --i) { + for (int j = n; j >= b; --j) { + f[i][j] = max(f[i][j], f[i - a][j - b] + 1); + } + } + } + return f[m][n]; + } + + pair count(string& s) { + int a = count_if(s.begin(), s.end(), [](char c) { return c == '0'; }); + return {a, s.size() - a}; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0474.Ones and Zeroes/Solution2.go b/solution/0400-0499/0474.Ones and Zeroes/Solution2.go new file mode 100644 index 0000000000000..c1ba32a3dd8ac --- /dev/null +++ b/solution/0400-0499/0474.Ones and Zeroes/Solution2.go @@ -0,0 +1,20 @@ +func findMaxForm(strs []string, m int, n int) int { + f := make([][]int, m+1) + for i := range f { + f[i] = make([]int, n+1) + } + for _, s := range strs { + a, b := count(s) + for j := m; j >= a; j-- { + for k := n; k >= b; k-- { + f[j][k] = max(f[j][k], f[j-a][k-b]+1) + } + } + } + return f[m][n] +} + +func count(s string) (int, int) { + a := strings.Count(s, "0") + return a, len(s) - a +} \ No newline at end of file diff --git a/solution/0400-0499/0474.Ones and Zeroes/Solution2.java b/solution/0400-0499/0474.Ones and Zeroes/Solution2.java new file mode 100644 index 0000000000000..c52e43cae8bb2 --- /dev/null +++ b/solution/0400-0499/0474.Ones and Zeroes/Solution2.java @@ -0,0 +1,22 @@ +class Solution { + public int findMaxForm(String[] strs, int m, int n) { + int[][] f = new int[m + 1][n + 1]; + for (String s : strs) { + int[] cnt = count(s); + for (int i = m; i >= cnt[0]; --i) { + for (int j = n; j >= cnt[1]; --j) { + f[i][j] = Math.max(f[i][j], f[i - cnt[0]][j - cnt[1]] + 1); + } + } + } + return f[m][n]; + } + + private int[] count(String s) { + int[] cnt = new int[2]; + for (int i = 0; i < s.length(); ++i) { + ++cnt[s.charAt(i) - '0']; + } + return cnt; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0474.Ones and Zeroes/Solution2.py b/solution/0400-0499/0474.Ones and Zeroes/Solution2.py new file mode 100644 index 0000000000000..428f518b06339 --- /dev/null +++ b/solution/0400-0499/0474.Ones and Zeroes/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def findMaxForm(self, strs: List[str], m: int, n: int) -> int: + f = [[0] * (n + 1) for _ in range(m + 1)] + for s in strs: + a, b = s.count("0"), s.count("1") + for i in range(m, a - 1, -1): + for j in range(n, b - 1, -1): + f[i][j] = max(f[i][j], f[i - a][j - b] + 1) + return f[m][n] diff --git a/solution/0400-0499/0474.Ones and Zeroes/Solution2.ts b/solution/0400-0499/0474.Ones and Zeroes/Solution2.ts new file mode 100644 index 0000000000000..dc1324af65a3b --- /dev/null +++ b/solution/0400-0499/0474.Ones and Zeroes/Solution2.ts @@ -0,0 +1,19 @@ +function findMaxForm(strs: string[], m: number, n: number): number { + const f = Array.from({ length: m + 1 }, () => Array.from({ length: n + 1 }, () => 0)); + const count = (s: string): [number, number] => { + let a = 0; + for (const c of s) { + a += c === '0' ? 1 : 0; + } + return [a, s.length - a]; + }; + for (const s of strs) { + const [a, b] = count(s); + for (let i = m; i >= a; --i) { + for (let j = n; j >= b; --j) { + f[i][j] = Math.max(f[i][j], f[i - a][j - b] + 1); + } + } + } + return f[m][n]; +} diff --git a/solution/0400-0499/0475.Heaters/Solution.java b/solution/0400-0499/0475.Heaters/Solution.java index 425f99e9e34cb..b3d021abc2bc9 100644 --- a/solution/0400-0499/0475.Heaters/Solution.java +++ b/solution/0400-0499/0475.Heaters/Solution.java @@ -13,4 +13,4 @@ public int findRadius(int[] houses, int[] heaters) { } return res; } -} +} \ No newline at end of file diff --git a/solution/0400-0499/0476.Number Complement/Solution.cpp b/solution/0400-0499/0476.Number Complement/Solution.cpp index 6de34695822b2..fe300aab45d2b 100644 --- a/solution/0400-0499/0476.Number Complement/Solution.cpp +++ b/solution/0400-0499/0476.Number Complement/Solution.cpp @@ -1,14 +1,7 @@ class Solution { public: int findComplement(int num) { - int ans = 0; - bool find = false; - for (int i = 30; i >= 0; --i) { - int b = num & (1 << i); - if (!find && b == 0) continue; - find = true; - if (b == 0) ans |= (1 << i); - } - return ans; + int full = pow(2, int(log2(num)) + 1) - 1; + return full ^ num; } }; \ No newline at end of file diff --git a/solution/0400-0499/0476.Number Complement/Solution.py b/solution/0400-0499/0476.Number Complement/Solution.py index 7156b7276f47c..86d2aed41aa0c 100644 --- a/solution/0400-0499/0476.Number Complement/Solution.py +++ b/solution/0400-0499/0476.Number Complement/Solution.py @@ -1,3 +1,12 @@ class Solution: def findComplement(self, num: int) -> int: - return num ^ (2 ** (len(bin(num)[2:])) - 1) + ans = 0 + find = False + for i in range(30, -1, -1): + b = num & (1 << i) + if not find and b == 0: + continue + find = True + if b == 0: + ans |= 1 << i + return ans diff --git a/solution/0400-0499/0476.Number Complement/Solution2.cpp b/solution/0400-0499/0476.Number Complement/Solution2.cpp new file mode 100644 index 0000000000000..6de34695822b2 --- /dev/null +++ b/solution/0400-0499/0476.Number Complement/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int findComplement(int num) { + int ans = 0; + bool find = false; + for (int i = 30; i >= 0; --i) { + int b = num & (1 << i); + if (!find && b == 0) continue; + find = true; + if (b == 0) ans |= (1 << i); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0476.Number Complement/Solution2.py b/solution/0400-0499/0476.Number Complement/Solution2.py new file mode 100644 index 0000000000000..7156b7276f47c --- /dev/null +++ b/solution/0400-0499/0476.Number Complement/Solution2.py @@ -0,0 +1,3 @@ +class Solution: + def findComplement(self, num: int) -> int: + return num ^ (2 ** (len(bin(num)[2:])) - 1) diff --git a/solution/0400-0499/0479.Largest Palindrome Product/Solution.cpp b/solution/0400-0499/0479.Largest Palindrome Product/Solution.cpp index fb09efbe4d301..3459daa7bad0e 100644 --- a/solution/0400-0499/0479.Largest Palindrome Product/Solution.cpp +++ b/solution/0400-0499/0479.Largest Palindrome Product/Solution.cpp @@ -1,18 +1,18 @@ -class Solution { -public: - int largestPalindrome(int n) { - int mx = pow(10, n) - 1; - for (int a = mx; a > mx / 10; --a) { - int b = a; - long x = a; - while (b) { - x = x * 10 + b % 10; - b /= 10; - } - for (long t = mx; t * t >= x; --t) - if (x % t == 0) - return x % 1337; - } - return 9; - } +class Solution { +public: + int largestPalindrome(int n) { + int mx = pow(10, n) - 1; + for (int a = mx; a > mx / 10; --a) { + int b = a; + long x = a; + while (b) { + x = x * 10 + b % 10; + b /= 10; + } + for (long t = mx; t * t >= x; --t) + if (x % t == 0) + return x % 1337; + } + return 9; + } }; \ No newline at end of file diff --git a/solution/0400-0499/0479.Largest Palindrome Product/Solution.java b/solution/0400-0499/0479.Largest Palindrome Product/Solution.java index c18e0d6606d09..1649425a10f79 100644 --- a/solution/0400-0499/0479.Largest Palindrome Product/Solution.java +++ b/solution/0400-0499/0479.Largest Palindrome Product/Solution.java @@ -1,19 +1,19 @@ -class Solution { - public int largestPalindrome(int n) { - int mx = (int) Math.pow(10, n) - 1; - for (int a = mx; a > mx / 10; --a) { - int b = a; - long x = a; - while (b != 0) { - x = x * 10 + b % 10; - b /= 10; - } - for (long t = mx; t * t >= x; --t) { - if (x % t == 0) { - return (int) (x % 1337); - } - } - } - return 9; - } +class Solution { + public int largestPalindrome(int n) { + int mx = (int) Math.pow(10, n) - 1; + for (int a = mx; a > mx / 10; --a) { + int b = a; + long x = a; + while (b != 0) { + x = x * 10 + b % 10; + b /= 10; + } + for (long t = mx; t * t >= x; --t) { + if (x % t == 0) { + return (int) (x % 1337); + } + } + } + return 9; + } } \ No newline at end of file diff --git a/solution/0400-0499/0479.Largest Palindrome Product/Solution.py b/solution/0400-0499/0479.Largest Palindrome Product/Solution.py index 76e862eb18f52..0a24be647a28b 100644 --- a/solution/0400-0499/0479.Largest Palindrome Product/Solution.py +++ b/solution/0400-0499/0479.Largest Palindrome Product/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def largestPalindrome(self, n: int) -> int: - mx = 10**n - 1 - for a in range(mx, mx // 10, -1): - b = x = a - while b: - x = x * 10 + b % 10 - b //= 10 - t = mx - while t * t >= x: - if x % t == 0: - return x % 1337 - t -= 1 - return 9 +class Solution: + def largestPalindrome(self, n: int) -> int: + mx = 10**n - 1 + for a in range(mx, mx // 10, -1): + b = x = a + while b: + x = x * 10 + b % 10 + b //= 10 + t = mx + while t * t >= x: + if x % t == 0: + return x % 1337 + t -= 1 + return 9 diff --git a/solution/0400-0499/0481.Magical String/Solution.py b/solution/0400-0499/0481.Magical String/Solution.py index a96a04b1adce7..6365fc7acc0ba 100644 --- a/solution/0400-0499/0481.Magical String/Solution.py +++ b/solution/0400-0499/0481.Magical String/Solution.py @@ -5,6 +5,7 @@ def magicalString(self, n: int) -> int: while len(s) < n: pre = s[-1] cur = 3 - pre + # cur 表示这一组的数字,s[i] 表示这一组数字出现的次数 s += [cur] * s[i] i += 1 return s[:n].count(1) diff --git a/solution/0400-0499/0483.Smallest Good Base/Solution.java b/solution/0400-0499/0483.Smallest Good Base/Solution.java index 665e72952bb42..a64898d0688aa 100644 --- a/solution/0400-0499/0483.Smallest Good Base/Solution.java +++ b/solution/0400-0499/0483.Smallest Good Base/Solution.java @@ -38,4 +38,4 @@ private long calc(long radix, int len) { } return sum; } -} +} \ No newline at end of file diff --git a/solution/0400-0499/0485.Max Consecutive Ones/Solution.php b/solution/0400-0499/0485.Max Consecutive Ones/Solution.php index e433784ebaf45..143d507224ae5 100644 --- a/solution/0400-0499/0485.Max Consecutive Ones/Solution.php +++ b/solution/0400-0499/0485.Max Consecutive Ones/Solution.php @@ -15,4 +15,4 @@ function findMaxConsecutiveOnes($nums) { } return max($tmp, $max); } -} \ No newline at end of file +} diff --git a/solution/0400-0499/0486.Predict the Winner/Solution.cpp b/solution/0400-0499/0486.Predict the Winner/Solution.cpp index 0d919bbf17695..58f6253f0ffdb 100644 --- a/solution/0400-0499/0486.Predict the Winner/Solution.cpp +++ b/solution/0400-0499/0486.Predict the Winner/Solution.cpp @@ -4,14 +4,15 @@ class Solution { int n = nums.size(); int f[n][n]; memset(f, 0, sizeof(f)); - for (int i = 0; i < n; ++i) { - f[i][i] = nums[i]; - } - for (int i = n - 2; ~i; --i) { - for (int j = i + 1; j < n; ++j) { - f[i][j] = max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]); + function dfs = [&](int i, int j) -> int { + if (i > j) { + return 0; } - } - return f[0][n - 1] >= 0; + if (f[i][j]) { + return f[i][j]; + } + return f[i][j] = max(nums[i] - dfs(i + 1, j), nums[j] - dfs(i, j - 1)); + }; + return dfs(0, n - 1) >= 0; } }; \ No newline at end of file diff --git a/solution/0400-0499/0486.Predict the Winner/Solution.go b/solution/0400-0499/0486.Predict the Winner/Solution.go index 8becdf3e650b3..d9d1cb82a6a71 100644 --- a/solution/0400-0499/0486.Predict the Winner/Solution.go +++ b/solution/0400-0499/0486.Predict the Winner/Solution.go @@ -1,14 +1,18 @@ func PredictTheWinner(nums []int) bool { n := len(nums) f := make([][]int, n) - for i, x := range nums { + for i := range f { f[i] = make([]int, n) - f[i][i] = x } - for i := n - 2; i >= 0; i-- { - for j := i + 1; j < n; j++ { - f[i][j] = max(nums[i]-f[i+1][j], nums[j]-f[i][j-1]) + var dfs func(i, j int) int + dfs = func(i, j int) int { + if i > j { + return 0 } + if f[i][j] == 0 { + f[i][j] = max(nums[i]-dfs(i+1, j), nums[j]-dfs(i, j-1)) + } + return f[i][j] } - return f[0][n-1] >= 0 + return dfs(0, n-1) >= 0 } \ No newline at end of file diff --git a/solution/0400-0499/0486.Predict the Winner/Solution.java b/solution/0400-0499/0486.Predict the Winner/Solution.java index 8ba95d347bf20..7cd2834256a20 100644 --- a/solution/0400-0499/0486.Predict the Winner/Solution.java +++ b/solution/0400-0499/0486.Predict the Winner/Solution.java @@ -1,15 +1,21 @@ class Solution { + private int[] nums; + private int[][] f; + public boolean PredictTheWinner(int[] nums) { + this.nums = nums; int n = nums.length; - int[][] f = new int[n][n]; - for (int i = 0; i < n; ++i) { - f[i][i] = nums[i]; + f = new int[n][n]; + return dfs(0, n - 1) >= 0; + } + + private int dfs(int i, int j) { + if (i > j) { + return 0; } - for (int i = n - 2; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - f[i][j] = Math.max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]); - } + if (f[i][j] != 0) { + return f[i][j]; } - return f[0][n - 1] >= 0; + return f[i][j] = Math.max(nums[i] - dfs(i + 1, j), nums[j] - dfs(i, j - 1)); } } \ No newline at end of file diff --git a/solution/0400-0499/0486.Predict the Winner/Solution.py b/solution/0400-0499/0486.Predict the Winner/Solution.py index ea29b78c717a7..577b203921414 100644 --- a/solution/0400-0499/0486.Predict the Winner/Solution.py +++ b/solution/0400-0499/0486.Predict the Winner/Solution.py @@ -1,10 +1,9 @@ class Solution: def PredictTheWinner(self, nums: List[int]) -> bool: - n = len(nums) - f = [[0] * n for _ in range(n)] - for i, x in enumerate(nums): - f[i][i] = x - for i in range(n - 2, -1, -1): - for j in range(i + 1, n): - f[i][j] = max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]) - return f[0][n - 1] >= 0 + @cache + def dfs(i: int, j: int) -> int: + if i > j: + return 0 + return max(nums[i] - dfs(i + 1, j), nums[j] - dfs(i, j - 1)) + + return dfs(0, len(nums) - 1) >= 0 diff --git a/solution/0400-0499/0486.Predict the Winner/Solution.ts b/solution/0400-0499/0486.Predict the Winner/Solution.ts index b276dadc5cb88..1cb89afa05346 100644 --- a/solution/0400-0499/0486.Predict the Winner/Solution.ts +++ b/solution/0400-0499/0486.Predict the Winner/Solution.ts @@ -1,13 +1,14 @@ function PredictTheWinner(nums: number[]): boolean { const n = nums.length; const f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(0)); - for (let i = 0; i < n; ++i) { - f[i][i] = nums[i]; - } - for (let i = n - 2; i >= 0; --i) { - for (let j = i + 1; j < n; ++j) { - f[i][j] = Math.max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]); + const dfs = (i: number, j: number): number => { + if (i > j) { + return 0; } - } - return f[0][n - 1] >= 0; + if (f[i][j] === 0) { + f[i][j] = Math.max(nums[i] - dfs(i + 1, j), nums[j] - dfs(i, j - 1)); + } + return f[i][j]; + }; + return dfs(0, n - 1) >= 0; } diff --git a/solution/0400-0499/0486.Predict the Winner/Solution2.cpp b/solution/0400-0499/0486.Predict the Winner/Solution2.cpp new file mode 100644 index 0000000000000..0d919bbf17695 --- /dev/null +++ b/solution/0400-0499/0486.Predict the Winner/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool PredictTheWinner(vector& nums) { + int n = nums.size(); + int f[n][n]; + memset(f, 0, sizeof(f)); + for (int i = 0; i < n; ++i) { + f[i][i] = nums[i]; + } + for (int i = n - 2; ~i; --i) { + for (int j = i + 1; j < n; ++j) { + f[i][j] = max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]); + } + } + return f[0][n - 1] >= 0; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0486.Predict the Winner/Solution2.go b/solution/0400-0499/0486.Predict the Winner/Solution2.go new file mode 100644 index 0000000000000..8becdf3e650b3 --- /dev/null +++ b/solution/0400-0499/0486.Predict the Winner/Solution2.go @@ -0,0 +1,14 @@ +func PredictTheWinner(nums []int) bool { + n := len(nums) + f := make([][]int, n) + for i, x := range nums { + f[i] = make([]int, n) + f[i][i] = x + } + for i := n - 2; i >= 0; i-- { + for j := i + 1; j < n; j++ { + f[i][j] = max(nums[i]-f[i+1][j], nums[j]-f[i][j-1]) + } + } + return f[0][n-1] >= 0 +} \ No newline at end of file diff --git a/solution/0400-0499/0486.Predict the Winner/Solution2.java b/solution/0400-0499/0486.Predict the Winner/Solution2.java new file mode 100644 index 0000000000000..8ba95d347bf20 --- /dev/null +++ b/solution/0400-0499/0486.Predict the Winner/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public boolean PredictTheWinner(int[] nums) { + int n = nums.length; + int[][] f = new int[n][n]; + for (int i = 0; i < n; ++i) { + f[i][i] = nums[i]; + } + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + f[i][j] = Math.max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]); + } + } + return f[0][n - 1] >= 0; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0486.Predict the Winner/Solution2.py b/solution/0400-0499/0486.Predict the Winner/Solution2.py new file mode 100644 index 0000000000000..ea29b78c717a7 --- /dev/null +++ b/solution/0400-0499/0486.Predict the Winner/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def PredictTheWinner(self, nums: List[int]) -> bool: + n = len(nums) + f = [[0] * n for _ in range(n)] + for i, x in enumerate(nums): + f[i][i] = x + for i in range(n - 2, -1, -1): + for j in range(i + 1, n): + f[i][j] = max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]) + return f[0][n - 1] >= 0 diff --git a/solution/0400-0499/0486.Predict the Winner/Solution2.ts b/solution/0400-0499/0486.Predict the Winner/Solution2.ts new file mode 100644 index 0000000000000..b276dadc5cb88 --- /dev/null +++ b/solution/0400-0499/0486.Predict the Winner/Solution2.ts @@ -0,0 +1,13 @@ +function PredictTheWinner(nums: number[]): boolean { + const n = nums.length; + const f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(0)); + for (let i = 0; i < n; ++i) { + f[i][i] = nums[i]; + } + for (let i = n - 2; i >= 0; --i) { + for (let j = i + 1; j < n; ++j) { + f[i][j] = Math.max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]); + } + } + return f[0][n - 1] >= 0; +} diff --git a/solution/0400-0499/0487.Max Consecutive Ones II/Solution.cpp b/solution/0400-0499/0487.Max Consecutive Ones II/Solution.cpp index 178e9b80178e1..350f8089a2c95 100644 --- a/solution/0400-0499/0487.Max Consecutive Ones II/Solution.cpp +++ b/solution/0400-0499/0487.Max Consecutive Ones II/Solution.cpp @@ -1,16 +1,29 @@ class Solution { public: int findMaxConsecutiveOnes(vector& nums) { - int l = 0, r = 0; - int k = 1; - while (r < nums.size()) { - if (nums[r++] == 0) { - --k; + int n = nums.size(); + vector left(n), right(n); + for (int i = 0; i < n; ++i) { + if (nums[i]) { + left[i] = i == 0 ? 1 : left[i - 1] + 1; } - if (k < 0 && nums[l++] == 0) { - ++k; + } + for (int i = n - 1; ~i; --i) { + if (nums[i]) { + right[i] = i == n - 1 ? 1 : right[i + 1] + 1; + } + } + int ans = 0; + for (int i = 0; i < n; ++i) { + int t = 0; + if (i) { + t += left[i - 1]; + } + if (i < n - 1) { + t += right[i + 1]; } + ans = max(ans, t + 1); } - return r - l; + return ans; } }; \ No newline at end of file diff --git a/solution/0400-0499/0487.Max Consecutive Ones II/Solution.go b/solution/0400-0499/0487.Max Consecutive Ones II/Solution.go index b0470bf69e722..c0ef60889a6a5 100644 --- a/solution/0400-0499/0487.Max Consecutive Ones II/Solution.go +++ b/solution/0400-0499/0487.Max Consecutive Ones II/Solution.go @@ -1,16 +1,35 @@ func findMaxConsecutiveOnes(nums []int) int { - l, r := 0, 0 - k := 1 - for ; r < len(nums); r++ { - if nums[r] == 0 { - k-- + n := len(nums) + left := make([]int, n) + right := make([]int, n) + for i, v := range nums { + if v == 1 { + if i == 0 { + left[i] = 1 + } else { + left[i] = left[i-1] + 1 + } } - if k < 0 { - if nums[l] == 0 { - k++ + } + for i := n - 1; i >= 0; i-- { + if nums[i] == 1 { + if i == n-1 { + right[i] = 1 + } else { + right[i] = right[i+1] + 1 } - l++ } } - return r - l + ans := 0 + for i := range nums { + t := 0 + if i > 0 { + t += left[i-1] + } + if i < n-1 { + t += right[i+1] + } + ans = max(ans, t+1) + } + return ans } \ No newline at end of file diff --git a/solution/0400-0499/0487.Max Consecutive Ones II/Solution.java b/solution/0400-0499/0487.Max Consecutive Ones II/Solution.java index 54b4fd3b93cff..aff3a28d350f1 100644 --- a/solution/0400-0499/0487.Max Consecutive Ones II/Solution.java +++ b/solution/0400-0499/0487.Max Consecutive Ones II/Solution.java @@ -1,15 +1,29 @@ class Solution { public int findMaxConsecutiveOnes(int[] nums) { - int l = 0, r = 0; - int k = 1; - while (r < nums.length) { - if (nums[r++] == 0) { - --k; + int n = nums.length; + int[] left = new int[n]; + int[] right = new int[n]; + for (int i = 0; i < n; ++i) { + if (nums[i] == 1) { + left[i] = i == 0 ? 1 : left[i - 1] + 1; } - if (k < 0 && nums[l++] == 0) { - ++k; + } + for (int i = n - 1; i >= 0; --i) { + if (nums[i] == 1) { + right[i] = i == n - 1 ? 1 : right[i + 1] + 1; + } + } + int ans = 0; + for (int i = 0; i < n; ++i) { + int t = 0; + if (i > 0) { + t += left[i - 1]; + } + if (i < n - 1) { + t += right[i + 1]; } + ans = Math.max(ans, t + 1); } - return r - l; + return ans; } } \ No newline at end of file diff --git a/solution/0400-0499/0487.Max Consecutive Ones II/Solution.py b/solution/0400-0499/0487.Max Consecutive Ones II/Solution.py index b7054bfad1627..c68b049c5c78f 100644 --- a/solution/0400-0499/0487.Max Consecutive Ones II/Solution.py +++ b/solution/0400-0499/0487.Max Consecutive Ones II/Solution.py @@ -1,13 +1,22 @@ class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: - l = r = 0 - k = 1 - while r < len(nums): - if nums[r] == 0: - k -= 1 - if k < 0: - if nums[l] == 0: - k += 1 - l += 1 - r += 1 - return r - l + ans = nums.count(1) + n = len(nums) + left = [0] * n + right = [0] * n + for i, v in enumerate(nums): + if v: + left[i] = 1 if i == 0 else left[i - 1] + 1 + for i in range(n - 1, -1, -1): + v = nums[i] + if v: + right[i] = 1 if i == n - 1 else right[i + 1] + 1 + ans = 0 + for i, v in enumerate(nums): + t = 0 + if i: + t += left[i - 1] + if i < n - 1: + t += right[i + 1] + ans = max(ans, t + 1) + return ans diff --git a/solution/0400-0499/0487.Max Consecutive Ones II/Solution2.cpp b/solution/0400-0499/0487.Max Consecutive Ones II/Solution2.cpp new file mode 100644 index 0000000000000..0e41eacc38733 --- /dev/null +++ b/solution/0400-0499/0487.Max Consecutive Ones II/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int findMaxConsecutiveOnes(vector& nums) { + int ans = 1; + int cnt = 0, j = 0; + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] == 0) { + ++cnt; + } + while (cnt > 1) { + if (nums[j++] == 0) { + --cnt; + } + } + ans = max(ans, i - j + 1); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0487.Max Consecutive Ones II/Solution2.go b/solution/0400-0499/0487.Max Consecutive Ones II/Solution2.go new file mode 100644 index 0000000000000..137e6bcb7bf48 --- /dev/null +++ b/solution/0400-0499/0487.Max Consecutive Ones II/Solution2.go @@ -0,0 +1,17 @@ +func findMaxConsecutiveOnes(nums []int) int { + ans := 1 + j, cnt := 0, 0 + for i, v := range nums { + if v == 0 { + cnt++ + } + for cnt > 1 { + if nums[j] == 0 { + cnt-- + } + j++ + } + ans = max(ans, i-j+1) + } + return ans +} \ No newline at end of file diff --git a/solution/0400-0499/0487.Max Consecutive Ones II/Solution2.java b/solution/0400-0499/0487.Max Consecutive Ones II/Solution2.java new file mode 100644 index 0000000000000..832bb7c7058df --- /dev/null +++ b/solution/0400-0499/0487.Max Consecutive Ones II/Solution2.java @@ -0,0 +1,18 @@ +class Solution { + public int findMaxConsecutiveOnes(int[] nums) { + int j = 0, cnt = 0; + int ans = 1; + for (int i = 0; i < nums.length; ++i) { + if (nums[i] == 0) { + ++cnt; + } + while (cnt > 1) { + if (nums[j++] == 0) { + --cnt; + } + } + ans = Math.max(ans, i - j + 1); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0487.Max Consecutive Ones II/Solution2.py b/solution/0400-0499/0487.Max Consecutive Ones II/Solution2.py new file mode 100644 index 0000000000000..a5f7c004d8524 --- /dev/null +++ b/solution/0400-0499/0487.Max Consecutive Ones II/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def findMaxConsecutiveOnes(self, nums: List[int]) -> int: + ans = 1 + cnt = j = 0 + for i, v in enumerate(nums): + if v == 0: + cnt += 1 + while cnt > 1: + if nums[j] == 0: + cnt -= 1 + j += 1 + ans = max(ans, i - j + 1) + return ans diff --git a/solution/0400-0499/0487.Max Consecutive Ones II/Solution3.cpp b/solution/0400-0499/0487.Max Consecutive Ones II/Solution3.cpp new file mode 100644 index 0000000000000..178e9b80178e1 --- /dev/null +++ b/solution/0400-0499/0487.Max Consecutive Ones II/Solution3.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int findMaxConsecutiveOnes(vector& nums) { + int l = 0, r = 0; + int k = 1; + while (r < nums.size()) { + if (nums[r++] == 0) { + --k; + } + if (k < 0 && nums[l++] == 0) { + ++k; + } + } + return r - l; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0487.Max Consecutive Ones II/Solution3.go b/solution/0400-0499/0487.Max Consecutive Ones II/Solution3.go new file mode 100644 index 0000000000000..b0470bf69e722 --- /dev/null +++ b/solution/0400-0499/0487.Max Consecutive Ones II/Solution3.go @@ -0,0 +1,16 @@ +func findMaxConsecutiveOnes(nums []int) int { + l, r := 0, 0 + k := 1 + for ; r < len(nums); r++ { + if nums[r] == 0 { + k-- + } + if k < 0 { + if nums[l] == 0 { + k++ + } + l++ + } + } + return r - l +} \ No newline at end of file diff --git a/solution/0400-0499/0487.Max Consecutive Ones II/Solution3.java b/solution/0400-0499/0487.Max Consecutive Ones II/Solution3.java new file mode 100644 index 0000000000000..54b4fd3b93cff --- /dev/null +++ b/solution/0400-0499/0487.Max Consecutive Ones II/Solution3.java @@ -0,0 +1,15 @@ +class Solution { + public int findMaxConsecutiveOnes(int[] nums) { + int l = 0, r = 0; + int k = 1; + while (r < nums.length) { + if (nums[r++] == 0) { + --k; + } + if (k < 0 && nums[l++] == 0) { + ++k; + } + } + return r - l; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0487.Max Consecutive Ones II/Solution3.py b/solution/0400-0499/0487.Max Consecutive Ones II/Solution3.py new file mode 100644 index 0000000000000..b7054bfad1627 --- /dev/null +++ b/solution/0400-0499/0487.Max Consecutive Ones II/Solution3.py @@ -0,0 +1,13 @@ +class Solution: + def findMaxConsecutiveOnes(self, nums: List[int]) -> int: + l = r = 0 + k = 1 + while r < len(nums): + if nums[r] == 0: + k -= 1 + if k < 0: + if nums[l] == 0: + k += 1 + l += 1 + r += 1 + return r - l diff --git a/solution/0400-0499/0489.Robot Room Cleaner/Solution.cpp b/solution/0400-0499/0489.Robot Room Cleaner/Solution.cpp index 01e4d130e06dd..c11f61ed0827c 100644 --- a/solution/0400-0499/0489.Robot Room Cleaner/Solution.cpp +++ b/solution/0400-0499/0489.Robot Room Cleaner/Solution.cpp @@ -1,44 +1,44 @@ -/** - * // This is the robot's control interface. - * // You should not implement it, or speculate about its implementation - * class Robot { - * public: - * // Returns true if the cell in front is open and robot moves into the cell. - * // Returns false if the cell in front is blocked and robot stays in the current cell. - * bool move(); - * - * // Robot will stay in the same cell after calling turnLeft/turnRight. - * // Each turn will be 90 degrees. - * void turnLeft(); - * void turnRight(); - * - * // Clean the current cell. - * void clean(); - * }; - */ - -class Solution { -public: - void cleanRoom(Robot& robot) { - int dirs[5] = {-1, 0, 1, 0, -1}; - set> vis; - function dfs = [&](int i, int j, int d) { - robot.clean(); - vis.insert({i, j}); - for (int k = 0; k < 4; ++k) { - int nd = (d + k) % 4; - int x = i + dirs[nd], y = j + dirs[nd + 1]; - if (!vis.count({x, y}) && robot.move()) { - dfs(x, y, nd); - robot.turnRight(); - robot.turnRight(); - robot.move(); - robot.turnRight(); - robot.turnRight(); - } - robot.turnRight(); - } - }; - dfs(0, 0, 0); - } +/** + * // This is the robot's control interface. + * // You should not implement it, or speculate about its implementation + * class Robot { + * public: + * // Returns true if the cell in front is open and robot moves into the cell. + * // Returns false if the cell in front is blocked and robot stays in the current cell. + * bool move(); + * + * // Robot will stay in the same cell after calling turnLeft/turnRight. + * // Each turn will be 90 degrees. + * void turnLeft(); + * void turnRight(); + * + * // Clean the current cell. + * void clean(); + * }; + */ + +class Solution { +public: + void cleanRoom(Robot& robot) { + int dirs[5] = {-1, 0, 1, 0, -1}; + set> vis; + function dfs = [&](int i, int j, int d) { + robot.clean(); + vis.insert({i, j}); + for (int k = 0; k < 4; ++k) { + int nd = (d + k) % 4; + int x = i + dirs[nd], y = j + dirs[nd + 1]; + if (!vis.count({x, y}) && robot.move()) { + dfs(x, y, nd); + robot.turnRight(); + robot.turnRight(); + robot.move(); + robot.turnRight(); + robot.turnRight(); + } + robot.turnRight(); + } + }; + dfs(0, 0, 0); + } }; \ No newline at end of file diff --git a/solution/0400-0499/0489.Robot Room Cleaner/Solution.java b/solution/0400-0499/0489.Robot Room Cleaner/Solution.java index 6b7343d80a471..8eec352b39d46 100644 --- a/solution/0400-0499/0489.Robot Room Cleaner/Solution.java +++ b/solution/0400-0499/0489.Robot Room Cleaner/Solution.java @@ -1,46 +1,46 @@ -/** - * // This is the robot's control interface. - * // You should not implement it, or speculate about its implementation - * interface Robot { - * // Returns true if the cell in front is open and robot moves into the cell. - * // Returns false if the cell in front is blocked and robot stays in the current cell. - * public boolean move(); - * - * // Robot will stay in the same cell after calling turnLeft/turnRight. - * // Each turn will be 90 degrees. - * public void turnLeft(); - * public void turnRight(); - * - * // Clean the current cell. - * public void clean(); - * } - */ - -class Solution { - private int[] dirs = {-1, 0, 1, 0, -1}; - private Set> vis = new HashSet<>(); - private Robot robot; - - public void cleanRoom(Robot robot) { - this.robot = robot; - dfs(0, 0, 0); - } - - private void dfs(int i, int j, int d) { - robot.clean(); - vis.add(List.of(i, j)); - for (int k = 0; k < 4; ++k) { - int nd = (d + k) % 4; - int x = i + dirs[nd], y = j + dirs[nd + 1]; - if (!vis.contains(List.of(x, y)) && robot.move()) { - dfs(x, y, nd); - robot.turnRight(); - robot.turnRight(); - robot.move(); - robot.turnRight(); - robot.turnRight(); - } - robot.turnRight(); - } - } +/** + * // This is the robot's control interface. + * // You should not implement it, or speculate about its implementation + * interface Robot { + * // Returns true if the cell in front is open and robot moves into the cell. + * // Returns false if the cell in front is blocked and robot stays in the current cell. + * public boolean move(); + * + * // Robot will stay in the same cell after calling turnLeft/turnRight. + * // Each turn will be 90 degrees. + * public void turnLeft(); + * public void turnRight(); + * + * // Clean the current cell. + * public void clean(); + * } + */ + +class Solution { + private int[] dirs = {-1, 0, 1, 0, -1}; + private Set> vis = new HashSet<>(); + private Robot robot; + + public void cleanRoom(Robot robot) { + this.robot = robot; + dfs(0, 0, 0); + } + + private void dfs(int i, int j, int d) { + robot.clean(); + vis.add(List.of(i, j)); + for (int k = 0; k < 4; ++k) { + int nd = (d + k) % 4; + int x = i + dirs[nd], y = j + dirs[nd + 1]; + if (!vis.contains(List.of(x, y)) && robot.move()) { + dfs(x, y, nd); + robot.turnRight(); + robot.turnRight(); + robot.move(); + robot.turnRight(); + robot.turnRight(); + } + robot.turnRight(); + } + } } \ No newline at end of file diff --git a/solution/0400-0499/0489.Robot Room Cleaner/Solution.py b/solution/0400-0499/0489.Robot Room Cleaner/Solution.py index 392eab8f9f8cd..2a32a473df8cd 100644 --- a/solution/0400-0499/0489.Robot Room Cleaner/Solution.py +++ b/solution/0400-0499/0489.Robot Room Cleaner/Solution.py @@ -1,58 +1,58 @@ -# """ -# This is the robot's control interface. -# You should not implement it, or speculate about its implementation -# """ -# class Robot: -# def move(self): -# """ -# Returns true if the cell in front is open and robot moves into the cell. -# Returns false if the cell in front is blocked and robot stays in the current cell. -# :rtype bool -# """ -# -# def turnLeft(self): -# """ -# Robot will stay in the same cell after calling turnLeft/turnRight. -# Each turn will be 90 degrees. -# :rtype void -# """ -# -# def turnRight(self): -# """ -# Robot will stay in the same cell after calling turnLeft/turnRight. -# Each turn will be 90 degrees. -# :rtype void -# """ -# -# def clean(self): -# """ -# Clean the current cell. -# :rtype void -# """ - - -class Solution: - def cleanRoom(self, robot): - """ - :type robot: Robot - :rtype: None - """ - - def dfs(i, j, d): - vis.add((i, j)) - robot.clean() - for k in range(4): - nd = (d + k) % 4 - x, y = i + dirs[nd], j + dirs[nd + 1] - if (x, y) not in vis and robot.move(): - dfs(x, y, nd) - robot.turnRight() - robot.turnRight() - robot.move() - robot.turnRight() - robot.turnRight() - robot.turnRight() - - dirs = (-1, 0, 1, 0, -1) - vis = set() - dfs(0, 0, 0) +# """ +# This is the robot's control interface. +# You should not implement it, or speculate about its implementation +# """ +# class Robot: +# def move(self): +# """ +# Returns true if the cell in front is open and robot moves into the cell. +# Returns false if the cell in front is blocked and robot stays in the current cell. +# :rtype bool +# """ +# +# def turnLeft(self): +# """ +# Robot will stay in the same cell after calling turnLeft/turnRight. +# Each turn will be 90 degrees. +# :rtype void +# """ +# +# def turnRight(self): +# """ +# Robot will stay in the same cell after calling turnLeft/turnRight. +# Each turn will be 90 degrees. +# :rtype void +# """ +# +# def clean(self): +# """ +# Clean the current cell. +# :rtype void +# """ + + +class Solution: + def cleanRoom(self, robot): + """ + :type robot: Robot + :rtype: None + """ + + def dfs(i, j, d): + vis.add((i, j)) + robot.clean() + for k in range(4): + nd = (d + k) % 4 + x, y = i + dirs[nd], j + dirs[nd + 1] + if (x, y) not in vis and robot.move(): + dfs(x, y, nd) + robot.turnRight() + robot.turnRight() + robot.move() + robot.turnRight() + robot.turnRight() + robot.turnRight() + + dirs = (-1, 0, 1, 0, -1) + vis = set() + dfs(0, 0, 0) diff --git a/solution/0400-0499/0490.The Maze/Solution.cpp b/solution/0400-0499/0490.The Maze/Solution.cpp index e17cfef2a19ab..d3e4c12e5b9c7 100644 --- a/solution/0400-0499/0490.The Maze/Solution.cpp +++ b/solution/0400-0499/0490.The Maze/Solution.cpp @@ -1,30 +1,34 @@ class Solution { public: + vector> maze; + vector> vis; + vector d; + int m; + int n; + bool hasPath(vector>& maze, vector& start, vector& destination) { - int m = maze.size(); - int n = maze[0].size(); - queue> q{{start}}; - vector> vis(m, vector(n)); - vis[start[0]][start[1]] = true; + m = maze.size(); + n = maze[0].size(); + d = destination; + vis.resize(m, vector(n, false)); + this->maze = maze; + dfs(start[0], start[1]); + return vis[d[0]][d[1]]; + } + + void dfs(int i, int j) { + if (vis[i][j]) return; + vis[i][j] = true; + if (i == d[0] && j == d[1]) return; vector dirs = {-1, 0, 1, 0, -1}; - while (!q.empty()) { - auto p = q.front(); - q.pop(); - int i = p[0], j = p[1]; - for (int k = 0; k < 4; ++k) { - int x = i, y = j; - int a = dirs[k], b = dirs[k + 1]; - while (x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0) { - x += a; - y += b; - } - if (x == destination[0] && y == destination[1]) return 1; - if (!vis[x][y]) { - vis[x][y] = true; - q.push({x, y}); - } + for (int k = 0; k < 4; ++k) { + int x = i, y = j; + int a = dirs[k], b = dirs[k + 1]; + while (x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0) { + x += a; + y += b; } + dfs(x, y); } - return 0; } }; \ No newline at end of file diff --git a/solution/0400-0499/0490.The Maze/Solution.go b/solution/0400-0499/0490.The Maze/Solution.go index b5ca6f8459ea5..50f592dbbc38a 100644 --- a/solution/0400-0499/0490.The Maze/Solution.go +++ b/solution/0400-0499/0490.The Maze/Solution.go @@ -4,12 +4,16 @@ func hasPath(maze [][]int, start []int, destination []int) bool { for i := range vis { vis[i] = make([]bool, n) } - vis[start[0]][start[1]] = true - q := [][]int{start} - dirs := []int{-1, 0, 1, 0, -1} - for len(q) > 0 { - i, j := q[0][0], q[0][1] - q = q[1:] + var dfs func(i, j int) + dfs = func(i, j int) { + if vis[i][j] { + return + } + vis[i][j] = true + if i == destination[0] && j == destination[1] { + return + } + dirs := []int{-1, 0, 1, 0, -1} for k := 0; k < 4; k++ { x, y := i, j a, b := dirs[k], dirs[k+1] @@ -17,14 +21,9 @@ func hasPath(maze [][]int, start []int, destination []int) bool { x += a y += b } - if x == destination[0] && y == destination[1] { - return true - } - if !vis[x][y] { - vis[x][y] = true - q = append(q, []int{x, y}) - } + dfs(x, y) } } - return false + dfs(start[0], start[1]) + return vis[destination[0]][destination[1]] } \ No newline at end of file diff --git a/solution/0400-0499/0490.The Maze/Solution.java b/solution/0400-0499/0490.The Maze/Solution.java index b58aa2b3209e1..e4a6d18247fab 100644 --- a/solution/0400-0499/0490.The Maze/Solution.java +++ b/solution/0400-0499/0490.The Maze/Solution.java @@ -1,32 +1,37 @@ class Solution { + private boolean[][] vis; + private int[][] maze; + private int[] d; + private int m; + private int n; + public boolean hasPath(int[][] maze, int[] start, int[] destination) { - int m = maze.length; - int n = maze[0].length; - boolean[][] vis = new boolean[m][n]; - vis[start[0]][start[1]] = true; - Deque q = new LinkedList<>(); - q.offer(start); + m = maze.length; + n = maze[0].length; + d = destination; + this.maze = maze; + vis = new boolean[m][n]; + dfs(start[0], start[1]); + return vis[d[0]][d[1]]; + } + + private void dfs(int i, int j) { + if (vis[i][j]) { + return; + } + vis[i][j] = true; + if (i == d[0] && j == d[1]) { + return; + } int[] dirs = {-1, 0, 1, 0, -1}; - while (!q.isEmpty()) { - int[] p = q.poll(); - int i = p[0], j = p[1]; - for (int k = 0; k < 4; ++k) { - int x = i, y = j; - int a = dirs[k], b = dirs[k + 1]; - while ( - x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0) { - x += a; - y += b; - } - if (x == destination[0] && y == destination[1]) { - return true; - } - if (!vis[x][y]) { - vis[x][y] = true; - q.offer(new int[] {x, y}); - } + for (int k = 0; k < 4; ++k) { + int x = i, y = j; + int a = dirs[k], b = dirs[k + 1]; + while (x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0) { + x += a; + y += b; } + dfs(x, y); } - return false; } } \ No newline at end of file diff --git a/solution/0400-0499/0490.The Maze/Solution.py b/solution/0400-0499/0490.The Maze/Solution.py index c93a05d47ad42..39f4a6b93ecfd 100644 --- a/solution/0400-0499/0490.The Maze/Solution.py +++ b/solution/0400-0499/0490.The Maze/Solution.py @@ -2,19 +2,19 @@ class Solution: def hasPath( self, maze: List[List[int]], start: List[int], destination: List[int] ) -> bool: - m, n = len(maze), len(maze[0]) - q = deque([start]) - rs, cs = start - vis = {(rs, cs)} - while q: - i, j = q.popleft() - for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: + def dfs(i, j): + if vis[i][j]: + return + vis[i][j] = True + if [i, j] == destination: + return + for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]: x, y = i, j while 0 <= x + a < m and 0 <= y + b < n and maze[x + a][y + b] == 0: x, y = x + a, y + b - if [x, y] == destination: - return True - if (x, y) not in vis: - vis.add((x, y)) - q.append((x, y)) - return False + dfs(x, y) + + m, n = len(maze), len(maze[0]) + vis = [[False] * n for _ in range(m)] + dfs(start[0], start[1]) + return vis[destination[0]][destination[1]] diff --git a/solution/0400-0499/0490.The Maze/Solution2.cpp b/solution/0400-0499/0490.The Maze/Solution2.cpp new file mode 100644 index 0000000000000..e17cfef2a19ab --- /dev/null +++ b/solution/0400-0499/0490.The Maze/Solution2.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + bool hasPath(vector>& maze, vector& start, vector& destination) { + int m = maze.size(); + int n = maze[0].size(); + queue> q{{start}}; + vector> vis(m, vector(n)); + vis[start[0]][start[1]] = true; + vector dirs = {-1, 0, 1, 0, -1}; + while (!q.empty()) { + auto p = q.front(); + q.pop(); + int i = p[0], j = p[1]; + for (int k = 0; k < 4; ++k) { + int x = i, y = j; + int a = dirs[k], b = dirs[k + 1]; + while (x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0) { + x += a; + y += b; + } + if (x == destination[0] && y == destination[1]) return 1; + if (!vis[x][y]) { + vis[x][y] = true; + q.push({x, y}); + } + } + } + return 0; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0490.The Maze/Solution2.go b/solution/0400-0499/0490.The Maze/Solution2.go new file mode 100644 index 0000000000000..b5ca6f8459ea5 --- /dev/null +++ b/solution/0400-0499/0490.The Maze/Solution2.go @@ -0,0 +1,30 @@ +func hasPath(maze [][]int, start []int, destination []int) bool { + m, n := len(maze), len(maze[0]) + vis := make([][]bool, m) + for i := range vis { + vis[i] = make([]bool, n) + } + vis[start[0]][start[1]] = true + q := [][]int{start} + dirs := []int{-1, 0, 1, 0, -1} + for len(q) > 0 { + i, j := q[0][0], q[0][1] + q = q[1:] + for k := 0; k < 4; k++ { + x, y := i, j + a, b := dirs[k], dirs[k+1] + for x+a >= 0 && x+a < m && y+b >= 0 && y+b < n && maze[x+a][y+b] == 0 { + x += a + y += b + } + if x == destination[0] && y == destination[1] { + return true + } + if !vis[x][y] { + vis[x][y] = true + q = append(q, []int{x, y}) + } + } + } + return false +} \ No newline at end of file diff --git a/solution/0400-0499/0490.The Maze/Solution2.java b/solution/0400-0499/0490.The Maze/Solution2.java new file mode 100644 index 0000000000000..b58aa2b3209e1 --- /dev/null +++ b/solution/0400-0499/0490.The Maze/Solution2.java @@ -0,0 +1,32 @@ +class Solution { + public boolean hasPath(int[][] maze, int[] start, int[] destination) { + int m = maze.length; + int n = maze[0].length; + boolean[][] vis = new boolean[m][n]; + vis[start[0]][start[1]] = true; + Deque q = new LinkedList<>(); + q.offer(start); + int[] dirs = {-1, 0, 1, 0, -1}; + while (!q.isEmpty()) { + int[] p = q.poll(); + int i = p[0], j = p[1]; + for (int k = 0; k < 4; ++k) { + int x = i, y = j; + int a = dirs[k], b = dirs[k + 1]; + while ( + x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0) { + x += a; + y += b; + } + if (x == destination[0] && y == destination[1]) { + return true; + } + if (!vis[x][y]) { + vis[x][y] = true; + q.offer(new int[] {x, y}); + } + } + } + return false; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0490.The Maze/Solution2.py b/solution/0400-0499/0490.The Maze/Solution2.py new file mode 100644 index 0000000000000..c93a05d47ad42 --- /dev/null +++ b/solution/0400-0499/0490.The Maze/Solution2.py @@ -0,0 +1,20 @@ +class Solution: + def hasPath( + self, maze: List[List[int]], start: List[int], destination: List[int] + ) -> bool: + m, n = len(maze), len(maze[0]) + q = deque([start]) + rs, cs = start + vis = {(rs, cs)} + while q: + i, j = q.popleft() + for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: + x, y = i, j + while 0 <= x + a < m and 0 <= y + b < n and maze[x + a][y + b] == 0: + x, y = x + a, y + b + if [x, y] == destination: + return True + if (x, y) not in vis: + vis.add((x, y)) + q.append((x, y)) + return False diff --git a/solution/0400-0499/0493.Reverse Pairs/Solution.cpp b/solution/0400-0499/0493.Reverse Pairs/Solution.cpp index 734c7a961fc74..5ea3c2474fdb9 100644 --- a/solution/0400-0499/0493.Reverse Pairs/Solution.cpp +++ b/solution/0400-0499/0493.Reverse Pairs/Solution.cpp @@ -1,50 +1,43 @@ -class BinaryIndexedTree { -public: - int n; - vector c; - - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); - } - } - - int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } - - int lowbit(int x) { - return x & -x; - } -}; - class Solution { public: int reversePairs(vector& nums) { - set s; - for (int num : nums) { - s.insert(num); - s.insert(num * 2ll); - } - unordered_map m; - int idx = 0; - for (long long num : s) m[num] = ++idx; - BinaryIndexedTree* tree = new BinaryIndexedTree(m.size()); - int ans = 0; - for (int i = nums.size() - 1; i >= 0; --i) { - ans += tree->query(m[nums[i]] - 1); - tree->update(m[nums[i] * 2ll], 1); - } - return ans; + int n = nums.size(); + int t[n]; + function mergeSort = [&](int l, int r) -> int { + if (l >= r) { + return 0; + } + int mid = (l + r) >> 1; + int ans = mergeSort(l, mid) + mergeSort(mid + 1, r); + int i = l, j = mid + 1, k = 0; + while (i <= mid && j <= r) { + if (nums[i] <= nums[j] * 2LL) { + ++i; + } else { + ans += mid - i + 1; + ++j; + } + } + i = l; + j = mid + 1; + while (i <= mid && j <= r) { + if (nums[i] <= nums[j]) { + t[k++] = nums[i++]; + } else { + t[k++] = nums[j++]; + } + } + while (i <= mid) { + t[k++] = nums[i++]; + } + while (j <= r) { + t[k++] = nums[j++]; + } + for (i = l; i <= r; ++i) { + nums[i] = t[i - l]; + } + return ans; + }; + return mergeSort(0, n - 1); } }; \ No newline at end of file diff --git a/solution/0400-0499/0493.Reverse Pairs/Solution.go b/solution/0400-0499/0493.Reverse Pairs/Solution.go index b369906680235..80ca05cb12dac 100644 --- a/solution/0400-0499/0493.Reverse Pairs/Solution.go +++ b/solution/0400-0499/0493.Reverse Pairs/Solution.go @@ -1,53 +1,42 @@ -type BinaryIndexedTree struct { - n int - c []int -} - -func newBinaryIndexedTree(n int) *BinaryIndexedTree { - c := make([]int, n+1) - return &BinaryIndexedTree{n, c} -} - -func (this *BinaryIndexedTree) lowbit(x int) int { - return x & -x -} - -func (this *BinaryIndexedTree) update(x, delta int) { - for x <= this.n { - this.c[x] += delta - x += this.lowbit(x) - } -} - -func (this *BinaryIndexedTree) query(x int) int { - s := 0 - for x > 0 { - s += this.c[x] - x -= this.lowbit(x) - } - return s -} - func reversePairs(nums []int) int { - s := make(map[int]bool) - for _, num := range nums { - s[num] = true - s[num*2] = true - } - var alls []int - for num := range s { - alls = append(alls, num) - } - sort.Ints(alls) - m := make(map[int]int) - for i, num := range alls { - m[num] = i + 1 - } - tree := newBinaryIndexedTree(len(m)) - ans := 0 - for i := len(nums) - 1; i >= 0; i-- { - ans += tree.query(m[nums[i]] - 1) - tree.update(m[nums[i]*2], 1) + n := len(nums) + t := make([]int, n) + var mergeSort func(l, r int) int + mergeSort = func(l, r int) int { + if l >= r { + return 0 + } + mid := (l + r) >> 1 + ans := mergeSort(l, mid) + mergeSort(mid+1, r) + i, j, k := l, mid+1, 0 + for i <= mid && j <= r { + if nums[i] <= nums[j]*2 { + i++ + } else { + ans += mid - i + 1 + j++ + } + } + i, j = l, mid+1 + for i <= mid && j <= r { + if nums[i] <= nums[j] { + t[k] = nums[i] + k, i = k+1, i+1 + } else { + t[k] = nums[j] + k, j = k+1, j+1 + } + } + for ; i <= mid; i, k = i+1, k+1 { + t[k] = nums[i] + } + for ; j <= r; j, k = j+1, k+1 { + t[k] = nums[j] + } + for i = l; i <= r; i++ { + nums[i] = t[i-l] + } + return ans } - return ans + return mergeSort(0, n-1) } \ No newline at end of file diff --git a/solution/0400-0499/0493.Reverse Pairs/Solution.java b/solution/0400-0499/0493.Reverse Pairs/Solution.java index d07a64ed49d0f..7666b0be18a79 100644 --- a/solution/0400-0499/0493.Reverse Pairs/Solution.java +++ b/solution/0400-0499/0493.Reverse Pairs/Solution.java @@ -1,52 +1,47 @@ class Solution { + private int[] nums; + private int[] t; + public int reversePairs(int[] nums) { - TreeSet ts = new TreeSet<>(); - for (int num : nums) { - ts.add((long) num); - ts.add((long) num * 2); + this.nums = nums; + int n = nums.length; + this.t = new int[n]; + return mergeSort(0, n - 1); + } + + private int mergeSort(int l, int r) { + if (l >= r) { + return 0; } - Map m = new HashMap<>(); - int idx = 0; - for (long num : ts) { - m.put(num, ++idx); + int mid = (l + r) >> 1; + int ans = mergeSort(l, mid) + mergeSort(mid + 1, r); + int i = l, j = mid + 1, k = 0; + while (i <= mid && j <= r) { + if (nums[i] <= nums[j] * 2L) { + ++i; + } else { + ans += mid - i + 1; + ++j; + } } - BinaryIndexedTree tree = new BinaryIndexedTree(m.size()); - int ans = 0; - for (int i = nums.length - 1; i >= 0; --i) { - int x = m.get((long) nums[i]); - ans += tree.query(x - 1); - tree.update(m.get((long) nums[i] * 2), 1); + i = l; + j = mid + 1; + while (i <= mid && j <= r) { + if (nums[i] <= nums[j]) { + t[k++] = nums[i++]; + } else { + t[k++] = nums[j++]; + } } - return ans; - } -} - -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); + while (i <= mid) { + t[k++] = nums[i++]; } - } - - public int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); + while (j <= r) { + t[k++] = nums[j++]; } - return s; - } - - public static int lowbit(int x) { - return x & -x; + for (i = l; i <= r; ++i) { + nums[i] = t[i - l]; + } + return ans; } } \ No newline at end of file diff --git a/solution/0400-0499/0493.Reverse Pairs/Solution.py b/solution/0400-0499/0493.Reverse Pairs/Solution.py index ae28d6d53b81d..da0f07ea3c537 100644 --- a/solution/0400-0499/0493.Reverse Pairs/Solution.py +++ b/solution/0400-0499/0493.Reverse Pairs/Solution.py @@ -1,36 +1,29 @@ -class BinaryIndexedTree: - def __init__(self, n): - self.n = n - self.c = [0] * (n + 1) - - @staticmethod - def lowbit(x): - return x & -x - - def update(self, x, delta): - while x <= self.n: - self.c[x] += delta - x += BinaryIndexedTree.lowbit(x) - - def query(self, x): - s = 0 - while x > 0: - s += self.c[x] - x -= BinaryIndexedTree.lowbit(x) - return s - - class Solution: def reversePairs(self, nums: List[int]) -> int: - s = set() - for num in nums: - s.add(num) - s.add(num * 2) - alls = sorted(s) - m = {v: i for i, v in enumerate(alls, 1)} - ans = 0 - tree = BinaryIndexedTree(len(m)) - for num in nums[::-1]: - ans += tree.query(m[num] - 1) - tree.update(m[num * 2], 1) - return ans + def merge_sort(l, r): + if l >= r: + return 0 + mid = (l + r) >> 1 + ans = merge_sort(l, mid) + merge_sort(mid + 1, r) + t = [] + i, j = l, mid + 1 + while i <= mid and j <= r: + if nums[i] <= 2 * nums[j]: + i += 1 + else: + ans += mid - i + 1 + j += 1 + i, j = l, mid + 1 + while i <= mid and j <= r: + if nums[i] <= nums[j]: + t.append(nums[i]) + i += 1 + else: + t.append(nums[j]) + j += 1 + t.extend(nums[i : mid + 1]) + t.extend(nums[j : r + 1]) + nums[l : r + 1] = t + return ans + + return merge_sort(0, len(nums) - 1) diff --git a/solution/0400-0499/0493.Reverse Pairs/Solution2.cpp b/solution/0400-0499/0493.Reverse Pairs/Solution2.cpp new file mode 100644 index 0000000000000..734c7a961fc74 --- /dev/null +++ b/solution/0400-0499/0493.Reverse Pairs/Solution2.cpp @@ -0,0 +1,50 @@ +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + int lowbit(int x) { + return x & -x; + } +}; + +class Solution { +public: + int reversePairs(vector& nums) { + set s; + for (int num : nums) { + s.insert(num); + s.insert(num * 2ll); + } + unordered_map m; + int idx = 0; + for (long long num : s) m[num] = ++idx; + BinaryIndexedTree* tree = new BinaryIndexedTree(m.size()); + int ans = 0; + for (int i = nums.size() - 1; i >= 0; --i) { + ans += tree->query(m[nums[i]] - 1); + tree->update(m[nums[i] * 2ll], 1); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0493.Reverse Pairs/Solution2.go b/solution/0400-0499/0493.Reverse Pairs/Solution2.go new file mode 100644 index 0000000000000..b369906680235 --- /dev/null +++ b/solution/0400-0499/0493.Reverse Pairs/Solution2.go @@ -0,0 +1,53 @@ +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) lowbit(x int) int { + return x & -x +} + +func (this *BinaryIndexedTree) update(x, delta int) { + for x <= this.n { + this.c[x] += delta + x += this.lowbit(x) + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= this.lowbit(x) + } + return s +} + +func reversePairs(nums []int) int { + s := make(map[int]bool) + for _, num := range nums { + s[num] = true + s[num*2] = true + } + var alls []int + for num := range s { + alls = append(alls, num) + } + sort.Ints(alls) + m := make(map[int]int) + for i, num := range alls { + m[num] = i + 1 + } + tree := newBinaryIndexedTree(len(m)) + ans := 0 + for i := len(nums) - 1; i >= 0; i-- { + ans += tree.query(m[nums[i]] - 1) + tree.update(m[nums[i]*2], 1) + } + return ans +} \ No newline at end of file diff --git a/solution/0400-0499/0493.Reverse Pairs/Solution2.java b/solution/0400-0499/0493.Reverse Pairs/Solution2.java new file mode 100644 index 0000000000000..d07a64ed49d0f --- /dev/null +++ b/solution/0400-0499/0493.Reverse Pairs/Solution2.java @@ -0,0 +1,52 @@ +class Solution { + public int reversePairs(int[] nums) { + TreeSet ts = new TreeSet<>(); + for (int num : nums) { + ts.add((long) num); + ts.add((long) num * 2); + } + Map m = new HashMap<>(); + int idx = 0; + for (long num : ts) { + m.put(num, ++idx); + } + BinaryIndexedTree tree = new BinaryIndexedTree(m.size()); + int ans = 0; + for (int i = nums.length - 1; i >= 0; --i) { + int x = m.get((long) nums[i]); + ans += tree.query(x - 1); + tree.update(m.get((long) nums[i] * 2), 1); + } + return ans; + } +} + +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + public static int lowbit(int x) { + return x & -x; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0493.Reverse Pairs/Solution2.py b/solution/0400-0499/0493.Reverse Pairs/Solution2.py new file mode 100644 index 0000000000000..ae28d6d53b81d --- /dev/null +++ b/solution/0400-0499/0493.Reverse Pairs/Solution2.py @@ -0,0 +1,36 @@ +class BinaryIndexedTree: + def __init__(self, n): + self.n = n + self.c = [0] * (n + 1) + + @staticmethod + def lowbit(x): + return x & -x + + def update(self, x, delta): + while x <= self.n: + self.c[x] += delta + x += BinaryIndexedTree.lowbit(x) + + def query(self, x): + s = 0 + while x > 0: + s += self.c[x] + x -= BinaryIndexedTree.lowbit(x) + return s + + +class Solution: + def reversePairs(self, nums: List[int]) -> int: + s = set() + for num in nums: + s.add(num) + s.add(num * 2) + alls = sorted(s) + m = {v: i for i, v in enumerate(alls, 1)} + ans = 0 + tree = BinaryIndexedTree(len(m)) + for num in nums[::-1]: + ans += tree.query(m[num] - 1) + tree.update(m[num * 2], 1) + return ans diff --git a/solution/0400-0499/0493.Reverse Pairs/Solution3.cpp b/solution/0400-0499/0493.Reverse Pairs/Solution3.cpp new file mode 100644 index 0000000000000..c97dbe128680b --- /dev/null +++ b/solution/0400-0499/0493.Reverse Pairs/Solution3.cpp @@ -0,0 +1,73 @@ +class Node { +public: + int l; + int r; + int v; +}; + +class SegmentTree { +public: + vector tr; + + SegmentTree(int n) { + tr.resize(4 * n); + for (int i = 0; i < tr.size(); ++i) tr[i] = new Node(); + build(1, 1, n); + } + + void build(int u, int l, int r) { + tr[u]->l = l; + tr[u]->r = r; + if (l == r) return; + int mid = (l + r) >> 1; + build(u << 1, l, mid); + build(u << 1 | 1, mid + 1, r); + } + + void modify(int u, int x, int v) { + if (tr[u]->l == x && tr[u]->r == x) { + tr[u]->v += v; + return; + } + int mid = (tr[u]->l + tr[u]->r) >> 1; + if (x <= mid) + modify(u << 1, x, v); + else + modify(u << 1 | 1, x, v); + pushup(u); + } + + void pushup(int u) { + tr[u]->v = tr[u << 1]->v + tr[u << 1 | 1]->v; + } + + int query(int u, int l, int r) { + if (tr[u]->l >= l && tr[u]->r <= r) return tr[u]->v; + int mid = (tr[u]->l + tr[u]->r) >> 1; + int v = 0; + if (l <= mid) v = query(u << 1, l, r); + if (r > mid) v += query(u << 1 | 1, l, r); + return v; + } +}; + +class Solution { +public: + int reversePairs(vector& nums) { + set s; + for (int num : nums) { + s.insert(num); + s.insert(num * 2ll); + } + unordered_map m; + int idx = 0; + for (long long num : s) m[num] = ++idx; + SegmentTree* tree = new SegmentTree(m.size()); + int ans = 0; + for (int i = nums.size() - 1; i >= 0; --i) { + ans += tree->query(1, 1, m[nums[i]] - 1); + tree->modify(1, m[nums[i] * 2ll], 1); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0493.Reverse Pairs/Solution3.java b/solution/0400-0499/0493.Reverse Pairs/Solution3.java new file mode 100644 index 0000000000000..967968f221ad9 --- /dev/null +++ b/solution/0400-0499/0493.Reverse Pairs/Solution3.java @@ -0,0 +1,84 @@ +class Solution { + public int reversePairs(int[] nums) { + TreeSet ts = new TreeSet<>(); + for (int num : nums) { + ts.add((long) num); + ts.add((long) num * 2); + } + Map m = new HashMap<>(); + int idx = 0; + for (long num : ts) { + m.put(num, ++idx); + } + SegmentTree tree = new SegmentTree(m.size()); + int ans = 0; + for (int i = nums.length - 1; i >= 0; --i) { + int x = m.get((long) nums[i]); + ans += tree.query(1, 1, x - 1); + tree.modify(1, m.get((long) nums[i] * 2), 1); + } + return ans; + } +} + +class Node { + int l; + int r; + int v; +} + +class SegmentTree { + private Node[] tr; + + public SegmentTree(int n) { + tr = new Node[4 * n]; + for (int i = 0; i < tr.length; ++i) { + tr[i] = new Node(); + } + build(1, 1, n); + } + + public void build(int u, int l, int r) { + tr[u].l = l; + tr[u].r = r; + if (l == r) { + return; + } + int mid = (l + r) >> 1; + build(u << 1, l, mid); + build(u << 1 | 1, mid + 1, r); + } + + public void modify(int u, int x, int v) { + if (tr[u].l == x && tr[u].r == x) { + tr[u].v += v; + return; + } + int mid = (tr[u].l + tr[u].r) >> 1; + if (x <= mid) { + modify(u << 1, x, v); + } else { + modify(u << 1 | 1, x, v); + } + pushup(u); + } + + public void pushup(int u) { + tr[u].v = tr[u << 1].v + tr[u << 1 | 1].v; + } + + public int query(int u, int l, int r) { + if (tr[u].l >= l && tr[u].r <= r) { + return tr[u].v; + } + int mid = (tr[u].l + tr[u].r) >> 1; + int v = 0; + if (l <= mid) { + v += query(u << 1, l, r); + } + if (r > mid) { + v += query(u << 1 | 1, l, r); + } + return v; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0493.Reverse Pairs/Solution3.py b/solution/0400-0499/0493.Reverse Pairs/Solution3.py new file mode 100644 index 0000000000000..ac7250c943b38 --- /dev/null +++ b/solution/0400-0499/0493.Reverse Pairs/Solution3.py @@ -0,0 +1,62 @@ +class Node: + def __init__(self): + self.l = 0 + self.r = 0 + self.v = 0 + + +class SegmentTree: + def __init__(self, n): + self.tr = [Node() for _ in range(4 * n)] + self.build(1, 1, n) + + def build(self, u, l, r): + self.tr[u].l = l + self.tr[u].r = r + if l == r: + return + mid = (l + r) >> 1 + self.build(u << 1, l, mid) + self.build(u << 1 | 1, mid + 1, r) + + def modify(self, u, x, v): + if self.tr[u].l == x and self.tr[u].r == x: + self.tr[u].v += 1 + return + mid = (self.tr[u].l + self.tr[u].r) >> 1 + if x <= mid: + self.modify(u << 1, x, v) + else: + self.modify(u << 1 | 1, x, v) + self.pushup(u) + + def pushup(self, u): + self.tr[u].v = self.tr[u << 1].v + self.tr[u << 1 | 1].v + + def query(self, u, l, r): + if self.tr[u].l >= l and self.tr[u].r <= r: + return self.tr[u].v + mid = (self.tr[u].l + self.tr[u].r) >> 1 + v = 0 + if l <= mid: + v += self.query(u << 1, l, r) + if r > mid: + v += self.query(u << 1 | 1, l, r) + return v + + +class Solution: + def reversePairs(self, nums: List[int]) -> int: + s = set() + for num in nums: + s.add(num) + s.add(num * 2) + alls = sorted(s) + m = {v: i for i, v in enumerate(alls, 1)} + tree = SegmentTree(len(m)) + ans = 0 + for v in nums[::-1]: + x = m[v] + ans += tree.query(1, 1, x - 1) + tree.modify(1, m[v * 2], 1) + return ans diff --git a/solution/0400-0499/0494.Target Sum/Solution.cpp b/solution/0400-0499/0494.Target Sum/Solution.cpp index ff81001c266fc..10446d089898e 100644 --- a/solution/0400-0499/0494.Target Sum/Solution.cpp +++ b/solution/0400-0499/0494.Target Sum/Solution.cpp @@ -1,14 +1,17 @@ -class Solution { -public: - int findTargetSumWays(vector& nums, int target) { - int s = accumulate(nums.begin(), nums.end(), 0); - if (s < target || (s - target) % 2 != 0) return 0; - int n = (s - target) / 2; - vector dp(n + 1); - dp[0] = 1; - for (int& v : nums) - for (int j = n; j >= v; --j) - dp[j] += dp[j - v]; - return dp[n]; - } +class Solution { +public: + int findTargetSumWays(vector& nums, int target) { + int s = accumulate(nums.begin(), nums.end(), 0); + if (s < target || (s - target) % 2 != 0) return 0; + int m = nums.size(), n = (s - target) / 2; + vector> dp(m + 1, vector(n + 1)); + dp[0][0] = 1; + for (int i = 1; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + dp[i][j] += dp[i - 1][j]; + if (nums[i - 1] <= j) dp[i][j] += dp[i - 1][j - nums[i - 1]]; + } + } + return dp[m][n]; + } }; \ No newline at end of file diff --git a/solution/0400-0499/0494.Target Sum/Solution.go b/solution/0400-0499/0494.Target Sum/Solution.go index ef5a7a7612059..e7e7df99f3e59 100644 --- a/solution/0400-0499/0494.Target Sum/Solution.go +++ b/solution/0400-0499/0494.Target Sum/Solution.go @@ -6,13 +6,19 @@ func findTargetSumWays(nums []int, target int) int { if s < target || (s-target)%2 != 0 { return 0 } - n := (s - target) / 2 - dp := make([]int, n+1) - dp[0] = 1 - for _, v := range nums { - for j := n; j >= v; j-- { - dp[j] += dp[j-v] + m, n := len(nums), (s-target)/2 + dp := make([][]int, m+1) + for i := range dp { + dp[i] = make([]int, n+1) + } + dp[0][0] = 1 + for i := 1; i <= m; i++ { + for j := 0; j <= n; j++ { + dp[i][j] = dp[i-1][j] + if nums[i-1] <= j { + dp[i][j] += dp[i-1][j-nums[i-1]] + } } } - return dp[n] + return dp[m][n] } \ No newline at end of file diff --git a/solution/0400-0499/0494.Target Sum/Solution.java b/solution/0400-0499/0494.Target Sum/Solution.java index f3f224f595fb9..72d225b158cdc 100644 --- a/solution/0400-0499/0494.Target Sum/Solution.java +++ b/solution/0400-0499/0494.Target Sum/Solution.java @@ -1,20 +1,24 @@ -class Solution { - public int findTargetSumWays(int[] nums, int target) { - int s = 0; - for (int v : nums) { - s += v; - } - if (s < target || (s - target) % 2 != 0) { - return 0; - } - int n = (s - target) / 2; - int[] dp = new int[n + 1]; - dp[0] = 1; - for (int v : nums) { - for (int j = n; j >= v; --j) { - dp[j] += dp[j - v]; - } - } - return dp[n]; - } +class Solution { + public int findTargetSumWays(int[] nums, int target) { + int s = 0; + for (int v : nums) { + s += v; + } + if (s < target || (s - target) % 2 != 0) { + return 0; + } + int m = nums.length; + int n = (s - target) / 2; + int[][] dp = new int[m + 1][n + 1]; + dp[0][0] = 1; + for (int i = 1; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + dp[i][j] = dp[i - 1][j]; + if (nums[i - 1] <= j) { + dp[i][j] += dp[i - 1][j - nums[i - 1]]; + } + } + } + return dp[m][n]; + } } \ No newline at end of file diff --git a/solution/0400-0499/0494.Target Sum/Solution.py b/solution/0400-0499/0494.Target Sum/Solution.py index 5d07b0bd585e2..1f7739d83dadb 100644 --- a/solution/0400-0499/0494.Target Sum/Solution.py +++ b/solution/0400-0499/0494.Target Sum/Solution.py @@ -1,12 +1,14 @@ -class Solution: - def findTargetSumWays(self, nums: List[int], target: int) -> int: - s = sum(nums) - if s < target or (s - target) % 2 != 0: - return 0 - n = (s - target) // 2 - dp = [0] * (n + 1) - dp[0] = 1 - for v in nums: - for j in range(n, v - 1, -1): - dp[j] += dp[j - v] - return dp[-1] +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + s = sum(nums) + if s < target or (s - target) % 2 != 0: + return 0 + m, n = len(nums), (s - target) // 2 + dp = [[0] * (n + 1) for _ in range(m + 1)] + dp[0][0] = 1 + for i in range(1, m + 1): + for j in range(n + 1): + dp[i][j] = dp[i - 1][j] + if nums[i - 1] <= j: + dp[i][j] += dp[i - 1][j - nums[i - 1]] + return dp[-1][-1] diff --git a/solution/0400-0499/0494.Target Sum/Solution2.cpp b/solution/0400-0499/0494.Target Sum/Solution2.cpp new file mode 100644 index 0000000000000..d0a2ab7c1e599 --- /dev/null +++ b/solution/0400-0499/0494.Target Sum/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int findTargetSumWays(vector& nums, int target) { + int s = accumulate(nums.begin(), nums.end(), 0); + if (s < target || (s - target) % 2 != 0) return 0; + int n = (s - target) / 2; + vector dp(n + 1); + dp[0] = 1; + for (int& v : nums) + for (int j = n; j >= v; --j) + dp[j] += dp[j - v]; + return dp[n]; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0494.Target Sum/Solution2.go b/solution/0400-0499/0494.Target Sum/Solution2.go new file mode 100644 index 0000000000000..ef5a7a7612059 --- /dev/null +++ b/solution/0400-0499/0494.Target Sum/Solution2.go @@ -0,0 +1,18 @@ +func findTargetSumWays(nums []int, target int) int { + s := 0 + for _, v := range nums { + s += v + } + if s < target || (s-target)%2 != 0 { + return 0 + } + n := (s - target) / 2 + dp := make([]int, n+1) + dp[0] = 1 + for _, v := range nums { + for j := n; j >= v; j-- { + dp[j] += dp[j-v] + } + } + return dp[n] +} \ No newline at end of file diff --git a/solution/0400-0499/0494.Target Sum/Solution2.java b/solution/0400-0499/0494.Target Sum/Solution2.java new file mode 100644 index 0000000000000..159e8e8bf201c --- /dev/null +++ b/solution/0400-0499/0494.Target Sum/Solution2.java @@ -0,0 +1,20 @@ +class Solution { + public int findTargetSumWays(int[] nums, int target) { + int s = 0; + for (int v : nums) { + s += v; + } + if (s < target || (s - target) % 2 != 0) { + return 0; + } + int n = (s - target) / 2; + int[] dp = new int[n + 1]; + dp[0] = 1; + for (int v : nums) { + for (int j = n; j >= v; --j) { + dp[j] += dp[j - v]; + } + } + return dp[n]; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0494.Target Sum/Solution2.py b/solution/0400-0499/0494.Target Sum/Solution2.py new file mode 100644 index 0000000000000..359016a473817 --- /dev/null +++ b/solution/0400-0499/0494.Target Sum/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + s = sum(nums) + if s < target or (s - target) % 2 != 0: + return 0 + n = (s - target) // 2 + dp = [0] * (n + 1) + dp[0] = 1 + for v in nums: + for j in range(n, v - 1, -1): + dp[j] += dp[j - v] + return dp[-1] diff --git a/solution/0400-0499/0494.Target Sum/Solution2.rs b/solution/0400-0499/0494.Target Sum/Solution2.rs new file mode 100644 index 0000000000000..fc185741e04ef --- /dev/null +++ b/solution/0400-0499/0494.Target Sum/Solution2.rs @@ -0,0 +1,29 @@ +impl Solution { + #[allow(dead_code)] + pub fn find_target_sum_ways(nums: Vec, target: i32) -> i32 { + let mut sum = 0; + for e in &nums { + sum += *e; + } + + if sum < target || (sum - target) % 2 != 0 { + // Just directly return + return 0; + } + + let n = ((sum - target) / 2) as usize; + let mut dp: Vec = vec![0; n + 1]; + + // Initialize the dp vector + dp[0] = 1; + + // Begin the actual dp phase + for e in &nums { + for i in (*e as usize..=n).rev() { + dp[i] += dp[i - (*e as usize)]; + } + } + + dp[n] + } +} diff --git a/solution/0400-0499/0494.Target Sum/Solution3.py b/solution/0400-0499/0494.Target Sum/Solution3.py new file mode 100644 index 0000000000000..36ad4e2f7b43a --- /dev/null +++ b/solution/0400-0499/0494.Target Sum/Solution3.py @@ -0,0 +1,12 @@ +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + @cache + def dfs(i, t): + if i == n: + if t == target: + return 1 + return 0 + return dfs(i + 1, t + nums[i]) + dfs(i + 1, t - nums[i]) + + ans, n = 0, len(nums) + return dfs(0, 0) diff --git a/solution/0400-0499/0495.Teemo Attacking/Solution.cs b/solution/0400-0499/0495.Teemo Attacking/Solution.cs index 5efd603e2b992..99ee43d542fff 100644 --- a/solution/0400-0499/0495.Teemo Attacking/Solution.cs +++ b/solution/0400-0499/0495.Teemo Attacking/Solution.cs @@ -7,4 +7,4 @@ public int FindPoisonedDuration(int[] timeSeries, int duration) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0400-0499/0496.Next Greater Element I/Solution.java b/solution/0400-0499/0496.Next Greater Element I/Solution.java index 6367c12a33660..ee2f5deb0eef6 100644 --- a/solution/0400-0499/0496.Next Greater Element I/Solution.java +++ b/solution/0400-0499/0496.Next Greater Element I/Solution.java @@ -1,17 +1,17 @@ class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { Deque stk = new ArrayDeque<>(); - Map mp = new HashMap<>(); - for (int num : nums2) { - while (!stk.isEmpty() && stk.peek() < num) { - mp.put(stk.pop(), num); + Map m = new HashMap<>(); + for (int v : nums2) { + while (!stk.isEmpty() && stk.peek() < v) { + m.put(stk.pop(), v); } - stk.push(num); + stk.push(v); } int n = nums1.length; int[] ans = new int[n]; for (int i = 0; i < n; ++i) { - ans[i] = mp.getOrDefault(nums1[i], -1); + ans[i] = m.getOrDefault(nums1[i], -1); } return ans; } diff --git a/solution/0400-0499/0496.Next Greater Element I/Solution2.cpp b/solution/0400-0499/0496.Next Greater Element I/Solution2.cpp new file mode 100644 index 0000000000000..8fd148a48d791 --- /dev/null +++ b/solution/0400-0499/0496.Next Greater Element I/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + vector nextGreaterElement(vector& nums1, vector& nums2) { + stack stk; + unordered_map m; + for (int i = nums2.size() - 1; ~i; --i) { + while (!stk.empty() && stk.top() <= nums2[i]) stk.pop(); + if (!stk.empty()) m[nums2[i]] = stk.top(); + stk.push(nums2[i]); + } + vector ans; + for (int& v : nums1) ans.push_back(m.count(v) ? m[v] : -1); + return ans; + } +}; \ No newline at end of file diff --git a/solution/0400-0499/0496.Next Greater Element I/Solution2.go b/solution/0400-0499/0496.Next Greater Element I/Solution2.go new file mode 100644 index 0000000000000..e4c138babc9d7 --- /dev/null +++ b/solution/0400-0499/0496.Next Greater Element I/Solution2.go @@ -0,0 +1,22 @@ +func nextGreaterElement(nums1 []int, nums2 []int) []int { + stk := []int{} + m := map[int]int{} + for i := len(nums2) - 1; i >= 0; i-- { + for len(stk) > 0 && stk[len(stk)-1] <= nums2[i] { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + m[nums2[i]] = stk[len(stk)-1] + } + stk = append(stk, nums2[i]) + } + var ans []int + for _, v := range nums1 { + val, ok := m[v] + if !ok { + val = -1 + } + ans = append(ans, val) + } + return ans +} \ No newline at end of file diff --git a/solution/0400-0499/0496.Next Greater Element I/Solution2.java b/solution/0400-0499/0496.Next Greater Element I/Solution2.java new file mode 100644 index 0000000000000..fd585b1ad1a5b --- /dev/null +++ b/solution/0400-0499/0496.Next Greater Element I/Solution2.java @@ -0,0 +1,21 @@ +class Solution { + public int[] nextGreaterElement(int[] nums1, int[] nums2) { + Deque stk = new ArrayDeque<>(); + Map m = new HashMap<>(); + for (int i = nums2.length - 1; i >= 0; --i) { + while (!stk.isEmpty() && stk.peek() <= nums2[i]) { + stk.pop(); + } + if (!stk.isEmpty()) { + m.put(nums2[i], stk.peek()); + } + stk.push(nums2[i]); + } + int n = nums1.length; + int[] ans = new int[n]; + for (int i = 0; i < n; ++i) { + ans[i] = m.getOrDefault(nums1[i], -1); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0400-0499/0496.Next Greater Element I/Solution2.js b/solution/0400-0499/0496.Next Greater Element I/Solution2.js new file mode 100644 index 0000000000000..7fd49e49310dd --- /dev/null +++ b/solution/0400-0499/0496.Next Greater Element I/Solution2.js @@ -0,0 +1,19 @@ +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var nextGreaterElement = function (nums1, nums2) { + let stk = []; + let m = {}; + for (let v of nums2.reverse()) { + while (stk && stk[stk.length - 1] <= v) { + stk.pop(); + } + if (stk) { + m[v] = stk[stk.length - 1]; + } + stk.push(v); + } + return nums1.map(e => m[e] || -1); +}; diff --git a/solution/0400-0499/0496.Next Greater Element I/Solution2.py b/solution/0400-0499/0496.Next Greater Element I/Solution2.py new file mode 100644 index 0000000000000..ce7da164957c2 --- /dev/null +++ b/solution/0400-0499/0496.Next Greater Element I/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: + m = {} + stk = [] + for v in nums2[::-1]: + while stk and stk[-1] <= v: + stk.pop() + if stk: + m[v] = stk[-1] + stk.append(v) + return [m.get(x, -1) for x in nums1] diff --git a/solution/0400-0499/0496.Next Greater Element I/Solution2.rs b/solution/0400-0499/0496.Next Greater Element I/Solution2.rs new file mode 100644 index 0000000000000..8ac2d1be7f398 --- /dev/null +++ b/solution/0400-0499/0496.Next Greater Element I/Solution2.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn next_greater_element(nums1: Vec, nums2: Vec) -> Vec { + nums1 + .iter() + .map(|target| { + let mut res = -1; + for num in nums2.iter().rev() { + if num == target { + break; + } + if num > target { + res = *num; + } + } + res + }) + .collect::>() + } +} diff --git a/solution/0500-0599/0500.Keyboard Row/Solution.cs b/solution/0500-0599/0500.Keyboard Row/Solution.cs index c25950363b588..514b13e2840fa 100644 --- a/solution/0500-0599/0500.Keyboard Row/Solution.cs +++ b/solution/0500-0599/0500.Keyboard Row/Solution.cs @@ -17,4 +17,4 @@ public string[] FindWords(string[] words) { } return ans.ToArray(); } -} \ No newline at end of file +} diff --git a/solution/0500-0599/0500.Keyboard Row/Solution.py b/solution/0500-0599/0500.Keyboard Row/Solution.py index c7249f0979e39..6a5b6188ecacd 100644 --- a/solution/0500-0599/0500.Keyboard Row/Solution.py +++ b/solution/0500-0599/0500.Keyboard Row/Solution.py @@ -1,9 +1,11 @@ class Solution: def findWords(self, words: List[str]) -> List[str]: + s1 = set('qwertyuiop') + s2 = set('asdfghjkl') + s3 = set('zxcvbnm') ans = [] - s = "12210111011122000010020202" for w in words: - x = s[ord(w[0].lower()) - ord('a')] - if all(s[ord(c.lower()) - ord('a')] == x for c in w): + s = set(w.lower()) + if s <= s1 or s <= s2 or s <= s3: ans.append(w) return ans diff --git a/solution/0500-0599/0500.Keyboard Row/Solution2.py b/solution/0500-0599/0500.Keyboard Row/Solution2.py new file mode 100644 index 0000000000000..c7249f0979e39 --- /dev/null +++ b/solution/0500-0599/0500.Keyboard Row/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def findWords(self, words: List[str]) -> List[str]: + ans = [] + s = "12210111011122000010020202" + for w in words: + x = s[ord(w[0].lower()) - ord('a')] + if all(s[ord(c.lower()) - ord('a')] == x for c in w): + ans.append(w) + return ans diff --git a/solution/0500-0599/0501.Find Mode in Binary Search Tree/Solution.cs b/solution/0500-0599/0501.Find Mode in Binary Search Tree/Solution.cs index 5c503a58e21ff..ac8922f1ef4e9 100644 --- a/solution/0500-0599/0501.Find Mode in Binary Search Tree/Solution.cs +++ b/solution/0500-0599/0501.Find Mode in Binary Search Tree/Solution.cs @@ -3,7 +3,7 @@ public class Solution { private int cnt; private TreeNode prev; private List res; - + public int[] FindMode(TreeNode root) { res = new List(); Dfs(root); @@ -13,7 +13,7 @@ public int[] FindMode(TreeNode root) { } return ans; } - + private void Dfs(TreeNode root) { if (root == null) { return; diff --git a/solution/0500-0599/0503.Next Greater Element II/Solution2.cpp b/solution/0500-0599/0503.Next Greater Element II/Solution2.cpp new file mode 100644 index 0000000000000..b49b83315d76b --- /dev/null +++ b/solution/0500-0599/0503.Next Greater Element II/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + vector nextGreaterElements(vector& nums) { + int n = nums.size(); + vector ans(n, -1); + stack stk; + for (int i = n * 2 - 1; ~i; --i) { + int j = i % n; + while (!stk.empty() && stk.top() <= nums[j]) stk.pop(); + if (!stk.empty()) ans[j] = stk.top(); + stk.push(nums[j]); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0500-0599/0503.Next Greater Element II/Solution2.go b/solution/0500-0599/0503.Next Greater Element II/Solution2.go new file mode 100644 index 0000000000000..789debf1b09e4 --- /dev/null +++ b/solution/0500-0599/0503.Next Greater Element II/Solution2.go @@ -0,0 +1,19 @@ +func nextGreaterElements(nums []int) []int { + n := len(nums) + ans := make([]int, n) + for i := range ans { + ans[i] = -1 + } + var stk []int + for i := n*2 - 1; i >= 0; i-- { + j := i % n + for len(stk) > 0 && stk[len(stk)-1] <= nums[j] { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + ans[j] = stk[len(stk)-1] + } + stk = append(stk, nums[j]) + } + return ans +} \ No newline at end of file diff --git a/solution/0500-0599/0503.Next Greater Element II/Solution2.java b/solution/0500-0599/0503.Next Greater Element II/Solution2.java new file mode 100644 index 0000000000000..2268f63e46197 --- /dev/null +++ b/solution/0500-0599/0503.Next Greater Element II/Solution2.java @@ -0,0 +1,19 @@ +class Solution { + public int[] nextGreaterElements(int[] nums) { + int n = nums.length; + int[] ans = new int[n]; + Arrays.fill(ans, -1); + Deque stk = new ArrayDeque<>(); + for (int i = n * 2 - 1; i >= 0; --i) { + int j = i % n; + while (!stk.isEmpty() && stk.peek() <= nums[j]) { + stk.pop(); + } + if (!stk.isEmpty()) { + ans[j] = stk.peek(); + } + stk.push(nums[j]); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0500-0599/0503.Next Greater Element II/Solution2.js b/solution/0500-0599/0503.Next Greater Element II/Solution2.js new file mode 100644 index 0000000000000..7ec2382124f7a --- /dev/null +++ b/solution/0500-0599/0503.Next Greater Element II/Solution2.js @@ -0,0 +1,20 @@ +/** + * @param {number[]} nums + * @return {number[]} + */ +var nextGreaterElements = function (nums) { + const n = nums.length; + let stk = []; + let ans = new Array(n).fill(-1); + for (let i = n * 2 - 1; ~i; --i) { + const j = i % n; + while (stk.length && stk[stk.length - 1] <= nums[j]) { + stk.pop(); + } + if (stk.length) { + ans[j] = stk[stk.length - 1]; + } + stk.push(nums[j]); + } + return ans; +}; diff --git a/solution/0500-0599/0503.Next Greater Element II/Solution2.py b/solution/0500-0599/0503.Next Greater Element II/Solution2.py new file mode 100644 index 0000000000000..4d60587d4eea2 --- /dev/null +++ b/solution/0500-0599/0503.Next Greater Element II/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def nextGreaterElements(self, nums: List[int]) -> List[int]: + n = len(nums) + ans = [-1] * n + stk = [] + for i in range(n * 2 - 1, -1, -1): + i %= n + while stk and stk[-1] <= nums[i]: + stk.pop() + if stk: + ans[i] = stk[-1] + stk.append(nums[i]) + return ans diff --git a/solution/0500-0599/0504.Base 7/Solution.java b/solution/0500-0599/0504.Base 7/Solution.java index 859cdc1c92d91..55fd958d252a2 100644 --- a/solution/0500-0599/0504.Base 7/Solution.java +++ b/solution/0500-0599/0504.Base 7/Solution.java @@ -13,4 +13,4 @@ public String convertToBase7(int num) { } return sb.reverse().toString(); } -} +} \ No newline at end of file diff --git a/solution/0500-0599/0505.The Maze II/Solution.cpp b/solution/0500-0599/0505.The Maze II/Solution.cpp index 5f9473ba6a2e7..86dd836c6147a 100644 --- a/solution/0500-0599/0505.The Maze II/Solution.cpp +++ b/solution/0500-0599/0505.The Maze II/Solution.cpp @@ -1,32 +1,32 @@ -class Solution { -public: - int shortestDistance(vector>& maze, vector& start, vector& destination) { - int m = maze.size(), n = maze[0].size(); - int dist[m][n]; - memset(dist, 0x3f, sizeof(dist)); - int si = start[0], sj = start[1]; - int di = destination[0], dj = destination[1]; - dist[si][sj] = 0; - queue> q; - q.emplace(si, sj); - int dirs[5] = {-1, 0, 1, 0, -1}; - while (!q.empty()) { - auto [i, j] = q.front(); - q.pop(); - for (int d = 0; d < 4; ++d) { - int x = i, y = j, k = dist[i][j]; - int a = dirs[d], b = dirs[d + 1]; - while (x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0) { - x += a; - y += b; - ++k; - } - if (k < dist[x][y]) { - dist[x][y] = k; - q.emplace(x, y); - } - } - } - return dist[di][dj] == 0x3f3f3f3f ? -1 : dist[di][dj]; - } +class Solution { +public: + int shortestDistance(vector>& maze, vector& start, vector& destination) { + int m = maze.size(), n = maze[0].size(); + int dist[m][n]; + memset(dist, 0x3f, sizeof(dist)); + int si = start[0], sj = start[1]; + int di = destination[0], dj = destination[1]; + dist[si][sj] = 0; + queue> q; + q.emplace(si, sj); + int dirs[5] = {-1, 0, 1, 0, -1}; + while (!q.empty()) { + auto [i, j] = q.front(); + q.pop(); + for (int d = 0; d < 4; ++d) { + int x = i, y = j, k = dist[i][j]; + int a = dirs[d], b = dirs[d + 1]; + while (x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0) { + x += a; + y += b; + ++k; + } + if (k < dist[x][y]) { + dist[x][y] = k; + q.emplace(x, y); + } + } + } + return dist[di][dj] == 0x3f3f3f3f ? -1 : dist[di][dj]; + } }; \ No newline at end of file diff --git a/solution/0500-0599/0505.The Maze II/Solution.java b/solution/0500-0599/0505.The Maze II/Solution.java index fb122232cca54..dc2a2cfd0b913 100644 --- a/solution/0500-0599/0505.The Maze II/Solution.java +++ b/solution/0500-0599/0505.The Maze II/Solution.java @@ -1,35 +1,35 @@ -class Solution { - public int shortestDistance(int[][] maze, int[] start, int[] destination) { - int m = maze.length, n = maze[0].length; - final int inf = 1 << 30; - int[][] dist = new int[m][n]; - for (var row : dist) { - Arrays.fill(row, inf); - } - int si = start[0], sj = start[1]; - int di = destination[0], dj = destination[1]; - dist[si][sj] = 0; - Deque q = new ArrayDeque<>(); - q.offer(new int[] {si, sj}); - int[] dirs = {-1, 0, 1, 0, -1}; - while (!q.isEmpty()) { - var p = q.poll(); - int i = p[0], j = p[1]; - for (int d = 0; d < 4; ++d) { - int x = i, y = j, k = dist[i][j]; - int a = dirs[d], b = dirs[d + 1]; - while ( - x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0) { - x += a; - y += b; - ++k; - } - if (k < dist[x][y]) { - dist[x][y] = k; - q.offer(new int[] {x, y}); - } - } - } - return dist[di][dj] == inf ? -1 : dist[di][dj]; - } +class Solution { + public int shortestDistance(int[][] maze, int[] start, int[] destination) { + int m = maze.length, n = maze[0].length; + final int inf = 1 << 30; + int[][] dist = new int[m][n]; + for (var row : dist) { + Arrays.fill(row, inf); + } + int si = start[0], sj = start[1]; + int di = destination[0], dj = destination[1]; + dist[si][sj] = 0; + Deque q = new ArrayDeque<>(); + q.offer(new int[] {si, sj}); + int[] dirs = {-1, 0, 1, 0, -1}; + while (!q.isEmpty()) { + var p = q.poll(); + int i = p[0], j = p[1]; + for (int d = 0; d < 4; ++d) { + int x = i, y = j, k = dist[i][j]; + int a = dirs[d], b = dirs[d + 1]; + while ( + x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0) { + x += a; + y += b; + ++k; + } + if (k < dist[x][y]) { + dist[x][y] = k; + q.offer(new int[] {x, y}); + } + } + } + return dist[di][dj] == inf ? -1 : dist[di][dj]; + } } \ No newline at end of file diff --git a/solution/0500-0599/0505.The Maze II/Solution.py b/solution/0500-0599/0505.The Maze II/Solution.py index b7354ec18cb10..973a93232d752 100644 --- a/solution/0500-0599/0505.The Maze II/Solution.py +++ b/solution/0500-0599/0505.The Maze II/Solution.py @@ -1,21 +1,21 @@ -class Solution: - def shortestDistance( - self, maze: List[List[int]], start: List[int], destination: List[int] - ) -> int: - m, n = len(maze), len(maze[0]) - dirs = (-1, 0, 1, 0, -1) - si, sj = start - di, dj = destination - q = deque([(si, sj)]) - dist = [[inf] * n for _ in range(m)] - dist[si][sj] = 0 - while q: - i, j = q.popleft() - for a, b in pairwise(dirs): - x, y, k = i, j, dist[i][j] - while 0 <= x + a < m and 0 <= y + b < n and maze[x + a][y + b] == 0: - x, y, k = x + a, y + b, k + 1 - if k < dist[x][y]: - dist[x][y] = k - q.append((x, y)) - return -1 if dist[di][dj] == inf else dist[di][dj] +class Solution: + def shortestDistance( + self, maze: List[List[int]], start: List[int], destination: List[int] + ) -> int: + m, n = len(maze), len(maze[0]) + dirs = (-1, 0, 1, 0, -1) + si, sj = start + di, dj = destination + q = deque([(si, sj)]) + dist = [[inf] * n for _ in range(m)] + dist[si][sj] = 0 + while q: + i, j = q.popleft() + for a, b in pairwise(dirs): + x, y, k = i, j, dist[i][j] + while 0 <= x + a < m and 0 <= y + b < n and maze[x + a][y + b] == 0: + x, y, k = x + a, y + b, k + 1 + if k < dist[x][y]: + dist[x][y] = k + q.append((x, y)) + return -1 if dist[di][dj] == inf else dist[di][dj] diff --git a/solution/0500-0599/0506.Relative Ranks/Solution.cpp b/solution/0500-0599/0506.Relative Ranks/Solution.cpp index 6c1b3cd320c0b..72e427deb83d0 100644 --- a/solution/0500-0599/0506.Relative Ranks/Solution.cpp +++ b/solution/0500-0599/0506.Relative Ranks/Solution.cpp @@ -13,4 +13,4 @@ class Solution { ans[idx[i].second] = i < 3 ? top3[i] : to_string(i + 1); return ans; } -}; +}; \ No newline at end of file diff --git a/solution/0500-0599/0507.Perfect Number/Solution.java b/solution/0500-0599/0507.Perfect Number/Solution.java index c96b6b0276385..d559d484dd724 100644 --- a/solution/0500-0599/0507.Perfect Number/Solution.java +++ b/solution/0500-0599/0507.Perfect Number/Solution.java @@ -1,4 +1,5 @@ class Solution { + public boolean checkPerfectNumber(int num) { if (num == 1) { return false; diff --git a/solution/0500-0599/0509.Fibonacci Number/Solution.php b/solution/0500-0599/0509.Fibonacci Number/Solution.php index 023e36f548c96..3f7633947f92b 100644 --- a/solution/0500-0599/0509.Fibonacci Number/Solution.php +++ b/solution/0500-0599/0509.Fibonacci Number/Solution.php @@ -13,4 +13,4 @@ function fib($n) { } return $dp[$n]; } -} \ No newline at end of file +} diff --git a/solution/0500-0599/0509.Fibonacci Number/Solution.ts b/solution/0500-0599/0509.Fibonacci Number/Solution.ts index 1ea0e9c07d40a..fb1d523630de5 100644 --- a/solution/0500-0599/0509.Fibonacci Number/Solution.ts +++ b/solution/0500-0599/0509.Fibonacci Number/Solution.ts @@ -2,7 +2,7 @@ function fib(n: number): number { let a = 0; let b = 1; for (let i = 0; i < n; i++) { - [a, b] = [a, a + b]; + [a, b] = [b, a + b]; } return a; } diff --git a/solution/0500-0599/0509.Fibonacci Number/Solution2.rs b/solution/0500-0599/0509.Fibonacci Number/Solution2.rs new file mode 100644 index 0000000000000..64505cf3d584b --- /dev/null +++ b/solution/0500-0599/0509.Fibonacci Number/Solution2.rs @@ -0,0 +1,8 @@ +impl Solution { + pub fn fib(n: i32) -> i32 { + if n < 2 { + return n; + } + Self::fib(n - 1) + Self::fib(n - 2) + } +} diff --git a/solution/0500-0599/0509.Fibonacci Number/Solution2.ts b/solution/0500-0599/0509.Fibonacci Number/Solution2.ts new file mode 100644 index 0000000000000..bd8a883d4f0ba --- /dev/null +++ b/solution/0500-0599/0509.Fibonacci Number/Solution2.ts @@ -0,0 +1,6 @@ +function fib(n: number): number { + if (n < 2) { + return n; + } + return fib(n - 1) + fib(n - 2); +} diff --git a/solution/0500-0599/0510.Inorder Successor in BST II/Solution.java b/solution/0500-0599/0510.Inorder Successor in BST II/Solution.java index b1e12a232a210..4c08acff226cc 100644 --- a/solution/0500-0599/0510.Inorder Successor in BST II/Solution.java +++ b/solution/0500-0599/0510.Inorder Successor in BST II/Solution.java @@ -9,6 +9,7 @@ class Node { */ class Solution { + public Node inorderSuccessor(Node node) { if (node.right != null) { node = node.right; diff --git a/solution/0500-0599/0512.Game Play Analysis II/Solution2.sql b/solution/0500-0599/0512.Game Play Analysis II/Solution2.sql new file mode 100644 index 0000000000000..38f002e48cc7a --- /dev/null +++ b/solution/0500-0599/0512.Game Play Analysis II/Solution2.sql @@ -0,0 +1,14 @@ +# Write your MySQL query statement below +WITH + T AS ( + SELECT + *, + RANK() OVER ( + PARTITION BY player_id + ORDER BY event_date + ) AS rk + FROM Activity + ) +SELECT player_id, device_id +FROM T +WHERE rk = 1; diff --git a/solution/0500-0599/0513.Find Bottom Left Tree Value/Solution2.cpp b/solution/0500-0599/0513.Find Bottom Left Tree Value/Solution2.cpp new file mode 100644 index 0000000000000..9128a785b3984 --- /dev/null +++ b/solution/0500-0599/0513.Find Bottom Left Tree Value/Solution2.cpp @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int ans = 0; + int mx = 0; + int findBottomLeftValue(TreeNode* root) { + dfs(root, 1); + return ans; + } + + void dfs(TreeNode* root, int curr) { + if (!root) return; + dfs(root->left, curr + 1); + dfs(root->right, curr + 1); + if (mx < curr) { + mx = curr; + ans = root->val; + } + } +}; \ No newline at end of file diff --git a/solution/0500-0599/0513.Find Bottom Left Tree Value/Solution2.go b/solution/0500-0599/0513.Find Bottom Left Tree Value/Solution2.go new file mode 100644 index 0000000000000..8fecc0e6873d2 --- /dev/null +++ b/solution/0500-0599/0513.Find Bottom Left Tree Value/Solution2.go @@ -0,0 +1,25 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func findBottomLeftValue(root *TreeNode) int { + ans, mx := 0, 0 + var dfs func(*TreeNode, int) + dfs = func(root *TreeNode, curr int) { + if root == nil { + return + } + dfs(root.Left, curr+1) + dfs(root.Right, curr+1) + if mx < curr { + mx = curr + ans = root.Val + } + } + dfs(root, 1) + return ans +} \ No newline at end of file diff --git a/solution/0500-0599/0513.Find Bottom Left Tree Value/Solution2.java b/solution/0500-0599/0513.Find Bottom Left Tree Value/Solution2.java new file mode 100644 index 0000000000000..c12f8518693ef --- /dev/null +++ b/solution/0500-0599/0513.Find Bottom Left Tree Value/Solution2.java @@ -0,0 +1,36 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int ans = 0; + private int mx = 0; + + public int findBottomLeftValue(TreeNode root) { + dfs(root, 1); + return ans; + } + + private void dfs(TreeNode root, int curr) { + if (root == null) { + return; + } + dfs(root.left, curr + 1); + dfs(root.right, curr + 1); + if (mx < curr) { + mx = curr; + ans = root.val; + } + } +} \ No newline at end of file diff --git a/solution/0500-0599/0513.Find Bottom Left Tree Value/Solution2.py b/solution/0500-0599/0513.Find Bottom Left Tree Value/Solution2.py new file mode 100644 index 0000000000000..1af09292e4312 --- /dev/null +++ b/solution/0500-0599/0513.Find Bottom Left Tree Value/Solution2.py @@ -0,0 +1,21 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def findBottomLeftValue(self, root: Optional[TreeNode]) -> int: + def dfs(root, curr): + if root is None: + return + dfs(root.left, curr + 1) + dfs(root.right, curr + 1) + nonlocal ans, mx + if mx < curr: + mx = curr + ans = root.val + + ans = mx = 0 + dfs(root, 1) + return ans diff --git a/solution/0500-0599/0513.Find Bottom Left Tree Value/Solution2.rs b/solution/0500-0599/0513.Find Bottom Left Tree Value/Solution2.rs new file mode 100644 index 0000000000000..cb06fc1b9d789 --- /dev/null +++ b/solution/0500-0599/0513.Find Bottom Left Tree Value/Solution2.rs @@ -0,0 +1,42 @@ +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +use std::collections::VecDeque; +impl Solution { + fn dfs(root: &Option>>, cur: i32, max: &mut i32, res: &mut i32) { + if root.is_none() { + return; + } + let root = root.as_ref().unwrap().borrow(); + Self::dfs(&root.left, cur + 1, max, res); + Self::dfs(&root.right, cur + 1, max, res); + if *max < cur { + *max = cur; + *res = root.val; + } + } + + pub fn find_bottom_left_value(root: Option>>) -> i32 { + let mut max = 0; + let mut res = 0; + Self::dfs(&root, 1, &mut max, &mut res); + res + } +} diff --git a/solution/0500-0599/0513.Find Bottom Left Tree Value/Solution2.ts b/solution/0500-0599/0513.Find Bottom Left Tree Value/Solution2.ts new file mode 100644 index 0000000000000..8f56764332daf --- /dev/null +++ b/solution/0500-0599/0513.Find Bottom Left Tree Value/Solution2.ts @@ -0,0 +1,32 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function findBottomLeftValue(root: TreeNode | null): number { + let mx = 0; + let ans = 0; + + function dfs(root, curr) { + if (!root) { + return; + } + dfs(root.left, curr + 1); + dfs(root.right, curr + 1); + if (mx < curr) { + mx = curr; + ans = root.val; + } + } + dfs(root, 1); + return ans; +} diff --git a/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution.py b/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution.py index 708486811e61b..05e9740d2dfd4 100644 --- a/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution.py +++ b/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution.py @@ -1,23 +1,23 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def largestValues(self, root: Optional[TreeNode]) -> List[int]: - if root is None: - return [] - q = deque([root]) - ans = [] - while q: - t = -inf - for _ in range(len(q)): - node = q.popleft() - t = max(t, node.val) - if node.left: - q.append(node.left) - if node.right: - q.append(node.right) - ans.append(t) - return ans +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def largestValues(self, root: Optional[TreeNode]) -> List[int]: + if root is None: + return [] + q = deque([root]) + ans = [] + while q: + t = -inf + for _ in range(len(q)): + node = q.popleft() + t = max(t, node.val) + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + ans.append(t) + return ans diff --git a/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution2.cpp b/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution2.cpp new file mode 100644 index 0000000000000..3b60a074091ca --- /dev/null +++ b/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution2.cpp @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector ans; + + vector largestValues(TreeNode* root) { + dfs(root, 0); + return ans; + } + + void dfs(TreeNode* root, int curr) { + if (!root) return; + if (curr == ans.size()) + ans.push_back(root->val); + else + ans[curr] = max(ans[curr], root->val); + dfs(root->left, curr + 1); + dfs(root->right, curr + 1); + } +}; \ No newline at end of file diff --git a/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution2.go b/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution2.go new file mode 100644 index 0000000000000..8daa0fc807f21 --- /dev/null +++ b/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution2.go @@ -0,0 +1,26 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func largestValues(root *TreeNode) []int { + var ans []int + var dfs func(*TreeNode, int) + dfs = func(root *TreeNode, curr int) { + if root == nil { + return + } + if curr == len(ans) { + ans = append(ans, root.Val) + } else { + ans[curr] = max(ans[curr], root.Val) + } + dfs(root.Left, curr+1) + dfs(root.Right, curr+1) + } + dfs(root, 0) + return ans +} \ No newline at end of file diff --git a/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution2.java b/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution2.java new file mode 100644 index 0000000000000..eb3bad81cc677 --- /dev/null +++ b/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution2.java @@ -0,0 +1,36 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private List ans = new ArrayList<>(); + + public List largestValues(TreeNode root) { + dfs(root, 0); + return ans; + } + + private void dfs(TreeNode root, int curr) { + if (root == null) { + return; + } + if (curr == ans.size()) { + ans.add(root.val); + } else { + ans.set(curr, Math.max(ans.get(curr), root.val)); + } + dfs(root.left, curr + 1); + dfs(root.right, curr + 1); + } +} \ No newline at end of file diff --git a/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution2.py b/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution2.py new file mode 100644 index 0000000000000..0f6fb83b4ee5d --- /dev/null +++ b/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution2.py @@ -0,0 +1,21 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def largestValues(self, root: Optional[TreeNode]) -> List[int]: + def dfs(root, curr): + if root is None: + return + if curr == len(ans): + ans.append(root.val) + else: + ans[curr] = max(ans[curr], root.val) + dfs(root.left, curr + 1) + dfs(root.right, curr + 1) + + ans = [] + dfs(root, 0) + return ans diff --git a/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution2.rs b/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution2.rs new file mode 100644 index 0000000000000..436c3c40c218f --- /dev/null +++ b/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution2.rs @@ -0,0 +1,41 @@ +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn dfs(root: &Option>>, depth: usize, res: &mut Vec) { + if root.is_none() { + return; + } + let node = root.as_ref().unwrap().borrow(); + if res.len() == depth { + res.push(node.val); + } else { + res[depth] = res[depth].max(node.val); + } + Self::dfs(&node.left, depth + 1, res); + Self::dfs(&node.right, depth + 1, res); + } + + pub fn largest_values(root: Option>>) -> Vec { + let mut res = Vec::new(); + Self::dfs(&root, 0, &mut res); + res + } +} diff --git a/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution2.ts b/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution2.ts new file mode 100644 index 0000000000000..a0e14f158c1a1 --- /dev/null +++ b/solution/0500-0599/0515.Find Largest Value in Each Tree Row/Solution2.ts @@ -0,0 +1,32 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function largestValues(root: TreeNode | null): number[] { + const res = []; + const dfs = (root: TreeNode | null, depth: number) => { + if (root == null) { + return; + } + const { val, left, right } = root; + if (res.length == depth) { + res.push(val); + } else { + res[depth] = Math.max(res[depth], val); + } + dfs(left, depth + 1); + dfs(right, depth + 1); + }; + dfs(root, 0); + return res; +} diff --git a/solution/0500-0599/0518.Coin Change II/Solution.java b/solution/0500-0599/0518.Coin Change II/Solution.java index 4084ad5e0ab04..490e102363b11 100644 --- a/solution/0500-0599/0518.Coin Change II/Solution.java +++ b/solution/0500-0599/0518.Coin Change II/Solution.java @@ -1,12 +1,15 @@ class Solution { public int change(int amount, int[] coins) { - int[] dp = new int[amount + 1]; - dp[0] = 1; - for (int coin : coins) { - for (int j = coin; j <= amount; j++) { - dp[j] += dp[j - coin]; + int m = coins.length; + int[][] dp = new int[m + 1][amount + 1]; + dp[0][0] = 1; + for (int i = 1; i <= m; ++i) { + for (int j = 0; j <= amount; ++j) { + for (int k = 0; k * coins[i - 1] <= j; ++k) { + dp[i][j] += dp[i - 1][j - coins[i - 1] * k]; + } } } - return dp[amount]; + return dp[m][amount]; } -} +} \ No newline at end of file diff --git a/solution/0500-0599/0518.Coin Change II/Solution2.java b/solution/0500-0599/0518.Coin Change II/Solution2.java new file mode 100644 index 0000000000000..84165a13c0907 --- /dev/null +++ b/solution/0500-0599/0518.Coin Change II/Solution2.java @@ -0,0 +1,17 @@ +class Solution { + public int change(int amount, int[] coins) { + int m = coins.length; + int[][] dp = new int[m + 1][amount + 1]; + dp[0][0] = 1; + for (int i = 1; i <= m; ++i) { + int v = coins[i - 1]; + for (int j = 0; j <= amount; ++j) { + dp[i][j] = dp[i - 1][j]; + if (j >= v) { + dp[i][j] += dp[i][j - v]; + } + } + } + return dp[m][amount]; + } +} \ No newline at end of file diff --git a/solution/0500-0599/0518.Coin Change II/Solution3.java b/solution/0500-0599/0518.Coin Change II/Solution3.java new file mode 100644 index 0000000000000..13126a286f269 --- /dev/null +++ b/solution/0500-0599/0518.Coin Change II/Solution3.java @@ -0,0 +1,13 @@ +class Solution { + public int change(int amount, int[] coins) { + int[] dp = new int[amount + 1]; + dp[0] = 1; + for (int coin : coins) { + // 顺序遍历,0-1背包问题是倒序遍历 + for (int j = coin; j <= amount; j++) { + dp[j] += dp[j - coin]; + } + } + return dp[amount]; + } +} \ No newline at end of file diff --git a/solution/0500-0599/0525.Contiguous Array/Solution.cpp b/solution/0500-0599/0525.Contiguous Array/Solution.cpp index 8344d29f987e5..7dfd55997f6af 100644 --- a/solution/0500-0599/0525.Contiguous Array/Solution.cpp +++ b/solution/0500-0599/0525.Contiguous Array/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - int findMaxLength(vector& nums) { - unordered_map mp; - int s = 0, ans = 0; - mp[0] = -1; - for (int i = 0; i < nums.size(); ++i) { - s += nums[i] == 1 ? 1 : -1; - if (mp.count(s)) - ans = max(ans, i - mp[s]); - else - mp[s] = i; - } - return ans; - } +class Solution { +public: + int findMaxLength(vector& nums) { + unordered_map mp; + int s = 0, ans = 0; + mp[0] = -1; + for (int i = 0; i < nums.size(); ++i) { + s += nums[i] == 1 ? 1 : -1; + if (mp.count(s)) + ans = max(ans, i - mp[s]); + else + mp[s] = i; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0500-0599/0526.Beautiful Arrangement/Solution.java b/solution/0500-0599/0526.Beautiful Arrangement/Solution.java index b3ea637058853..5d150ec2e841c 100644 --- a/solution/0500-0599/0526.Beautiful Arrangement/Solution.java +++ b/solution/0500-0599/0526.Beautiful Arrangement/Solution.java @@ -1,19 +1,39 @@ class Solution { - public int countArrangement(int N) { - int maxn = 1 << N; - int[] f = new int[maxn]; - f[0] = 1; - for (int i = 0; i < maxn; ++i) { - int s = 1; - for (int j = 0; j < N; ++j) { - s += (i >> j) & 1; - } - for (int j = 1; j <= N; ++j) { - if (((i >> (j - 1) & 1) == 0) && (s % j == 0 || j % s == 0)) { - f[i | (1 << (j - 1))] += f[i]; + private int n; + private int ans; + private boolean[] vis; + private Map> match; + + public int countArrangement(int n) { + this.n = n; + ans = 0; + vis = new boolean[n + 1]; + match = new HashMap<>(); + for (int i = 1; i <= n; ++i) { + for (int j = 1; j <= n; ++j) { + if (i % j == 0 || j % i == 0) { + match.computeIfAbsent(i, k -> new ArrayList<>()).add(j); } } } - return f[maxn - 1]; + dfs(1); + return ans; + } + + private void dfs(int i) { + if (i == n + 1) { + ++ans; + return; + } + if (!match.containsKey(i)) { + return; + } + for (int j : match.get(i)) { + if (!vis[j]) { + vis[j] = true; + dfs(i + 1); + vis[j] = false; + } + } } -} +} \ No newline at end of file diff --git a/solution/0500-0599/0526.Beautiful Arrangement/Solution2.java b/solution/0500-0599/0526.Beautiful Arrangement/Solution2.java new file mode 100644 index 0000000000000..c7ad4ae64bbeb --- /dev/null +++ b/solution/0500-0599/0526.Beautiful Arrangement/Solution2.java @@ -0,0 +1,19 @@ +class Solution { + public int countArrangement(int N) { + int maxn = 1 << N; + int[] f = new int[maxn]; + f[0] = 1; + for (int i = 0; i < maxn; ++i) { + int s = 1; + for (int j = 0; j < N; ++j) { + s += (i >> j) & 1; + } + for (int j = 1; j <= N; ++j) { + if (((i >> (j - 1) & 1) == 0) && (s % j == 0 || j % s == 0)) { + f[i | (1 << (j - 1))] += f[i]; + } + } + } + return f[maxn - 1]; + } +} \ No newline at end of file diff --git a/solution/0500-0599/0527.Word Abbreviation/Solution.cpp b/solution/0500-0599/0527.Word Abbreviation/Solution.cpp index 3bbae74b544ab..14215b59aa06c 100644 --- a/solution/0500-0599/0527.Word Abbreviation/Solution.cpp +++ b/solution/0500-0599/0527.Word Abbreviation/Solution.cpp @@ -1,61 +1,61 @@ -class Trie { -public: - Trie() - : cnt(0) { - fill(children.begin(), children.end(), nullptr); - } - - void insert(const string& w) { - Trie* node = this; - for (char c : w) { - int idx = c - 'a'; - if (node->children[idx] == nullptr) { - node->children[idx] = new Trie(); - } - node = node->children[idx]; - ++node->cnt; - } - } - - int search(const string& w) { - Trie* node = this; - int ans = 0; - for (char c : w) { - ++ans; - int idx = c - 'a'; - node = node->children[idx]; - if (node->cnt == 1) { - return ans; - } - } - return w.size(); - } - -private: - array children; - int cnt; -}; - -class Solution { -public: - vector wordsAbbreviation(vector& words) { - map, Trie*> tries; - for (const auto& w : words) { - pair key = {static_cast(w.size()), w.back() - 'a'}; - if (tries.find(key) == tries.end()) { - tries[key] = new Trie(); - } - tries[key]->insert(w); - } - - vector ans; - for (const auto& w : words) { - int m = w.size(); - pair key = {m, w.back() - 'a'}; - int cnt = tries[key]->search(w); - ans.push_back((cnt + 2 >= m) ? w : w.substr(0, cnt) + to_string(m - cnt - 1) + w.back()); - } - - return ans; - } +class Trie { +public: + Trie() + : cnt(0) { + fill(children.begin(), children.end(), nullptr); + } + + void insert(const string& w) { + Trie* node = this; + for (char c : w) { + int idx = c - 'a'; + if (node->children[idx] == nullptr) { + node->children[idx] = new Trie(); + } + node = node->children[idx]; + ++node->cnt; + } + } + + int search(const string& w) { + Trie* node = this; + int ans = 0; + for (char c : w) { + ++ans; + int idx = c - 'a'; + node = node->children[idx]; + if (node->cnt == 1) { + return ans; + } + } + return w.size(); + } + +private: + array children; + int cnt; +}; + +class Solution { +public: + vector wordsAbbreviation(vector& words) { + map, Trie*> tries; + for (const auto& w : words) { + pair key = {static_cast(w.size()), w.back() - 'a'}; + if (tries.find(key) == tries.end()) { + tries[key] = new Trie(); + } + tries[key]->insert(w); + } + + vector ans; + for (const auto& w : words) { + int m = w.size(); + pair key = {m, w.back() - 'a'}; + int cnt = tries[key]->search(w); + ans.push_back((cnt + 2 >= m) ? w : w.substr(0, cnt) + to_string(m - cnt - 1) + w.back()); + } + + return ans; + } }; \ No newline at end of file diff --git a/solution/0500-0599/0527.Word Abbreviation/Solution.java b/solution/0500-0599/0527.Word Abbreviation/Solution.java index fbf65c878e2c2..88f056fc96f6d 100644 --- a/solution/0500-0599/0527.Word Abbreviation/Solution.java +++ b/solution/0500-0599/0527.Word Abbreviation/Solution.java @@ -1,49 +1,49 @@ -class Trie { - private final Trie[] children = new Trie[26]; - private int cnt; - - public void insert(String w) { - Trie node = this; - for (char c : w.toCharArray()) { - int idx = c - 'a'; - if (node.children[idx] == null) { - node.children[idx] = new Trie(); - } - node = node.children[idx]; - ++node.cnt; - } - } - - public int search(String w) { - Trie node = this; - int ans = 0; - for (char c : w.toCharArray()) { - ++ans; - int idx = c - 'a'; - node = node.children[idx]; - if (node.cnt == 1) { - return ans; - } - } - return w.length(); - } -} - -class Solution { - public List wordsAbbreviation(List words) { - Map, Trie> tries = new HashMap<>(); - for (var w : words) { - var key = List.of(w.length(), w.charAt(w.length() - 1) - 'a'); - tries.putIfAbsent(key, new Trie()); - tries.get(key).insert(w); - } - List ans = new ArrayList<>(); - for (var w : words) { - int m = w.length(); - var key = List.of(m, w.charAt(m - 1) - 'a'); - int cnt = tries.get(key).search(w); - ans.add(cnt + 2 >= m ? w : w.substring(0, cnt) + (m - cnt - 1) + w.substring(m - 1)); - } - return ans; - } +class Trie { + private final Trie[] children = new Trie[26]; + private int cnt; + + public void insert(String w) { + Trie node = this; + for (char c : w.toCharArray()) { + int idx = c - 'a'; + if (node.children[idx] == null) { + node.children[idx] = new Trie(); + } + node = node.children[idx]; + ++node.cnt; + } + } + + public int search(String w) { + Trie node = this; + int ans = 0; + for (char c : w.toCharArray()) { + ++ans; + int idx = c - 'a'; + node = node.children[idx]; + if (node.cnt == 1) { + return ans; + } + } + return w.length(); + } +} + +class Solution { + public List wordsAbbreviation(List words) { + Map, Trie> tries = new HashMap<>(); + for (var w : words) { + var key = List.of(w.length(), w.charAt(w.length() - 1) - 'a'); + tries.putIfAbsent(key, new Trie()); + tries.get(key).insert(w); + } + List ans = new ArrayList<>(); + for (var w : words) { + int m = w.length(); + var key = List.of(m, w.charAt(m - 1) - 'a'); + int cnt = tries.get(key).search(w); + ans.add(cnt + 2 >= m ? w : w.substring(0, cnt) + (m - cnt - 1) + w.substring(m - 1)); + } + return ans; + } } \ No newline at end of file diff --git a/solution/0500-0599/0527.Word Abbreviation/Solution.py b/solution/0500-0599/0527.Word Abbreviation/Solution.py index 380679cb7aee7..2936efda31f54 100644 --- a/solution/0500-0599/0527.Word Abbreviation/Solution.py +++ b/solution/0500-0599/0527.Word Abbreviation/Solution.py @@ -1,43 +1,43 @@ -class Trie: - __slots__ = ["children", "cnt"] - - def __init__(self): - self.children = [None] * 26 - self.cnt = 0 - - def insert(self, w: str): - node = self - for c in w: - idx = ord(c) - ord("a") - if not node.children[idx]: - node.children[idx] = Trie() - node = node.children[idx] - node.cnt += 1 - - def search(self, w: str) -> int: - node = self - cnt = 0 - for c in w: - cnt += 1 - idx = ord(c) - ord("a") - node = node.children[idx] - if node.cnt == 1: - return cnt - return len(w) - - -class Solution: - def wordsAbbreviation(self, words: List[str]) -> List[str]: - tries = {} - for w in words: - m = len(w) - if (m, w[-1]) not in tries: - tries[(m, w[-1])] = Trie() - tries[(m, w[-1])].insert(w) - ans = [] - for w in words: - cnt = tries[(len(w), w[-1])].search(w) - ans.append( - w if cnt + 2 >= len(w) else w[:cnt] + str(len(w) - cnt - 1) + w[-1] - ) - return ans +class Trie: + __slots__ = ["children", "cnt"] + + def __init__(self): + self.children = [None] * 26 + self.cnt = 0 + + def insert(self, w: str): + node = self + for c in w: + idx = ord(c) - ord("a") + if not node.children[idx]: + node.children[idx] = Trie() + node = node.children[idx] + node.cnt += 1 + + def search(self, w: str) -> int: + node = self + cnt = 0 + for c in w: + cnt += 1 + idx = ord(c) - ord("a") + node = node.children[idx] + if node.cnt == 1: + return cnt + return len(w) + + +class Solution: + def wordsAbbreviation(self, words: List[str]) -> List[str]: + tries = {} + for w in words: + m = len(w) + if (m, w[-1]) not in tries: + tries[(m, w[-1])] = Trie() + tries[(m, w[-1])].insert(w) + ans = [] + for w in words: + cnt = tries[(len(w), w[-1])].search(w) + ans.append( + w if cnt + 2 >= len(w) else w[:cnt] + str(len(w) - cnt - 1) + w[-1] + ) + return ans diff --git a/solution/0500-0599/0529.Minesweeper/Solution.cpp b/solution/0500-0599/0529.Minesweeper/Solution.cpp index eb3fd4d2a0abf..bcdae47bb812c 100644 --- a/solution/0500-0599/0529.Minesweeper/Solution.cpp +++ b/solution/0500-0599/0529.Minesweeper/Solution.cpp @@ -1,37 +1,37 @@ -class Solution { -public: - vector> updateBoard(vector>& board, vector& click) { - int m = board.size(), n = board[0].size(); - int i = click[0], j = click[1]; - - function dfs = [&](int i, int j) { - int cnt = 0; - for (int x = i - 1; x <= i + 1; ++x) { - for (int y = j - 1; y <= j + 1; ++y) { - if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'M') { - ++cnt; - } - } - } - if (cnt) { - board[i][j] = cnt + '0'; - } else { - board[i][j] = 'B'; - for (int x = i - 1; x <= i + 1; ++x) { - for (int y = j - 1; y <= j + 1; ++y) { - if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'E') { - dfs(x, y); - } - } - } - } - }; - - if (board[i][j] == 'M') { - board[i][j] = 'X'; - } else { - dfs(i, j); - } - return board; - } +class Solution { +public: + vector> updateBoard(vector>& board, vector& click) { + int m = board.size(), n = board[0].size(); + int i = click[0], j = click[1]; + + function dfs = [&](int i, int j) { + int cnt = 0; + for (int x = i - 1; x <= i + 1; ++x) { + for (int y = j - 1; y <= j + 1; ++y) { + if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'M') { + ++cnt; + } + } + } + if (cnt) { + board[i][j] = cnt + '0'; + } else { + board[i][j] = 'B'; + for (int x = i - 1; x <= i + 1; ++x) { + for (int y = j - 1; y <= j + 1; ++y) { + if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'E') { + dfs(x, y); + } + } + } + } + }; + + if (board[i][j] == 'M') { + board[i][j] = 'X'; + } else { + dfs(i, j); + } + return board; + } }; \ No newline at end of file diff --git a/solution/0500-0599/0529.Minesweeper/Solution.java b/solution/0500-0599/0529.Minesweeper/Solution.java index 6db0ec4339ad7..8292afbc49ed7 100644 --- a/solution/0500-0599/0529.Minesweeper/Solution.java +++ b/solution/0500-0599/0529.Minesweeper/Solution.java @@ -1,41 +1,41 @@ -class Solution { - private char[][] board; - private int m; - private int n; - - public char[][] updateBoard(char[][] board, int[] click) { - m = board.length; - n = board[0].length; - this.board = board; - int i = click[0], j = click[1]; - if (board[i][j] == 'M') { - board[i][j] = 'X'; - } else { - dfs(i, j); - } - return board; - } - - private void dfs(int i, int j) { - int cnt = 0; - for (int x = i - 1; x <= i + 1; ++x) { - for (int y = j - 1; y <= j + 1; ++y) { - if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'M') { - ++cnt; - } - } - } - if (cnt > 0) { - board[i][j] = (char) (cnt + '0'); - } else { - board[i][j] = 'B'; - for (int x = i - 1; x <= i + 1; ++x) { - for (int y = j - 1; y <= j + 1; ++y) { - if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'E') { - dfs(x, y); - } - } - } - } - } +class Solution { + private char[][] board; + private int m; + private int n; + + public char[][] updateBoard(char[][] board, int[] click) { + m = board.length; + n = board[0].length; + this.board = board; + int i = click[0], j = click[1]; + if (board[i][j] == 'M') { + board[i][j] = 'X'; + } else { + dfs(i, j); + } + return board; + } + + private void dfs(int i, int j) { + int cnt = 0; + for (int x = i - 1; x <= i + 1; ++x) { + for (int y = j - 1; y <= j + 1; ++y) { + if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'M') { + ++cnt; + } + } + } + if (cnt > 0) { + board[i][j] = (char) (cnt + '0'); + } else { + board[i][j] = 'B'; + for (int x = i - 1; x <= i + 1; ++x) { + for (int y = j - 1; y <= j + 1; ++y) { + if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'E') { + dfs(x, y); + } + } + } + } + } } \ No newline at end of file diff --git a/solution/0500-0599/0529.Minesweeper/Solution.py b/solution/0500-0599/0529.Minesweeper/Solution.py index cff7322e721c8..e7a83ce7c93a8 100644 --- a/solution/0500-0599/0529.Minesweeper/Solution.py +++ b/solution/0500-0599/0529.Minesweeper/Solution.py @@ -1,24 +1,24 @@ -class Solution: - def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: - def dfs(i: int, j: int): - cnt = 0 - for x in range(i - 1, i + 2): - for y in range(j - 1, j + 2): - if 0 <= x < m and 0 <= y < n and board[x][y] == "M": - cnt += 1 - if cnt: - board[i][j] = str(cnt) - else: - board[i][j] = "B" - for x in range(i - 1, i + 2): - for y in range(j - 1, j + 2): - if 0 <= x < m and 0 <= y < n and board[x][y] == "E": - dfs(x, y) - - m, n = len(board), len(board[0]) - i, j = click - if board[i][j] == "M": - board[i][j] = "X" - else: - dfs(i, j) - return board +class Solution: + def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: + def dfs(i: int, j: int): + cnt = 0 + for x in range(i - 1, i + 2): + for y in range(j - 1, j + 2): + if 0 <= x < m and 0 <= y < n and board[x][y] == "M": + cnt += 1 + if cnt: + board[i][j] = str(cnt) + else: + board[i][j] = "B" + for x in range(i - 1, i + 2): + for y in range(j - 1, j + 2): + if 0 <= x < m and 0 <= y < n and board[x][y] == "E": + dfs(x, y) + + m, n = len(board), len(board[0]) + i, j = click + if board[i][j] == "M": + board[i][j] = "X" + else: + dfs(i, j) + return board diff --git a/solution/0500-0599/0534.Game Play Analysis III/Solution2.sql b/solution/0500-0599/0534.Game Play Analysis III/Solution2.sql new file mode 100644 index 0000000000000..abcccfcee4937 --- /dev/null +++ b/solution/0500-0599/0534.Game Play Analysis III/Solution2.sql @@ -0,0 +1,10 @@ +# Write your MySQL query statement below +SELECT + t1.player_id, + t1.event_date, + SUM(t2.games_played) AS games_played_so_far +FROM + Activity AS t1, + Activity AS t2 +WHERE t1.player_id = t2.player_id AND t1.event_date >= t2.event_date +GROUP BY 1, 2; diff --git a/solution/0500-0599/0534.Game Play Analysis III/Solution3.sql b/solution/0500-0599/0534.Game Play Analysis III/Solution3.sql new file mode 100644 index 0000000000000..522fe2a10767a --- /dev/null +++ b/solution/0500-0599/0534.Game Play Analysis III/Solution3.sql @@ -0,0 +1,9 @@ +# Write your MySQL query statement below +SELECT + t1.player_id, + t1.event_date, + SUM(t2.games_played) AS games_played_so_far +FROM + Activity AS t1 + CROSS JOIN Activity AS t2 ON t1.player_id = t2.player_id AND t1.event_date >= t2.event_date +GROUP BY 1, 2; diff --git a/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.cpp b/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.cpp index 4f15c632cf1ad..d09946d08af8c 100644 --- a/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.cpp +++ b/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.cpp @@ -11,30 +11,18 @@ */ class Solution { public: + int s = 0; + TreeNode* convertBST(TreeNode* root) { - int s = 0; - TreeNode* node = root; - while (root) { - if (root->right == nullptr) { - s += root->val; - root->val = s; - root = root->left; - } else { - TreeNode* next = root->right; - while (next->left && next->left != root) { - next = next->left; - } - if (next->left == nullptr) { - next->left = root; - root = root->right; - } else { - s += root->val; - root->val = s; - next->left = nullptr; - root = root->left; - } - } - } - return node; + dfs(root); + return root; + } + + void dfs(TreeNode* root) { + if (!root) return; + dfs(root->right); + s += root->val; + root->val = s; + dfs(root->left); } }; \ No newline at end of file diff --git a/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.go b/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.go index 0d65242a64844..0d1de756b71f9 100644 --- a/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.go +++ b/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.go @@ -8,27 +8,16 @@ */ func convertBST(root *TreeNode) *TreeNode { s := 0 - node := root - for root != nil { - if root.Right == nil { - s += root.Val - root.Val = s - root = root.Left - } else { - next := root.Right - for next.Left != nil && next.Left != root { - next = next.Left - } - if next.Left == nil { - next.Left = root - root = root.Right - } else { - s += root.Val - root.Val = s - next.Left = nil - root = root.Left - } + var dfs func(*TreeNode) + dfs = func(root *TreeNode) { + if root == nil { + return } + dfs(root.Right) + s += root.Val + root.Val = s + dfs(root.Left) } - return node + dfs(root) + return root } \ No newline at end of file diff --git a/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.java b/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.java index 113824439a80e..36ca53db916b0 100644 --- a/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.java +++ b/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.java @@ -14,30 +14,20 @@ * } */ class Solution { + private int s; + public TreeNode convertBST(TreeNode root) { - int s = 0; - TreeNode node = root; - while (root != null) { - if (root.right == null) { - s += root.val; - root.val = s; - root = root.left; - } else { - TreeNode next = root.right; - while (next.left != null && next.left != root) { - next = next.left; - } - if (next.left == null) { - next.left = root; - root = root.right; - } else { - s += root.val; - root.val = s; - next.left = null; - root = root.left; - } - } + dfs(root); + return root; + } + + private void dfs(TreeNode root) { + if (root == null) { + return; } - return node; + dfs(root.right); + s += root.val; + root.val = s; + dfs(root.left); } } \ No newline at end of file diff --git a/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.js b/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.js index e69de29bb2d1d..9a7fee299a340 100644 --- a/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.js +++ b/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.js @@ -0,0 +1,26 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {TreeNode} + */ +var convertBST = function (root) { + let s = 0; + function dfs(root) { + if (!root) { + return; + } + dfs(root.right); + s += root.val; + root.val = s; + dfs(root.left); + } + dfs(root); + return root; +}; diff --git a/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.py b/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.py index 85480fbfd5341..841ac059c67fb 100644 --- a/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.py +++ b/solution/0500-0599/0538.Convert BST to Greater Tree/Solution.py @@ -6,23 +6,15 @@ # self.right = right class Solution: def convertBST(self, root: TreeNode) -> TreeNode: + def dfs(root): + nonlocal s + if root is None: + return + dfs(root.right) + s += root.val + root.val = s + dfs(root.left) + s = 0 - node = root - while root: - if root.right is None: - s += root.val - root.val = s - root = root.left - else: - next = root.right - while next.left and next.left != root: - next = next.left - if next.left is None: - next.left = root - root = root.right - else: - s += root.val - root.val = s - next.left = None - root = root.left - return node + dfs(root) + return root diff --git a/solution/0500-0599/0538.Convert BST to Greater Tree/Solution2.cpp b/solution/0500-0599/0538.Convert BST to Greater Tree/Solution2.cpp new file mode 100644 index 0000000000000..4f15c632cf1ad --- /dev/null +++ b/solution/0500-0599/0538.Convert BST to Greater Tree/Solution2.cpp @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* convertBST(TreeNode* root) { + int s = 0; + TreeNode* node = root; + while (root) { + if (root->right == nullptr) { + s += root->val; + root->val = s; + root = root->left; + } else { + TreeNode* next = root->right; + while (next->left && next->left != root) { + next = next->left; + } + if (next->left == nullptr) { + next->left = root; + root = root->right; + } else { + s += root->val; + root->val = s; + next->left = nullptr; + root = root->left; + } + } + } + return node; + } +}; \ No newline at end of file diff --git a/solution/0500-0599/0538.Convert BST to Greater Tree/Solution2.go b/solution/0500-0599/0538.Convert BST to Greater Tree/Solution2.go new file mode 100644 index 0000000000000..0d65242a64844 --- /dev/null +++ b/solution/0500-0599/0538.Convert BST to Greater Tree/Solution2.go @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func convertBST(root *TreeNode) *TreeNode { + s := 0 + node := root + for root != nil { + if root.Right == nil { + s += root.Val + root.Val = s + root = root.Left + } else { + next := root.Right + for next.Left != nil && next.Left != root { + next = next.Left + } + if next.Left == nil { + next.Left = root + root = root.Right + } else { + s += root.Val + root.Val = s + next.Left = nil + root = root.Left + } + } + } + return node +} \ No newline at end of file diff --git a/solution/0500-0599/0538.Convert BST to Greater Tree/Solution2.java b/solution/0500-0599/0538.Convert BST to Greater Tree/Solution2.java new file mode 100644 index 0000000000000..113824439a80e --- /dev/null +++ b/solution/0500-0599/0538.Convert BST to Greater Tree/Solution2.java @@ -0,0 +1,43 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode convertBST(TreeNode root) { + int s = 0; + TreeNode node = root; + while (root != null) { + if (root.right == null) { + s += root.val; + root.val = s; + root = root.left; + } else { + TreeNode next = root.right; + while (next.left != null && next.left != root) { + next = next.left; + } + if (next.left == null) { + next.left = root; + root = root.right; + } else { + s += root.val; + root.val = s; + next.left = null; + root = root.left; + } + } + } + return node; + } +} \ No newline at end of file diff --git a/solution/0500-0599/0538.Convert BST to Greater Tree/Solution2.py b/solution/0500-0599/0538.Convert BST to Greater Tree/Solution2.py new file mode 100644 index 0000000000000..85480fbfd5341 --- /dev/null +++ b/solution/0500-0599/0538.Convert BST to Greater Tree/Solution2.py @@ -0,0 +1,28 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def convertBST(self, root: TreeNode) -> TreeNode: + s = 0 + node = root + while root: + if root.right is None: + s += root.val + root.val = s + root = root.left + else: + next = root.right + while next.left and next.left != root: + next = next.left + if next.left is None: + next.left = root + root = root.right + else: + s += root.val + root.val = s + next.left = None + root = root.left + return node diff --git a/solution/0500-0599/0540.Single Element in a Sorted Array/Solution.c b/solution/0500-0599/0540.Single Element in a Sorted Array/Solution.c index 2d41992d2c21a..0eb20cd2cd26e 100644 --- a/solution/0500-0599/0540.Single Element in a Sorted Array/Solution.c +++ b/solution/0500-0599/0540.Single Element in a Sorted Array/Solution.c @@ -10,4 +10,4 @@ int singleNonDuplicate(int* nums, int numsSize) { } } return nums[left]; -} +} \ No newline at end of file diff --git a/solution/0500-0599/0543.Diameter of Binary Tree/Solution.c b/solution/0500-0599/0543.Diameter of Binary Tree/Solution.c index e09ab2271552c..03aaad1cedc4c 100644 --- a/solution/0500-0599/0543.Diameter of Binary Tree/Solution.c +++ b/solution/0500-0599/0543.Diameter of Binary Tree/Solution.c @@ -23,4 +23,4 @@ int diameterOfBinaryTree(struct TreeNode* root) { int res = 0; dfs(root, &res); return res; -} +} \ No newline at end of file diff --git a/solution/0500-0599/0543.Diameter of Binary Tree/Solution2.py b/solution/0500-0599/0543.Diameter of Binary Tree/Solution2.py new file mode 100644 index 0000000000000..aa1f617d5fb0a --- /dev/null +++ b/solution/0500-0599/0543.Diameter of Binary Tree/Solution2.py @@ -0,0 +1,41 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def diameterOfBinaryTree(self, root: TreeNode) -> int: + def build(root): + if root is None: + return + nonlocal d + if root.left: + d[root].add(root.left) + d[root.left].add(root) + if root.right: + d[root].add(root.right) + d[root.right].add(root) + build(root.left) + build(root.right) + + def dfs(u, t): + nonlocal ans, vis, d, next + if u in vis: + return + vis.add(u) + if t > ans: + ans = t + next = u + for v in d[u]: + dfs(v, t + 1) + + d = defaultdict(set) + ans = 0 + next = root + build(root) + vis = set() + dfs(next, 0) + vis.clear() + dfs(next, 0) + return ans diff --git a/solution/0500-0599/0547.Number of Provinces/Solution2.cpp b/solution/0500-0599/0547.Number of Provinces/Solution2.cpp new file mode 100644 index 0000000000000..c466dfc6cf782 --- /dev/null +++ b/solution/0500-0599/0547.Number of Provinces/Solution2.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int findCircleNum(vector>& isConnected) { + int n = isConnected.size(); + int p[n]; + iota(p, p + n, 0); + function find = [&](int x) -> int { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + }; + int ans = n; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + if (isConnected[i][j]) { + int pa = find(i), pb = find(j); + if (pa != pb) { + p[pa] = pb; + --ans; + } + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0500-0599/0547.Number of Provinces/Solution2.go b/solution/0500-0599/0547.Number of Provinces/Solution2.go new file mode 100644 index 0000000000000..f054dfa8b9d80 --- /dev/null +++ b/solution/0500-0599/0547.Number of Provinces/Solution2.go @@ -0,0 +1,27 @@ +func findCircleNum(isConnected [][]int) (ans int) { + n := len(isConnected) + p := make([]int, n) + for i := range p { + p[i] = i + } + var find func(x int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + ans = n + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + if isConnected[i][j] == 1 { + pa, pb := find(i), find(j) + if pa != pb { + p[pa] = pb + ans-- + } + } + } + } + return +} \ No newline at end of file diff --git a/solution/0500-0599/0547.Number of Provinces/Solution2.java b/solution/0500-0599/0547.Number of Provinces/Solution2.java new file mode 100644 index 0000000000000..935ba7ad09d33 --- /dev/null +++ b/solution/0500-0599/0547.Number of Provinces/Solution2.java @@ -0,0 +1,31 @@ +class Solution { + private int[] p; + + public int findCircleNum(int[][] isConnected) { + int n = isConnected.length; + p = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + } + int ans = n; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + if (isConnected[i][j] == 1) { + int pa = find(i), pb = find(j); + if (pa != pb) { + p[pa] = pb; + --ans; + } + } + } + } + return ans; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} \ No newline at end of file diff --git a/solution/0500-0599/0547.Number of Provinces/Solution2.py b/solution/0500-0599/0547.Number of Provinces/Solution2.py new file mode 100644 index 0000000000000..f42bff39e0b6d --- /dev/null +++ b/solution/0500-0599/0547.Number of Provinces/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def findCircleNum(self, isConnected: List[List[int]]) -> int: + def find(x: int) -> int: + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + n = len(isConnected) + p = list(range(n)) + ans = n + for i in range(n): + for j in range(i + 1, n): + if isConnected[i][j]: + pa, pb = find(i), find(j) + if pa != pb: + p[pa] = pb + ans -= 1 + return ans diff --git a/solution/0500-0599/0547.Number of Provinces/Solution2.ts b/solution/0500-0599/0547.Number of Provinces/Solution2.ts new file mode 100644 index 0000000000000..2488b343ae76e --- /dev/null +++ b/solution/0500-0599/0547.Number of Provinces/Solution2.ts @@ -0,0 +1,27 @@ +function findCircleNum(isConnected: number[][]): number { + const n = isConnected.length; + const p: number[] = new Array(n); + for (let i = 0; i < n; ++i) { + p[i] = i; + } + const find = (x: number): number => { + if (p[x] !== x) { + p[x] = find(p[x]); + } + return p[x]; + }; + let ans = n; + for (let i = 0; i < n; ++i) { + for (let j = i + 1; j < n; ++j) { + if (isConnected[i][j]) { + const pa = find(i); + const pb = find(j); + if (pa !== pb) { + p[pa] = pb; + --ans; + } + } + } + } + return ans; +} diff --git a/solution/0500-0599/0550.Game Play Analysis IV/Solution2.sql b/solution/0500-0599/0550.Game Play Analysis IV/Solution2.sql new file mode 100644 index 0000000000000..53ebf38c6e350 --- /dev/null +++ b/solution/0500-0599/0550.Game Play Analysis IV/Solution2.sql @@ -0,0 +1,21 @@ +# Write your MySQL query statement below +WITH + T AS ( + SELECT + player_id, + DATEDIFF( + LEAD(event_date) OVER ( + PARTITION BY player_id + ORDER BY event_date + ), + event_date + ) = 1 AS st, + RANK() OVER ( + PARTITION BY player_id + ORDER BY event_date + ) AS rk + FROM Activity + ) +SELECT ROUND(COUNT(IF(st = 1, player_id, NULL)) / COUNT(DISTINCT player_id), 2) AS fraction +FROM T +WHERE rk = 1; diff --git a/solution/0500-0599/0551.Student Attendance Record I/Solution.cpp b/solution/0500-0599/0551.Student Attendance Record I/Solution.cpp index d5359de1228d7..056f8a9c4a538 100644 --- a/solution/0500-0599/0551.Student Attendance Record I/Solution.cpp +++ b/solution/0500-0599/0551.Student Attendance Record I/Solution.cpp @@ -3,4 +3,4 @@ class Solution { bool checkRecord(string s) { return count(s.begin(), s.end(), 'A') < 2 && s.find("LLL") == string::npos; } -}; +}; \ No newline at end of file diff --git a/solution/0500-0599/0552.Student Attendance Record II/Solution.cpp b/solution/0500-0599/0552.Student Attendance Record II/Solution.cpp index 623efb981dc48..56dd945f6afaf 100644 --- a/solution/0500-0599/0552.Student Attendance Record II/Solution.cpp +++ b/solution/0500-0599/0552.Student Attendance Record II/Solution.cpp @@ -1,33 +1,31 @@ -constexpr int MOD = 1e9 + 7; +int f[100010][2][3]; +const int mod = 1e9 + 7; class Solution { public: int checkRecord(int n) { - using ll = long long; - vector>> dp(n, vector>(2, vector(3))); - - // base case - dp[0][0][0] = dp[0][0][1] = dp[0][1][0] = 1; + this->n = n; + memset(f, -1, sizeof(f)); + return dfs(0, 0, 0); + } - for (int i = 1; i < n; ++i) { - // A - dp[i][1][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % MOD; - // L - dp[i][0][1] = dp[i - 1][0][0]; - dp[i][0][2] = dp[i - 1][0][1]; - dp[i][1][1] = dp[i - 1][1][0]; - dp[i][1][2] = dp[i - 1][1][1]; - // P - dp[i][0][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % MOD; - dp[i][1][0] = (dp[i][1][0] + dp[i - 1][1][0] + dp[i - 1][1][1] + dp[i - 1][1][2]) % MOD; + int dfs(int i, int j, int k) { + if (i >= n) { + return 1; } - - ll ans = 0; - for (int j = 0; j < 2; ++j) { - for (int k = 0; k < 3; ++k) { - ans = (ans + dp[n - 1][j][k]) % MOD; - } + if (f[i][j][k] != -1) { + return f[i][j][k]; } - return ans; + int ans = dfs(i + 1, j, 0); + if (j == 0) { + ans = (ans + dfs(i + 1, j + 1, 0)) % mod; + } + if (k < 2) { + ans = (ans + dfs(i + 1, j, k + 1)) % mod; + } + return f[i][j][k] = ans; } -}; + +private: + int n; +}; \ No newline at end of file diff --git a/solution/0500-0599/0552.Student Attendance Record II/Solution.go b/solution/0500-0599/0552.Student Attendance Record II/Solution.go index 37061d998760a..0303e58477486 100644 --- a/solution/0500-0599/0552.Student Attendance Record II/Solution.go +++ b/solution/0500-0599/0552.Student Attendance Record II/Solution.go @@ -1,37 +1,32 @@ -const _mod int = 1e9 + 7 - func checkRecord(n int) int { - dp := make([][][]int, n) - for i := 0; i < n; i++ { - dp[i] = make([][]int, 2) - for j := 0; j < 2; j++ { - dp[i][j] = make([]int, 3) + f := make([][][]int, n) + for i := range f { + f[i] = make([][]int, 2) + for j := range f[i] { + f[i][j] = make([]int, 3) + for k := range f[i][j] { + f[i][j][k] = -1 + } } } - - // base case - dp[0][0][0] = 1 - dp[0][0][1] = 1 - dp[0][1][0] = 1 - - for i := 1; i < n; i++ { - // A - dp[i][1][0] = (dp[i-1][0][0] + dp[i-1][0][1] + dp[i-1][0][2]) % _mod - // L - dp[i][0][1] = dp[i-1][0][0] - dp[i][0][2] = dp[i-1][0][1] - dp[i][1][1] = dp[i-1][1][0] - dp[i][1][2] = dp[i-1][1][1] - // P - dp[i][0][0] = (dp[i-1][0][0] + dp[i-1][0][1] + dp[i-1][0][2]) % _mod - dp[i][1][0] = (dp[i][1][0] + dp[i-1][1][0] + dp[i-1][1][1] + dp[i-1][1][2]) % _mod - } - - var ans int - for j := 0; j < 2; j++ { - for k := 0; k < 3; k++ { - ans = (ans + dp[n-1][j][k]) % _mod + const mod = 1e9 + 7 + var dfs func(i, j, k int) int + dfs = func(i, j, k int) int { + if i >= n { + return 1 + } + if f[i][j][k] != -1 { + return f[i][j][k] + } + ans := dfs(i+1, j, 0) + if j == 0 { + ans = (ans + dfs(i+1, j+1, 0)) % mod + } + if k < 2 { + ans = (ans + dfs(i+1, j, k+1)) % mod } + f[i][j][k] = ans + return ans } - return ans + return dfs(0, 0, 0) } \ No newline at end of file diff --git a/solution/0500-0599/0552.Student Attendance Record II/Solution.java b/solution/0500-0599/0552.Student Attendance Record II/Solution.java index 449a4ef465a1c..4cf148b416e5d 100644 --- a/solution/0500-0599/0552.Student Attendance Record II/Solution.java +++ b/solution/0500-0599/0552.Student Attendance Record II/Solution.java @@ -1,33 +1,28 @@ class Solution { - private static final int MOD = 1000000007; + private final int mod = (int) 1e9 + 7; + private int n; + private Integer[][][] f; public int checkRecord(int n) { - long[][][] dp = new long[n][2][3]; - - // base case - dp[0][0][0] = 1; - dp[0][0][1] = 1; - dp[0][1][0] = 1; + this.n = n; + f = new Integer[n][2][3]; + return dfs(0, 0, 0); + } - for (int i = 1; i < n; i++) { - // A - dp[i][1][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % MOD; - // L - dp[i][0][1] = dp[i - 1][0][0]; - dp[i][0][2] = dp[i - 1][0][1]; - dp[i][1][1] = dp[i - 1][1][0]; - dp[i][1][2] = dp[i - 1][1][1]; - // P - dp[i][0][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % MOD; - dp[i][1][0] = (dp[i][1][0] + dp[i - 1][1][0] + dp[i - 1][1][1] + dp[i - 1][1][2]) % MOD; + private int dfs(int i, int j, int k) { + if (i >= n) { + return 1; } - - long ans = 0; - for (int j = 0; j < 2; j++) { - for (int k = 0; k < 3; k++) { - ans = (ans + dp[n - 1][j][k]) % MOD; - } + if (f[i][j][k] != null) { + return f[i][j][k]; + } + int ans = dfs(i + 1, j, 0); + if (j == 0) { + ans = (ans + dfs(i + 1, j + 1, 0)) % mod; + } + if (k < 2) { + ans = (ans + dfs(i + 1, j, k + 1)) % mod; } - return (int) ans; + return f[i][j][k] = ans; } -} +} \ No newline at end of file diff --git a/solution/0500-0599/0552.Student Attendance Record II/Solution.py b/solution/0500-0599/0552.Student Attendance Record II/Solution.py index 58fccfc870d9e..306a97e5a6ab0 100644 --- a/solution/0500-0599/0552.Student Attendance Record II/Solution.py +++ b/solution/0500-0599/0552.Student Attendance Record II/Solution.py @@ -1,27 +1,18 @@ class Solution: def checkRecord(self, n: int) -> int: - mod = int(1e9 + 7) - dp = [[[0, 0, 0], [0, 0, 0]] for _ in range(n)] + @cache + def dfs(i, j, k): + if i >= n: + return 1 + ans = 0 + if j == 0: + ans += dfs(i + 1, j + 1, 0) + if k < 2: + ans += dfs(i + 1, j, k + 1) + ans += dfs(i + 1, j, 0) + return ans % mod - # base case - dp[0][0][0] = dp[0][0][1] = dp[0][1][0] = 1 - - for i in range(1, n): - # A - dp[i][1][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % mod - # L - dp[i][0][1] = dp[i - 1][0][0] - dp[i][0][2] = dp[i - 1][0][1] - dp[i][1][1] = dp[i - 1][1][0] - dp[i][1][2] = dp[i - 1][1][1] - # P - dp[i][0][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % mod - dp[i][1][0] = ( - dp[i][1][0] + dp[i - 1][1][0] + dp[i - 1][1][1] + dp[i - 1][1][2] - ) % mod - - ans = 0 - for j in range(2): - for k in range(3): - ans = (ans + dp[n - 1][j][k]) % mod + mod = 10**9 + 7 + ans = dfs(0, 0, 0) + dfs.cache_clear() return ans diff --git a/solution/0500-0599/0552.Student Attendance Record II/Solution2.cpp b/solution/0500-0599/0552.Student Attendance Record II/Solution2.cpp new file mode 100644 index 0000000000000..e6b2be032d809 --- /dev/null +++ b/solution/0500-0599/0552.Student Attendance Record II/Solution2.cpp @@ -0,0 +1,33 @@ +constexpr int MOD = 1e9 + 7; + +class Solution { +public: + int checkRecord(int n) { + using ll = long long; + vector>> dp(n, vector>(2, vector(3))); + + // base case + dp[0][0][0] = dp[0][0][1] = dp[0][1][0] = 1; + + for (int i = 1; i < n; ++i) { + // A + dp[i][1][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % MOD; + // L + dp[i][0][1] = dp[i - 1][0][0]; + dp[i][0][2] = dp[i - 1][0][1]; + dp[i][1][1] = dp[i - 1][1][0]; + dp[i][1][2] = dp[i - 1][1][1]; + // P + dp[i][0][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % MOD; + dp[i][1][0] = (dp[i][1][0] + dp[i - 1][1][0] + dp[i - 1][1][1] + dp[i - 1][1][2]) % MOD; + } + + ll ans = 0; + for (int j = 0; j < 2; ++j) { + for (int k = 0; k < 3; ++k) { + ans = (ans + dp[n - 1][j][k]) % MOD; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0500-0599/0552.Student Attendance Record II/Solution2.go b/solution/0500-0599/0552.Student Attendance Record II/Solution2.go new file mode 100644 index 0000000000000..37061d998760a --- /dev/null +++ b/solution/0500-0599/0552.Student Attendance Record II/Solution2.go @@ -0,0 +1,37 @@ +const _mod int = 1e9 + 7 + +func checkRecord(n int) int { + dp := make([][][]int, n) + for i := 0; i < n; i++ { + dp[i] = make([][]int, 2) + for j := 0; j < 2; j++ { + dp[i][j] = make([]int, 3) + } + } + + // base case + dp[0][0][0] = 1 + dp[0][0][1] = 1 + dp[0][1][0] = 1 + + for i := 1; i < n; i++ { + // A + dp[i][1][0] = (dp[i-1][0][0] + dp[i-1][0][1] + dp[i-1][0][2]) % _mod + // L + dp[i][0][1] = dp[i-1][0][0] + dp[i][0][2] = dp[i-1][0][1] + dp[i][1][1] = dp[i-1][1][0] + dp[i][1][2] = dp[i-1][1][1] + // P + dp[i][0][0] = (dp[i-1][0][0] + dp[i-1][0][1] + dp[i-1][0][2]) % _mod + dp[i][1][0] = (dp[i][1][0] + dp[i-1][1][0] + dp[i-1][1][1] + dp[i-1][1][2]) % _mod + } + + var ans int + for j := 0; j < 2; j++ { + for k := 0; k < 3; k++ { + ans = (ans + dp[n-1][j][k]) % _mod + } + } + return ans +} \ No newline at end of file diff --git a/solution/0500-0599/0552.Student Attendance Record II/Solution2.java b/solution/0500-0599/0552.Student Attendance Record II/Solution2.java new file mode 100644 index 0000000000000..533f54ded66ba --- /dev/null +++ b/solution/0500-0599/0552.Student Attendance Record II/Solution2.java @@ -0,0 +1,33 @@ +class Solution { + private static final int MOD = 1000000007; + + public int checkRecord(int n) { + long[][][] dp = new long[n][2][3]; + + // base case + dp[0][0][0] = 1; + dp[0][0][1] = 1; + dp[0][1][0] = 1; + + for (int i = 1; i < n; i++) { + // A + dp[i][1][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % MOD; + // L + dp[i][0][1] = dp[i - 1][0][0]; + dp[i][0][2] = dp[i - 1][0][1]; + dp[i][1][1] = dp[i - 1][1][0]; + dp[i][1][2] = dp[i - 1][1][1]; + // P + dp[i][0][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % MOD; + dp[i][1][0] = (dp[i][1][0] + dp[i - 1][1][0] + dp[i - 1][1][1] + dp[i - 1][1][2]) % MOD; + } + + long ans = 0; + for (int j = 0; j < 2; j++) { + for (int k = 0; k < 3; k++) { + ans = (ans + dp[n - 1][j][k]) % MOD; + } + } + return (int) ans; + } +} \ No newline at end of file diff --git a/solution/0500-0599/0552.Student Attendance Record II/Solution2.py b/solution/0500-0599/0552.Student Attendance Record II/Solution2.py new file mode 100644 index 0000000000000..58fccfc870d9e --- /dev/null +++ b/solution/0500-0599/0552.Student Attendance Record II/Solution2.py @@ -0,0 +1,27 @@ +class Solution: + def checkRecord(self, n: int) -> int: + mod = int(1e9 + 7) + dp = [[[0, 0, 0], [0, 0, 0]] for _ in range(n)] + + # base case + dp[0][0][0] = dp[0][0][1] = dp[0][1][0] = 1 + + for i in range(1, n): + # A + dp[i][1][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % mod + # L + dp[i][0][1] = dp[i - 1][0][0] + dp[i][0][2] = dp[i - 1][0][1] + dp[i][1][1] = dp[i - 1][1][0] + dp[i][1][2] = dp[i - 1][1][1] + # P + dp[i][0][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % mod + dp[i][1][0] = ( + dp[i][1][0] + dp[i - 1][1][0] + dp[i - 1][1][1] + dp[i - 1][1][2] + ) % mod + + ans = 0 + for j in range(2): + for k in range(3): + ans = (ans + dp[n - 1][j][k]) % mod + return ans diff --git a/solution/0500-0599/0554.Brick Wall/Solution.java b/solution/0500-0599/0554.Brick Wall/Solution.java index f1002d8080f79..e4447835bcbbf 100644 --- a/solution/0500-0599/0554.Brick Wall/Solution.java +++ b/solution/0500-0599/0554.Brick Wall/Solution.java @@ -11,4 +11,4 @@ public int leastBricks(List> wall) { int max = cnt.values().stream().max(Comparator.naturalOrder()).orElse(0); return wall.size() - max; } -} +} \ No newline at end of file diff --git a/solution/0500-0599/0555.Split Concatenated Strings/Solution.java b/solution/0500-0599/0555.Split Concatenated Strings/Solution.java index 46f6a2566dd75..59ffff9633614 100644 --- a/solution/0500-0599/0555.Split Concatenated Strings/Solution.java +++ b/solution/0500-0599/0555.Split Concatenated Strings/Solution.java @@ -38,4 +38,4 @@ public String splitLoopedString(String[] strs) { } return ans; } -} +} \ No newline at end of file diff --git a/solution/0500-0599/0557.Reverse Words in a String III/Solution.php b/solution/0500-0599/0557.Reverse Words in a String III/Solution.php index c9ed593e8983e..4e17b554f7695 100644 --- a/solution/0500-0599/0557.Reverse Words in a String III/Solution.php +++ b/solution/0500-0599/0557.Reverse Words in a String III/Solution.php @@ -10,4 +10,4 @@ function reverseWords($s) { } return implode(' ', $sArr); } -} \ No newline at end of file +} diff --git a/solution/0500-0599/0560.Subarray Sum Equals K/Solution.rs b/solution/0500-0599/0560.Subarray Sum Equals K/Solution.rs index 5dccef7f5e726..5a6eb2313e9c1 100644 --- a/solution/0500-0599/0560.Subarray Sum Equals K/Solution.rs +++ b/solution/0500-0599/0560.Subarray Sum Equals K/Solution.rs @@ -1,16 +1,19 @@ -use std::collections::HashMap; - impl Solution { - pub fn subarray_sum(nums: Vec, k: i32) -> i32 { - let mut res = 0; - let mut sum = 0; - let mut map = HashMap::new(); - map.insert(0, 1); - nums.iter().for_each(|num| { - sum += num; - res += map.get(&(sum - k)).unwrap_or(&0); - map.insert(sum, map.get(&sum).unwrap_or(&0) + 1); - }); - res + pub fn subarray_sum(mut nums: Vec, k: i32) -> i32 { + let n = nums.len(); + let mut count = 0; + for i in 0..n { + let num = nums[i]; + if num == k { + count += 1; + } + for j in 0..i { + nums[j] += num; + if nums[j] == k { + count += 1; + } + } + } + count } } diff --git a/solution/0500-0599/0560.Subarray Sum Equals K/Solution2.rs b/solution/0500-0599/0560.Subarray Sum Equals K/Solution2.rs new file mode 100644 index 0000000000000..5dccef7f5e726 --- /dev/null +++ b/solution/0500-0599/0560.Subarray Sum Equals K/Solution2.rs @@ -0,0 +1,16 @@ +use std::collections::HashMap; + +impl Solution { + pub fn subarray_sum(nums: Vec, k: i32) -> i32 { + let mut res = 0; + let mut sum = 0; + let mut map = HashMap::new(); + map.insert(0, 1); + nums.iter().for_each(|num| { + sum += num; + res += map.get(&(sum - k)).unwrap_or(&0); + map.insert(sum, map.get(&sum).unwrap_or(&0) + 1); + }); + res + } +} diff --git a/solution/0500-0599/0562.Longest Line of Consecutive One in Matrix/Solution.py b/solution/0500-0599/0562.Longest Line of Consecutive One in Matrix/Solution.py index 501d71487cab8..d6e8647f6949a 100644 --- a/solution/0500-0599/0562.Longest Line of Consecutive One in Matrix/Solution.py +++ b/solution/0500-0599/0562.Longest Line of Consecutive One in Matrix/Solution.py @@ -8,8 +8,7 @@ def longestLine(self, mat: List[List[int]]) -> int: ans = 0 for i in range(1, m + 1): for j in range(1, n + 1): - v = mat[i - 1][j - 1] - if v: + if mat[i - 1][j - 1]: a[i][j] = a[i - 1][j] + 1 b[i][j] = b[i][j - 1] + 1 c[i][j] = c[i - 1][j - 1] + 1 diff --git a/solution/0500-0599/0565.Array Nesting/Solution.cpp b/solution/0500-0599/0565.Array Nesting/Solution.cpp index a67ab3cb0554c..c0df7f34bda8d 100644 --- a/solution/0500-0599/0565.Array Nesting/Solution.cpp +++ b/solution/0500-0599/0565.Array Nesting/Solution.cpp @@ -1,18 +1,20 @@ class Solution { public: int arrayNesting(vector& nums) { - int ans = 0, n = nums.size(); + int n = nums.size(); + vector vis(n); + int res = 0; for (int i = 0; i < n; ++i) { - int cnt = 0; - int j = i; - while (nums[j] < n) { - int k = nums[j]; - nums[j] = n; - j = k; - ++cnt; + if (vis[i]) continue; + int cur = nums[i], m = 1; + vis[cur] = true; + while (nums[cur] != nums[i]) { + cur = nums[cur]; + ++m; + vis[cur] = true; } - ans = max(ans, cnt); + res = max(res, m); } - return ans; + return res; } }; \ No newline at end of file diff --git a/solution/0500-0599/0565.Array Nesting/Solution.go b/solution/0500-0599/0565.Array Nesting/Solution.go index bd60f8258d054..5c1e7a0cf5d16 100644 --- a/solution/0500-0599/0565.Array Nesting/Solution.go +++ b/solution/0500-0599/0565.Array Nesting/Solution.go @@ -1,15 +1,20 @@ func arrayNesting(nums []int) int { - ans, n := 0, len(nums) - for i := range nums { - cnt, j := 0, i - for nums[j] != n { - k := nums[j] - nums[j] = n - j = k - cnt++ + n := len(nums) + vis := make([]bool, n) + ans := 0 + for i := 0; i < n; i++ { + if vis[i] { + continue } - if ans < cnt { - ans = cnt + cur, m := nums[i], 1 + vis[cur] = true + for nums[cur] != nums[i] { + cur = nums[cur] + m++ + vis[cur] = true + } + if m > ans { + ans = m } } return ans diff --git a/solution/0500-0599/0565.Array Nesting/Solution.java b/solution/0500-0599/0565.Array Nesting/Solution.java index 8d19499b2e4f4..fe8ca125d4f97 100644 --- a/solution/0500-0599/0565.Array Nesting/Solution.java +++ b/solution/0500-0599/0565.Array Nesting/Solution.java @@ -1,17 +1,21 @@ class Solution { public int arrayNesting(int[] nums) { - int ans = 0, n = nums.length; - for (int i = 0; i < n; ++i) { - int cnt = 0; - int j = i; - while (nums[j] < n) { - int k = nums[j]; - nums[j] = n; - j = k; - ++cnt; + int n = nums.length; + boolean[] vis = new boolean[n]; + int res = 0; + for (int i = 0; i < n; i++) { + if (vis[i]) { + continue; } - ans = Math.max(ans, cnt); + int cur = nums[i], m = 1; + vis[cur] = true; + while (nums[cur] != nums[i]) { + cur = nums[cur]; + m++; + vis[cur] = true; + } + res = Math.max(res, m); } - return ans; + return res; } -} +} \ No newline at end of file diff --git a/solution/0500-0599/0565.Array Nesting/Solution.py b/solution/0500-0599/0565.Array Nesting/Solution.py index 75bae2754f17a..d9f2f4f215bc1 100644 --- a/solution/0500-0599/0565.Array Nesting/Solution.py +++ b/solution/0500-0599/0565.Array Nesting/Solution.py @@ -1,12 +1,16 @@ class Solution: def arrayNesting(self, nums: List[int]) -> int: - ans, n = 0, len(nums) + n = len(nums) + vis = [False] * n + res = 0 for i in range(n): - cnt = 0 - while nums[i] != n: - j = nums[i] - nums[i] = n - i = j - cnt += 1 - ans = max(ans, cnt) - return ans + if vis[i]: + continue + cur, m = nums[i], 1 + vis[cur] = True + while nums[cur] != nums[i]: + cur = nums[cur] + m += 1 + vis[cur] = True + res = max(res, m) + return res diff --git a/solution/0500-0599/0565.Array Nesting/Solution2.cpp b/solution/0500-0599/0565.Array Nesting/Solution2.cpp new file mode 100644 index 0000000000000..a67ab3cb0554c --- /dev/null +++ b/solution/0500-0599/0565.Array Nesting/Solution2.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int arrayNesting(vector& nums) { + int ans = 0, n = nums.size(); + for (int i = 0; i < n; ++i) { + int cnt = 0; + int j = i; + while (nums[j] < n) { + int k = nums[j]; + nums[j] = n; + j = k; + ++cnt; + } + ans = max(ans, cnt); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0500-0599/0565.Array Nesting/Solution2.go b/solution/0500-0599/0565.Array Nesting/Solution2.go new file mode 100644 index 0000000000000..bd60f8258d054 --- /dev/null +++ b/solution/0500-0599/0565.Array Nesting/Solution2.go @@ -0,0 +1,16 @@ +func arrayNesting(nums []int) int { + ans, n := 0, len(nums) + for i := range nums { + cnt, j := 0, i + for nums[j] != n { + k := nums[j] + nums[j] = n + j = k + cnt++ + } + if ans < cnt { + ans = cnt + } + } + return ans +} \ No newline at end of file diff --git a/solution/0500-0599/0565.Array Nesting/Solution2.java b/solution/0500-0599/0565.Array Nesting/Solution2.java new file mode 100644 index 0000000000000..80b4ae2d81218 --- /dev/null +++ b/solution/0500-0599/0565.Array Nesting/Solution2.java @@ -0,0 +1,17 @@ +class Solution { + public int arrayNesting(int[] nums) { + int ans = 0, n = nums.length; + for (int i = 0; i < n; ++i) { + int cnt = 0; + int j = i; + while (nums[j] < n) { + int k = nums[j]; + nums[j] = n; + j = k; + ++cnt; + } + ans = Math.max(ans, cnt); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0500-0599/0565.Array Nesting/Solution2.py b/solution/0500-0599/0565.Array Nesting/Solution2.py new file mode 100644 index 0000000000000..75bae2754f17a --- /dev/null +++ b/solution/0500-0599/0565.Array Nesting/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def arrayNesting(self, nums: List[int]) -> int: + ans, n = 0, len(nums) + for i in range(n): + cnt = 0 + while nums[i] != n: + j = nums[i] + nums[i] = n + i = j + cnt += 1 + ans = max(ans, cnt) + return ans diff --git a/solution/0500-0599/0566.Reshape the Matrix/Solution.c b/solution/0500-0599/0566.Reshape the Matrix/Solution.c index 8d5074da82ae6..b7f072930c0f9 100644 --- a/solution/0500-0599/0566.Reshape the Matrix/Solution.c +++ b/solution/0500-0599/0566.Reshape the Matrix/Solution.c @@ -20,4 +20,4 @@ int** matrixReshape(int** mat, int matSize, int* matColSize, int r, int c, int* ans[i / c][i % c] = mat[i / matColSize[0]][i % matColSize[0]]; } return ans; -} +} \ No newline at end of file diff --git a/solution/0500-0599/0566.Reshape the Matrix/Solution2.ts b/solution/0500-0599/0566.Reshape the Matrix/Solution2.ts new file mode 100644 index 0000000000000..929936524d459 --- /dev/null +++ b/solution/0500-0599/0566.Reshape the Matrix/Solution2.ts @@ -0,0 +1,12 @@ +function matrixReshape(mat: number[][], r: number, c: number): number[][] { + const m = mat.length; + const n = mat[0].length; + if (m * n !== r * c) { + return mat; + } + const ans = Array.from({ length: r }, () => new Array(c).fill(0)); + for (let i = 0; i < r * c; i++) { + ans[Math.floor(i / c)][i % c] = mat[Math.floor(i / n)][i % n]; + } + return ans; +} diff --git a/solution/0500-0599/0567.Permutation in String/Solution.cpp b/solution/0500-0599/0567.Permutation in String/Solution.cpp index bfcaf32a285cd..e5c08e7543eaf 100644 --- a/solution/0500-0599/0567.Permutation in String/Solution.cpp +++ b/solution/0500-0599/0567.Permutation in String/Solution.cpp @@ -5,36 +5,18 @@ class Solution { if (n > m) { return false; } - vector cnt(26); + vector cnt1(26), cnt2(26); for (int i = 0; i < n; ++i) { - --cnt[s1[i] - 'a']; - ++cnt[s2[i] - 'a']; + ++cnt1[s1[i] - 'a']; + ++cnt2[s2[i] - 'a']; } - int diff = 0; - for (int x : cnt) { - if (x) { - ++diff; - } - } - if (diff == 0) { + if (cnt1 == cnt2) { return true; } for (int i = n; i < m; ++i) { - int a = s2[i - n] - 'a'; - int b = s2[i] - 'a'; - if (cnt[b] == 0) { - ++diff; - } - if (++cnt[b] == 0) { - --diff; - } - if (cnt[a] == 0) { - ++diff; - } - if (--cnt[a] == 0) { - --diff; - } - if (diff == 0) { + ++cnt2[s2[i] - 'a']; + --cnt2[s2[i - n] - 'a']; + if (cnt1 == cnt2) { return true; } } diff --git a/solution/0500-0599/0567.Permutation in String/Solution.go b/solution/0500-0599/0567.Permutation in String/Solution.go index d16d0a95f04c3..c9bfe4586b63a 100644 --- a/solution/0500-0599/0567.Permutation in String/Solution.go +++ b/solution/0500-0599/0567.Permutation in String/Solution.go @@ -3,37 +3,19 @@ func checkInclusion(s1 string, s2 string) bool { if n > m { return false } - cnt := [26]int{} + cnt1 := [26]int{} + cnt2 := [26]int{} for i := range s1 { - cnt[s1[i]-'a']-- - cnt[s2[i]-'a']++ + cnt1[s1[i]-'a']++ + cnt2[s2[i]-'a']++ } - diff := 0 - for _, x := range cnt { - if x != 0 { - diff++ - } - } - if diff == 0 { + if cnt1 == cnt2 { return true } for i := n; i < m; i++ { - a, b := s2[i-n]-'a', s2[i]-'a' - if cnt[b] == 0 { - diff++ - } - cnt[b]++ - if cnt[b] == 0 { - diff-- - } - if cnt[a] == 0 { - diff++ - } - cnt[a]-- - if cnt[a] == 0 { - diff-- - } - if diff == 0 { + cnt2[s2[i]-'a']++ + cnt2[s2[i-n]-'a']-- + if cnt1 == cnt2 { return true } } diff --git a/solution/0500-0599/0567.Permutation in String/Solution.java b/solution/0500-0599/0567.Permutation in String/Solution.java index 751eab8186779..d6bf80c9e6754 100644 --- a/solution/0500-0599/0567.Permutation in String/Solution.java +++ b/solution/0500-0599/0567.Permutation in String/Solution.java @@ -5,36 +5,19 @@ public boolean checkInclusion(String s1, String s2) { if (n > m) { return false; } - int[] cnt = new int[26]; + int[] cnt1 = new int[26]; + int[] cnt2 = new int[26]; for (int i = 0; i < n; ++i) { - --cnt[s1.charAt(i) - 'a']; - ++cnt[s2.charAt(i) - 'a']; + ++cnt1[s1.charAt(i) - 'a']; + ++cnt2[s2.charAt(i) - 'a']; } - int diff = 0; - for (int x : cnt) { - if (x != 0) { - ++diff; - } - } - if (diff == 0) { + if (Arrays.equals(cnt1, cnt2)) { return true; } for (int i = n; i < m; ++i) { - int a = s2.charAt(i - n) - 'a'; - int b = s2.charAt(i) - 'a'; - if (cnt[b] == 0) { - ++diff; - } - if (++cnt[b] == 0) { - --diff; - } - if (cnt[a] == 0) { - ++diff; - } - if (--cnt[a] == 0) { - --diff; - } - if (diff == 0) { + ++cnt2[s2.charAt(i) - 'a']; + --cnt2[s2.charAt(i - n) - 'a']; + if (Arrays.equals(cnt1, cnt2)) { return true; } } diff --git a/solution/0500-0599/0567.Permutation in String/Solution.py b/solution/0500-0599/0567.Permutation in String/Solution.py index 445fdf4b6f29d..9b2118a9c87d5 100644 --- a/solution/0500-0599/0567.Permutation in String/Solution.py +++ b/solution/0500-0599/0567.Permutation in String/Solution.py @@ -1,30 +1,13 @@ class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: - n, m = len(s1), len(s2) - if n > m: - return False - cnt = Counter() - for a, b in zip(s1, s2): - cnt[a] -= 1 - cnt[b] += 1 - diff = sum(x != 0 for x in cnt.values()) - if diff == 0: + n = len(s1) + cnt1 = Counter(s1) + cnt2 = Counter(s2[:n]) + if cnt1 == cnt2: return True - for i in range(n, m): - a, b = s2[i - n], s2[i] - - if cnt[b] == 0: - diff += 1 - cnt[b] += 1 - if cnt[b] == 0: - diff -= 1 - - if cnt[a] == 0: - diff += 1 - cnt[a] -= 1 - if cnt[a] == 0: - diff -= 1 - - if diff == 0: + for i in range(n, len(s2)): + cnt2[s2[i]] += 1 + cnt2[s2[i - n]] -= 1 + if cnt1 == cnt2: return True return False diff --git a/solution/0500-0599/0567.Permutation in String/Solution2.cpp b/solution/0500-0599/0567.Permutation in String/Solution2.cpp new file mode 100644 index 0000000000000..bfcaf32a285cd --- /dev/null +++ b/solution/0500-0599/0567.Permutation in String/Solution2.cpp @@ -0,0 +1,43 @@ +class Solution { +public: + bool checkInclusion(string s1, string s2) { + int n = s1.size(), m = s2.size(); + if (n > m) { + return false; + } + vector cnt(26); + for (int i = 0; i < n; ++i) { + --cnt[s1[i] - 'a']; + ++cnt[s2[i] - 'a']; + } + int diff = 0; + for (int x : cnt) { + if (x) { + ++diff; + } + } + if (diff == 0) { + return true; + } + for (int i = n; i < m; ++i) { + int a = s2[i - n] - 'a'; + int b = s2[i] - 'a'; + if (cnt[b] == 0) { + ++diff; + } + if (++cnt[b] == 0) { + --diff; + } + if (cnt[a] == 0) { + ++diff; + } + if (--cnt[a] == 0) { + --diff; + } + if (diff == 0) { + return true; + } + } + return false; + } +}; \ No newline at end of file diff --git a/solution/0500-0599/0567.Permutation in String/Solution2.go b/solution/0500-0599/0567.Permutation in String/Solution2.go new file mode 100644 index 0000000000000..d16d0a95f04c3 --- /dev/null +++ b/solution/0500-0599/0567.Permutation in String/Solution2.go @@ -0,0 +1,41 @@ +func checkInclusion(s1 string, s2 string) bool { + n, m := len(s1), len(s2) + if n > m { + return false + } + cnt := [26]int{} + for i := range s1 { + cnt[s1[i]-'a']-- + cnt[s2[i]-'a']++ + } + diff := 0 + for _, x := range cnt { + if x != 0 { + diff++ + } + } + if diff == 0 { + return true + } + for i := n; i < m; i++ { + a, b := s2[i-n]-'a', s2[i]-'a' + if cnt[b] == 0 { + diff++ + } + cnt[b]++ + if cnt[b] == 0 { + diff-- + } + if cnt[a] == 0 { + diff++ + } + cnt[a]-- + if cnt[a] == 0 { + diff-- + } + if diff == 0 { + return true + } + } + return false +} \ No newline at end of file diff --git a/solution/0500-0599/0567.Permutation in String/Solution2.java b/solution/0500-0599/0567.Permutation in String/Solution2.java new file mode 100644 index 0000000000000..751eab8186779 --- /dev/null +++ b/solution/0500-0599/0567.Permutation in String/Solution2.java @@ -0,0 +1,43 @@ +class Solution { + public boolean checkInclusion(String s1, String s2) { + int n = s1.length(); + int m = s2.length(); + if (n > m) { + return false; + } + int[] cnt = new int[26]; + for (int i = 0; i < n; ++i) { + --cnt[s1.charAt(i) - 'a']; + ++cnt[s2.charAt(i) - 'a']; + } + int diff = 0; + for (int x : cnt) { + if (x != 0) { + ++diff; + } + } + if (diff == 0) { + return true; + } + for (int i = n; i < m; ++i) { + int a = s2.charAt(i - n) - 'a'; + int b = s2.charAt(i) - 'a'; + if (cnt[b] == 0) { + ++diff; + } + if (++cnt[b] == 0) { + --diff; + } + if (cnt[a] == 0) { + ++diff; + } + if (--cnt[a] == 0) { + --diff; + } + if (diff == 0) { + return true; + } + } + return false; + } +} \ No newline at end of file diff --git a/solution/0500-0599/0567.Permutation in String/Solution2.py b/solution/0500-0599/0567.Permutation in String/Solution2.py new file mode 100644 index 0000000000000..445fdf4b6f29d --- /dev/null +++ b/solution/0500-0599/0567.Permutation in String/Solution2.py @@ -0,0 +1,30 @@ +class Solution: + def checkInclusion(self, s1: str, s2: str) -> bool: + n, m = len(s1), len(s2) + if n > m: + return False + cnt = Counter() + for a, b in zip(s1, s2): + cnt[a] -= 1 + cnt[b] += 1 + diff = sum(x != 0 for x in cnt.values()) + if diff == 0: + return True + for i in range(n, m): + a, b = s2[i - n], s2[i] + + if cnt[b] == 0: + diff += 1 + cnt[b] += 1 + if cnt[b] == 0: + diff -= 1 + + if cnt[a] == 0: + diff += 1 + cnt[a] -= 1 + if cnt[a] == 0: + diff -= 1 + + if diff == 0: + return True + return False diff --git a/solution/0500-0599/0567.Permutation in String/Solution3.go b/solution/0500-0599/0567.Permutation in String/Solution3.go new file mode 100644 index 0000000000000..f99fd03558243 --- /dev/null +++ b/solution/0500-0599/0567.Permutation in String/Solution3.go @@ -0,0 +1,26 @@ +func checkInclusion(s1 string, s2 string) bool { + need, window := make(map[byte]int), make(map[byte]int) + validate, left, right := 0, 0, 0 + for i := range s1 { + need[s1[i]] += 1 + } + for ; right < len(s2); right++ { + c := s2[right] + window[c] += 1 + if need[c] == window[c] { + validate++ + } + for right-left+1 >= len(s1) { + if validate == len(need) { + return true + } + d := s2[left] + if need[d] == window[d] { + validate-- + } + window[d] -= 1 + left++ + } + } + return false +} \ No newline at end of file diff --git a/solution/0500-0599/0574.Winning Candidate/Solution.sql b/solution/0500-0599/0574.Winning Candidate/Solution.sql index 249034be82a7c..39635b0bc4a6a 100644 --- a/solution/0500-0599/0574.Winning Candidate/Solution.sql +++ b/solution/0500-0599/0574.Winning Candidate/Solution.sql @@ -1,8 +1,13 @@ # Write your MySQL query statement below -SELECT name +SELECT + Name FROM - Candidate AS c - LEFT JOIN Vote AS v ON c.id = v.candidateId -GROUP BY c.id -ORDER BY COUNT(1) DESC -LIMIT 1; + ( + SELECT + CandidateId AS id + FROM Vote + GROUP BY CandidateId + ORDER BY COUNT(id) DESC + LIMIT 1 + ) AS t + INNER JOIN Candidate AS c ON t.id = c.id; diff --git a/solution/0500-0599/0574.Winning Candidate/Solution2.sql b/solution/0500-0599/0574.Winning Candidate/Solution2.sql new file mode 100644 index 0000000000000..249034be82a7c --- /dev/null +++ b/solution/0500-0599/0574.Winning Candidate/Solution2.sql @@ -0,0 +1,8 @@ +# Write your MySQL query statement below +SELECT name +FROM + Candidate AS c + LEFT JOIN Vote AS v ON c.id = v.candidateId +GROUP BY c.id +ORDER BY COUNT(1) DESC +LIMIT 1; diff --git a/solution/0500-0599/0576.Out of Boundary Paths/Solution2.java b/solution/0500-0599/0576.Out of Boundary Paths/Solution2.java new file mode 100644 index 0000000000000..4d337135243e3 --- /dev/null +++ b/solution/0500-0599/0576.Out of Boundary Paths/Solution2.java @@ -0,0 +1,28 @@ +class Solution { + public int findPaths(int m, int n, int N, int i, int j) { + final int MOD = (int) (1e9 + 7); + final int[] dirs = new int[] {-1, 0, 1, 0, -1}; + int[][] f = new int[m][n]; + f[i][j] = 1; + int res = 0; + for (int step = 0; step < N; ++step) { + int[][] temp = new int[m][n]; + for (int x = 0; x < m; ++x) { + for (int y = 0; y < n; ++y) { + for (int k = 0; k < 4; ++k) { + int tx = x + dirs[k], ty = y + dirs[k + 1]; + if (tx >= 0 && tx < m && ty >= 0 && ty < n) { + temp[tx][ty] += f[x][y]; + temp[tx][ty] %= MOD; + } else { + res += f[x][y]; + res %= MOD; + } + } + } + } + f = temp; + } + return res; + } +} \ No newline at end of file diff --git a/solution/0500-0599/0578.Get Highest Answer Rate Question/Solution.sql b/solution/0500-0599/0578.Get Highest Answer Rate Question/Solution.sql index 93c2e56a5a56e..3d31f50d7f5f0 100644 --- a/solution/0500-0599/0578.Get Highest Answer Rate Question/Solution.sql +++ b/solution/0500-0599/0578.Get Highest Answer Rate Question/Solution.sql @@ -1,13 +1,6 @@ -WITH - T AS ( - SELECT - question_id AS survey_log, - (SUM(action = 'answer') OVER (PARTITION BY question_id)) / ( - SUM(action = 'show') OVER (PARTITION BY question_id) - ) AS ratio - FROM SurveyLog - ) -SELECT survey_log -FROM T -ORDER BY ratio DESC, 1 +# Write your MySQL query statement below +SELECT question_id AS survey_log +FROM SurveyLog +GROUP BY 1 +ORDER BY SUM(action = 'answer') / SUM(action = 'show') DESC, 1 LIMIT 1; diff --git a/solution/0500-0599/0578.Get Highest Answer Rate Question/Solution2.sql b/solution/0500-0599/0578.Get Highest Answer Rate Question/Solution2.sql new file mode 100644 index 0000000000000..93c2e56a5a56e --- /dev/null +++ b/solution/0500-0599/0578.Get Highest Answer Rate Question/Solution2.sql @@ -0,0 +1,13 @@ +WITH + T AS ( + SELECT + question_id AS survey_log, + (SUM(action = 'answer') OVER (PARTITION BY question_id)) / ( + SUM(action = 'show') OVER (PARTITION BY question_id) + ) AS ratio + FROM SurveyLog + ) +SELECT survey_log +FROM T +ORDER BY ratio DESC, 1 +LIMIT 1; diff --git a/solution/0500-0599/0579.Find Cumulative Salary of an Employee/Solution.sql b/solution/0500-0599/0579.Find Cumulative Salary of an Employee/Solution.sql index d7e0629c81a28..1dc5992310316 100644 --- a/solution/0500-0599/0579.Find Cumulative Salary of an Employee/Solution.sql +++ b/solution/0500-0599/0579.Find Cumulative Salary of an Employee/Solution.sql @@ -1,21 +1,19 @@ # Write your MySQL query statement below -WITH - T AS ( +SELECT + id, + month, + SUM(salary) OVER ( + PARTITION BY id + ORDER BY month + RANGE 2 PRECEDING + ) AS Salary +FROM employee +WHERE + (id, month) NOT IN ( SELECT id, - month, - SUM(salary) OVER ( - PARTITION BY id - ORDER BY month - RANGE 2 PRECEDING - ) AS salary, - RANK() OVER ( - PARTITION BY id - ORDER BY month DESC - ) AS rk + MAX(month) FROM Employee + GROUP BY id ) -SELECT id, month, salary -FROM T -WHERE rk > 1 -ORDER BY 1, 2 DESC; +ORDER BY id, month DESC; diff --git a/solution/0500-0599/0579.Find Cumulative Salary of an Employee/Solution2.sql b/solution/0500-0599/0579.Find Cumulative Salary of an Employee/Solution2.sql new file mode 100644 index 0000000000000..d7e0629c81a28 --- /dev/null +++ b/solution/0500-0599/0579.Find Cumulative Salary of an Employee/Solution2.sql @@ -0,0 +1,21 @@ +# Write your MySQL query statement below +WITH + T AS ( + SELECT + id, + month, + SUM(salary) OVER ( + PARTITION BY id + ORDER BY month + RANGE 2 PRECEDING + ) AS salary, + RANK() OVER ( + PARTITION BY id + ORDER BY month DESC + ) AS rk + FROM Employee + ) +SELECT id, month, salary +FROM T +WHERE rk > 1 +ORDER BY 1, 2 DESC; diff --git a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.cpp b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.cpp index 9bfbfa5fcd74f..2171778268a1c 100644 --- a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.cpp +++ b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.cpp @@ -1,22 +1,15 @@ -class Solution { -public: - int findUnsortedSubarray(vector& nums) { - const int inf = 1e9; - int n = nums.size(); - int l = -1, r = -1; - int mi = inf, mx = -inf; - for (int i = 0; i < n; ++i) { - if (mx > nums[i]) { - r = i; - } else { - mx = nums[i]; - } - if (mi < nums[n - i - 1]) { - l = n - i - 1; - } else { - mi = nums[n - i - 1]; - } - } - return r == -1 ? 0 : r - l + 1; - } +class Solution { +public: + int findUnsortedSubarray(vector& nums) { + vector arr = nums; + sort(arr.begin(), arr.end()); + int l = 0, r = arr.size() - 1; + while (l <= r && arr[l] == nums[l]) { + l++; + } + while (l <= r && arr[r] == nums[r]) { + r--; + } + return r - l + 1; + } }; \ No newline at end of file diff --git a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.go b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.go index 47377f228fd37..699385f3a9dc3 100644 --- a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.go +++ b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.go @@ -1,22 +1,13 @@ func findUnsortedSubarray(nums []int) int { - const inf = 1 << 30 - n := len(nums) - l, r := -1, -1 - mi, mx := inf, -inf - for i, x := range nums { - if mx > x { - r = i - } else { - mx = x - } - if mi < nums[n-i-1] { - l = n - i - 1 - } else { - mi = nums[n-i-1] - } + arr := make([]int, len(nums)) + copy(arr, nums) + sort.Ints(arr) + l, r := 0, len(arr)-1 + for l <= r && nums[l] == arr[l] { + l++ } - if r == -1 { - return 0 + for l <= r && nums[r] == arr[r] { + r-- } return r - l + 1 } \ No newline at end of file diff --git a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.java b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.java index 149c2cb5e7b8e..6a2e4ff947273 100644 --- a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.java +++ b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.java @@ -1,21 +1,14 @@ -class Solution { - public int findUnsortedSubarray(int[] nums) { - final int inf = 1 << 30; - int n = nums.length; - int l = -1, r = -1; - int mi = inf, mx = -inf; - for (int i = 0; i < n; ++i) { - if (mx > nums[i]) { - r = i; - } else { - mx = nums[i]; - } - if (mi < nums[n - i - 1]) { - l = n - i - 1; - } else { - mi = nums[n - i - 1]; - } - } - return r == -1 ? 0 : r - l + 1; - } +class Solution { + public int findUnsortedSubarray(int[] nums) { + int[] arr = nums.clone(); + Arrays.sort(arr); + int l = 0, r = arr.length - 1; + while (l <= r && nums[l] == arr[l]) { + l++; + } + while (l <= r && nums[r] == arr[r]) { + r--; + } + return r - l + 1; + } } \ No newline at end of file diff --git a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.py b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.py index 5b435b89abea0..ca9a9e9ed0a43 100644 --- a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.py +++ b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.py @@ -1,15 +1,9 @@ -class Solution: - def findUnsortedSubarray(self, nums: List[int]) -> int: - mi, mx = inf, -inf - l = r = -1 - n = len(nums) - for i, x in enumerate(nums): - if mx > x: - r = i - else: - mx = x - if mi < nums[n - i - 1]: - l = n - i - 1 - else: - mi = nums[n - i - 1] - return 0 if r == -1 else r - l + 1 +class Solution: + def findUnsortedSubarray(self, nums: List[int]) -> int: + arr = sorted(nums) + l, r = 0, len(nums) - 1 + while l <= r and nums[l] == arr[l]: + l += 1 + while l <= r and nums[r] == arr[r]: + r -= 1 + return r - l + 1 diff --git a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.ts b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.ts index 0fb845b6d0dd9..c9905746ff8bd 100644 --- a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.ts +++ b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution.ts @@ -1,18 +1,12 @@ function findUnsortedSubarray(nums: number[]): number { - let [l, r] = [-1, -1]; - let [mi, mx] = [Infinity, -Infinity]; - const n = nums.length; - for (let i = 0; i < n; ++i) { - if (mx > nums[i]) { - r = i; - } else { - mx = nums[i]; - } - if (mi < nums[n - i - 1]) { - l = n - i - 1; - } else { - mi = nums[n - i - 1]; - } + const arr = [...nums]; + arr.sort((a, b) => a - b); + let [l, r] = [0, arr.length - 1]; + while (l <= r && arr[l] === nums[l]) { + ++l; } - return r === -1 ? 0 : r - l + 1; + while (l <= r && arr[r] === nums[r]) { + --r; + } + return r - l + 1; } diff --git a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution2.cpp b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution2.cpp new file mode 100644 index 0000000000000..f8e56b3a7a7c0 --- /dev/null +++ b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution2.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int findUnsortedSubarray(vector& nums) { + const int inf = 1e9; + int n = nums.size(); + int l = -1, r = -1; + int mi = inf, mx = -inf; + for (int i = 0; i < n; ++i) { + if (mx > nums[i]) { + r = i; + } else { + mx = nums[i]; + } + if (mi < nums[n - i - 1]) { + l = n - i - 1; + } else { + mi = nums[n - i - 1]; + } + } + return r == -1 ? 0 : r - l + 1; + } +}; \ No newline at end of file diff --git a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution2.go b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution2.go new file mode 100644 index 0000000000000..47377f228fd37 --- /dev/null +++ b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution2.go @@ -0,0 +1,22 @@ +func findUnsortedSubarray(nums []int) int { + const inf = 1 << 30 + n := len(nums) + l, r := -1, -1 + mi, mx := inf, -inf + for i, x := range nums { + if mx > x { + r = i + } else { + mx = x + } + if mi < nums[n-i-1] { + l = n - i - 1 + } else { + mi = nums[n-i-1] + } + } + if r == -1 { + return 0 + } + return r - l + 1 +} \ No newline at end of file diff --git a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution2.java b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution2.java new file mode 100644 index 0000000000000..3479467fe90cb --- /dev/null +++ b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution2.java @@ -0,0 +1,21 @@ +class Solution { + public int findUnsortedSubarray(int[] nums) { + final int inf = 1 << 30; + int n = nums.length; + int l = -1, r = -1; + int mi = inf, mx = -inf; + for (int i = 0; i < n; ++i) { + if (mx > nums[i]) { + r = i; + } else { + mx = nums[i]; + } + if (mi < nums[n - i - 1]) { + l = n - i - 1; + } else { + mi = nums[n - i - 1]; + } + } + return r == -1 ? 0 : r - l + 1; + } +} \ No newline at end of file diff --git a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution2.py b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution2.py new file mode 100644 index 0000000000000..d799f4aeafd13 --- /dev/null +++ b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution2.py @@ -0,0 +1,15 @@ +class Solution: + def findUnsortedSubarray(self, nums: List[int]) -> int: + mi, mx = inf, -inf + l = r = -1 + n = len(nums) + for i, x in enumerate(nums): + if mx > x: + r = i + else: + mx = x + if mi < nums[n - i - 1]: + l = n - i - 1 + else: + mi = nums[n - i - 1] + return 0 if r == -1 else r - l + 1 diff --git a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution2.ts b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution2.ts new file mode 100644 index 0000000000000..0fb845b6d0dd9 --- /dev/null +++ b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/Solution2.ts @@ -0,0 +1,18 @@ +function findUnsortedSubarray(nums: number[]): number { + let [l, r] = [-1, -1]; + let [mi, mx] = [Infinity, -Infinity]; + const n = nums.length; + for (let i = 0; i < n; ++i) { + if (mx > nums[i]) { + r = i; + } else { + mx = nums[i]; + } + if (mi < nums[n - i - 1]) { + l = n - i - 1; + } else { + mi = nums[n - i - 1]; + } + } + return r === -1 ? 0 : r - l + 1; +} diff --git a/solution/0500-0599/0582.Kill Process/Solution.cpp b/solution/0500-0599/0582.Kill Process/Solution.cpp index 637c453ece01f..15bbc4ac2097c 100644 --- a/solution/0500-0599/0582.Kill Process/Solution.cpp +++ b/solution/0500-0599/0582.Kill Process/Solution.cpp @@ -1,19 +1,19 @@ -class Solution { -public: - vector killProcess(vector& pid, vector& ppid, int kill) { - unordered_map> g; - int n = pid.size(); - for (int i = 0; i < n; ++i) { - g[ppid[i]].push_back(pid[i]); - } - vector ans; - function dfs = [&](int i) { - ans.push_back(i); - for (int j : g[i]) { - dfs(j); - } - }; - dfs(kill); - return ans; - } +class Solution { +public: + vector killProcess(vector& pid, vector& ppid, int kill) { + unordered_map> g; + int n = pid.size(); + for (int i = 0; i < n; ++i) { + g[ppid[i]].push_back(pid[i]); + } + vector ans; + function dfs = [&](int i) { + ans.push_back(i); + for (int j : g[i]) { + dfs(j); + } + }; + dfs(kill); + return ans; + } }; \ No newline at end of file diff --git a/solution/0500-0599/0582.Kill Process/Solution.java b/solution/0500-0599/0582.Kill Process/Solution.java index be3c68ca350d4..994433267c073 100644 --- a/solution/0500-0599/0582.Kill Process/Solution.java +++ b/solution/0500-0599/0582.Kill Process/Solution.java @@ -1,20 +1,20 @@ -class Solution { - private Map> g = new HashMap<>(); - private List ans = new ArrayList<>(); - - public List killProcess(List pid, List ppid, int kill) { - int n = pid.size(); - for (int i = 0; i < n; ++i) { - g.computeIfAbsent(ppid.get(i), k -> new ArrayList<>()).add(pid.get(i)); - } - dfs(kill); - return ans; - } - - private void dfs(int i) { - ans.add(i); - for (int j : g.getOrDefault(i, Collections.emptyList())) { - dfs(j); - } - } +class Solution { + private Map> g = new HashMap<>(); + private List ans = new ArrayList<>(); + + public List killProcess(List pid, List ppid, int kill) { + int n = pid.size(); + for (int i = 0; i < n; ++i) { + g.computeIfAbsent(ppid.get(i), k -> new ArrayList<>()).add(pid.get(i)); + } + dfs(kill); + return ans; + } + + private void dfs(int i) { + ans.add(i); + for (int j : g.getOrDefault(i, Collections.emptyList())) { + dfs(j); + } + } } \ No newline at end of file diff --git a/solution/0500-0599/0582.Kill Process/Solution.py b/solution/0500-0599/0582.Kill Process/Solution.py index e0e63f3743c53..c080d5d06e6dd 100644 --- a/solution/0500-0599/0582.Kill Process/Solution.py +++ b/solution/0500-0599/0582.Kill Process/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]: - def dfs(i: int): - ans.append(i) - for j in g[i]: - dfs(j) - - g = defaultdict(list) - for i, p in zip(pid, ppid): - g[p].append(i) - ans = [] - dfs(kill) - return ans +class Solution: + def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]: + def dfs(i: int): + ans.append(i) + for j in g[i]: + dfs(j) + + g = defaultdict(list) + for i, p in zip(pid, ppid): + g[p].append(i) + ans = [] + dfs(kill) + return ans diff --git a/solution/0500-0599/0583.Delete Operation for Two Strings/Solution.cpp b/solution/0500-0599/0583.Delete Operation for Two Strings/Solution.cpp index 8e676eb01d247..5ffd550dab721 100644 --- a/solution/0500-0599/0583.Delete Operation for Two Strings/Solution.cpp +++ b/solution/0500-0599/0583.Delete Operation for Two Strings/Solution.cpp @@ -1,18 +1,18 @@ -class Solution { -public: - int minDistance(string word1, string word2) { - int m = word1.size(), n = word2.size(); - vector> dp(m + 1, vector(n + 1)); - for (int i = 1; i <= m; ++i) dp[i][0] = i; - for (int j = 1; j <= n; ++j) dp[0][j] = j; - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (word1[i - 1] == word2[j - 1]) - dp[i][j] = dp[i - 1][j - 1]; - else - dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]); - } - } - return dp[m][n]; - } +class Solution { +public: + int minDistance(string word1, string word2) { + int m = word1.size(), n = word2.size(); + vector> dp(m + 1, vector(n + 1)); + for (int i = 1; i <= m; ++i) dp[i][0] = i; + for (int j = 1; j <= n; ++j) dp[0][j] = j; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (word1[i - 1] == word2[j - 1]) + dp[i][j] = dp[i - 1][j - 1]; + else + dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]); + } + } + return dp[m][n]; + } }; \ No newline at end of file diff --git a/solution/0500-0599/0583.Delete Operation for Two Strings/Solution.java b/solution/0500-0599/0583.Delete Operation for Two Strings/Solution.java index 244cd1c8e08f2..9c6451dcfc900 100644 --- a/solution/0500-0599/0583.Delete Operation for Two Strings/Solution.java +++ b/solution/0500-0599/0583.Delete Operation for Two Strings/Solution.java @@ -1,22 +1,22 @@ -class Solution { - public int minDistance(String word1, String word2) { - int m = word1.length(), n = word2.length(); - int[][] dp = new int[m + 1][n + 1]; - for (int i = 1; i <= m; ++i) { - dp[i][0] = i; - } - for (int j = 1; j <= n; ++j) { - dp[0][j] = j; - } - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (word1.charAt(i - 1) == word2.charAt(j - 1)) { - dp[i][j] = dp[i - 1][j - 1]; - } else { - dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1]); - } - } - } - return dp[m][n]; - } +class Solution { + public int minDistance(String word1, String word2) { + int m = word1.length(), n = word2.length(); + int[][] dp = new int[m + 1][n + 1]; + for (int i = 1; i <= m; ++i) { + dp[i][0] = i; + } + for (int j = 1; j <= n; ++j) { + dp[0][j] = j; + } + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (word1.charAt(i - 1) == word2.charAt(j - 1)) { + dp[i][j] = dp[i - 1][j - 1]; + } else { + dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1]); + } + } + } + return dp[m][n]; + } } \ No newline at end of file diff --git a/solution/0500-0599/0583.Delete Operation for Two Strings/Solution.py b/solution/0500-0599/0583.Delete Operation for Two Strings/Solution.py index 99854b025668a..a66aaf76d4210 100644 --- a/solution/0500-0599/0583.Delete Operation for Two Strings/Solution.py +++ b/solution/0500-0599/0583.Delete Operation for Two Strings/Solution.py @@ -1,15 +1,15 @@ -class Solution: - def minDistance(self, word1: str, word2: str) -> int: - m, n = len(word1), len(word2) - dp = [[0] * (n + 1) for _ in range(m + 1)] - for i in range(1, m + 1): - dp[i][0] = i - for j in range(1, n + 1): - dp[0][j] = j - for i in range(1, m + 1): - for j in range(1, n + 1): - if word1[i - 1] == word2[j - 1]: - dp[i][j] = dp[i - 1][j - 1] - else: - dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]) - return dp[-1][-1] +class Solution: + def minDistance(self, word1: str, word2: str) -> int: + m, n = len(word1), len(word2) + dp = [[0] * (n + 1) for _ in range(m + 1)] + for i in range(1, m + 1): + dp[i][0] = i + for j in range(1, n + 1): + dp[0][j] = j + for i in range(1, m + 1): + for j in range(1, n + 1): + if word1[i - 1] == word2[j - 1]: + dp[i][j] = dp[i - 1][j - 1] + else: + dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]) + return dp[-1][-1] diff --git a/solution/0500-0599/0586.Customer Placing the Largest Number of Orders/Solution.sql b/solution/0500-0599/0586.Customer Placing the Largest Number of Orders/Solution.sql index d23b1d5e04ed3..fa3f0541e2853 100644 --- a/solution/0500-0599/0586.Customer Placing the Largest Number of Orders/Solution.sql +++ b/solution/0500-0599/0586.Customer Placing the Largest Number of Orders/Solution.sql @@ -1,6 +1,7 @@ # Write your MySQL query statement below -SELECT customer_number -FROM Orders -GROUP BY 1 +SELECT + customer_number +FROM orders +GROUP BY customer_number ORDER BY COUNT(1) DESC LIMIT 1; diff --git a/solution/0500-0599/0586.Customer Placing the Largest Number of Orders/Solution2.sql b/solution/0500-0599/0586.Customer Placing the Largest Number of Orders/Solution2.sql new file mode 100644 index 0000000000000..4b0571f7ade72 --- /dev/null +++ b/solution/0500-0599/0586.Customer Placing the Largest Number of Orders/Solution2.sql @@ -0,0 +1,7 @@ +/* Write your T-SQL query statement below */ +SELECT TOP 1 + customer_number +FROM + orders +GROUP BY customer_number +ORDER BY COUNT(customer_number) DESC; diff --git a/solution/0500-0599/0587.Erect the Fence/Solution.cpp b/solution/0500-0599/0587.Erect the Fence/Solution.cpp index fec27cc5ca467..420cd1e69d25d 100644 --- a/solution/0500-0599/0587.Erect the Fence/Solution.cpp +++ b/solution/0500-0599/0587.Erect the Fence/Solution.cpp @@ -1,29 +1,29 @@ -class Solution { -public: - vector> outerTrees(vector>& trees) { - int n = trees.size(); - if (n < 4) return trees; - sort(trees.begin(), trees.end()); - vector vis(n); - vector stk(n + 10); - int cnt = 1; - for (int i = 1; i < n; ++i) { - while (cnt > 1 && cross(trees[stk[cnt - 1]], trees[stk[cnt - 2]], trees[i]) < 0) vis[stk[--cnt]] = false; - vis[i] = true; - stk[cnt++] = i; - } - int m = cnt; - for (int i = n - 1; i >= 0; --i) { - if (vis[i]) continue; - while (cnt > m && cross(trees[stk[cnt - 1]], trees[stk[cnt - 2]], trees[i]) < 0) --cnt; - stk[cnt++] = i; - } - vector> ans; - for (int i = 0; i < cnt - 1; ++i) ans.push_back(trees[stk[i]]); - return ans; - } - - int cross(vector& a, vector& b, vector& c) { - return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]); - } +class Solution { +public: + vector> outerTrees(vector>& trees) { + int n = trees.size(); + if (n < 4) return trees; + sort(trees.begin(), trees.end()); + vector vis(n); + vector stk(n + 10); + int cnt = 1; + for (int i = 1; i < n; ++i) { + while (cnt > 1 && cross(trees[stk[cnt - 1]], trees[stk[cnt - 2]], trees[i]) < 0) vis[stk[--cnt]] = false; + vis[i] = true; + stk[cnt++] = i; + } + int m = cnt; + for (int i = n - 1; i >= 0; --i) { + if (vis[i]) continue; + while (cnt > m && cross(trees[stk[cnt - 1]], trees[stk[cnt - 2]], trees[i]) < 0) --cnt; + stk[cnt++] = i; + } + vector> ans; + for (int i = 0; i < cnt - 1; ++i) ans.push_back(trees[stk[i]]); + return ans; + } + + int cross(vector& a, vector& b, vector& c) { + return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]); + } }; \ No newline at end of file diff --git a/solution/0500-0599/0587.Erect the Fence/Solution.java b/solution/0500-0599/0587.Erect the Fence/Solution.java index 5993ba610ba37..1a17c49e07c2a 100644 --- a/solution/0500-0599/0587.Erect the Fence/Solution.java +++ b/solution/0500-0599/0587.Erect the Fence/Solution.java @@ -1,38 +1,38 @@ -class Solution { - public int[][] outerTrees(int[][] trees) { - int n = trees.length; - if (n < 4) { - return trees; - } - Arrays.sort(trees, (a, b) -> { return a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]; }); - boolean[] vis = new boolean[n]; - int[] stk = new int[n + 10]; - int cnt = 1; - for (int i = 1; i < n; ++i) { - while (cnt > 1 && cross(trees[stk[cnt - 1]], trees[stk[cnt - 2]], trees[i]) < 0) { - vis[stk[--cnt]] = false; - } - vis[i] = true; - stk[cnt++] = i; - } - int m = cnt; - for (int i = n - 1; i >= 0; --i) { - if (vis[i]) { - continue; - } - while (cnt > m && cross(trees[stk[cnt - 1]], trees[stk[cnt - 2]], trees[i]) < 0) { - --cnt; - } - stk[cnt++] = i; - } - int[][] ans = new int[cnt - 1][2]; - for (int i = 0; i < ans.length; ++i) { - ans[i] = trees[stk[i]]; - } - return ans; - } - - private int cross(int[] a, int[] b, int[] c) { - return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]); - } +class Solution { + public int[][] outerTrees(int[][] trees) { + int n = trees.length; + if (n < 4) { + return trees; + } + Arrays.sort(trees, (a, b) -> { return a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]; }); + boolean[] vis = new boolean[n]; + int[] stk = new int[n + 10]; + int cnt = 1; + for (int i = 1; i < n; ++i) { + while (cnt > 1 && cross(trees[stk[cnt - 1]], trees[stk[cnt - 2]], trees[i]) < 0) { + vis[stk[--cnt]] = false; + } + vis[i] = true; + stk[cnt++] = i; + } + int m = cnt; + for (int i = n - 1; i >= 0; --i) { + if (vis[i]) { + continue; + } + while (cnt > m && cross(trees[stk[cnt - 1]], trees[stk[cnt - 2]], trees[i]) < 0) { + --cnt; + } + stk[cnt++] = i; + } + int[][] ans = new int[cnt - 1][2]; + for (int i = 0; i < ans.length; ++i) { + ans[i] = trees[stk[i]]; + } + return ans; + } + + private int cross(int[] a, int[] b, int[] c) { + return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]); + } } \ No newline at end of file diff --git a/solution/0500-0599/0587.Erect the Fence/Solution.py b/solution/0500-0599/0587.Erect the Fence/Solution.py index c8ad2704c9515..dff8cfe0af8aa 100644 --- a/solution/0500-0599/0587.Erect the Fence/Solution.py +++ b/solution/0500-0599/0587.Erect the Fence/Solution.py @@ -1,26 +1,26 @@ -class Solution: - def outerTrees(self, trees: List[List[int]]) -> List[List[int]]: - def cross(i, j, k): - a, b, c = trees[i], trees[j], trees[k] - return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) - - n = len(trees) - if n < 4: - return trees - trees.sort() - vis = [False] * n - stk = [0] - for i in range(1, n): - while len(stk) > 1 and cross(stk[-2], stk[-1], i) < 0: - vis[stk.pop()] = False - vis[i] = True - stk.append(i) - m = len(stk) - for i in range(n - 2, -1, -1): - if vis[i]: - continue - while len(stk) > m and cross(stk[-2], stk[-1], i) < 0: - stk.pop() - stk.append(i) - stk.pop() - return [trees[i] for i in stk] +class Solution: + def outerTrees(self, trees: List[List[int]]) -> List[List[int]]: + def cross(i, j, k): + a, b, c = trees[i], trees[j], trees[k] + return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) + + n = len(trees) + if n < 4: + return trees + trees.sort() + vis = [False] * n + stk = [0] + for i in range(1, n): + while len(stk) > 1 and cross(stk[-2], stk[-1], i) < 0: + vis[stk.pop()] = False + vis[i] = True + stk.append(i) + m = len(stk) + for i in range(n - 2, -1, -1): + if vis[i]: + continue + while len(stk) > m and cross(stk[-2], stk[-1], i) < 0: + stk.pop() + stk.append(i) + stk.pop() + return [trees[i] for i in stk] diff --git a/solution/0500-0599/0589.N-ary Tree Preorder Traversal/Solution.c b/solution/0500-0599/0589.N-ary Tree Preorder Traversal/Solution.c index 08dcedadf2289..7140ad3e2ee29 100644 --- a/solution/0500-0599/0589.N-ary Tree Preorder Traversal/Solution.c +++ b/solution/0500-0599/0589.N-ary Tree Preorder Traversal/Solution.c @@ -26,4 +26,4 @@ int* preorder(struct Node* root, int* returnSize) { *returnSize = 0; dfs(root, ans, returnSize); return ans; -} +} \ No newline at end of file diff --git a/solution/0500-0599/0589.N-ary Tree Preorder Traversal/Solution.ts b/solution/0500-0599/0589.N-ary Tree Preorder Traversal/Solution.ts index 277dd4a6f05f1..45e4c63cdf869 100644 --- a/solution/0500-0599/0589.N-ary Tree Preorder Traversal/Solution.ts +++ b/solution/0500-0599/0589.N-ary Tree Preorder Traversal/Solution.ts @@ -11,16 +11,18 @@ */ function preorder(root: Node | null): number[] { - const ans = []; - const dfs = (root: Node | null) => { - if (root == null) { - return; + const res = []; + if (root == null) { + return res; + } + const stack = [root]; + while (stack.length !== 0) { + const { val, children } = stack.pop(); + res.push(val); + const n = children.length; + for (let i = n - 1; i >= 0; i--) { + stack.push(children[i]); } - ans.push(root.val); - for (const node of root.children) { - dfs(node); - } - }; - dfs(root); - return ans; + } + return res; } diff --git a/solution/0500-0599/0589.N-ary Tree Preorder Traversal/Solution2.ts b/solution/0500-0599/0589.N-ary Tree Preorder Traversal/Solution2.ts new file mode 100644 index 0000000000000..277dd4a6f05f1 --- /dev/null +++ b/solution/0500-0599/0589.N-ary Tree Preorder Traversal/Solution2.ts @@ -0,0 +1,26 @@ +/** + * Definition for node. + * class Node { + * val: number + * children: Node[] + * constructor(val?: number) { + * this.val = (val===undefined ? 0 : val) + * this.children = [] + * } + * } + */ + +function preorder(root: Node | null): number[] { + const ans = []; + const dfs = (root: Node | null) => { + if (root == null) { + return; + } + ans.push(root.val); + for (const node of root.children) { + dfs(node); + } + }; + dfs(root); + return ans; +} diff --git a/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution.cpp b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution.cpp index 503466f53b156..29bfbc7f6557c 100644 --- a/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution.cpp +++ b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution.cpp @@ -22,15 +22,13 @@ class Solution { public: vector postorder(Node* root) { vector ans; - if (!root) return ans; - stack stk{{root}}; - while (!stk.empty()) { - root = stk.top(); - ans.push_back(root->val); - stk.pop(); - for (Node* child : root->children) stk.push(child); - } - reverse(ans.begin(), ans.end()); + dfs(root, ans); return ans; } + + void dfs(Node* root, vector& ans) { + if (!root) return; + for (auto& child : root->children) dfs(child, ans); + ans.push_back(root->val); + } }; \ No newline at end of file diff --git a/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution.go b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution.go index 308a46cd1c701..ff31cb5dde495 100644 --- a/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution.go +++ b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution.go @@ -8,17 +8,16 @@ func postorder(root *Node) []int { var ans []int - if root == nil { - return ans - } - stk := []*Node{root} - for len(stk) > 0 { - root = stk[len(stk)-1] - stk = stk[:len(stk)-1] - ans = append([]int{root.Val}, ans...) + var dfs func(root *Node) + dfs = func(root *Node) { + if root == nil { + return + } for _, child := range root.Children { - stk = append(stk, child) + dfs(child) } + ans = append(ans, root.Val) } + dfs(root) return ans } \ No newline at end of file diff --git a/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution.java b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution.java index aa556ce2ad6a9..0954c3edda17a 100644 --- a/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution.java +++ b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution.java @@ -18,20 +18,22 @@ public Node(int _val, List _children) { */ class Solution { + + private List ans; + public List postorder(Node root) { - LinkedList ans = new LinkedList<>(); + ans = new ArrayList<>(); + dfs(root); + return ans; + } + + private void dfs(Node root) { if (root == null) { - return ans; + return; } - Deque stk = new ArrayDeque<>(); - stk.offer(root); - while (!stk.isEmpty()) { - root = stk.pollLast(); - ans.addFirst(root.val); - for (Node child : root.children) { - stk.offer(child); - } + for (Node child : root.children) { + dfs(child); } - return ans; + ans.add(root.val); } } \ No newline at end of file diff --git a/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution.py b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution.py index 307c627e35928..ddf9c2aab9164 100644 --- a/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution.py +++ b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution.py @@ -9,13 +9,13 @@ def __init__(self, val=None, children=None): class Solution: def postorder(self, root: 'Node') -> List[int]: + def dfs(root): + if root is None: + return + for child in root.children: + dfs(child) + ans.append(root.val) + ans = [] - if root is None: - return ans - stk = [root] - while stk: - node = stk.pop() - ans.append(node.val) - for child in node.children: - stk.append(child) - return ans[::-1] + dfs(root) + return ans diff --git a/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution2.cpp b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution2.cpp new file mode 100644 index 0000000000000..503466f53b156 --- /dev/null +++ b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution2.cpp @@ -0,0 +1,36 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { +public: + vector postorder(Node* root) { + vector ans; + if (!root) return ans; + stack stk{{root}}; + while (!stk.empty()) { + root = stk.top(); + ans.push_back(root->val); + stk.pop(); + for (Node* child : root->children) stk.push(child); + } + reverse(ans.begin(), ans.end()); + return ans; + } +}; \ No newline at end of file diff --git a/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution2.go b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution2.go new file mode 100644 index 0000000000000..308a46cd1c701 --- /dev/null +++ b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution2.go @@ -0,0 +1,24 @@ +/** + * Definition for a Node. + * type Node struct { + * Val int + * Children []*Node + * } + */ + +func postorder(root *Node) []int { + var ans []int + if root == nil { + return ans + } + stk := []*Node{root} + for len(stk) > 0 { + root = stk[len(stk)-1] + stk = stk[:len(stk)-1] + ans = append([]int{root.Val}, ans...) + for _, child := range root.Children { + stk = append(stk, child) + } + } + return ans +} \ No newline at end of file diff --git a/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution2.java b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution2.java new file mode 100644 index 0000000000000..aa556ce2ad6a9 --- /dev/null +++ b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution2.java @@ -0,0 +1,37 @@ +/* +// Definition for a Node. +class Node { + public int val; + public List children; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, List _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { + public List postorder(Node root) { + LinkedList ans = new LinkedList<>(); + if (root == null) { + return ans; + } + Deque stk = new ArrayDeque<>(); + stk.offer(root); + while (!stk.isEmpty()) { + root = stk.pollLast(); + ans.addFirst(root.val); + for (Node child : root.children) { + stk.offer(child); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution2.py b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution2.py new file mode 100644 index 0000000000000..307c627e35928 --- /dev/null +++ b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution2.py @@ -0,0 +1,21 @@ +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" + + +class Solution: + def postorder(self, root: 'Node') -> List[int]: + ans = [] + if root is None: + return ans + stk = [root] + while stk: + node = stk.pop() + ans.append(node.val) + for child in node.children: + stk.append(child) + return ans[::-1] diff --git a/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution2.ts b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution2.ts new file mode 100644 index 0000000000000..ac1c5e862956b --- /dev/null +++ b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution2.ts @@ -0,0 +1,31 @@ +/** + * Definition for node. + * class Node { + * val: number + * children: Node[] + * constructor(val?: number) { + * this.val = (val===undefined ? 0 : val) + * this.children = [] + * } + * } + */ + +function postorder(root: Node | null): number[] { + const res = []; + if (root == null) { + return res; + } + const stack = [root]; + while (stack.length !== 0) { + const target = stack[stack.length - 1]; + if (target.children == null) { + res.push(stack.pop().val); + } else { + for (let i = target.children.length - 1; i >= 0; i--) { + stack.push(target.children[i]); + } + target.children = null; + } + } + return res; +} diff --git a/solution/0500-0599/0594.Longest Harmonious Subsequence/Solution.py b/solution/0500-0599/0594.Longest Harmonious Subsequence/Solution.py index ee61dd832dc05..8cc8a4b7538ef 100644 --- a/solution/0500-0599/0594.Longest Harmonious Subsequence/Solution.py +++ b/solution/0500-0599/0594.Longest Harmonious Subsequence/Solution.py @@ -1,7 +1,7 @@ class Solution: def findLHS(self, nums: List[int]) -> int: - counter = Counter(nums) ans = 0 + counter = Counter(nums) for num in nums: if num + 1 in counter: ans = max(ans, counter[num] + counter[num + 1]) diff --git a/solution/0500-0599/0594.Longest Harmonious Subsequence/Solution2.py b/solution/0500-0599/0594.Longest Harmonious Subsequence/Solution2.py new file mode 100644 index 0000000000000..1c4cf735b54cf --- /dev/null +++ b/solution/0500-0599/0594.Longest Harmonious Subsequence/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def findLHS(self, nums: List[int]) -> int: + counter = Counter(nums) + return max( + [counter[num] + counter[num + 1] for num in nums if num + 1 in counter], + default=0, + ) diff --git a/solution/0500-0599/0595.Big Countries/Solution2.sql b/solution/0500-0599/0595.Big Countries/Solution2.sql new file mode 100644 index 0000000000000..3c227433a6b43 --- /dev/null +++ b/solution/0500-0599/0595.Big Countries/Solution2.sql @@ -0,0 +1,8 @@ +# Write your MySQL query statement below +SELECT name, population, area +FROM World +WHERE area >= 3000000 +UNION +SELECT name, population, area +FROM World +WHERE population >= 25000000; diff --git a/solution/0500-0599/0599.Minimum Index Sum of Two Lists/Solution.java b/solution/0500-0599/0599.Minimum Index Sum of Two Lists/Solution.java index 666bdf2ef7d92..fafafbab7ab6f 100644 --- a/solution/0500-0599/0599.Minimum Index Sum of Two Lists/Solution.java +++ b/solution/0500-0599/0599.Minimum Index Sum of Two Lists/Solution.java @@ -1,4 +1,5 @@ class Solution { + public String[] findRestaurant(String[] list1, String[] list2) { Map mp = new HashMap<>(); for (int i = 0; i < list2.length; ++i) { diff --git a/solution/0500-0599/0599.Minimum Index Sum of Two Lists/Solution2.cpp b/solution/0500-0599/0599.Minimum Index Sum of Two Lists/Solution2.cpp new file mode 100644 index 0000000000000..43a34545c3b22 --- /dev/null +++ b/solution/0500-0599/0599.Minimum Index Sum of Two Lists/Solution2.cpp @@ -0,0 +1,22 @@ +func findRestaurant(list1[] string, list2[] string)[] string { +mp:= make(map[string]int) + for i, v := range list2 { + mp[v] = i + } + mi := 2000 + var ans []string + for i, v := range list1 { + if _ + , ok : = mp[v]; + ok { + t: + = i + mp[v] if t < mi { + ans = [] string { v } mi = t + } + else if t == mi { + ans = append(ans, v) + } + } + } + return ans +} \ No newline at end of file diff --git a/solution/0600-0699/0603.Consecutive Available Seats/Solution.sql b/solution/0600-0699/0603.Consecutive Available Seats/Solution.sql index 56f8c1130022e..9859fc220222d 100644 --- a/solution/0600-0699/0603.Consecutive Available Seats/Solution.sql +++ b/solution/0600-0699/0603.Consecutive Available Seats/Solution.sql @@ -1,15 +1,6 @@ # Write your MySQL query statement below -WITH - T AS ( - SELECT - *, - SUM(free = 1) OVER ( - ORDER BY seat_id - ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING - ) AS cnt - FROM Cinema - ) -SELECT seat_id -FROM T -WHERE free = 1 AND cnt > 1 +SELECT DISTINCT a.seat_id +FROM + Cinema AS a + JOIN Cinema AS b ON ABS(a.seat_id - b.seat_id) = 1 AND a.free AND b.free ORDER BY 1; diff --git a/solution/0600-0699/0603.Consecutive Available Seats/Solution2.sql b/solution/0600-0699/0603.Consecutive Available Seats/Solution2.sql new file mode 100644 index 0000000000000..9a0246ee4bd71 --- /dev/null +++ b/solution/0600-0699/0603.Consecutive Available Seats/Solution2.sql @@ -0,0 +1,12 @@ +# Write your MySQL query statement below +WITH + T AS ( + SELECT + seat_id, + (free + (LAG(free) OVER (ORDER BY seat_id))) AS a, + (free + (LEAD(free) OVER (ORDER BY seat_id))) AS b + FROM Cinema + ) +SELECT seat_id +FROM T +WHERE a = 2 OR b = 2; diff --git a/solution/0600-0699/0603.Consecutive Available Seats/Solution3.sql b/solution/0600-0699/0603.Consecutive Available Seats/Solution3.sql new file mode 100644 index 0000000000000..56f8c1130022e --- /dev/null +++ b/solution/0600-0699/0603.Consecutive Available Seats/Solution3.sql @@ -0,0 +1,15 @@ +# Write your MySQL query statement below +WITH + T AS ( + SELECT + *, + SUM(free = 1) OVER ( + ORDER BY seat_id + ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING + ) AS cnt + FROM Cinema + ) +SELECT seat_id +FROM T +WHERE free = 1 AND cnt > 1 +ORDER BY 1; diff --git a/solution/0600-0699/0605.Can Place Flowers/Solution.cpp b/solution/0600-0699/0605.Can Place Flowers/Solution.cpp index 9b93861cfe7c8..4b17f99e884df 100644 --- a/solution/0600-0699/0605.Can Place Flowers/Solution.cpp +++ b/solution/0600-0699/0605.Can Place Flowers/Solution.cpp @@ -1,4 +1,4 @@ -class Solution { +class Solution { public: bool canPlaceFlowers(vector& flowerbed, int n) { int m = flowerbed.size(); diff --git a/solution/0600-0699/0605.Can Place Flowers/Solution.php b/solution/0600-0699/0605.Can Place Flowers/Solution.php index e68a6862d8ecf..af6eb893fb624 100644 --- a/solution/0600-0699/0605.Can Place Flowers/Solution.php +++ b/solution/0600-0699/0605.Can Place Flowers/Solution.php @@ -17,4 +17,4 @@ function canPlaceFlowers($flowerbed, $n) { } return $n <= 0; } -} \ No newline at end of file +} diff --git a/solution/0600-0699/0611.Valid Triangle Number/Solution.cpp b/solution/0600-0699/0611.Valid Triangle Number/Solution.cpp index f3b34710dcdf3..1fbf4a37f0895 100644 --- a/solution/0600-0699/0611.Valid Triangle Number/Solution.cpp +++ b/solution/0600-0699/0611.Valid Triangle Number/Solution.cpp @@ -1,14 +1,14 @@ -class Solution { -public: - int triangleNumber(vector& nums) { - sort(nums.begin(), nums.end()); - int ans = 0, n = nums.size(); - for (int i = 0; i < n - 2; ++i) { - for (int j = i + 1; j < n - 1; ++j) { - int k = lower_bound(nums.begin() + j + 1, nums.end(), nums[i] + nums[j]) - nums.begin() - 1; - ans += k - j; - } - } - return ans; - } +class Solution { +public: + int triangleNumber(vector& nums) { + sort(nums.begin(), nums.end()); + int ans = 0, n = nums.size(); + for (int i = 0; i < n - 2; ++i) { + for (int j = i + 1; j < n - 1; ++j) { + int k = lower_bound(nums.begin() + j + 1, nums.end(), nums[i] + nums[j]) - nums.begin() - 1; + ans += k - j; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0600-0699/0611.Valid Triangle Number/Solution.java b/solution/0600-0699/0611.Valid Triangle Number/Solution.java index e7970bc1b568b..4f71cb6b66318 100644 --- a/solution/0600-0699/0611.Valid Triangle Number/Solution.java +++ b/solution/0600-0699/0611.Valid Triangle Number/Solution.java @@ -16,4 +16,4 @@ public int triangleNumber(int[] nums) { } return res; } -} +} \ No newline at end of file diff --git a/solution/0600-0699/0611.Valid Triangle Number/Solution.py b/solution/0600-0699/0611.Valid Triangle Number/Solution.py index 2aa308361c075..3e91b1affe2cc 100644 --- a/solution/0600-0699/0611.Valid Triangle Number/Solution.py +++ b/solution/0600-0699/0611.Valid Triangle Number/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def triangleNumber(self, nums: List[int]) -> int: - nums.sort() - ans, n = 0, len(nums) - for i in range(n - 2): - for j in range(i + 1, n - 1): - k = bisect_left(nums, nums[i] + nums[j], lo=j + 1) - 1 - ans += k - j - return ans +class Solution: + def triangleNumber(self, nums: List[int]) -> int: + nums.sort() + ans, n = 0, len(nums) + for i in range(n - 2): + for j in range(i + 1, n - 1): + k = bisect_left(nums, nums[i] + nums[j], lo=j + 1) - 1 + ans += k - j + return ans diff --git a/solution/0600-0699/0611.Valid Triangle Number/Solution2.java b/solution/0600-0699/0611.Valid Triangle Number/Solution2.java new file mode 100644 index 0000000000000..13a17cbea293c --- /dev/null +++ b/solution/0600-0699/0611.Valid Triangle Number/Solution2.java @@ -0,0 +1,21 @@ +class Solution { + public int triangleNumber(int[] nums) { + Arrays.sort(nums); + int ans = 0; + for (int i = 0, n = nums.length; i < n - 2; ++i) { + for (int j = i + 1; j < n - 1; ++j) { + int left = j + 1, right = n; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] >= nums[i] + nums[j]) { + right = mid; + } else { + left = mid + 1; + } + } + ans += left - j - 1; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0613.Shortest Distance in a Line/Solution2.sql b/solution/0600-0699/0613.Shortest Distance in a Line/Solution2.sql new file mode 100644 index 0000000000000..d285465db9c30 --- /dev/null +++ b/solution/0600-0699/0613.Shortest Distance in a Line/Solution2.sql @@ -0,0 +1,5 @@ +# Write your MySQL query statement below +SELECT x - LAG(x) OVER (ORDER BY x) AS shortest +FROM Point +ORDER BY 1 +LIMIT 1, 1; diff --git a/solution/0600-0699/0615.Average Salary Departments VS Company/Solution.sql b/solution/0600-0699/0615.Average Salary Departments VS Company/Solution.sql index 43c33cc8e0e6f..3a011f75222da 100644 --- a/solution/0600-0699/0615.Average Salary Departments VS Company/Solution.sql +++ b/solution/0600-0699/0615.Average Salary Departments VS Company/Solution.sql @@ -1,26 +1,21 @@ # Write your MySQL query statement below WITH - S AS ( - SELECT * - FROM - Salary - JOIN Employee USING (employee_id) - ), - T AS ( + t AS ( SELECT DATE_FORMAT(pay_date, '%Y-%m') AS pay_month, department_id, - AVG(amount) OVER (PARTITION BY pay_date, department_id) AS department_avg, - AVG(amount) OVER (PARTITION BY pay_date) AS company_avg - FROM S + AVG(amount) OVER (PARTITION BY pay_date) AS company_avg_amount, + AVG(amount) OVER (PARTITION BY pay_date, department_id) AS department_avg_amount + FROM + Salary AS s + JOIN Employee AS e ON s.employee_id = e.employee_id ) -SELECT +SELECT DISTINCT pay_month, department_id, CASE - WHEN AVG(department_avg) > AVG(company_avg) THEN 'higher' - WHEN AVG(department_avg) < AVG(company_avg) THEN 'lower' - ELSE 'same' + WHEN company_avg_amount = department_avg_amount THEN 'same' + WHEN company_avg_amount < department_avg_amount THEN 'higher' + ELSE 'lower' END AS comparison -FROM T -GROUP BY 1, 2; +FROM t; diff --git a/solution/0600-0699/0615.Average Salary Departments VS Company/Solution2.sql b/solution/0600-0699/0615.Average Salary Departments VS Company/Solution2.sql new file mode 100644 index 0000000000000..43c33cc8e0e6f --- /dev/null +++ b/solution/0600-0699/0615.Average Salary Departments VS Company/Solution2.sql @@ -0,0 +1,26 @@ +# Write your MySQL query statement below +WITH + S AS ( + SELECT * + FROM + Salary + JOIN Employee USING (employee_id) + ), + T AS ( + SELECT + DATE_FORMAT(pay_date, '%Y-%m') AS pay_month, + department_id, + AVG(amount) OVER (PARTITION BY pay_date, department_id) AS department_avg, + AVG(amount) OVER (PARTITION BY pay_date) AS company_avg + FROM S + ) +SELECT + pay_month, + department_id, + CASE + WHEN AVG(department_avg) > AVG(company_avg) THEN 'higher' + WHEN AVG(department_avg) < AVG(company_avg) THEN 'lower' + ELSE 'same' + END AS comparison +FROM T +GROUP BY 1, 2; diff --git a/solution/0600-0699/0619.Biggest Single Number/Solution2.sql b/solution/0600-0699/0619.Biggest Single Number/Solution2.sql new file mode 100644 index 0000000000000..1ae9adc9b5eb9 --- /dev/null +++ b/solution/0600-0699/0619.Biggest Single Number/Solution2.sql @@ -0,0 +1,10 @@ +# Write your MySQL query statement below +SELECT + CASE + WHEN COUNT(1) = 1 THEN num + ELSE NULL + END AS num +FROM MyNumbers +GROUP BY num +ORDER BY 1 DESC +LIMIT 1; diff --git a/solution/0600-0699/0621.Task Scheduler/Solution.cs b/solution/0600-0699/0621.Task Scheduler/Solution.cs index efeae187abc15..9f441118cd726 100644 --- a/solution/0600-0699/0621.Task Scheduler/Solution.cs +++ b/solution/0600-0699/0621.Task Scheduler/Solution.cs @@ -12,4 +12,4 @@ public int LeastInterval(char[] tasks, int n) { } return Math.Max(tasks.Length, (x - 1) * (n + 1) + s); } -} \ No newline at end of file +} diff --git a/solution/0600-0699/0623.Add One Row to Tree/Solution.ts b/solution/0600-0699/0623.Add One Row to Tree/Solution.ts index 244b816d24435..32d5d91cf3cb9 100644 --- a/solution/0600-0699/0623.Add One Row to Tree/Solution.ts +++ b/solution/0600-0699/0623.Add One Row to Tree/Solution.ts @@ -13,22 +13,21 @@ */ function addOneRow(root: TreeNode | null, val: number, depth: number): TreeNode | null { - if (depth === 1) { - return new TreeNode(val, root); - } - - const queue = [root]; - for (let i = 1; i < depth - 1; i++) { - const n = queue.length; - for (let j = 0; j < n; j++) { - const { left, right } = queue.shift(); - left && queue.push(left); - right && queue.push(right); + function dfs(root, d) { + if (!root) { + return; } + if (d == depth - 1) { + root.left = new TreeNode(val, root.left, null); + root.right = new TreeNode(val, null, root.right); + return; + } + dfs(root.left, d + 1); + dfs(root.right, d + 1); } - for (const node of queue) { - node.left = new TreeNode(val, node.left); - node.right = new TreeNode(val, null, node.right); + if (depth == 1) { + return new TreeNode(val, root); } + dfs(root, 1); return root; } diff --git a/solution/0600-0699/0623.Add One Row to Tree/Solution2.cpp b/solution/0600-0699/0623.Add One Row to Tree/Solution2.cpp new file mode 100644 index 0000000000000..d9edd241be02a --- /dev/null +++ b/solution/0600-0699/0623.Add One Row to Tree/Solution2.cpp @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* addOneRow(TreeNode* root, int val, int depth) { + if (depth == 1) return new TreeNode(val, root, nullptr); + queue q{{root}}; + int i = 0; + while (!q.empty()) { + ++i; + for (int k = q.size(); k; --k) { + TreeNode* node = q.front(); + q.pop(); + if (node->left) q.push(node->left); + if (node->right) q.push(node->right); + if (i == depth - 1) { + node->left = new TreeNode(val, node->left, nullptr); + node->right = new TreeNode(val, nullptr, node->right); + } + } + } + return root; + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0623.Add One Row to Tree/Solution2.go b/solution/0600-0699/0623.Add One Row to Tree/Solution2.go new file mode 100644 index 0000000000000..ff039cea0642d --- /dev/null +++ b/solution/0600-0699/0623.Add One Row to Tree/Solution2.go @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func addOneRow(root *TreeNode, val int, depth int) *TreeNode { + if depth == 1 { + return &TreeNode{val, root, nil} + } + q := []*TreeNode{root} + i := 0 + for len(q) > 0 { + i++ + for k := len(q); k > 0; k-- { + node := q[0] + q = q[1:] + if node.Left != nil { + q = append(q, node.Left) + } + if node.Right != nil { + q = append(q, node.Right) + } + if i == depth-1 { + node.Left = &TreeNode{val, node.Left, nil} + node.Right = &TreeNode{val, nil, node.Right} + } + } + } + return root +} \ No newline at end of file diff --git a/solution/0600-0699/0623.Add One Row to Tree/Solution2.java b/solution/0600-0699/0623.Add One Row to Tree/Solution2.java new file mode 100644 index 0000000000000..2010e49116af9 --- /dev/null +++ b/solution/0600-0699/0623.Add One Row to Tree/Solution2.java @@ -0,0 +1,42 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode addOneRow(TreeNode root, int val, int depth) { + if (depth == 1) { + return new TreeNode(val, root, null); + } + Deque q = new ArrayDeque<>(); + q.offer(root); + int i = 0; + while (!q.isEmpty()) { + ++i; + for (int k = q.size(); k > 0; --k) { + TreeNode node = q.pollFirst(); + if (node.left != null) { + q.offer(node.left); + } + if (node.right != null) { + q.offer(node.right); + } + if (i == depth - 1) { + node.left = new TreeNode(val, node.left, null); + node.right = new TreeNode(val, null, node.right); + } + } + } + return root; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0623.Add One Row to Tree/Solution2.py b/solution/0600-0699/0623.Add One Row to Tree/Solution2.py new file mode 100644 index 0000000000000..c1fd23f935e24 --- /dev/null +++ b/solution/0600-0699/0623.Add One Row to Tree/Solution2.py @@ -0,0 +1,26 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def addOneRow( + self, root: Optional[TreeNode], val: int, depth: int + ) -> Optional[TreeNode]: + if depth == 1: + return TreeNode(val, root) + q = deque([root]) + i = 0 + while q: + i += 1 + for _ in range(len(q)): + node = q.popleft() + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + if i == depth - 1: + node.left = TreeNode(val, node.left, None) + node.right = TreeNode(val, None, node.right) + return root diff --git a/solution/0600-0699/0623.Add One Row to Tree/Solution2.ts b/solution/0600-0699/0623.Add One Row to Tree/Solution2.ts new file mode 100644 index 0000000000000..244b816d24435 --- /dev/null +++ b/solution/0600-0699/0623.Add One Row to Tree/Solution2.ts @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function addOneRow(root: TreeNode | null, val: number, depth: number): TreeNode | null { + if (depth === 1) { + return new TreeNode(val, root); + } + + const queue = [root]; + for (let i = 1; i < depth - 1; i++) { + const n = queue.length; + for (let j = 0; j < n; j++) { + const { left, right } = queue.shift(); + left && queue.push(left); + right && queue.push(right); + } + } + for (const node of queue) { + node.left = new TreeNode(val, node.left); + node.right = new TreeNode(val, null, node.right); + } + return root; +} diff --git a/solution/0600-0699/0626.Exchange Seats/Solution2.sql b/solution/0600-0699/0626.Exchange Seats/Solution2.sql new file mode 100644 index 0000000000000..43164a011c5b3 --- /dev/null +++ b/solution/0600-0699/0626.Exchange Seats/Solution2.sql @@ -0,0 +1,13 @@ +# Write your MySQL query statement below +SELECT + id + ( + CASE + WHEN id % 2 = 1 + AND id != (SELECT MAX(id) FROM Seat) THEN 1 + WHEN id % 2 = 0 THEN -1 + ELSE 0 + END + ) AS id, + student +FROM Seat +ORDER BY 1; diff --git a/solution/0600-0699/0626.Exchange Seats/Solution3.sql b/solution/0600-0699/0626.Exchange Seats/Solution3.sql new file mode 100644 index 0000000000000..11c3d928deaff --- /dev/null +++ b/solution/0600-0699/0626.Exchange Seats/Solution3.sql @@ -0,0 +1,5 @@ +# Write your MySQL query statement below +SELECT + RANK() OVER (ORDER BY (id - 1) ^ 1) AS id, + student +FROM Seat; diff --git a/solution/0600-0699/0626.Exchange Seats/Solution4.sql b/solution/0600-0699/0626.Exchange Seats/Solution4.sql new file mode 100644 index 0000000000000..bbc20d95bae94 --- /dev/null +++ b/solution/0600-0699/0626.Exchange Seats/Solution4.sql @@ -0,0 +1,10 @@ +# Write your MySQL query statement below +SELECT + CASE + WHEN id & 1 = 0 THEN id - 1 + WHEN ROW_NUMBER() OVER (ORDER BY id) != COUNT(id) OVER () THEN id + 1 + ELSE id + END AS id, + student +FROM Seat +ORDER BY 1; diff --git a/solution/0600-0699/0627.Swap Salary/Solution.sql b/solution/0600-0699/0627.Swap Salary/Solution.sql index 91ff515211582..0a39fa7db93f8 100644 --- a/solution/0600-0699/0627.Swap Salary/Solution.sql +++ b/solution/0600-0699/0627.Swap Salary/Solution.sql @@ -1,3 +1,5 @@ -# Write your MySQL query statement below -UPDATE Salary -SET sex = IF(sex = 'f', 'm', 'f'); +UPDATE salary +SET sex = CASE sex + WHEN 'm' THEN 'f' + ELSE 'm' +END; diff --git a/solution/0600-0699/0627.Swap Salary/Solution2.sql b/solution/0600-0699/0627.Swap Salary/Solution2.sql new file mode 100644 index 0000000000000..91ff515211582 --- /dev/null +++ b/solution/0600-0699/0627.Swap Salary/Solution2.sql @@ -0,0 +1,3 @@ +# Write your MySQL query statement below +UPDATE Salary +SET sex = IF(sex = 'f', 'm', 'f'); diff --git a/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.cpp b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.cpp index bb40f11e9a12d..219f994da748f 100644 --- a/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.cpp +++ b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.cpp @@ -1,27 +1,10 @@ class Solution { public: int maximumProduct(vector& nums) { - const int inf = 1 << 30; - int mi1 = inf, mi2 = inf; - int mx1 = -inf, mx2 = -inf, mx3 = -inf; - for (int x : nums) { - if (x < mi1) { - mi2 = mi1; - mi1 = x; - } else if (x < mi2) { - mi2 = x; - } - if (x > mx1) { - mx3 = mx2; - mx2 = mx1; - mx1 = x; - } else if (x > mx2) { - mx3 = mx2; - mx2 = x; - } else if (x > mx3) { - mx3 = x; - } - } - return max(mi1 * mi2 * mx1, mx1 * mx2 * mx3); + sort(nums.begin(), nums.end()); + int n = nums.size(); + int a = nums[n - 1] * nums[n - 2] * nums[n - 3]; + int b = nums[n - 1] * nums[0] * nums[1]; + return max(a, b); } }; \ No newline at end of file diff --git a/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.go b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.go index 562cdc79af876..ae9103b4cf843 100644 --- a/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.go +++ b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.go @@ -1,20 +1,10 @@ func maximumProduct(nums []int) int { - const inf = 1 << 30 - mi1, mi2 := inf, inf - mx1, mx2, mx3 := -inf, -inf, -inf - for _, x := range nums { - if x < mi1 { - mi1, mi2 = x, mi1 - } else if x < mi2 { - mi2 = x - } - if x > mx1 { - mx1, mx2, mx3 = x, mx1, mx2 - } else if x > mx2 { - mx2, mx3 = x, mx2 - } else if x > mx3 { - mx3 = x - } + sort.Ints(nums) + n := len(nums) + a := nums[n-1] * nums[n-2] * nums[n-3] + b := nums[n-1] * nums[0] * nums[1] + if a > b { + return a } - return max(mi1*mi2*mx1, mx1*mx2*mx3) + return b } \ No newline at end of file diff --git a/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.java b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.java index cca664aea76a3..67b78f5ce0de1 100644 --- a/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.java +++ b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.java @@ -1,26 +1,9 @@ class Solution { public int maximumProduct(int[] nums) { - final int inf = 1 << 30; - int mi1 = inf, mi2 = inf; - int mx1 = -inf, mx2 = -inf, mx3 = -inf; - for (int x : nums) { - if (x < mi1) { - mi2 = mi1; - mi1 = x; - } else if (x < mi2) { - mi2 = x; - } - if (x > mx1) { - mx3 = mx2; - mx2 = mx1; - mx1 = x; - } else if (x > mx2) { - mx3 = mx2; - mx2 = x; - } else if (x > mx3) { - mx3 = x; - } - } - return Math.max(mi1 * mi2 * mx1, mx1 * mx2 * mx3); + Arrays.sort(nums); + int n = nums.length; + int a = nums[n - 1] * nums[n - 2] * nums[n - 3]; + int b = nums[n - 1] * nums[0] * nums[1]; + return Math.max(a, b); } } \ No newline at end of file diff --git a/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.py b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.py index 803e24798a868..3c53828b2346a 100644 --- a/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.py +++ b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.py @@ -1,5 +1,6 @@ class Solution: def maximumProduct(self, nums: List[int]) -> int: - top3 = nlargest(3, nums) - bottom2 = nlargest(2, nums, key=lambda x: -x) - return max(top3[0] * top3[1] * top3[2], top3[0] * bottom2[0] * bottom2[1]) + nums.sort() + a = nums[-1] * nums[-2] * nums[-3] + b = nums[-1] * nums[0] * nums[1] + return max(a, b) diff --git a/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.ts b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.ts index d3d287c66dbd4..e6b3bb9a03109 100644 --- a/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.ts +++ b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.ts @@ -1,27 +1,7 @@ function maximumProduct(nums: number[]): number { - const inf = 1 << 30; - let mi1 = inf, - mi2 = inf; - let mx1 = -inf, - mx2 = -inf, - mx3 = -inf; - for (const x of nums) { - if (x < mi1) { - mi2 = mi1; - mi1 = x; - } else if (x < mi2) { - mi2 = x; - } - if (x > mx1) { - mx3 = mx2; - mx2 = mx1; - mx1 = x; - } else if (x > mx2) { - mx3 = mx2; - mx2 = x; - } else if (x > mx3) { - mx3 = x; - } - } - return Math.max(mi1 * mi2 * mx1, mx1 * mx2 * mx3); + nums.sort((a, b) => a - b); + const n = nums.length; + const a = nums[n - 1] * nums[n - 2] * nums[n - 3]; + const b = nums[n - 1] * nums[0] * nums[1]; + return Math.max(a, b); } diff --git a/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution2.cpp b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution2.cpp new file mode 100644 index 0000000000000..bb40f11e9a12d --- /dev/null +++ b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution2.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int maximumProduct(vector& nums) { + const int inf = 1 << 30; + int mi1 = inf, mi2 = inf; + int mx1 = -inf, mx2 = -inf, mx3 = -inf; + for (int x : nums) { + if (x < mi1) { + mi2 = mi1; + mi1 = x; + } else if (x < mi2) { + mi2 = x; + } + if (x > mx1) { + mx3 = mx2; + mx2 = mx1; + mx1 = x; + } else if (x > mx2) { + mx3 = mx2; + mx2 = x; + } else if (x > mx3) { + mx3 = x; + } + } + return max(mi1 * mi2 * mx1, mx1 * mx2 * mx3); + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution2.go b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution2.go new file mode 100644 index 0000000000000..562cdc79af876 --- /dev/null +++ b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution2.go @@ -0,0 +1,20 @@ +func maximumProduct(nums []int) int { + const inf = 1 << 30 + mi1, mi2 := inf, inf + mx1, mx2, mx3 := -inf, -inf, -inf + for _, x := range nums { + if x < mi1 { + mi1, mi2 = x, mi1 + } else if x < mi2 { + mi2 = x + } + if x > mx1 { + mx1, mx2, mx3 = x, mx1, mx2 + } else if x > mx2 { + mx2, mx3 = x, mx2 + } else if x > mx3 { + mx3 = x + } + } + return max(mi1*mi2*mx1, mx1*mx2*mx3) +} \ No newline at end of file diff --git a/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution2.java b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution2.java new file mode 100644 index 0000000000000..cca664aea76a3 --- /dev/null +++ b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution2.java @@ -0,0 +1,26 @@ +class Solution { + public int maximumProduct(int[] nums) { + final int inf = 1 << 30; + int mi1 = inf, mi2 = inf; + int mx1 = -inf, mx2 = -inf, mx3 = -inf; + for (int x : nums) { + if (x < mi1) { + mi2 = mi1; + mi1 = x; + } else if (x < mi2) { + mi2 = x; + } + if (x > mx1) { + mx3 = mx2; + mx2 = mx1; + mx1 = x; + } else if (x > mx2) { + mx3 = mx2; + mx2 = x; + } else if (x > mx3) { + mx3 = x; + } + } + return Math.max(mi1 * mi2 * mx1, mx1 * mx2 * mx3); + } +} \ No newline at end of file diff --git a/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution2.py b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution2.py new file mode 100644 index 0000000000000..803e24798a868 --- /dev/null +++ b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution2.py @@ -0,0 +1,5 @@ +class Solution: + def maximumProduct(self, nums: List[int]) -> int: + top3 = nlargest(3, nums) + bottom2 = nlargest(2, nums, key=lambda x: -x) + return max(top3[0] * top3[1] * top3[2], top3[0] * bottom2[0] * bottom2[1]) diff --git a/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution2.ts b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution2.ts new file mode 100644 index 0000000000000..d3d287c66dbd4 --- /dev/null +++ b/solution/0600-0699/0628.Maximum Product of Three Numbers/Solution2.ts @@ -0,0 +1,27 @@ +function maximumProduct(nums: number[]): number { + const inf = 1 << 30; + let mi1 = inf, + mi2 = inf; + let mx1 = -inf, + mx2 = -inf, + mx3 = -inf; + for (const x of nums) { + if (x < mi1) { + mi2 = mi1; + mi1 = x; + } else if (x < mi2) { + mi2 = x; + } + if (x > mx1) { + mx3 = mx2; + mx2 = mx1; + mx1 = x; + } else if (x > mx2) { + mx3 = mx2; + mx2 = x; + } else if (x > mx3) { + mx3 = x; + } + } + return Math.max(mi1 * mi2 * mx1, mx1 * mx2 * mx3); +} diff --git a/solution/0600-0699/0630.Course Schedule III/Solution.cpp b/solution/0600-0699/0630.Course Schedule III/Solution.cpp index f680ec8290fc7..6415c1b67cdaf 100644 --- a/solution/0600-0699/0630.Course Schedule III/Solution.cpp +++ b/solution/0600-0699/0630.Course Schedule III/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - int scheduleCourse(vector>& courses) { - sort(courses.begin(), courses.end(), [](const vector& a, const vector& b) { - return a[1] < b[1]; - }); - priority_queue pq; - int s = 0; - for (auto& e : courses) { - int duration = e[0], last = e[1]; - pq.push(duration); - s += duration; - while (s > last) { - s -= pq.top(); - pq.pop(); - } - } - return pq.size(); - } +class Solution { +public: + int scheduleCourse(vector>& courses) { + sort(courses.begin(), courses.end(), [](const vector& a, const vector& b) { + return a[1] < b[1]; + }); + priority_queue pq; + int s = 0; + for (auto& e : courses) { + int duration = e[0], last = e[1]; + pq.push(duration); + s += duration; + while (s > last) { + s -= pq.top(); + pq.pop(); + } + } + return pq.size(); + } }; \ No newline at end of file diff --git a/solution/0600-0699/0630.Course Schedule III/Solution.java b/solution/0600-0699/0630.Course Schedule III/Solution.java index f9d78b09ea04b..f893a7665d23f 100644 --- a/solution/0600-0699/0630.Course Schedule III/Solution.java +++ b/solution/0600-0699/0630.Course Schedule III/Solution.java @@ -1,16 +1,16 @@ -class Solution { - public int scheduleCourse(int[][] courses) { - Arrays.sort(courses, (a, b) -> a[1] - b[1]); - PriorityQueue pq = new PriorityQueue<>((a, b) -> b - a); - int s = 0; - for (var e : courses) { - int duration = e[0], last = e[1]; - pq.offer(duration); - s += duration; - while (s > last) { - s -= pq.poll(); - } - } - return pq.size(); - } +class Solution { + public int scheduleCourse(int[][] courses) { + Arrays.sort(courses, (a, b) -> a[1] - b[1]); + PriorityQueue pq = new PriorityQueue<>((a, b) -> b - a); + int s = 0; + for (var e : courses) { + int duration = e[0], last = e[1]; + pq.offer(duration); + s += duration; + while (s > last) { + s -= pq.poll(); + } + } + return pq.size(); + } } \ No newline at end of file diff --git a/solution/0600-0699/0630.Course Schedule III/Solution.py b/solution/0600-0699/0630.Course Schedule III/Solution.py index 87c1025f562a5..698d8c4cd647a 100644 --- a/solution/0600-0699/0630.Course Schedule III/Solution.py +++ b/solution/0600-0699/0630.Course Schedule III/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def scheduleCourse(self, courses: List[List[int]]) -> int: - courses.sort(key=lambda x: x[1]) - pq = [] - s = 0 - for duration, last in courses: - heappush(pq, -duration) - s += duration - while s > last: - s += heappop(pq) - return len(pq) +class Solution: + def scheduleCourse(self, courses: List[List[int]]) -> int: + courses.sort(key=lambda x: x[1]) + pq = [] + s = 0 + for duration, last in courses: + heappush(pq, -duration) + s += duration + while s > last: + s += heappop(pq) + return len(pq) diff --git a/solution/0600-0699/0632.Smallest Range Covering Elements from K Lists/Solution.py b/solution/0600-0699/0632.Smallest Range Covering Elements from K Lists/Solution.py index 85cb9724454c1..74e394658907c 100644 --- a/solution/0600-0699/0632.Smallest Range Covering Elements from K Lists/Solution.py +++ b/solution/0600-0699/0632.Smallest Range Covering Elements from K Lists/Solution.py @@ -5,7 +5,7 @@ def smallestRange(self, nums: List[List[int]]) -> List[int]: cnt = Counter() ans = [-inf, inf] j = 0 - for b, v in t: + for i, (b, v) in enumerate(t): cnt[v] += 1 while len(cnt) == len(nums): a = t[j][0] diff --git a/solution/0600-0699/0633.Sum of Square Numbers/Solution.cpp b/solution/0600-0699/0633.Sum of Square Numbers/Solution.cpp index f34606fef1cbc..c703d372a5b40 100644 --- a/solution/0600-0699/0633.Sum of Square Numbers/Solution.cpp +++ b/solution/0600-0699/0633.Sum of Square Numbers/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - bool judgeSquareSum(int c) { - long a = 0, b = (long) sqrt(c); - while (a <= b) { - long s = a * a + b * b; - if (s == c) return true; - if (s < c) - ++a; - else - --b; - } - return false; - } +class Solution { +public: + bool judgeSquareSum(int c) { + long a = 0, b = (long) sqrt(c); + while (a <= b) { + long s = a * a + b * b; + if (s == c) return true; + if (s < c) + ++a; + else + --b; + } + return false; + } }; \ No newline at end of file diff --git a/solution/0600-0699/0633.Sum of Square Numbers/Solution.java b/solution/0600-0699/0633.Sum of Square Numbers/Solution.java index f51c1cb43c85c..86125a9fefc29 100644 --- a/solution/0600-0699/0633.Sum of Square Numbers/Solution.java +++ b/solution/0600-0699/0633.Sum of Square Numbers/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public boolean judgeSquareSum(int c) { - long a = 0, b = (long) Math.sqrt(c); - while (a <= b) { - long s = a * a + b * b; - if (s == c) { - return true; - } - if (s < c) { - ++a; - } else { - --b; - } - } - return false; - } +class Solution { + public boolean judgeSquareSum(int c) { + long a = 0, b = (long) Math.sqrt(c); + while (a <= b) { + long s = a * a + b * b; + if (s == c) { + return true; + } + if (s < c) { + ++a; + } else { + --b; + } + } + return false; + } } \ No newline at end of file diff --git a/solution/0600-0699/0633.Sum of Square Numbers/Solution.py b/solution/0600-0699/0633.Sum of Square Numbers/Solution.py index 9d07275892014..04ac3800769f5 100644 --- a/solution/0600-0699/0633.Sum of Square Numbers/Solution.py +++ b/solution/0600-0699/0633.Sum of Square Numbers/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def judgeSquareSum(self, c: int) -> bool: - a, b = 0, int(sqrt(c)) - while a <= b: - s = a**2 + b**2 - if s == c: - return True - if s < c: - a += 1 - else: - b -= 1 - return False +class Solution: + def judgeSquareSum(self, c: int) -> bool: + a, b = 0, int(sqrt(c)) + while a <= b: + s = a**2 + b**2 + if s == c: + return True + if s < c: + a += 1 + else: + b -= 1 + return False diff --git a/solution/0600-0699/0634.Find the Derangement of An Array/Solution.cpp b/solution/0600-0699/0634.Find the Derangement of An Array/Solution.cpp index 3900f5c08baf8..3f28ace8b2a15 100644 --- a/solution/0600-0699/0634.Find the Derangement of An Array/Solution.cpp +++ b/solution/0600-0699/0634.Find the Derangement of An Array/Solution.cpp @@ -1,13 +1,13 @@ class Solution { public: int findDerangement(int n) { - long long a = 1, b = 0; + long long f[n + 1]; + memset(f, 0, sizeof(f)); + f[0] = 1; const int mod = 1e9 + 7; - for (int i = 2; i <= n; ++i) { - long long c = (i - 1) * (a + b) % mod; - a = b; - b = c; + for (int i = 2; i <= n; i++) { + f[i] = (i - 1LL) * (f[i - 1] + f[i - 2]) % mod; } - return b; + return f[n]; } }; \ No newline at end of file diff --git a/solution/0600-0699/0634.Find the Derangement of An Array/Solution.go b/solution/0600-0699/0634.Find the Derangement of An Array/Solution.go index d5f9b2cda7202..92fc80bae6d34 100644 --- a/solution/0600-0699/0634.Find the Derangement of An Array/Solution.go +++ b/solution/0600-0699/0634.Find the Derangement of An Array/Solution.go @@ -1,8 +1,9 @@ func findDerangement(n int) int { - a, b := 1, 0 + f := make([]int, n+1) + f[0] = 1 const mod = 1e9 + 7 for i := 2; i <= n; i++ { - a, b = b, (i-1)*(a+b)%mod + f[i] = (i - 1) * (f[i-1] + f[i-2]) % mod } - return b + return f[n] } \ No newline at end of file diff --git a/solution/0600-0699/0634.Find the Derangement of An Array/Solution.java b/solution/0600-0699/0634.Find the Derangement of An Array/Solution.java index 5cf28d89916b5..593c1d2f160d2 100644 --- a/solution/0600-0699/0634.Find the Derangement of An Array/Solution.java +++ b/solution/0600-0699/0634.Find the Derangement of An Array/Solution.java @@ -1,12 +1,11 @@ class Solution { public int findDerangement(int n) { + long[] f = new long[n + 1]; + f[0] = 1; final int mod = (int) 1e9 + 7; - long a = 1, b = 0; for (int i = 2; i <= n; ++i) { - long c = (i - 1) * (a + b) % mod; - a = b; - b = c; + f[i] = (i - 1) * (f[i - 1] + f[i - 2]) % mod; } - return (int) b; + return (int) f[n]; } } \ No newline at end of file diff --git a/solution/0600-0699/0634.Find the Derangement of An Array/Solution.py b/solution/0600-0699/0634.Find the Derangement of An Array/Solution.py index c69b5edd617ef..6f8b7805cb1b9 100644 --- a/solution/0600-0699/0634.Find the Derangement of An Array/Solution.py +++ b/solution/0600-0699/0634.Find the Derangement of An Array/Solution.py @@ -1,7 +1,7 @@ class Solution: def findDerangement(self, n: int) -> int: mod = 10**9 + 7 - a, b = 1, 0 + f = [1] + [0] * n for i in range(2, n + 1): - a, b = b, ((i - 1) * (a + b)) % mod - return b + f[i] = (i - 1) * (f[i - 1] + f[i - 2]) % mod + return f[n] diff --git a/solution/0600-0699/0634.Find the Derangement of An Array/Solution2.cpp b/solution/0600-0699/0634.Find the Derangement of An Array/Solution2.cpp new file mode 100644 index 0000000000000..3900f5c08baf8 --- /dev/null +++ b/solution/0600-0699/0634.Find the Derangement of An Array/Solution2.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int findDerangement(int n) { + long long a = 1, b = 0; + const int mod = 1e9 + 7; + for (int i = 2; i <= n; ++i) { + long long c = (i - 1) * (a + b) % mod; + a = b; + b = c; + } + return b; + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0634.Find the Derangement of An Array/Solution2.go b/solution/0600-0699/0634.Find the Derangement of An Array/Solution2.go new file mode 100644 index 0000000000000..d5f9b2cda7202 --- /dev/null +++ b/solution/0600-0699/0634.Find the Derangement of An Array/Solution2.go @@ -0,0 +1,8 @@ +func findDerangement(n int) int { + a, b := 1, 0 + const mod = 1e9 + 7 + for i := 2; i <= n; i++ { + a, b = b, (i-1)*(a+b)%mod + } + return b +} \ No newline at end of file diff --git a/solution/0600-0699/0634.Find the Derangement of An Array/Solution2.java b/solution/0600-0699/0634.Find the Derangement of An Array/Solution2.java new file mode 100644 index 0000000000000..5cf28d89916b5 --- /dev/null +++ b/solution/0600-0699/0634.Find the Derangement of An Array/Solution2.java @@ -0,0 +1,12 @@ +class Solution { + public int findDerangement(int n) { + final int mod = (int) 1e9 + 7; + long a = 1, b = 0; + for (int i = 2; i <= n; ++i) { + long c = (i - 1) * (a + b) % mod; + a = b; + b = c; + } + return (int) b; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0634.Find the Derangement of An Array/Solution2.py b/solution/0600-0699/0634.Find the Derangement of An Array/Solution2.py new file mode 100644 index 0000000000000..c69b5edd617ef --- /dev/null +++ b/solution/0600-0699/0634.Find the Derangement of An Array/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def findDerangement(self, n: int) -> int: + mod = 10**9 + 7 + a, b = 1, 0 + for i in range(2, n + 1): + a, b = b, ((i - 1) * (a + b)) % mod + return b diff --git a/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.cpp b/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.cpp new file mode 100644 index 0000000000000..e2162f7578f14 --- /dev/null +++ b/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.cpp @@ -0,0 +1,41 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ + +using ll = long long; + +class Solution { +public: + vector s; + vector cnt; + + vector averageOfLevels(TreeNode* root) { + dfs(root, 0); + vector ans(s.size()); + for (int i = 0; i < s.size(); ++i) { + ans[i] = (s[i] * 1.0 / cnt[i]); + } + return ans; + } + + void dfs(TreeNode* root, int i) { + if (!root) return; + if (s.size() == i) { + s.push_back(root->val); + cnt.push_back(1); + } else { + s[i] += root->val; + cnt[i]++; + } + dfs(root->left, i + 1); + dfs(root->right, i + 1); + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.go b/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.go new file mode 100644 index 0000000000000..122aca06df0a4 --- /dev/null +++ b/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.go @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func averageOfLevels(root *TreeNode) []float64 { + s := []int{} + cnt := []int{} + var dfs func(root *TreeNode, i int) + dfs = func(root *TreeNode, i int) { + if root == nil { + return + } + if len(s) == i { + s = append(s, root.Val) + cnt = append(cnt, 1) + } else { + s[i] += root.Val + cnt[i]++ + } + dfs(root.Left, i+1) + dfs(root.Right, i+1) + } + dfs(root, 0) + ans := []float64{} + for i, t := range s { + ans = append(ans, float64(t)/float64(cnt[i])) + } + return ans +} \ No newline at end of file diff --git a/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.java b/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.java new file mode 100644 index 0000000000000..93828af39236f --- /dev/null +++ b/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.java @@ -0,0 +1,43 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private List s = new ArrayList<>(); + private List cnt = new ArrayList<>(); + + public List averageOfLevels(TreeNode root) { + dfs(root, 0); + List ans = new ArrayList<>(); + for (int i = 0; i < s.size(); ++i) { + ans.add(s.get(i) * 1.0 / cnt.get(i)); + } + return ans; + } + + private void dfs(TreeNode root, int i) { + if (root == null) { + return; + } + if (s.size() == i) { + s.add((long) root.val); + cnt.add(1); + } else { + s.set(i, s.get(i) + root.val); + cnt.set(i, cnt.get(i) + 1); + } + dfs(root.left, i + 1); + dfs(root.right, i + 1); + } +} \ No newline at end of file diff --git a/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.js b/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.js new file mode 100644 index 0000000000000..e9fdddf35751c --- /dev/null +++ b/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.js @@ -0,0 +1,36 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var averageOfLevels = function (root) { + let s = []; + let cnt = []; + function dfs(root, i) { + if (!root) { + return; + } + if (s.length == i) { + s.push(root.val); + cnt.push(1); + } else { + s[i] += root.val; + cnt[i]++; + } + dfs(root.left, i + 1); + dfs(root.right, i + 1); + } + dfs(root, 0); + let ans = []; + for (let i = 0; i < s.length; ++i) { + ans.push(s[i] / cnt[i]); + } + return ans; +}; diff --git a/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.py b/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.py new file mode 100644 index 0000000000000..97aedba8398d8 --- /dev/null +++ b/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.py @@ -0,0 +1,22 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: + def dfs(root, i): + if root is None: + return + if len(s) == i: + s.append([root.val, 1]) + else: + s[i][0] += root.val + s[i][1] += 1 + dfs(root.left, i + 1) + dfs(root.right, i + 1) + + s = [] + dfs(root, 0) + return [a / b for a, b in s] diff --git a/solution/0600-0699/0639.Decode Ways II/Solution.java b/solution/0600-0699/0639.Decode Ways II/Solution.java index 84306c489898a..f40359cceec7a 100644 --- a/solution/0600-0699/0639.Decode Ways II/Solution.java +++ b/solution/0600-0699/0639.Decode Ways II/Solution.java @@ -45,4 +45,4 @@ public int numDecodings(String s) { return (int) c; } -} +} \ No newline at end of file diff --git a/solution/0600-0699/0643.Maximum Average Subarray I/Solution.php b/solution/0600-0699/0643.Maximum Average Subarray I/Solution.php index 3ef8826f2215c..755c1b7206bd7 100644 --- a/solution/0600-0699/0643.Maximum Average Subarray I/Solution.php +++ b/solution/0600-0699/0643.Maximum Average Subarray I/Solution.php @@ -16,4 +16,4 @@ function findMaxAverage($nums, $k) { } return $max / $k; } -} \ No newline at end of file +} diff --git a/solution/0600-0699/0644.Maximum Average Subarray II/Solution.cpp b/solution/0600-0699/0644.Maximum Average Subarray II/Solution.cpp index dfbce0ccef50a..c86bd38670963 100644 --- a/solution/0600-0699/0644.Maximum Average Subarray II/Solution.cpp +++ b/solution/0600-0699/0644.Maximum Average Subarray II/Solution.cpp @@ -1,37 +1,37 @@ -class Solution { -public: - double findMaxAverage(vector& nums, int k) { - double eps = 1e-5; - double l = *min_element(nums.begin(), nums.end()); - double r = *max_element(nums.begin(), nums.end()); - auto check = [&](double v) { - double s = 0; - for (int i = 0; i < k; ++i) { - s += nums[i] - v; - } - if (s >= 0) { - return true; - } - double t = 0; - double mi = 0; - for (int i = k; i < nums.size(); ++i) { - s += nums[i] - v; - t += nums[i - k] - v; - mi = min(mi, t); - if (s >= mi) { - return true; - } - } - return false; - }; - while (r - l >= eps) { - double mid = (l + r) / 2; - if (check(mid)) { - l = mid; - } else { - r = mid; - } - } - return l; - } +class Solution { +public: + double findMaxAverage(vector& nums, int k) { + double eps = 1e-5; + double l = *min_element(nums.begin(), nums.end()); + double r = *max_element(nums.begin(), nums.end()); + auto check = [&](double v) { + double s = 0; + for (int i = 0; i < k; ++i) { + s += nums[i] - v; + } + if (s >= 0) { + return true; + } + double t = 0; + double mi = 0; + for (int i = k; i < nums.size(); ++i) { + s += nums[i] - v; + t += nums[i - k] - v; + mi = min(mi, t); + if (s >= mi) { + return true; + } + } + return false; + }; + while (r - l >= eps) { + double mid = (l + r) / 2; + if (check(mid)) { + l = mid; + } else { + r = mid; + } + } + return l; + } }; \ No newline at end of file diff --git a/solution/0600-0699/0644.Maximum Average Subarray II/Solution.java b/solution/0600-0699/0644.Maximum Average Subarray II/Solution.java index 51a69f43bea65..5aba80d70fc28 100644 --- a/solution/0600-0699/0644.Maximum Average Subarray II/Solution.java +++ b/solution/0600-0699/0644.Maximum Average Subarray II/Solution.java @@ -1,40 +1,40 @@ -class Solution { - public double findMaxAverage(int[] nums, int k) { - double eps = 1e-5; - double l = 1e10, r = -1e10; - for (int x : nums) { - l = Math.min(l, x); - r = Math.max(r, x); - } - while (r - l >= eps) { - double mid = (l + r) / 2; - if (check(nums, k, mid)) { - l = mid; - } else { - r = mid; - } - } - return l; - } - - private boolean check(int[] nums, int k, double v) { - double s = 0; - for (int i = 0; i < k; ++i) { - s += nums[i] - v; - } - if (s >= 0) { - return true; - } - double t = 0; - double mi = 0; - for (int i = k; i < nums.length; ++i) { - s += nums[i] - v; - t += nums[i - k] - v; - mi = Math.min(mi, t); - if (s >= mi) { - return true; - } - } - return false; - } +class Solution { + public double findMaxAverage(int[] nums, int k) { + double eps = 1e-5; + double l = 1e10, r = -1e10; + for (int x : nums) { + l = Math.min(l, x); + r = Math.max(r, x); + } + while (r - l >= eps) { + double mid = (l + r) / 2; + if (check(nums, k, mid)) { + l = mid; + } else { + r = mid; + } + } + return l; + } + + private boolean check(int[] nums, int k, double v) { + double s = 0; + for (int i = 0; i < k; ++i) { + s += nums[i] - v; + } + if (s >= 0) { + return true; + } + double t = 0; + double mi = 0; + for (int i = k; i < nums.length; ++i) { + s += nums[i] - v; + t += nums[i - k] - v; + mi = Math.min(mi, t); + if (s >= mi) { + return true; + } + } + return false; + } } \ No newline at end of file diff --git a/solution/0600-0699/0644.Maximum Average Subarray II/Solution.py b/solution/0600-0699/0644.Maximum Average Subarray II/Solution.py index 204d27465b5fa..3d10aa119f18c 100644 --- a/solution/0600-0699/0644.Maximum Average Subarray II/Solution.py +++ b/solution/0600-0699/0644.Maximum Average Subarray II/Solution.py @@ -1,24 +1,24 @@ -class Solution: - def findMaxAverage(self, nums: List[int], k: int) -> float: - def check(v: float) -> bool: - s = sum(nums[:k]) - k * v - if s >= 0: - return True - t = mi = 0 - for i in range(k, len(nums)): - s += nums[i] - v - t += nums[i - k] - v - mi = min(mi, t) - if s >= mi: - return True - return False - - eps = 1e-5 - l, r = min(nums), max(nums) - while r - l >= eps: - mid = (l + r) / 2 - if check(mid): - l = mid - else: - r = mid - return l +class Solution: + def findMaxAverage(self, nums: List[int], k: int) -> float: + def check(v: float) -> bool: + s = sum(nums[:k]) - k * v + if s >= 0: + return True + t = mi = 0 + for i in range(k, len(nums)): + s += nums[i] - v + t += nums[i - k] - v + mi = min(mi, t) + if s >= mi: + return True + return False + + eps = 1e-5 + l, r = min(nums), max(nums) + while r - l >= eps: + mid = (l + r) / 2 + if check(mid): + l = mid + else: + r = mid + return l diff --git a/solution/0600-0699/0645.Set Mismatch/Solution.cpp b/solution/0600-0699/0645.Set Mismatch/Solution.cpp index e08f21e60a0c1..adde28a7777f6 100644 --- a/solution/0600-0699/0645.Set Mismatch/Solution.cpp +++ b/solution/0600-0699/0645.Set Mismatch/Solution.cpp @@ -1,27 +1,14 @@ -class Solution { -public: - vector findErrorNums(vector& nums) { - int n = nums.size(); - int xs = 0; - for (int i = 1; i <= n; ++i) { - xs ^= i ^ nums[i - 1]; - } - int lb = xs & -xs; - int a = 0; - for (int i = 1; i <= n; ++i) { - if (i & lb) { - a ^= i; - } - if (nums[i - 1] & lb) { - a ^= nums[i - 1]; - } - } - int b = xs ^ a; - for (int i = 0; i < n; ++i) { - if (nums[i] == a) { - return {a, b}; - } - } - return {b, a}; - } +class Solution { +public: + vector findErrorNums(vector& nums) { + int n = nums.size(); + int s1 = (1 + n) * n / 2; + int s2 = 0; + unordered_set set(nums.begin(), nums.end()); + for (int x : set) { + s2 += x; + } + int s = accumulate(nums.begin(), nums.end(), 0); + return {s - s2, s1 - s2}; + } }; \ No newline at end of file diff --git a/solution/0600-0699/0645.Set Mismatch/Solution.go b/solution/0600-0699/0645.Set Mismatch/Solution.go index ab485e1856262..dfb0f8975a854 100644 --- a/solution/0600-0699/0645.Set Mismatch/Solution.go +++ b/solution/0600-0699/0645.Set Mismatch/Solution.go @@ -1,23 +1,14 @@ func findErrorNums(nums []int) []int { - xs := 0 - for i, x := range nums { - xs ^= x ^ (i + 1) - } - lb := xs & -xs - a := 0 - for i, x := range nums { - if (i+1)&lb != 0 { - a ^= (i + 1) - } - if x&lb != 0 { - a ^= x - } - } - b := xs ^ a + n := len(nums) + s1 := (1 + n) * n / 2 + s2, s := 0, 0 + set := map[int]bool{} for _, x := range nums { - if x == a { - return []int{a, b} + if !set[x] { + set[x] = true + s2 += x } + s += x } - return []int{b, a} + return []int{s - s2, s1 - s2} } \ No newline at end of file diff --git a/solution/0600-0699/0645.Set Mismatch/Solution.java b/solution/0600-0699/0645.Set Mismatch/Solution.java index d4da115a83be9..0397cf41f0e26 100644 --- a/solution/0600-0699/0645.Set Mismatch/Solution.java +++ b/solution/0600-0699/0645.Set Mismatch/Solution.java @@ -1,26 +1,16 @@ -class Solution { - public int[] findErrorNums(int[] nums) { - int n = nums.length; - int xs = 0; - for (int i = 1; i <= n; ++i) { - xs ^= i ^ nums[i - 1]; - } - int lb = xs & -xs; - int a = 0; - for (int i = 1; i <= n; ++i) { - if ((i & lb) > 0) { - a ^= i; - } - if ((nums[i - 1] & lb) > 0) { - a ^= nums[i - 1]; - } - } - int b = xs ^ a; - for (int i = 0; i < n; ++i) { - if (nums[i] == a) { - return new int[] {a, b}; - } - } - return new int[] {b, a}; - } +class Solution { + public int[] findErrorNums(int[] nums) { + int n = nums.length; + int s1 = (1 + n) * n / 2; + int s2 = 0; + Set set = new HashSet<>(); + int s = 0; + for (int x : nums) { + if (set.add(x)) { + s2 += x; + } + s += x; + } + return new int[] {s - s2, s1 - s2}; + } } \ No newline at end of file diff --git a/solution/0600-0699/0645.Set Mismatch/Solution.py b/solution/0600-0699/0645.Set Mismatch/Solution.py index 10c999b8c5b50..289dfd90e9e53 100644 --- a/solution/0600-0699/0645.Set Mismatch/Solution.py +++ b/solution/0600-0699/0645.Set Mismatch/Solution.py @@ -1,17 +1,7 @@ -class Solution: - def findErrorNums(self, nums: List[int]) -> List[int]: - xs = 0 - for i, x in enumerate(nums, 1): - xs ^= i ^ x - a = 0 - lb = xs & -xs - for i, x in enumerate(nums, 1): - if i & lb: - a ^= i - if x & lb: - a ^= x - b = xs ^ a - for x in nums: - if x == a: - return [a, b] - return [b, a] +class Solution: + def findErrorNums(self, nums: List[int]) -> List[int]: + n = len(nums) + s1 = (1 + n) * n // 2 + s2 = sum(set(nums)) + s = sum(nums) + return [s - s2, s1 - s2] diff --git a/solution/0600-0699/0645.Set Mismatch/Solution.rs b/solution/0600-0699/0645.Set Mismatch/Solution.rs index 88cd7e6875d3e..1957412fa9b0c 100644 --- a/solution/0600-0699/0645.Set Mismatch/Solution.rs +++ b/solution/0600-0699/0645.Set Mismatch/Solution.rs @@ -1,25 +1,10 @@ +use std::collections::HashSet; impl Solution { pub fn find_error_nums(nums: Vec) -> Vec { - let mut xs = 0; - for (i, x) in nums.iter().enumerate() { - xs ^= ((i + 1) as i32) ^ x; - } - let mut a = 0; - let lb = xs & -xs; - for (i, x) in nums.iter().enumerate() { - if (((i + 1) as i32) & lb) != 0 { - a ^= (i + 1) as i32; - } - if (*x & lb) != 0 { - a ^= *x; - } - } - let b = xs ^ a; - for x in nums.iter() { - if *x == a { - return vec![a, b]; - } - } - vec![b, a] + let n = nums.len() as i32; + let s1 = ((1 + n) * n) / 2; + let s2 = nums.iter().cloned().collect::>().iter().sum::(); + let s: i32 = nums.iter().sum(); + vec![s - s2, s1 - s2] } } diff --git a/solution/0600-0699/0645.Set Mismatch/Solution.ts b/solution/0600-0699/0645.Set Mismatch/Solution.ts index 8a89356b633ba..02438fb0d133c 100644 --- a/solution/0600-0699/0645.Set Mismatch/Solution.ts +++ b/solution/0600-0699/0645.Set Mismatch/Solution.ts @@ -1,19 +1,7 @@ function findErrorNums(nums: number[]): number[] { const n = nums.length; - let xs = 0; - for (let i = 1; i <= n; ++i) { - xs ^= i ^ nums[i - 1]; - } - const lb = xs & -xs; - let a = 0; - for (let i = 1; i <= n; ++i) { - if (i & lb) { - a ^= i; - } - if (nums[i - 1] & lb) { - a ^= nums[i - 1]; - } - } - const b = xs ^ a; - return nums.includes(a) ? [a, b] : [b, a]; + const s1 = (n * (n + 1)) >> 1; + const s2 = [...new Set(nums)].reduce((a, b) => a + b); + const s = nums.reduce((a, b) => a + b); + return [s - s2, s1 - s2]; } diff --git a/solution/0600-0699/0645.Set Mismatch/Solution2.cpp b/solution/0600-0699/0645.Set Mismatch/Solution2.cpp new file mode 100644 index 0000000000000..3a10d2acff286 --- /dev/null +++ b/solution/0600-0699/0645.Set Mismatch/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + vector findErrorNums(vector& nums) { + int n = nums.size(); + unordered_map cnt; + for (int x : nums) { + ++cnt[x]; + } + vector ans(2); + for (int x = 1; x <= n; ++x) { + if (cnt[x] == 2) { + ans[0] = x; + } else if (cnt[x] == 0) { + ans[1] = x; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0645.Set Mismatch/Solution2.go b/solution/0600-0699/0645.Set Mismatch/Solution2.go new file mode 100644 index 0000000000000..3f0d4a1fe62bc --- /dev/null +++ b/solution/0600-0699/0645.Set Mismatch/Solution2.go @@ -0,0 +1,16 @@ +func findErrorNums(nums []int) []int { + n := len(nums) + cnt := map[int]int{} + for _, x := range nums { + cnt[x]++ + } + ans := make([]int, 2) + for x := 1; x <= n; x++ { + if cnt[x] == 2 { + ans[0] = x + } else if cnt[x] == 0 { + ans[1] = x + } + } + return ans +} \ No newline at end of file diff --git a/solution/0600-0699/0645.Set Mismatch/Solution2.java b/solution/0600-0699/0645.Set Mismatch/Solution2.java new file mode 100644 index 0000000000000..c188caf36215a --- /dev/null +++ b/solution/0600-0699/0645.Set Mismatch/Solution2.java @@ -0,0 +1,19 @@ +class Solution { + public int[] findErrorNums(int[] nums) { + int n = nums.length; + Map cnt = new HashMap<>(n); + for (int x : nums) { + cnt.merge(x, 1, Integer::sum); + } + int[] ans = new int[2]; + for (int x = 1; x <= n; ++x) { + int t = cnt.getOrDefault(x, 0); + if (t == 2) { + ans[0] = x; + } else if (t == 0) { + ans[1] = x; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0645.Set Mismatch/Solution2.py b/solution/0600-0699/0645.Set Mismatch/Solution2.py new file mode 100644 index 0000000000000..d673c7ee36d94 --- /dev/null +++ b/solution/0600-0699/0645.Set Mismatch/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def findErrorNums(self, nums: List[int]) -> List[int]: + cnt = Counter(nums) + n = len(nums) + ans = [0] * 2 + for x in range(1, n + 1): + if cnt[x] == 2: + ans[0] = x + if cnt[x] == 0: + ans[1] = x + return ans diff --git a/solution/0600-0699/0645.Set Mismatch/Solution2.rs b/solution/0600-0699/0645.Set Mismatch/Solution2.rs new file mode 100644 index 0000000000000..88cd7e6875d3e --- /dev/null +++ b/solution/0600-0699/0645.Set Mismatch/Solution2.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn find_error_nums(nums: Vec) -> Vec { + let mut xs = 0; + for (i, x) in nums.iter().enumerate() { + xs ^= ((i + 1) as i32) ^ x; + } + let mut a = 0; + let lb = xs & -xs; + for (i, x) in nums.iter().enumerate() { + if (((i + 1) as i32) & lb) != 0 { + a ^= (i + 1) as i32; + } + if (*x & lb) != 0 { + a ^= *x; + } + } + let b = xs ^ a; + for x in nums.iter() { + if *x == a { + return vec![a, b]; + } + } + vec![b, a] + } +} diff --git a/solution/0600-0699/0645.Set Mismatch/Solution2.ts b/solution/0600-0699/0645.Set Mismatch/Solution2.ts new file mode 100644 index 0000000000000..155f925d8e7e3 --- /dev/null +++ b/solution/0600-0699/0645.Set Mismatch/Solution2.ts @@ -0,0 +1,17 @@ +function findErrorNums(nums: number[]): number[] { + const n = nums.length; + const cnt: Map = new Map(); + for (const x of nums) { + cnt.set(x, (cnt.get(x) || 0) + 1); + } + const ans: number[] = new Array(2).fill(0); + for (let x = 1; x <= n; ++x) { + const t = cnt.get(x) || 0; + if (t === 2) { + ans[0] = x; + } else if (t === 0) { + ans[1] = x; + } + } + return ans; +} diff --git a/solution/0600-0699/0645.Set Mismatch/Solution3.cpp b/solution/0600-0699/0645.Set Mismatch/Solution3.cpp new file mode 100644 index 0000000000000..d051f1d24ea04 --- /dev/null +++ b/solution/0600-0699/0645.Set Mismatch/Solution3.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector findErrorNums(vector& nums) { + int n = nums.size(); + int xs = 0; + for (int i = 1; i <= n; ++i) { + xs ^= i ^ nums[i - 1]; + } + int lb = xs & -xs; + int a = 0; + for (int i = 1; i <= n; ++i) { + if (i & lb) { + a ^= i; + } + if (nums[i - 1] & lb) { + a ^= nums[i - 1]; + } + } + int b = xs ^ a; + for (int i = 0; i < n; ++i) { + if (nums[i] == a) { + return {a, b}; + } + } + return {b, a}; + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0645.Set Mismatch/Solution3.go b/solution/0600-0699/0645.Set Mismatch/Solution3.go new file mode 100644 index 0000000000000..ab485e1856262 --- /dev/null +++ b/solution/0600-0699/0645.Set Mismatch/Solution3.go @@ -0,0 +1,23 @@ +func findErrorNums(nums []int) []int { + xs := 0 + for i, x := range nums { + xs ^= x ^ (i + 1) + } + lb := xs & -xs + a := 0 + for i, x := range nums { + if (i+1)&lb != 0 { + a ^= (i + 1) + } + if x&lb != 0 { + a ^= x + } + } + b := xs ^ a + for _, x := range nums { + if x == a { + return []int{a, b} + } + } + return []int{b, a} +} \ No newline at end of file diff --git a/solution/0600-0699/0645.Set Mismatch/Solution3.java b/solution/0600-0699/0645.Set Mismatch/Solution3.java new file mode 100644 index 0000000000000..50d4c9386edfc --- /dev/null +++ b/solution/0600-0699/0645.Set Mismatch/Solution3.java @@ -0,0 +1,26 @@ +class Solution { + public int[] findErrorNums(int[] nums) { + int n = nums.length; + int xs = 0; + for (int i = 1; i <= n; ++i) { + xs ^= i ^ nums[i - 1]; + } + int lb = xs & -xs; + int a = 0; + for (int i = 1; i <= n; ++i) { + if ((i & lb) > 0) { + a ^= i; + } + if ((nums[i - 1] & lb) > 0) { + a ^= nums[i - 1]; + } + } + int b = xs ^ a; + for (int i = 0; i < n; ++i) { + if (nums[i] == a) { + return new int[] {a, b}; + } + } + return new int[] {b, a}; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0645.Set Mismatch/Solution3.py b/solution/0600-0699/0645.Set Mismatch/Solution3.py new file mode 100644 index 0000000000000..69bd26332009e --- /dev/null +++ b/solution/0600-0699/0645.Set Mismatch/Solution3.py @@ -0,0 +1,17 @@ +class Solution: + def findErrorNums(self, nums: List[int]) -> List[int]: + xs = 0 + for i, x in enumerate(nums, 1): + xs ^= i ^ x + a = 0 + lb = xs & -xs + for i, x in enumerate(nums, 1): + if i & lb: + a ^= i + if x & lb: + a ^= x + b = xs ^ a + for x in nums: + if x == a: + return [a, b] + return [b, a] diff --git a/solution/0600-0699/0645.Set Mismatch/Solution3.ts b/solution/0600-0699/0645.Set Mismatch/Solution3.ts new file mode 100644 index 0000000000000..8a89356b633ba --- /dev/null +++ b/solution/0600-0699/0645.Set Mismatch/Solution3.ts @@ -0,0 +1,19 @@ +function findErrorNums(nums: number[]): number[] { + const n = nums.length; + let xs = 0; + for (let i = 1; i <= n; ++i) { + xs ^= i ^ nums[i - 1]; + } + const lb = xs & -xs; + let a = 0; + for (let i = 1; i <= n; ++i) { + if (i & lb) { + a ^= i; + } + if (nums[i - 1] & lb) { + a ^= nums[i - 1]; + } + } + const b = xs ^ a; + return nums.includes(a) ? [a, b] : [b, a]; +} diff --git a/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.cpp b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.cpp index c409253301c9a..7e5ae31eea5e7 100644 --- a/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.cpp +++ b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - int findLongestChain(vector>& pairs) { - sort(pairs.begin(), pairs.end(), [](vector& a, vector b) { - return a[1] < b[1]; - }); - int ans = 0, cur = INT_MIN; - for (auto& p : pairs) { - if (cur < p[0]) { - cur = p[1]; - ++ans; - } - } - return ans; - } +class Solution { +public: + int findLongestChain(vector>& pairs) { + sort(pairs.begin(), pairs.end()); + int n = pairs.size(); + vector dp(n, 1); + for (int i = 0; i < n; ++i) { + int c = pairs[i][0]; + for (int j = 0; j < i; ++j) { + int b = pairs[j][1]; + if (b < c) dp[i] = max(dp[i], dp[j] + 1); + } + } + return *max_element(dp.begin(), dp.end()); + } }; \ No newline at end of file diff --git a/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.go b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.go index 643704bb0862c..3fcf7543dc448 100644 --- a/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.go +++ b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.go @@ -1,13 +1,20 @@ func findLongestChain(pairs [][]int) int { sort.Slice(pairs, func(i, j int) bool { - return pairs[i][1] < pairs[j][1] + return pairs[i][0] < pairs[j][0] }) - ans, cur := 0, math.MinInt32 - for _, p := range pairs { - if cur < p[0] { - cur = p[1] - ans++ + n := len(pairs) + dp := make([]int, n) + ans := 0 + for i := range pairs { + dp[i] = 1 + c := pairs[i][0] + for j := range pairs[:i] { + b := pairs[j][1] + if b < c { + dp[i] = max(dp[i], dp[j]+1) + } } + ans = max(ans, dp[i]) } return ans } \ No newline at end of file diff --git a/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.java b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.java index 470f648e6bbaf..d44518bd8b050 100644 --- a/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.java +++ b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.java @@ -1,14 +1,20 @@ -class Solution { - public int findLongestChain(int[][] pairs) { - Arrays.sort(pairs, Comparator.comparingInt(a -> a[1])); - int ans = 0; - int cur = Integer.MIN_VALUE; - for (int[] p : pairs) { - if (cur < p[0]) { - cur = p[1]; - ++ans; - } - } - return ans; - } +class Solution { + public int findLongestChain(int[][] pairs) { + Arrays.sort(pairs, Comparator.comparingInt(a -> a[0])); + int n = pairs.length; + int[] dp = new int[n]; + int ans = 0; + for (int i = 0; i < n; ++i) { + dp[i] = 1; + int c = pairs[i][0]; + for (int j = 0; j < i; ++j) { + int b = pairs[j][1]; + if (b < c) { + dp[i] = Math.max(dp[i], dp[j] + 1); + } + } + ans = Math.max(ans, dp[i]); + } + return ans; + } } \ No newline at end of file diff --git a/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.py b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.py index bbb0b614a808b..56f01722dbecc 100644 --- a/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.py +++ b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.py @@ -1,8 +1,9 @@ -class Solution: - def findLongestChain(self, pairs: List[List[int]]) -> int: - ans, cur = 0, -inf - for a, b in sorted(pairs, key=lambda x: x[1]): - if cur < a: - cur = b - ans += 1 - return ans +class Solution: + def findLongestChain(self, pairs: List[List[int]]) -> int: + pairs.sort() + dp = [1] * len(pairs) + for i, (c, _) in enumerate(pairs): + for j, (_, b) in enumerate(pairs[:i]): + if b < c: + dp[i] = max(dp[i], dp[j] + 1) + return max(dp) diff --git a/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.rs b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.rs index d0777c6f45ff2..3f48a5cc34b5d 100644 --- a/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.rs +++ b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.rs @@ -1,16 +1,15 @@ impl Solution { pub fn find_longest_chain(mut pairs: Vec>) -> i32 { - pairs.sort_by(|a, b| a[1].cmp(&b[1])); - let mut res = 0; - let mut pre = i32::MIN; - for pair in pairs.iter() { - let a = pair[0]; - let b = pair[1]; - if pre < a { - pre = b; - res += 1; + pairs.sort_by(|a, b| a[0].cmp(&b[0])); + let n = pairs.len(); + let mut dp = vec![1; n]; + for i in 0..n { + for j in 0..i { + if pairs[i][0] > pairs[j][1] { + dp[i] = dp[i].max(dp[j] + 1); + } } } - res + dp[n - 1] } } diff --git a/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.ts b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.ts index be43073629fa3..7f69a598b7fa0 100644 --- a/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.ts +++ b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution.ts @@ -1,12 +1,13 @@ function findLongestChain(pairs: number[][]): number { - pairs.sort((a, b) => a[1] - b[1]); - let res = 0; - let pre = -Infinity; - for (const [a, b] of pairs) { - if (pre < a) { - pre = b; - res++; + pairs.sort((a, b) => a[0] - b[0]); + const n = pairs.length; + const dp = new Array(n).fill(1); + for (let i = 0; i < n; i++) { + for (let j = 0; j < i; j++) { + if (pairs[i][0] > pairs[j][1]) { + dp[i] = Math.max(dp[i], dp[j] + 1); + } } } - return res; + return dp[n - 1]; } diff --git a/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution2.cpp b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution2.cpp new file mode 100644 index 0000000000000..ea27e73eacd27 --- /dev/null +++ b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int findLongestChain(vector>& pairs) { + sort(pairs.begin(), pairs.end(), [](vector& a, vector b) { + return a[1] < b[1]; + }); + int ans = 0, cur = INT_MIN; + for (auto& p : pairs) { + if (cur < p[0]) { + cur = p[1]; + ++ans; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution2.go b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution2.go new file mode 100644 index 0000000000000..643704bb0862c --- /dev/null +++ b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution2.go @@ -0,0 +1,13 @@ +func findLongestChain(pairs [][]int) int { + sort.Slice(pairs, func(i, j int) bool { + return pairs[i][1] < pairs[j][1] + }) + ans, cur := 0, math.MinInt32 + for _, p := range pairs { + if cur < p[0] { + cur = p[1] + ans++ + } + } + return ans +} \ No newline at end of file diff --git a/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution2.java b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution2.java new file mode 100644 index 0000000000000..c1dfaeb56edd4 --- /dev/null +++ b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public int findLongestChain(int[][] pairs) { + Arrays.sort(pairs, Comparator.comparingInt(a -> a[1])); + int ans = 0; + int cur = Integer.MIN_VALUE; + for (int[] p : pairs) { + if (cur < p[0]) { + cur = p[1]; + ++ans; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution2.py b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution2.py new file mode 100644 index 0000000000000..ae9d7776c387d --- /dev/null +++ b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def findLongestChain(self, pairs: List[List[int]]) -> int: + ans, cur = 0, -inf + for a, b in sorted(pairs, key=lambda x: x[1]): + if cur < a: + cur = b + ans += 1 + return ans diff --git a/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution2.rs b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution2.rs new file mode 100644 index 0000000000000..d0777c6f45ff2 --- /dev/null +++ b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution2.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn find_longest_chain(mut pairs: Vec>) -> i32 { + pairs.sort_by(|a, b| a[1].cmp(&b[1])); + let mut res = 0; + let mut pre = i32::MIN; + for pair in pairs.iter() { + let a = pair[0]; + let b = pair[1]; + if pre < a { + pre = b; + res += 1; + } + } + res + } +} diff --git a/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution2.ts b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution2.ts new file mode 100644 index 0000000000000..be43073629fa3 --- /dev/null +++ b/solution/0600-0699/0646.Maximum Length of Pair Chain/Solution2.ts @@ -0,0 +1,12 @@ +function findLongestChain(pairs: number[][]): number { + pairs.sort((a, b) => a[1] - b[1]); + let res = 0; + let pre = -Infinity; + for (const [a, b] of pairs) { + if (pre < a) { + pre = b; + res++; + } + } + return res; +} diff --git a/solution/0600-0699/0647.Palindromic Substrings/Solution.java b/solution/0600-0699/0647.Palindromic Substrings/Solution.java index 62987940055cc..07ac180e5c693 100644 --- a/solution/0600-0699/0647.Palindromic Substrings/Solution.java +++ b/solution/0600-0699/0647.Palindromic Substrings/Solution.java @@ -1,25 +1,15 @@ class Solution { public int countSubstrings(String s) { - StringBuilder sb = new StringBuilder("^#"); - for (char ch : s.toCharArray()) { - sb.append(ch).append('#'); - } - String t = sb.append('$').toString(); - int n = t.length(); - int[] p = new int[n]; - int pos = 0, maxRight = 0; int ans = 0; - for (int i = 1; i < n - 1; i++) { - p[i] = maxRight > i ? Math.min(maxRight - i, p[2 * pos - i]) : 1; - while (t.charAt(i - p[i]) == t.charAt(i + p[i])) { - p[i]++; - } - if (i + p[i] > maxRight) { - maxRight = i + p[i]; - pos = i; + int n = s.length(); + for (int k = 0; k < n * 2 - 1; ++k) { + int i = k / 2, j = (k + 1) / 2; + while (i >= 0 && j < n && s.charAt(i) == s.charAt(j)) { + ++ans; + --i; + ++j; } - ans += p[i] / 2; } return ans; } -} +} \ No newline at end of file diff --git a/solution/0600-0699/0647.Palindromic Substrings/Solution.py b/solution/0600-0699/0647.Palindromic Substrings/Solution.py index 9e0bdd8c6eeb9..b0e84409de31a 100644 --- a/solution/0600-0699/0647.Palindromic Substrings/Solution.py +++ b/solution/0600-0699/0647.Palindromic Substrings/Solution.py @@ -1,16 +1,9 @@ class Solution: def countSubstrings(self, s: str) -> int: - t = '^#' + '#'.join(s) + '#$' - n = len(t) - p = [0 for _ in range(n)] - pos, maxRight = 0, 0 - ans = 0 - for i in range(1, n - 1): - p[i] = min(maxRight - i, p[2 * pos - i]) if maxRight > i else 1 - while t[i - p[i]] == t[i + p[i]]: - p[i] += 1 - if i + p[i] > maxRight: - maxRight = i + p[i] - pos = i - ans += p[i] // 2 + ans, n = 0, len(s) + for k in range(n * 2 - 1): + i, j = k // 2, (k + 1) // 2 + while ~i and j < n and s[i] == s[j]: + ans += 1 + i, j = i - 1, j + 1 return ans diff --git a/solution/0600-0699/0647.Palindromic Substrings/Solution2.java b/solution/0600-0699/0647.Palindromic Substrings/Solution2.java new file mode 100644 index 0000000000000..ad44cfc61d180 --- /dev/null +++ b/solution/0600-0699/0647.Palindromic Substrings/Solution2.java @@ -0,0 +1,25 @@ +class Solution { + public int countSubstrings(String s) { + StringBuilder sb = new StringBuilder("^#"); + for (char ch : s.toCharArray()) { + sb.append(ch).append('#'); + } + String t = sb.append('$').toString(); + int n = t.length(); + int[] p = new int[n]; + int pos = 0, maxRight = 0; + int ans = 0; + for (int i = 1; i < n - 1; i++) { + p[i] = maxRight > i ? Math.min(maxRight - i, p[2 * pos - i]) : 1; + while (t.charAt(i - p[i]) == t.charAt(i + p[i])) { + p[i]++; + } + if (i + p[i] > maxRight) { + maxRight = i + p[i]; + pos = i; + } + ans += p[i] / 2; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0647.Palindromic Substrings/Solution2.py b/solution/0600-0699/0647.Palindromic Substrings/Solution2.py new file mode 100644 index 0000000000000..9e0bdd8c6eeb9 --- /dev/null +++ b/solution/0600-0699/0647.Palindromic Substrings/Solution2.py @@ -0,0 +1,16 @@ +class Solution: + def countSubstrings(self, s: str) -> int: + t = '^#' + '#'.join(s) + '#$' + n = len(t) + p = [0 for _ in range(n)] + pos, maxRight = 0, 0 + ans = 0 + for i in range(1, n - 1): + p[i] = min(maxRight - i, p[2 * pos - i]) if maxRight > i else 1 + while t[i - p[i]] == t[i + p[i]]: + p[i] += 1 + if i + p[i] > maxRight: + maxRight = i + p[i] + pos = i + ans += p[i] // 2 + return ans diff --git a/solution/0600-0699/0648.Replace Words/Solution.java b/solution/0600-0699/0648.Replace Words/Solution.java index 505b6190a3757..ad7971ab23a32 100644 --- a/solution/0600-0699/0648.Replace Words/Solution.java +++ b/solution/0600-0699/0648.Replace Words/Solution.java @@ -1,46 +1,17 @@ -class Trie { - private Trie[] children = new Trie[26]; - private int ref = -1; - - public void insert(String w, int i) { - Trie node = this; - for (int j = 0; j < w.length(); ++j) { - int idx = w.charAt(j) - 'a'; - if (node.children[idx] == null) { - node.children[idx] = new Trie(); - } - node = node.children[idx]; - } - node.ref = i; - } - - public int search(String w) { - Trie node = this; - for (int j = 0; j < w.length(); ++j) { - int idx = w.charAt(j) - 'a'; - if (node.children[idx] == null) { - return -1; - } - node = node.children[idx]; - if (node.ref != -1) { - return node.ref; - } - } - return -1; - } -} - class Solution { public String replaceWords(List dictionary, String sentence) { - Trie trie = new Trie(); - for (int i = 0; i < dictionary.size(); ++i) { - trie.insert(dictionary.get(i), i); - } - List ans = new ArrayList<>(); - for (String w : sentence.split("\\s")) { - int idx = trie.search(w); - ans.add(idx == -1 ? w : dictionary.get(idx)); + Set s = new HashSet<>(dictionary); + String[] words = sentence.split(" "); + for (int i = 0; i < words.length; ++i) { + String word = words[i]; + for (int j = 1; j <= word.length(); ++j) { + String t = word.substring(0, j); + if (s.contains(t)) { + words[i] = t; + break; + } + } } - return String.join(" ", ans); + return String.join(" ", words); } } \ No newline at end of file diff --git a/solution/0600-0699/0648.Replace Words/Solution2.java b/solution/0600-0699/0648.Replace Words/Solution2.java new file mode 100644 index 0000000000000..505b6190a3757 --- /dev/null +++ b/solution/0600-0699/0648.Replace Words/Solution2.java @@ -0,0 +1,46 @@ +class Trie { + private Trie[] children = new Trie[26]; + private int ref = -1; + + public void insert(String w, int i) { + Trie node = this; + for (int j = 0; j < w.length(); ++j) { + int idx = w.charAt(j) - 'a'; + if (node.children[idx] == null) { + node.children[idx] = new Trie(); + } + node = node.children[idx]; + } + node.ref = i; + } + + public int search(String w) { + Trie node = this; + for (int j = 0; j < w.length(); ++j) { + int idx = w.charAt(j) - 'a'; + if (node.children[idx] == null) { + return -1; + } + node = node.children[idx]; + if (node.ref != -1) { + return node.ref; + } + } + return -1; + } +} + +class Solution { + public String replaceWords(List dictionary, String sentence) { + Trie trie = new Trie(); + for (int i = 0; i < dictionary.size(); ++i) { + trie.insert(dictionary.get(i), i); + } + List ans = new ArrayList<>(); + for (String w : sentence.split("\\s")) { + int idx = trie.search(w); + ans.add(idx == -1 ? w : dictionary.get(idx)); + } + return String.join(" ", ans); + } +} \ No newline at end of file diff --git a/solution/0600-0699/0649.Dota2 Senate/Solution.cpp b/solution/0600-0699/0649.Dota2 Senate/Solution.cpp index 82c69998cb906..0c257acf84194 100644 --- a/solution/0600-0699/0649.Dota2 Senate/Solution.cpp +++ b/solution/0600-0699/0649.Dota2 Senate/Solution.cpp @@ -1,27 +1,27 @@ -class Solution { -public: - string predictPartyVictory(string senate) { - int n = senate.size(); - queue qr; - queue qd; - for (int i = 0; i < n; ++i) { - if (senate[i] == 'R') { - qr.push(i); - } else { - qd.push(i); - } - } - while (!qr.empty() && !qd.empty()) { - int r = qr.front(); - int d = qd.front(); - qr.pop(); - qd.pop(); - if (r < d) { - qr.push(r + n); - } else { - qd.push(d + n); - } - } - return qr.empty() ? "Dire" : "Radiant"; - } +class Solution { +public: + string predictPartyVictory(string senate) { + int n = senate.size(); + queue qr; + queue qd; + for (int i = 0; i < n; ++i) { + if (senate[i] == 'R') { + qr.push(i); + } else { + qd.push(i); + } + } + while (!qr.empty() && !qd.empty()) { + int r = qr.front(); + int d = qd.front(); + qr.pop(); + qd.pop(); + if (r < d) { + qr.push(r + n); + } else { + qd.push(d + n); + } + } + return qr.empty() ? "Dire" : "Radiant"; + } }; \ No newline at end of file diff --git a/solution/0600-0699/0649.Dota2 Senate/Solution.java b/solution/0600-0699/0649.Dota2 Senate/Solution.java index 4380d6cf6b907..66fb68341dcc9 100644 --- a/solution/0600-0699/0649.Dota2 Senate/Solution.java +++ b/solution/0600-0699/0649.Dota2 Senate/Solution.java @@ -1,24 +1,24 @@ -class Solution { - public String predictPartyVictory(String senate) { - int n = senate.length(); - Deque qr = new ArrayDeque<>(); - Deque qd = new ArrayDeque<>(); - for (int i = 0; i < n; ++i) { - if (senate.charAt(i) == 'R') { - qr.offer(i); - } else { - qd.offer(i); - } - } - while (!qr.isEmpty() && !qd.isEmpty()) { - if (qr.peek() < qd.peek()) { - qr.offer(qr.peek() + n); - } else { - qd.offer(qd.peek() + n); - } - qr.poll(); - qd.poll(); - } - return qr.isEmpty() ? "Dire" : "Radiant"; - } +class Solution { + public String predictPartyVictory(String senate) { + int n = senate.length(); + Deque qr = new ArrayDeque<>(); + Deque qd = new ArrayDeque<>(); + for (int i = 0; i < n; ++i) { + if (senate.charAt(i) == 'R') { + qr.offer(i); + } else { + qd.offer(i); + } + } + while (!qr.isEmpty() && !qd.isEmpty()) { + if (qr.peek() < qd.peek()) { + qr.offer(qr.peek() + n); + } else { + qd.offer(qd.peek() + n); + } + qr.poll(); + qd.poll(); + } + return qr.isEmpty() ? "Dire" : "Radiant"; + } } \ No newline at end of file diff --git a/solution/0600-0699/0649.Dota2 Senate/Solution.py b/solution/0600-0699/0649.Dota2 Senate/Solution.py index 623435a5d318d..d8d349915fdcc 100644 --- a/solution/0600-0699/0649.Dota2 Senate/Solution.py +++ b/solution/0600-0699/0649.Dota2 Senate/Solution.py @@ -1,18 +1,18 @@ -class Solution: - def predictPartyVictory(self, senate: str) -> str: - qr = deque() - qd = deque() - for i, c in enumerate(senate): - if c == "R": - qr.append(i) - else: - qd.append(i) - n = len(senate) - while qr and qd: - if qr[0] < qd[0]: - qr.append(qr[0] + n) - else: - qd.append(qd[0] + n) - qr.popleft() - qd.popleft() - return "Radiant" if qr else "Dire" +class Solution: + def predictPartyVictory(self, senate: str) -> str: + qr = deque() + qd = deque() + for i, c in enumerate(senate): + if c == "R": + qr.append(i) + else: + qd.append(i) + n = len(senate) + while qr and qd: + if qr[0] < qd[0]: + qr.append(qr[0] + n) + else: + qd.append(qd[0] + n) + qr.popleft() + qd.popleft() + return "Radiant" if qr else "Dire" diff --git a/solution/0600-0699/0650.2 Keys Keyboard/Solution.java b/solution/0600-0699/0650.2 Keys Keyboard/Solution.java index 71530a125e599..909bff12c6408 100644 --- a/solution/0600-0699/0650.2 Keys Keyboard/Solution.java +++ b/solution/0600-0699/0650.2 Keys Keyboard/Solution.java @@ -1,12 +1,26 @@ class Solution { + private int[] f; + public int minSteps(int n) { - int res = 0; - for (int i = 2; n > 1; ++i) { - while (n % i == 0) { - res += i; - n /= i; + f = new int[n + 1]; + Arrays.fill(f, -1); + return dfs(n); + } + + private int dfs(int n) { + if (n == 1) { + return 0; + } + if (f[n] != -1) { + return f[n]; + } + int ans = n; + for (int i = 2; i * i <= n; ++i) { + if (n % i == 0) { + ans = Math.min(ans, dfs(n / i) + i); } } - return res; + f[n] = ans; + return ans; } -} +} \ No newline at end of file diff --git a/solution/0600-0699/0650.2 Keys Keyboard/Solution2.cpp b/solution/0600-0699/0650.2 Keys Keyboard/Solution2.cpp new file mode 100644 index 0000000000000..f749314955673 --- /dev/null +++ b/solution/0600-0699/0650.2 Keys Keyboard/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int minSteps(int n) { + vector dp(n + 1); + iota(dp.begin(), dp.end(), 0); + dp[1] = 0; + for (int i = 2; i < n + 1; ++i) { + for (int j = 2; j * j <= i; ++j) { + if (i % j == 0) { + dp[i] = min(dp[i], dp[i / j] + j); + } + } + } + return dp[n]; + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0650.2 Keys Keyboard/Solution2.go b/solution/0600-0699/0650.2 Keys Keyboard/Solution2.go new file mode 100644 index 0000000000000..eb302854a05a1 --- /dev/null +++ b/solution/0600-0699/0650.2 Keys Keyboard/Solution2.go @@ -0,0 +1,15 @@ +func minSteps(n int) int { + dp := make([]int, n+1) + for i := range dp { + dp[i] = i + } + dp[1] = 0 + for i := 2; i < n+1; i++ { + for j := 2; j*j <= i; j++ { + if i%j == 0 { + dp[i] = min(dp[i], dp[i/j]+j) + } + } + } + return dp[n] +} \ No newline at end of file diff --git a/solution/0600-0699/0650.2 Keys Keyboard/Solution2.java b/solution/0600-0699/0650.2 Keys Keyboard/Solution2.java new file mode 100644 index 0000000000000..546c2294a03e4 --- /dev/null +++ b/solution/0600-0699/0650.2 Keys Keyboard/Solution2.java @@ -0,0 +1,17 @@ +class Solution { + public int minSteps(int n) { + int[] dp = new int[n + 1]; + for (int i = 0; i < n + 1; ++i) { + dp[i] = i; + } + dp[1] = 0; + for (int i = 2; i < n + 1; ++i) { + for (int j = 2; j * j <= i; ++j) { + if (i % j == 0) { + dp[i] = Math.min(dp[i], dp[i / j] + j); + } + } + } + return dp[n]; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0650.2 Keys Keyboard/Solution2.py b/solution/0600-0699/0650.2 Keys Keyboard/Solution2.py new file mode 100644 index 0000000000000..64c5f49f24e38 --- /dev/null +++ b/solution/0600-0699/0650.2 Keys Keyboard/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def minSteps(self, n: int) -> int: + dp = list(range(n + 1)) + dp[1] = 0 + for i in range(2, n + 1): + j = 2 + while j * j <= i: + if i % j == 0: + dp[i] = min(dp[i], dp[i // j] + j) + j += 1 + return dp[-1] diff --git a/solution/0600-0699/0650.2 Keys Keyboard/Solution3.java b/solution/0600-0699/0650.2 Keys Keyboard/Solution3.java new file mode 100644 index 0000000000000..4fb8c31672c1e --- /dev/null +++ b/solution/0600-0699/0650.2 Keys Keyboard/Solution3.java @@ -0,0 +1,12 @@ +class Solution { + public int minSteps(int n) { + int res = 0; + for (int i = 2; n > 1; ++i) { + while (n % i == 0) { + res += i; + n /= i; + } + } + return res; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution.rs b/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution.rs index 99e11ed72e66d..ab16e174a2ddb 100644 --- a/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution.rs +++ b/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution.rs @@ -16,9 +16,9 @@ // } // } // } +use std::rc::Rc; use std::cell::RefCell; use std::collections::{ HashSet, VecDeque }; -use std::rc::Rc; impl Solution { pub fn find_target(root: Option>>, k: i32) -> bool { let mut set = HashSet::new(); diff --git a/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution2.cpp b/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution2.cpp new file mode 100644 index 0000000000000..888c22190bd82 --- /dev/null +++ b/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution2.cpp @@ -0,0 +1,35 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool findTarget(TreeNode* root, int k) { + queue q{{root}}; + unordered_set vis; + while (!q.empty()) { + for (int n = q.size(); n; --n) { + TreeNode* node = q.front(); + q.pop(); + if (vis.count(k - node->val)) { + return true; + } + vis.insert(node->val); + if (node->left) { + q.push(node->left); + } + if (node->right) { + q.push(node->right); + } + } + } + return false; + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution2.go b/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution2.go new file mode 100644 index 0000000000000..cb0ceff33a424 --- /dev/null +++ b/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution2.go @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func findTarget(root *TreeNode, k int) bool { + q := []*TreeNode{root} + vis := map[int]bool{} + for len(q) > 0 { + for n := len(q); n > 0; n-- { + node := q[0] + q = q[1:] + if vis[k-node.Val] { + return true + } + vis[node.Val] = true + if node.Left != nil { + q = append(q, node.Left) + } + if node.Right != nil { + q = append(q, node.Right) + } + } + } + return false +} \ No newline at end of file diff --git a/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution2.java b/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution2.java new file mode 100644 index 0000000000000..61be2b9a63db0 --- /dev/null +++ b/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution2.java @@ -0,0 +1,38 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean findTarget(TreeNode root, int k) { + Deque q = new ArrayDeque<>(); + q.offer(root); + Set vis = new HashSet<>(); + while (!q.isEmpty()) { + for (int n = q.size(); n > 0; --n) { + TreeNode node = q.poll(); + if (vis.contains(k - node.val)) { + return true; + } + vis.add(node.val); + if (node.left != null) { + q.offer(node.left); + } + if (node.right != null) { + q.offer(node.right); + } + } + } + return false; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution2.py b/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution2.py new file mode 100644 index 0000000000000..d46f1256014e4 --- /dev/null +++ b/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution2.py @@ -0,0 +1,21 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def findTarget(self, root: Optional[TreeNode], k: int) -> bool: + q = deque([root]) + vis = set() + while q: + for _ in range(len(q)): + node = q.popleft() + if k - node.val in vis: + return True + vis.add(node.val) + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + return False diff --git a/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution2.ts b/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution2.ts new file mode 100644 index 0000000000000..1fdd9a16fee1c --- /dev/null +++ b/solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution2.ts @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function findTarget(root: TreeNode | null, k: number): boolean { + const q = [root]; + const vis = new Set(); + while (q.length) { + for (let n = q.length; n; --n) { + const { val, left, right } = q.shift(); + if (vis.has(k - val)) { + return true; + } + vis.add(val); + left && q.push(left); + right && q.push(right); + } + } + return false; +} diff --git a/solution/0600-0699/0654.Maximum Binary Tree/Solution.c b/solution/0600-0699/0654.Maximum Binary Tree/Solution.c index bbfdab7644347..2bb1ed3ca0f9c 100644 --- a/solution/0600-0699/0654.Maximum Binary Tree/Solution.c +++ b/solution/0600-0699/0654.Maximum Binary Tree/Solution.c @@ -28,4 +28,4 @@ struct TreeNode* construct(int* nums, int start, int end) { struct TreeNode* constructMaximumBinaryTree(int* nums, int numsSize) { return construct(nums, 0, numsSize); -} +} \ No newline at end of file diff --git a/solution/0600-0699/0654.Maximum Binary Tree/Solution2.cpp b/solution/0600-0699/0654.Maximum Binary Tree/Solution2.cpp new file mode 100644 index 0000000000000..155995d899d18 --- /dev/null +++ b/solution/0600-0699/0654.Maximum Binary Tree/Solution2.cpp @@ -0,0 +1,82 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Node { +public: + int l, r, v; +}; + +class SegmentTree { +public: + vector tr; + vector nums; + + SegmentTree(vector& nums) { + this->nums = nums; + int n = nums.size(); + tr.resize(n << 2); + for (int i = 0; i < tr.size(); ++i) tr[i] = new Node(); + build(1, 1, n); + } + + void build(int u, int l, int r) { + tr[u]->l = l; + tr[u]->r = r; + if (l == r) { + tr[u]->v = nums[l - 1]; + return; + } + int mid = (l + r) >> 1; + build(u << 1, l, mid); + build(u << 1 | 1, mid + 1, r); + pushup(u); + } + + int query(int u, int l, int r) { + if (tr[u]->l >= l && tr[u]->r <= r) return tr[u]->v; + int mid = (tr[u]->l + tr[u]->r) >> 1; + int v = 0; + if (l <= mid) v = query(u << 1, l, r); + if (r > mid) v = max(v, query(u << 1 | 1, l, r)); + return v; + } + + void pushup(int u) { + tr[u]->v = max(tr[u << 1]->v, tr[u << 1 | 1]->v); + } +}; + +class Solution { +public: + SegmentTree* tree; + vector nums; + vector d; + + TreeNode* constructMaximumBinaryTree(vector& nums) { + tree = new SegmentTree(nums); + this->nums = nums; + d.assign(1010, 0); + int n = nums.size(); + for (int i = 0; i < n; ++i) d[nums[i]] = i + 1; + return dfs(1, nums.size()); + } + + TreeNode* dfs(int l, int r) { + if (l > r) { + return nullptr; + } + int val = tree->query(1, l, r); + TreeNode* root = new TreeNode(val); + root->left = dfs(l, d[val] - 1); + root->right = dfs(d[val] + 1, r); + return root; + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0654.Maximum Binary Tree/Solution2.go b/solution/0600-0699/0654.Maximum Binary Tree/Solution2.go new file mode 100644 index 0000000000000..bd36da70ab356 --- /dev/null +++ b/solution/0600-0699/0654.Maximum Binary Tree/Solution2.go @@ -0,0 +1,81 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func constructMaximumBinaryTree(nums []int) *TreeNode { + d := make([]int, 1010) + for i, v := range nums { + d[v] = i + 1 + } + tree := newSegmentTree(nums) + var dfs func(l, r int) *TreeNode + dfs = func(l, r int) *TreeNode { + if l > r { + return nil + } + val := tree.query(1, l, r) + root := &TreeNode{Val: val} + root.Left = dfs(l, d[val]-1) + root.Right = dfs(d[val]+1, r) + return root + } + + return dfs(1, len(nums)) +} + +type node struct { + l int + r int + v int +} + +type segmentTree struct { + nums []int + tr []*node +} + +func newSegmentTree(nums []int) *segmentTree { + n := len(nums) + tr := make([]*node, n<<2) + for i := range tr { + tr[i] = &node{} + } + t := &segmentTree{nums, tr} + t.build(1, 1, n) + return t +} + +func (t *segmentTree) build(u, l, r int) { + t.tr[u].l, t.tr[u].r = l, r + if l == r { + t.tr[u].v = t.nums[l-1] + return + } + mid := (l + r) >> 1 + t.build(u<<1, l, mid) + t.build(u<<1|1, mid+1, r) + t.pushup(u) +} + +func (t *segmentTree) query(u, l, r int) int { + if t.tr[u].l >= l && t.tr[u].r <= r { + return t.tr[u].v + } + mid := (t.tr[u].l + t.tr[u].r) >> 1 + v := 0 + if l <= mid { + v = t.query(u<<1, l, r) + } + if r > mid { + v = max(v, t.query(u<<1|1, l, r)) + } + return v +} + +func (t *segmentTree) pushup(u int) { + t.tr[u].v = max(t.tr[u<<1].v, t.tr[u<<1|1].v) +} \ No newline at end of file diff --git a/solution/0600-0699/0654.Maximum Binary Tree/Solution2.java b/solution/0600-0699/0654.Maximum Binary Tree/Solution2.java new file mode 100644 index 0000000000000..1f68fb7a1b870 --- /dev/null +++ b/solution/0600-0699/0654.Maximum Binary Tree/Solution2.java @@ -0,0 +1,94 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private SegmentTree tree; + private int[] nums; + private static int[] d = new int[1010]; + + public TreeNode constructMaximumBinaryTree(int[] nums) { + int n = nums.length; + this.nums = nums; + tree = new SegmentTree(nums); + for (int i = 0; i < n; ++i) { + d[nums[i]] = i + 1; + } + return dfs(1, n); + } + + private TreeNode dfs(int l, int r) { + if (l > r) { + return null; + } + int val = tree.query(1, l, r); + TreeNode root = new TreeNode(val); + root.left = dfs(l, d[val] - 1); + root.right = dfs(d[val] + 1, r); + return root; + } +} + +class Node { + int l; + int r; + int v; +} + +class SegmentTree { + Node[] tr; + int[] nums; + + public SegmentTree(int[] nums) { + int n = nums.length; + this.nums = nums; + tr = new Node[n << 2]; + for (int i = 0; i < tr.length; ++i) { + tr[i] = new Node(); + } + build(1, 1, n); + } + + private void build(int u, int l, int r) { + tr[u].l = l; + tr[u].r = r; + if (l == r) { + tr[u].v = nums[l - 1]; + return; + } + int mid = (l + r) >> 1; + build(u << 1, l, mid); + build(u << 1 | 1, mid + 1, r); + pushup(u); + } + + public int query(int u, int l, int r) { + if (tr[u].l >= l && tr[u].r <= r) { + return tr[u].v; + } + int mid = (tr[u].l + tr[u].r) >> 1; + int v = 0; + if (l <= mid) { + v = query(u << 1, l, r); + } + if (r > mid) { + v = Math.max(v, query(u << 1 | 1, l, r)); + } + return v; + } + + private void pushup(int u) { + tr[u].v = Math.max(tr[u << 1].v, tr[u << 1 | 1].v); + } +} \ No newline at end of file diff --git a/solution/0600-0699/0654.Maximum Binary Tree/Solution2.py b/solution/0600-0699/0654.Maximum Binary Tree/Solution2.py new file mode 100644 index 0000000000000..601f6177fadf0 --- /dev/null +++ b/solution/0600-0699/0654.Maximum Binary Tree/Solution2.py @@ -0,0 +1,59 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]: + def dfs(l, r): + if l > r: + return None + val = tree.query(1, l, r) + root = TreeNode(val) + root.left = dfs(l, d[val] - 1) + root.right = dfs(d[val] + 1, r) + return root + + d = {v: i for i, v in enumerate(nums, 1)} + tree = SegmentTree(nums) + return dfs(1, len(nums)) + + +class Node: + def __init__(self): + self.l = 0 + self.r = 0 + self.v = 0 + + +class SegmentTree: + def __init__(self, nums): + self.nums = nums + n = len(nums) + self.tr = [Node() for _ in range(n << 2)] + self.build(1, 1, n) + + def build(self, u, l, r): + self.tr[u].l, self.tr[u].r = l, r + if l == r: + self.tr[u].v = self.nums[l - 1] + return + mid = (l + r) >> 1 + self.build(u << 1, l, mid) + self.build(u << 1 | 1, mid + 1, r) + self.pushup(u) + + def query(self, u, l, r): + if self.tr[u].l >= l and self.tr[u].r <= r: + return self.tr[u].v + mid = (self.tr[u].l + self.tr[u].r) >> 1 + v = 0 + if l <= mid: + v = max(v, self.query(u << 1, l, r)) + if r > mid: + v = max(v, self.query(u << 1 | 1, l, r)) + return v + + def pushup(self, u): + self.tr[u].v = max(self.tr[u << 1].v, self.tr[u << 1 | 1].v) diff --git a/solution/0600-0699/0654.Maximum Binary Tree/Solution3.cpp b/solution/0600-0699/0654.Maximum Binary Tree/Solution3.cpp new file mode 100644 index 0000000000000..4a6ce489c6e25 --- /dev/null +++ b/solution/0600-0699/0654.Maximum Binary Tree/Solution3.cpp @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* constructMaximumBinaryTree(vector& nums) { + stack stk; + for (int v : nums) { + TreeNode* node = new TreeNode(v); + TreeNode* last = nullptr; + while (!stk.empty() && stk.top()->val < v) { + last = stk.top(); + stk.pop(); + } + node->left = last; + if (!stk.empty()) { + stk.top()->right = node; + } + stk.push(node); + } + while (stk.size() > 1) { + stk.pop(); + } + return stk.top(); + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0654.Maximum Binary Tree/Solution3.go b/solution/0600-0699/0654.Maximum Binary Tree/Solution3.go new file mode 100644 index 0000000000000..1ec737d1d24e1 --- /dev/null +++ b/solution/0600-0699/0654.Maximum Binary Tree/Solution3.go @@ -0,0 +1,25 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func constructMaximumBinaryTree(nums []int) *TreeNode { + stk := []*TreeNode{} + for _, v := range nums { + node := &TreeNode{Val: v} + var last *TreeNode + for len(stk) > 0 && stk[len(stk)-1].Val < v { + last = stk[len(stk)-1] + stk = stk[:len(stk)-1] + } + node.Left = last + if len(stk) > 0 { + stk[len(stk)-1].Right = node + } + stk = append(stk, node) + } + return stk[0] +} \ No newline at end of file diff --git a/solution/0600-0699/0654.Maximum Binary Tree/Solution3.java b/solution/0600-0699/0654.Maximum Binary Tree/Solution3.java new file mode 100644 index 0000000000000..6026ff005af2a --- /dev/null +++ b/solution/0600-0699/0654.Maximum Binary Tree/Solution3.java @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode constructMaximumBinaryTree(int[] nums) { + Deque stk = new ArrayDeque<>(); + for (int v : nums) { + TreeNode node = new TreeNode(v); + TreeNode last = null; + while (!stk.isEmpty() && stk.peek().val < v) { + last = stk.pop(); + } + node.left = last; + if (!stk.isEmpty()) { + stk.peek().right = node; + } + stk.push(node); + } + return stk.getLast(); + } +} \ No newline at end of file diff --git a/solution/0600-0699/0654.Maximum Binary Tree/Solution3.py b/solution/0600-0699/0654.Maximum Binary Tree/Solution3.py new file mode 100644 index 0000000000000..afe6d9f65b1f9 --- /dev/null +++ b/solution/0600-0699/0654.Maximum Binary Tree/Solution3.py @@ -0,0 +1,19 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]: + stk = [] + for v in nums: + node = TreeNode(v) + last = None + while stk and stk[-1].val < v: + last = stk.pop() + node.left = last + if stk: + stk[-1].right = node + stk.append(node) + return stk[0] diff --git a/solution/0600-0699/0655.Print Binary Tree/Solution2.cpp b/solution/0600-0699/0655.Print Binary Tree/Solution2.cpp new file mode 100644 index 0000000000000..a27569d57bfa6 --- /dev/null +++ b/solution/0600-0699/0655.Print Binary Tree/Solution2.cpp @@ -0,0 +1,46 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> printTree(TreeNode* root) { + int h = height(root); + int m = h + 1, n = (1 << (h + 1)) - 1; + vector> ans(m, vector(n, "")); + queue> q; + q.push({root, 0, (n - 1) / 2}); + while (!q.empty()) { + auto p = q.front(); + q.pop(); + root = get<0>(p); + int r = get<1>(p), c = get<2>(p); + ans[r][c] = to_string(root->val); + if (root->left) q.push({root->left, r + 1, c - pow(2, h - r - 1)}); + if (root->right) q.push({root->right, r + 1, c + pow(2, h - r - 1)}); + } + return ans; + } + + int height(TreeNode* root) { + int h = -1; + queue q{{root}}; + while (!q.empty()) { + ++h; + for (int n = q.size(); n; --n) { + root = q.front(); + q.pop(); + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } + } + return h; + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0655.Print Binary Tree/Solution2.go b/solution/0600-0699/0655.Print Binary Tree/Solution2.go new file mode 100644 index 0000000000000..7d630db880a55 --- /dev/null +++ b/solution/0600-0699/0655.Print Binary Tree/Solution2.go @@ -0,0 +1,59 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func printTree(root *TreeNode) [][]string { + h := height(root) + m, n := h+1, (1<<(h+1))-1 + ans := make([][]string, m) + for i := range ans { + ans[i] = make([]string, n) + for j := range ans[i] { + ans[i][j] = "" + } + } + q := []tuple{tuple{root, 0, (n - 1) / 2}} + for len(q) > 0 { + p := q[0] + q = q[1:] + root := p.node + r, c := p.r, p.c + ans[r][c] = strconv.Itoa(root.Val) + if root.Left != nil { + q = append(q, tuple{root.Left, r + 1, c - int(math.Pow(float64(2), float64(h-r-1)))}) + } + if root.Right != nil { + q = append(q, tuple{root.Right, r + 1, c + int(math.Pow(float64(2), float64(h-r-1)))}) + } + } + return ans +} + +func height(root *TreeNode) int { + h := -1 + q := []*TreeNode{root} + for len(q) > 0 { + h++ + for n := len(q); n > 0; n-- { + root := q[0] + q = q[1:] + if root.Left != nil { + q = append(q, root.Left) + } + if root.Right != nil { + q = append(q, root.Right) + } + } + } + return h +} + +type tuple struct { + node *TreeNode + r int + c int +} \ No newline at end of file diff --git a/solution/0600-0699/0655.Print Binary Tree/Solution2.java b/solution/0600-0699/0655.Print Binary Tree/Solution2.java new file mode 100644 index 0000000000000..70dcfdc1eea23 --- /dev/null +++ b/solution/0600-0699/0655.Print Binary Tree/Solution2.java @@ -0,0 +1,75 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List> printTree(TreeNode root) { + int h = height(root); + int m = h + 1, n = (1 << (h + 1)) - 1; + String[][] res = new String[m][n]; + for (int i = 0; i < m; ++i) { + Arrays.fill(res[i], ""); + } + Deque q = new ArrayDeque<>(); + q.offer(new Tuple(root, 0, (n - 1) / 2)); + while (!q.isEmpty()) { + Tuple p = q.pollFirst(); + root = p.node; + int r = p.r, c = p.c; + res[r][c] = String.valueOf(root.val); + if (root.left != null) { + q.offer(new Tuple(root.left, r + 1, c - (1 << (h - r - 1)))); + } + if (root.right != null) { + q.offer(new Tuple(root.right, r + 1, c + (1 << (h - r - 1)))); + } + } + List> ans = new ArrayList<>(); + for (String[] t : res) { + ans.add(Arrays.asList(t)); + } + return ans; + } + + private int height(TreeNode root) { + Deque q = new ArrayDeque<>(); + q.offer(root); + int h = -1; + while (!q.isEmpty()) { + ++h; + for (int n = q.size(); n > 0; --n) { + root = q.pollFirst(); + if (root.left != null) { + q.offer(root.left); + } + if (root.right != null) { + q.offer(root.right); + } + } + } + return h; + } +} + +class Tuple { + TreeNode node; + int r; + int c; + + public Tuple(TreeNode node, int r, int c) { + this.node = node; + this.r = r; + this.c = c; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0655.Print Binary Tree/Solution2.py b/solution/0600-0699/0655.Print Binary Tree/Solution2.py new file mode 100644 index 0000000000000..2c05523f07596 --- /dev/null +++ b/solution/0600-0699/0655.Print Binary Tree/Solution2.py @@ -0,0 +1,33 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def printTree(self, root: Optional[TreeNode]) -> List[List[str]]: + def height(root): + q = deque([root]) + h = -1 + while q: + h += 1 + for _ in range(len(q)): + root = q.popleft() + if root.left: + q.append(root.left) + if root.right: + q.append(root.right) + return h + + h = height(root) + m, n = h + 1, 2 ** (h + 1) - 1 + ans = [[""] * n for _ in range(m)] + q = deque([(root, 0, (n - 1) // 2)]) + while q: + node, r, c = q.popleft() + ans[r][c] = str(node.val) + if node.left: + q.append((node.left, r + 1, c - 2 ** (h - r - 1))) + if node.right: + q.append((node.right, r + 1, c + 2 ** (h - r - 1))) + return ans diff --git a/solution/0600-0699/0658.Find K Closest Elements/Solution.cpp b/solution/0600-0699/0658.Find K Closest Elements/Solution.cpp index e7d9ca4ab0ab8..85b29971e193d 100644 --- a/solution/0600-0699/0658.Find K Closest Elements/Solution.cpp +++ b/solution/0600-0699/0658.Find K Closest Elements/Solution.cpp @@ -1,14 +1,17 @@ -class Solution { -public: - vector findClosestElements(vector& arr, int k, int x) { - int left = 0, right = arr.size() - k; - while (left < right) { - int mid = (left + right) >> 1; - if (x - arr[mid] <= arr[mid + k] - x) - right = mid; - else - left = mid + 1; - } - return vector(arr.begin() + left, arr.begin() + left + k); - } +int target; + +class Solution { +public: + static bool cmp(int& a, int& b) { + int v = abs(a - target) - abs(b - target); + return v == 0 ? a < b : v < 0; + } + + vector findClosestElements(vector& arr, int k, int x) { + target = x; + sort(arr.begin(), arr.end(), cmp); + vector ans(arr.begin(), arr.begin() + k); + sort(ans.begin(), ans.end()); + return ans; + } }; \ No newline at end of file diff --git a/solution/0600-0699/0658.Find K Closest Elements/Solution.go b/solution/0600-0699/0658.Find K Closest Elements/Solution.go index 6c0b4af7cb2a6..f947f3c130c91 100644 --- a/solution/0600-0699/0658.Find K Closest Elements/Solution.go +++ b/solution/0600-0699/0658.Find K Closest Elements/Solution.go @@ -1,12 +1,19 @@ func findClosestElements(arr []int, k int, x int) []int { - left, right := 0, len(arr)-k - for left < right { - mid := (left + right) >> 1 - if x-arr[mid] <= arr[mid+k]-x { - right = mid - } else { - left = mid + 1 + sort.Slice(arr, func(i, j int) bool { + v := abs(arr[i]-x) - abs(arr[j]-x) + if v == 0 { + return arr[i] < arr[j] } + return v < 0 + }) + ans := arr[:k] + sort.Ints(ans) + return ans +} + +func abs(x int) int { + if x >= 0 { + return x } - return arr[left : left+k] + return -x } \ No newline at end of file diff --git a/solution/0600-0699/0658.Find K Closest Elements/Solution.java b/solution/0600-0699/0658.Find K Closest Elements/Solution.java index a67992b3bd1bb..52d59a5ee13ae 100644 --- a/solution/0600-0699/0658.Find K Closest Elements/Solution.java +++ b/solution/0600-0699/0658.Find K Closest Elements/Solution.java @@ -1,19 +1,14 @@ -class Solution { - public List findClosestElements(int[] arr, int k, int x) { - int left = 0; - int right = arr.length - k; - while (left < right) { - int mid = (left + right) >> 1; - if (x - arr[mid] <= arr[mid + k] - x) { - right = mid; - } else { - left = mid + 1; - } - } - List ans = new ArrayList<>(); - for (int i = left; i < left + k; ++i) { - ans.add(arr[i]); - } - return ans; - } +class Solution { + public List findClosestElements(int[] arr, int k, int x) { + List ans = Arrays.stream(arr) + .boxed() + .sorted((a, b) -> { + int v = Math.abs(a - x) - Math.abs(b - x); + return v == 0 ? a - b : v; + }) + .collect(Collectors.toList()); + ans = ans.subList(0, k); + Collections.sort(ans); + return ans; + } } \ No newline at end of file diff --git a/solution/0600-0699/0658.Find K Closest Elements/Solution.py b/solution/0600-0699/0658.Find K Closest Elements/Solution.py index 79b855bb310a7..5738a7545ec7c 100644 --- a/solution/0600-0699/0658.Find K Closest Elements/Solution.py +++ b/solution/0600-0699/0658.Find K Closest Elements/Solution.py @@ -1,10 +1,4 @@ -class Solution: - def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: - left, right = 0, len(arr) - k - while left < right: - mid = (left + right) >> 1 - if x - arr[mid] <= arr[mid + k] - x: - right = mid - else: - left = mid + 1 - return arr[left : left + k] +class Solution: + def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: + arr.sort(key=lambda v: abs(v - x)) + return sorted(arr[:k]) diff --git a/solution/0600-0699/0658.Find K Closest Elements/Solution.rs b/solution/0600-0699/0658.Find K Closest Elements/Solution.rs index 30b487dc83605..cdc920f848f6c 100644 --- a/solution/0600-0699/0658.Find K Closest Elements/Solution.rs +++ b/solution/0600-0699/0658.Find K Closest Elements/Solution.rs @@ -1,17 +1,15 @@ impl Solution { pub fn find_closest_elements(arr: Vec, k: i32, x: i32) -> Vec { - let k = k as usize; let n = arr.len(); - let mut left = 0; - let mut right = n - k; - while left < right { - let mid = left + (right - left) / 2; - if x - arr[mid] > arr[mid + k] - x { - left = mid + 1; + let mut l = 0; + let mut r = n; + while r - l != (k as usize) { + if x - arr[l] <= arr[r - 1] - x { + r -= 1; } else { - right = mid; + l += 1; } } - arr[left..left + k].to_vec() + arr[l..r].to_vec() } } diff --git a/solution/0600-0699/0658.Find K Closest Elements/Solution.ts b/solution/0600-0699/0658.Find K Closest Elements/Solution.ts index 547a703ed4776..65853a926ba1e 100644 --- a/solution/0600-0699/0658.Find K Closest Elements/Solution.ts +++ b/solution/0600-0699/0658.Find K Closest Elements/Solution.ts @@ -1,13 +1,12 @@ function findClosestElements(arr: number[], k: number, x: number): number[] { - let left = 0; - let right = arr.length - k; - while (left < right) { - const mid = (left + right) >> 1; - if (x - arr[mid] <= arr[mid + k] - x) { - right = mid; + let l = 0; + let r = arr.length; + while (r - l > k) { + if (x - arr[l] <= arr[r - 1] - x) { + --r; } else { - left = mid + 1; + ++l; } } - return arr.slice(left, left + k); + return arr.slice(l, r); } diff --git a/solution/0600-0699/0658.Find K Closest Elements/Solution2.cpp b/solution/0600-0699/0658.Find K Closest Elements/Solution2.cpp new file mode 100644 index 0000000000000..8db0306666952 --- /dev/null +++ b/solution/0600-0699/0658.Find K Closest Elements/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + vector findClosestElements(vector& arr, int k, int x) { + int l = 0, r = arr.size(); + while (r - l > k) { + if (x - arr[l] <= arr[r - 1] - x) { + --r; + } else { + ++l; + } + } + return vector(arr.begin() + l, arr.begin() + r); + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0658.Find K Closest Elements/Solution2.go b/solution/0600-0699/0658.Find K Closest Elements/Solution2.go new file mode 100644 index 0000000000000..3ea03fea33d24 --- /dev/null +++ b/solution/0600-0699/0658.Find K Closest Elements/Solution2.go @@ -0,0 +1,11 @@ +func findClosestElements(arr []int, k int, x int) []int { + l, r := 0, len(arr) + for r-l > k { + if x-arr[l] <= arr[r-1]-x { + r-- + } else { + l++ + } + } + return arr[l:r] +} \ No newline at end of file diff --git a/solution/0600-0699/0658.Find K Closest Elements/Solution2.java b/solution/0600-0699/0658.Find K Closest Elements/Solution2.java new file mode 100644 index 0000000000000..95373db27d2d4 --- /dev/null +++ b/solution/0600-0699/0658.Find K Closest Elements/Solution2.java @@ -0,0 +1,17 @@ +class Solution { + public List findClosestElements(int[] arr, int k, int x) { + int l = 0, r = arr.length; + while (r - l > k) { + if (x - arr[l] <= arr[r - 1] - x) { + --r; + } else { + ++l; + } + } + List ans = new ArrayList<>(); + for (int i = l; i < r; ++i) { + ans.add(arr[i]); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0658.Find K Closest Elements/Solution2.py b/solution/0600-0699/0658.Find K Closest Elements/Solution2.py new file mode 100644 index 0000000000000..72398c7443d36 --- /dev/null +++ b/solution/0600-0699/0658.Find K Closest Elements/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: + l, r = 0, len(arr) + while r - l > k: + if x - arr[l] <= arr[r - 1] - x: + r -= 1 + else: + l += 1 + return arr[l:r] diff --git a/solution/0600-0699/0658.Find K Closest Elements/Solution2.rs b/solution/0600-0699/0658.Find K Closest Elements/Solution2.rs new file mode 100644 index 0000000000000..30b487dc83605 --- /dev/null +++ b/solution/0600-0699/0658.Find K Closest Elements/Solution2.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn find_closest_elements(arr: Vec, k: i32, x: i32) -> Vec { + let k = k as usize; + let n = arr.len(); + let mut left = 0; + let mut right = n - k; + while left < right { + let mid = left + (right - left) / 2; + if x - arr[mid] > arr[mid + k] - x { + left = mid + 1; + } else { + right = mid; + } + } + arr[left..left + k].to_vec() + } +} diff --git a/solution/0600-0699/0658.Find K Closest Elements/Solution2.ts b/solution/0600-0699/0658.Find K Closest Elements/Solution2.ts new file mode 100644 index 0000000000000..547a703ed4776 --- /dev/null +++ b/solution/0600-0699/0658.Find K Closest Elements/Solution2.ts @@ -0,0 +1,13 @@ +function findClosestElements(arr: number[], k: number, x: number): number[] { + let left = 0; + let right = arr.length - k; + while (left < right) { + const mid = (left + right) >> 1; + if (x - arr[mid] <= arr[mid + k] - x) { + right = mid; + } else { + left = mid + 1; + } + } + return arr.slice(left, left + k); +} diff --git a/solution/0600-0699/0658.Find K Closest Elements/Solution3.cpp b/solution/0600-0699/0658.Find K Closest Elements/Solution3.cpp new file mode 100644 index 0000000000000..4e3fbe07cf679 --- /dev/null +++ b/solution/0600-0699/0658.Find K Closest Elements/Solution3.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + vector findClosestElements(vector& arr, int k, int x) { + int left = 0, right = arr.size() - k; + while (left < right) { + int mid = (left + right) >> 1; + if (x - arr[mid] <= arr[mid + k] - x) + right = mid; + else + left = mid + 1; + } + return vector(arr.begin() + left, arr.begin() + left + k); + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0658.Find K Closest Elements/Solution3.go b/solution/0600-0699/0658.Find K Closest Elements/Solution3.go new file mode 100644 index 0000000000000..6c0b4af7cb2a6 --- /dev/null +++ b/solution/0600-0699/0658.Find K Closest Elements/Solution3.go @@ -0,0 +1,12 @@ +func findClosestElements(arr []int, k int, x int) []int { + left, right := 0, len(arr)-k + for left < right { + mid := (left + right) >> 1 + if x-arr[mid] <= arr[mid+k]-x { + right = mid + } else { + left = mid + 1 + } + } + return arr[left : left+k] +} \ No newline at end of file diff --git a/solution/0600-0699/0658.Find K Closest Elements/Solution3.java b/solution/0600-0699/0658.Find K Closest Elements/Solution3.java new file mode 100644 index 0000000000000..0ed8f1166aa7e --- /dev/null +++ b/solution/0600-0699/0658.Find K Closest Elements/Solution3.java @@ -0,0 +1,19 @@ +class Solution { + public List findClosestElements(int[] arr, int k, int x) { + int left = 0; + int right = arr.length - k; + while (left < right) { + int mid = (left + right) >> 1; + if (x - arr[mid] <= arr[mid + k] - x) { + right = mid; + } else { + left = mid + 1; + } + } + List ans = new ArrayList<>(); + for (int i = left; i < left + k; ++i) { + ans.add(arr[i]); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0658.Find K Closest Elements/Solution3.py b/solution/0600-0699/0658.Find K Closest Elements/Solution3.py new file mode 100644 index 0000000000000..b74e3a3fa8573 --- /dev/null +++ b/solution/0600-0699/0658.Find K Closest Elements/Solution3.py @@ -0,0 +1,10 @@ +class Solution: + def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: + left, right = 0, len(arr) - k + while left < right: + mid = (left + right) >> 1 + if x - arr[mid] <= arr[mid + k] - x: + right = mid + else: + left = mid + 1 + return arr[left : left + k] diff --git a/solution/0600-0699/0661.Image Smoother/Solution.cpp b/solution/0600-0699/0661.Image Smoother/Solution.cpp index a0a552ba38375..958cde2f9a9d4 100644 --- a/solution/0600-0699/0661.Image Smoother/Solution.cpp +++ b/solution/0600-0699/0661.Image Smoother/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - vector> imageSmoother(vector>& img) { - int m = img.size(), n = img[0].size(); - vector> ans(m, vector(n)); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - int s = 0, cnt = 0; - for (int x = i - 1; x <= i + 1; ++x) { - for (int y = j - 1; y <= j + 1; ++y) { - if (x < 0 || x >= m || y < 0 || y >= n) continue; - ++cnt; - s += img[x][y]; - } - } - ans[i][j] = s / cnt; - } - } - return ans; - } +class Solution { +public: + vector> imageSmoother(vector>& img) { + int m = img.size(), n = img[0].size(); + vector> ans(m, vector(n)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + int s = 0, cnt = 0; + for (int x = i - 1; x <= i + 1; ++x) { + for (int y = j - 1; y <= j + 1; ++y) { + if (x < 0 || x >= m || y < 0 || y >= n) continue; + ++cnt; + s += img[x][y]; + } + } + ans[i][j] = s / cnt; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0600-0699/0661.Image Smoother/Solution.java b/solution/0600-0699/0661.Image Smoother/Solution.java index 04508bbc00af1..948a2caa0fa00 100644 --- a/solution/0600-0699/0661.Image Smoother/Solution.java +++ b/solution/0600-0699/0661.Image Smoother/Solution.java @@ -1,23 +1,23 @@ -class Solution { - public int[][] imageSmoother(int[][] img) { - int m = img.length; - int n = img[0].length; - int[][] ans = new int[m][n]; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - int s = 0; - int cnt = 0; - for (int x = i - 1; x <= i + 1; ++x) { - for (int y = j - 1; y <= j + 1; ++y) { - if (x >= 0 && x < m && y >= 0 && y < n) { - ++cnt; - s += img[x][y]; - } - } - } - ans[i][j] = s / cnt; - } - } - return ans; - } +class Solution { + public int[][] imageSmoother(int[][] img) { + int m = img.length; + int n = img[0].length; + int[][] ans = new int[m][n]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + int s = 0; + int cnt = 0; + for (int x = i - 1; x <= i + 1; ++x) { + for (int y = j - 1; y <= j + 1; ++y) { + if (x >= 0 && x < m && y >= 0 && y < n) { + ++cnt; + s += img[x][y]; + } + } + } + ans[i][j] = s / cnt; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0600-0699/0661.Image Smoother/Solution.py b/solution/0600-0699/0661.Image Smoother/Solution.py index 9772cbb543703..9bbc1623db2c0 100644 --- a/solution/0600-0699/0661.Image Smoother/Solution.py +++ b/solution/0600-0699/0661.Image Smoother/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def imageSmoother(self, img: List[List[int]]) -> List[List[int]]: - m, n = len(img), len(img[0]) - ans = [[0] * n for _ in range(m)] - for i in range(m): - for j in range(n): - s = cnt = 0 - for x in range(i - 1, i + 2): - for y in range(j - 1, j + 2): - if 0 <= x < m and 0 <= y < n: - cnt += 1 - s += img[x][y] - ans[i][j] = s // cnt - return ans +class Solution: + def imageSmoother(self, img: List[List[int]]) -> List[List[int]]: + m, n = len(img), len(img[0]) + ans = [[0] * n for _ in range(m)] + for i in range(m): + for j in range(n): + s = cnt = 0 + for x in range(i - 1, i + 2): + for y in range(j - 1, j + 2): + if 0 <= x < m and 0 <= y < n: + cnt += 1 + s += img[x][y] + ans[i][j] = s // cnt + return ans diff --git a/solution/0600-0699/0662.Maximum Width of Binary Tree/Solution2.cpp b/solution/0600-0699/0662.Maximum Width of Binary Tree/Solution2.cpp new file mode 100644 index 0000000000000..343de6878c847 --- /dev/null +++ b/solution/0600-0699/0662.Maximum Width of Binary Tree/Solution2.cpp @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector t; + int ans = 1; + using ull = unsigned long long; + + int widthOfBinaryTree(TreeNode* root) { + dfs(root, 0, 1); + return ans; + } + + void dfs(TreeNode* root, int depth, ull i) { + if (!root) return; + if (t.size() == depth) { + t.push_back(i); + } else { + ans = max(ans, (int) (i - t[depth] + 1)); + } + dfs(root->left, depth + 1, i << 1); + dfs(root->right, depth + 1, i << 1 | 1); + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0662.Maximum Width of Binary Tree/Solution2.go b/solution/0600-0699/0662.Maximum Width of Binary Tree/Solution2.go new file mode 100644 index 0000000000000..13daec717dfb3 --- /dev/null +++ b/solution/0600-0699/0662.Maximum Width of Binary Tree/Solution2.go @@ -0,0 +1,27 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func widthOfBinaryTree(root *TreeNode) int { + ans := 1 + t := []int{} + var dfs func(root *TreeNode, depth, i int) + dfs = func(root *TreeNode, depth, i int) { + if root == nil { + return + } + if len(t) == depth { + t = append(t, i) + } else { + ans = max(ans, i-t[depth]+1) + } + dfs(root.Left, depth+1, i<<1) + dfs(root.Right, depth+1, i<<1|1) + } + dfs(root, 0, 1) + return ans +} \ No newline at end of file diff --git a/solution/0600-0699/0662.Maximum Width of Binary Tree/Solution2.java b/solution/0600-0699/0662.Maximum Width of Binary Tree/Solution2.java new file mode 100644 index 0000000000000..02d7be33e5f06 --- /dev/null +++ b/solution/0600-0699/0662.Maximum Width of Binary Tree/Solution2.java @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int ans = 1; + private List t = new ArrayList<>(); + + public int widthOfBinaryTree(TreeNode root) { + dfs(root, 0, 1); + return ans; + } + + private void dfs(TreeNode root, int depth, int i) { + if (root == null) { + return; + } + if (t.size() == depth) { + t.add(i); + } else { + ans = Math.max(ans, i - t.get(depth) + 1); + } + dfs(root.left, depth + 1, i << 1); + dfs(root.right, depth + 1, i << 1 | 1); + } +} \ No newline at end of file diff --git a/solution/0600-0699/0662.Maximum Width of Binary Tree/Solution2.py b/solution/0600-0699/0662.Maximum Width of Binary Tree/Solution2.py new file mode 100644 index 0000000000000..8913b0a70e320 --- /dev/null +++ b/solution/0600-0699/0662.Maximum Width of Binary Tree/Solution2.py @@ -0,0 +1,23 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int: + def dfs(root, depth, i): + if root is None: + return + if len(t) == depth: + t.append(i) + else: + nonlocal ans + ans = max(ans, i - t[depth] + 1) + dfs(root.left, depth + 1, i << 1) + dfs(root.right, depth + 1, i << 1 | 1) + + ans = 1 + t = [] + dfs(root, 0, 1) + return ans diff --git a/solution/0600-0699/0669.Trim a Binary Search Tree/Solution.c b/solution/0600-0699/0669.Trim a Binary Search Tree/Solution.c index 4a21b57ac856e..c26180d6726e5 100644 --- a/solution/0600-0699/0669.Trim a Binary Search Tree/Solution.c +++ b/solution/0600-0699/0669.Trim a Binary Search Tree/Solution.c @@ -20,4 +20,4 @@ struct TreeNode* trimBST(struct TreeNode* root, int low, int high) { root->left = trimBST(root->left, low, high); root->right = trimBST(root->right, low, high); return root; -} +} \ No newline at end of file diff --git a/solution/0600-0699/0669.Trim a Binary Search Tree/Solution2.cpp b/solution/0600-0699/0669.Trim a Binary Search Tree/Solution2.cpp new file mode 100644 index 0000000000000..2393341eaf3e0 --- /dev/null +++ b/solution/0600-0699/0669.Trim a Binary Search Tree/Solution2.cpp @@ -0,0 +1,39 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* trimBST(TreeNode* root, int low, int high) { + while (root && (root->val < low || root->val > high)) { + root = root->val < low ? root->right : root->left; + } + if (!root) { + return root; + } + TreeNode* node = root; + while (node->left) { + if (node->left->val < low) { + node->left = node->left->right; + } else { + node = node->left; + } + } + node = root; + while (node->right) { + if (node->right->val > high) { + node->right = node->right->left; + } else { + node = node->right; + } + } + return root; + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0669.Trim a Binary Search Tree/Solution2.go b/solution/0600-0699/0669.Trim a Binary Search Tree/Solution2.go new file mode 100644 index 0000000000000..075c12cc2f73d --- /dev/null +++ b/solution/0600-0699/0669.Trim a Binary Search Tree/Solution2.go @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func trimBST(root *TreeNode, low int, high int) *TreeNode { + for root != nil && (root.Val < low || root.Val > high) { + if root.Val < low { + root = root.Right + } else { + root = root.Left + } + } + if root == nil { + return nil + } + node := root + for node.Left != nil { + if node.Left.Val < low { + node.Left = node.Left.Right + } else { + node = node.Left + } + } + node = root + for node.Right != nil { + if node.Right.Val > high { + node.Right = node.Right.Left + } else { + node = node.Right + } + } + return root +} \ No newline at end of file diff --git a/solution/0600-0699/0669.Trim a Binary Search Tree/Solution2.java b/solution/0600-0699/0669.Trim a Binary Search Tree/Solution2.java new file mode 100644 index 0000000000000..389a5d93bb973 --- /dev/null +++ b/solution/0600-0699/0669.Trim a Binary Search Tree/Solution2.java @@ -0,0 +1,42 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode trimBST(TreeNode root, int low, int high) { + while (root != null && (root.val < low || root.val > high)) { + root = root.val < low ? root.right : root.left; + } + if (root == null) { + return null; + } + TreeNode node = root; + while (node.left != null) { + if (node.left.val < low) { + node.left = node.left.right; + } else { + node = node.left; + } + } + node = root; + while (node.right != null) { + if (node.right.val > high) { + node.right = node.right.left; + } else { + node = node.right; + } + } + return root; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0669.Trim a Binary Search Tree/Solution2.js b/solution/0600-0699/0669.Trim a Binary Search Tree/Solution2.js new file mode 100644 index 0000000000000..d8ba9ec29cafc --- /dev/null +++ b/solution/0600-0699/0669.Trim a Binary Search Tree/Solution2.js @@ -0,0 +1,39 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} low + * @param {number} high + * @return {TreeNode} + */ +var trimBST = function (root, low, high) { + while (root && (root.val < low || root.val > high)) { + root = root.val < low ? root.right : root.left; + } + if (!root) { + return root; + } + let node = root; + while (node.left) { + if (node.left.val < low) { + node.left = node.left.right; + } else { + node = node.left; + } + } + node = root; + while (node.right) { + if (node.right.val > high) { + node.right = node.right.left; + } else { + node = node.right; + } + } + return root; +}; diff --git a/solution/0600-0699/0669.Trim a Binary Search Tree/Solution2.py b/solution/0600-0699/0669.Trim a Binary Search Tree/Solution2.py new file mode 100644 index 0000000000000..d40e499971f3f --- /dev/null +++ b/solution/0600-0699/0669.Trim a Binary Search Tree/Solution2.py @@ -0,0 +1,27 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def trimBST( + self, root: Optional[TreeNode], low: int, high: int + ) -> Optional[TreeNode]: + while root and (root.val < low or root.val > high): + root = root.left if root.val > high else root.right + if root is None: + return None + node = root + while node.left: + if node.left.val < low: + node.left = node.left.right + else: + node = node.left + node = root + while node.right: + if node.right.val > high: + node.right = node.right.left + else: + node = node.right + return root diff --git a/solution/0600-0699/0670.Maximum Swap/Solution.cpp b/solution/0600-0699/0670.Maximum Swap/Solution.cpp index 3c3a737d64cbb..34a63a1176df1 100644 --- a/solution/0600-0699/0670.Maximum Swap/Solution.cpp +++ b/solution/0600-0699/0670.Maximum Swap/Solution.cpp @@ -1,22 +1,22 @@ -class Solution { -public: - int maximumSwap(int num) { - string s = to_string(num); - int n = s.size(); - vector d(n); - iota(d.begin(), d.end(), 0); - for (int i = n - 2; ~i; --i) { - if (s[i] <= s[d[i + 1]]) { - d[i] = d[i + 1]; - } - } - for (int i = 0; i < n; ++i) { - int j = d[i]; - if (s[i] < s[j]) { - swap(s[i], s[j]); - break; - } - } - return stoi(s); - } +class Solution { +public: + int maximumSwap(int num) { + string s = to_string(num); + int n = s.size(); + vector d(n); + iota(d.begin(), d.end(), 0); + for (int i = n - 2; ~i; --i) { + if (s[i] <= s[d[i + 1]]) { + d[i] = d[i + 1]; + } + } + for (int i = 0; i < n; ++i) { + int j = d[i]; + if (s[i] < s[j]) { + swap(s[i], s[j]); + break; + } + } + return stoi(s); + } }; \ No newline at end of file diff --git a/solution/0600-0699/0670.Maximum Swap/Solution.java b/solution/0600-0699/0670.Maximum Swap/Solution.java index 9efdfc9d6cb2e..94b3004c81ac2 100644 --- a/solution/0600-0699/0670.Maximum Swap/Solution.java +++ b/solution/0600-0699/0670.Maximum Swap/Solution.java @@ -1,25 +1,25 @@ -class Solution { - public int maximumSwap(int num) { - char[] s = String.valueOf(num).toCharArray(); - int n = s.length; - int[] d = new int[n]; - for (int i = 0; i < n; ++i) { - d[i] = i; - } - for (int i = n - 2; i >= 0; --i) { - if (s[i] <= s[d[i + 1]]) { - d[i] = d[i + 1]; - } - } - for (int i = 0; i < n; ++i) { - int j = d[i]; - if (s[i] < s[j]) { - char t = s[i]; - s[i] = s[j]; - s[j] = t; - break; - } - } - return Integer.parseInt(String.valueOf(s)); - } +class Solution { + public int maximumSwap(int num) { + char[] s = String.valueOf(num).toCharArray(); + int n = s.length; + int[] d = new int[n]; + for (int i = 0; i < n; ++i) { + d[i] = i; + } + for (int i = n - 2; i >= 0; --i) { + if (s[i] <= s[d[i + 1]]) { + d[i] = d[i + 1]; + } + } + for (int i = 0; i < n; ++i) { + int j = d[i]; + if (s[i] < s[j]) { + char t = s[i]; + s[i] = s[j]; + s[j] = t; + break; + } + } + return Integer.parseInt(String.valueOf(s)); + } } \ No newline at end of file diff --git a/solution/0600-0699/0670.Maximum Swap/Solution.py b/solution/0600-0699/0670.Maximum Swap/Solution.py index 916d052735e04..3f4db396b101f 100644 --- a/solution/0600-0699/0670.Maximum Swap/Solution.py +++ b/solution/0600-0699/0670.Maximum Swap/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def maximumSwap(self, num: int) -> int: - s = list(str(num)) - n = len(s) - d = list(range(n)) - for i in range(n - 2, -1, -1): - if s[i] <= s[d[i + 1]]: - d[i] = d[i + 1] - for i, j in enumerate(d): - if s[i] < s[j]: - s[i], s[j] = s[j], s[i] - break - return int(''.join(s)) +class Solution: + def maximumSwap(self, num: int) -> int: + s = list(str(num)) + n = len(s) + d = list(range(n)) + for i in range(n - 2, -1, -1): + if s[i] <= s[d[i + 1]]: + d[i] = d[i + 1] + for i, j in enumerate(d): + if s[i] < s[j]: + s[i], s[j] = s[j], s[i] + break + return int(''.join(s)) diff --git a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.cpp b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.cpp index 91cdf2651a142..7f13e002b6d7e 100644 --- a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.cpp +++ b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.cpp @@ -1,56 +1,28 @@ -class BinaryIndexedTree { -private: - int n; - vector c; - vector d; - -public: - BinaryIndexedTree(int n) - : n(n) - , c(n + 1, 0) - , d(n + 1, 0) {} - - void update(int x, int v, int cnt) { - while (x <= n) { - if (c[x] < v) { - c[x] = v; - d[x] = cnt; - } else if (c[x] == v) { - d[x] += cnt; - } - x += x & -x; - } - } - - pair query(int x) { - int v = 0, cnt = 0; - while (x > 0) { - if (c[x] > v) { - v = c[x]; - cnt = d[x]; - } else if (c[x] == v) { - cnt += d[x]; - } - x -= x & -x; - } - return {v, cnt}; - } -}; - -class Solution { -public: - int findNumberOfLIS(vector& nums) { - vector arr = nums; - sort(arr.begin(), arr.end()); - arr.erase(unique(arr.begin(), arr.end()), arr.end()); - int m = arr.size(); - BinaryIndexedTree tree(m); - for (int x : nums) { - auto it = lower_bound(arr.begin(), arr.end(), x); - int i = distance(arr.begin(), it) + 1; - auto [v, cnt] = tree.query(i - 1); - tree.update(i, v + 1, max(cnt, 1)); - } - return tree.query(m).second; - } +class Solution { +public: + int findNumberOfLIS(vector& nums) { + int n = nums.size(); + int mx = 0, ans = 0; + vector f(n, 1); + vector cnt(n, 1); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + if (f[i] < f[j] + 1) { + f[i] = f[j] + 1; + cnt[i] = cnt[j]; + } else if (f[i] == f[j] + 1) { + cnt[i] += cnt[j]; + } + } + } + if (mx < f[i]) { + mx = f[i]; + ans = cnt[i]; + } else if (mx == f[i]) { + ans += cnt[i]; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.go b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.go index 6c13cc584c80d..38e39c0446705 100644 --- a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.go +++ b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.go @@ -1,54 +1,24 @@ -type BinaryIndexedTree struct { - n int - c []int - d []int -} - -func newBinaryIndexedTree(n int) BinaryIndexedTree { - return BinaryIndexedTree{ - n: n, - c: make([]int, n+1), - d: make([]int, n+1), - } -} - -func (bit *BinaryIndexedTree) update(x, v, cnt int) { - for x <= bit.n { - if bit.c[x] < v { - bit.c[x] = v - bit.d[x] = cnt - } else if bit.c[x] == v { - bit.d[x] += cnt +func findNumberOfLIS(nums []int) (ans int) { + n, mx := len(nums), 0 + f := make([]int, n) + cnt := make([]int, n) + for i, x := range nums { + for j, y := range nums[:i] { + if y < x { + if f[i] < f[j]+1 { + f[i] = f[j] + 1 + cnt[i] = cnt[j] + } else if f[i] == f[j]+1 { + cnt[i] += cnt[j] + } + } } - x += x & -x - } -} - -func (bit *BinaryIndexedTree) query(x int) (int, int) { - v, cnt := 0, 0 - for x > 0 { - if bit.c[x] > v { - v = bit.c[x] - cnt = bit.d[x] - } else if bit.c[x] == v { - cnt += bit.d[x] + if mx < f[i] { + mx = f[i] + ans = cnt[i] + } else if mx == f[i] { + ans += cnt[i] } - x -= x & -x - } - return v, cnt -} - -func findNumberOfLIS(nums []int) int { - arr := make([]int, len(nums)) - copy(arr, nums) - sort.Ints(arr) - m := len(arr) - tree := newBinaryIndexedTree(m) - for _, x := range nums { - i := sort.SearchInts(arr, x) + 1 - v, cnt := tree.query(i - 1) - tree.update(i, v+1, max(cnt, 1)) } - _, ans := tree.query(m) - return ans + return } \ No newline at end of file diff --git a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.java b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.java index 5d24cfd431672..e7134b3029709 100644 --- a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.java +++ b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.java @@ -1,55 +1,29 @@ -class BinaryIndexedTree { - private int n; - private int[] c; - private int[] d; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - d = new int[n + 1]; - } - - public void update(int x, int v, int cnt) { - while (x <= n) { - if (c[x] < v) { - c[x] = v; - d[x] = cnt; - } else if (c[x] == v) { - d[x] += cnt; - } - x += x & -x; - } - } - - public int[] query(int x) { - int v = 0, cnt = 0; - while (x > 0) { - if (c[x] > v) { - v = c[x]; - cnt = d[x]; - } else if (c[x] == v) { - cnt += d[x]; - } - x -= x & -x; - } - return new int[] {v, cnt}; - } -} - -public class Solution { - public int findNumberOfLIS(int[] nums) { - // int[] arr = Arrays.stream(nums).distinct().sorted().toArray(); - int[] arr = nums.clone(); - Arrays.sort(arr); - int m = arr.length; - BinaryIndexedTree tree = new BinaryIndexedTree(m); - for (int x : nums) { - int i = Arrays.binarySearch(arr, x) + 1; - int[] t = tree.query(i - 1); - int v = t[0]; - int cnt = t[1]; - tree.update(i, v + 1, Math.max(cnt, 1)); - } - return tree.query(m)[1]; - } +class Solution { + public int findNumberOfLIS(int[] nums) { + int n = nums.length; + int[] f = new int[n]; + int[] cnt = new int[n]; + int mx = 0, ans = 0; + for (int i = 0; i < n; ++i) { + f[i] = 1; + cnt[i] = 1; + for (int j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + if (f[i] < f[j] + 1) { + f[i] = f[j] + 1; + cnt[i] = cnt[j]; + } else if (f[i] == f[j] + 1) { + cnt[i] += cnt[j]; + } + } + } + if (mx < f[i]) { + mx = f[i]; + ans = cnt[i]; + } else if (mx == f[i]) { + ans += cnt[i]; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.py b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.py index 0dafd82c88d78..cc408278b8faa 100644 --- a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.py +++ b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.py @@ -1,39 +1,20 @@ -class BinaryIndexedTree: - __slots__ = ["n", "c", "d"] - - def __init__(self, n): - self.n = n - self.c = [0] * (n + 1) - self.d = [0] * (n + 1) - - def update(self, x, v, cnt): - while x <= self.n: - if self.c[x] < v: - self.c[x] = v - self.d[x] = cnt - elif self.c[x] == v: - self.d[x] += cnt - x += x & -x - - def query(self, x): - v = cnt = 0 - while x: - if self.c[x] > v: - v = self.c[x] - cnt = self.d[x] - elif self.c[x] == v: - cnt += self.d[x] - x -= x & -x - return v, cnt - - -class Solution: - def findNumberOfLIS(self, nums: List[int]) -> int: - arr = sorted(set(nums)) - m = len(arr) - tree = BinaryIndexedTree(m) - for x in nums: - i = bisect_left(arr, x) + 1 - v, cnt = tree.query(i - 1) - tree.update(i, v + 1, max(cnt, 1)) - return tree.query(m)[1] +class Solution: + def findNumberOfLIS(self, nums: List[int]) -> int: + n = len(nums) + f = [1] * n + cnt = [1] * n + mx = 0 + for i in range(n): + for j in range(i): + if nums[j] < nums[i]: + if f[i] < f[j] + 1: + f[i] = f[j] + 1 + cnt[i] = cnt[j] + elif f[i] == f[j] + 1: + cnt[i] += cnt[j] + if mx < f[i]: + mx = f[i] + ans = cnt[i] + elif mx == f[i]: + ans += cnt[i] + return ans diff --git a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.rs b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.rs index ab8ada320a120..1291d7f5abc8e 100644 --- a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.rs +++ b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.rs @@ -1,59 +1,28 @@ -struct BinaryIndexedTree { - n: usize, - c: Vec, - d: Vec, -} - -impl BinaryIndexedTree { - fn new(n: usize) -> BinaryIndexedTree { - BinaryIndexedTree { - n, - c: vec![0; n + 1], - d: vec![0; n + 1], - } - } - - fn update(&mut self, x: usize, v: i32, cnt: i32) { - let mut x = x as usize; - while x <= self.n { - if self.c[x] < v { - self.c[x] = v; - self.d[x] = cnt; - } else if self.c[x] == v { - self.d[x] += cnt; - } - x += x & x.wrapping_neg(); - } - } - - fn query(&self, mut x: usize) -> (i32, i32) { - let (mut v, mut cnt) = (0, 0); - while x > 0 { - if self.c[x] > v { - v = self.c[x]; - cnt = self.d[x]; - } else if self.c[x] == v { - cnt += self.d[x]; - } - x -= x & x.wrapping_neg(); - } - (v, cnt) - } -} - impl Solution { pub fn find_number_of_lis(nums: Vec) -> i32 { - let mut arr: Vec = nums.iter().cloned().collect(); - arr.sort(); - let m = arr.len(); - let mut tree = BinaryIndexedTree::new(m); - for x in nums.iter() { - if let Ok(i) = arr.binary_search(x) { - let (v, cnt) = tree.query(i); - tree.update(i + 1, v + 1, cnt.max(1)); + let n = nums.len(); + let mut ans = 0; + let mut mx = 0; + let mut f = vec![1; n]; + let mut cnt = vec![1; n]; + for i in 0..n { + for j in 0..i { + if nums[j] < nums[i] { + if f[i] < f[j] + 1 { + f[i] = f[j] + 1; + cnt[i] = cnt[j]; + } else if f[i] == f[j] + 1 { + cnt[i] += cnt[j]; + } + } + } + if mx < f[i] { + mx = f[i]; + ans = cnt[i]; + } else if mx == f[i] { + ans += cnt[i]; } } - let (_, ans) = tree.query(m); ans } } diff --git a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.ts b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.ts index 02db626d34d85..641a7a38bb2a4 100644 --- a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.ts +++ b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.ts @@ -1,63 +1,25 @@ -class BinaryIndexedTree { - private n: number; - private c: number[]; - private d: number[]; - - constructor(n: number) { - this.n = n; - this.c = Array(n + 1).fill(0); - this.d = Array(n + 1).fill(0); - } - - update(x: number, v: number, cnt: number): void { - while (x <= this.n) { - if (this.c[x] < v) { - this.c[x] = v; - this.d[x] = cnt; - } else if (this.c[x] === v) { - this.d[x] += cnt; - } - x += x & -x; - } - } - - query(x: number): [number, number] { - let v = 0; - let cnt = 0; - while (x > 0) { - if (this.c[x] > v) { - v = this.c[x]; - cnt = this.d[x]; - } else if (this.c[x] === v) { - cnt += this.d[x]; - } - x -= x & -x; - } - return [v, cnt]; - } -} - function findNumberOfLIS(nums: number[]): number { - const arr: number[] = [...new Set(nums)].sort((a, b) => a - b); - const m: number = arr.length; - const tree: BinaryIndexedTree = new BinaryIndexedTree(m); - const search = (x: number): number => { - let l = 0, - r = arr.length; - while (l < r) { - const mid = (l + r) >> 1; - if (arr[mid] >= x) { - r = mid; - } else { - l = mid + 1; + const n = nums.length; + let [ans, mx] = [0, 0]; + const f: number[] = Array(n).fill(1); + const cnt: number[] = Array(n).fill(1); + for (let i = 0; i < n; ++i) { + for (let j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + if (f[i] < f[j] + 1) { + f[i] = f[j] + 1; + cnt[i] = cnt[j]; + } else if (f[i] === f[j] + 1) { + cnt[i] += cnt[j]; + } } } - return l + 1; - }; - for (const x of nums) { - const i: number = search(x); - const [v, cnt]: [number, number] = tree.query(i - 1); - tree.update(i, v + 1, Math.max(cnt, 1)); + if (mx < f[i]) { + mx = f[i]; + ans = cnt[i]; + } else if (mx === f[i]) { + ans += cnt[i]; + } } - return tree.query(m)[1]; + return ans; } diff --git a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.cpp b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.cpp new file mode 100644 index 0000000000000..4369060edadc5 --- /dev/null +++ b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.cpp @@ -0,0 +1,56 @@ +class BinaryIndexedTree { +private: + int n; + vector c; + vector d; + +public: + BinaryIndexedTree(int n) + : n(n) + , c(n + 1, 0) + , d(n + 1, 0) {} + + void update(int x, int v, int cnt) { + while (x <= n) { + if (c[x] < v) { + c[x] = v; + d[x] = cnt; + } else if (c[x] == v) { + d[x] += cnt; + } + x += x & -x; + } + } + + pair query(int x) { + int v = 0, cnt = 0; + while (x > 0) { + if (c[x] > v) { + v = c[x]; + cnt = d[x]; + } else if (c[x] == v) { + cnt += d[x]; + } + x -= x & -x; + } + return {v, cnt}; + } +}; + +class Solution { +public: + int findNumberOfLIS(vector& nums) { + vector arr = nums; + sort(arr.begin(), arr.end()); + arr.erase(unique(arr.begin(), arr.end()), arr.end()); + int m = arr.size(); + BinaryIndexedTree tree(m); + for (int x : nums) { + auto it = lower_bound(arr.begin(), arr.end(), x); + int i = distance(arr.begin(), it) + 1; + auto [v, cnt] = tree.query(i - 1); + tree.update(i, v + 1, max(cnt, 1)); + } + return tree.query(m).second; + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.go b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.go new file mode 100644 index 0000000000000..6c13cc584c80d --- /dev/null +++ b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.go @@ -0,0 +1,54 @@ +type BinaryIndexedTree struct { + n int + c []int + d []int +} + +func newBinaryIndexedTree(n int) BinaryIndexedTree { + return BinaryIndexedTree{ + n: n, + c: make([]int, n+1), + d: make([]int, n+1), + } +} + +func (bit *BinaryIndexedTree) update(x, v, cnt int) { + for x <= bit.n { + if bit.c[x] < v { + bit.c[x] = v + bit.d[x] = cnt + } else if bit.c[x] == v { + bit.d[x] += cnt + } + x += x & -x + } +} + +func (bit *BinaryIndexedTree) query(x int) (int, int) { + v, cnt := 0, 0 + for x > 0 { + if bit.c[x] > v { + v = bit.c[x] + cnt = bit.d[x] + } else if bit.c[x] == v { + cnt += bit.d[x] + } + x -= x & -x + } + return v, cnt +} + +func findNumberOfLIS(nums []int) int { + arr := make([]int, len(nums)) + copy(arr, nums) + sort.Ints(arr) + m := len(arr) + tree := newBinaryIndexedTree(m) + for _, x := range nums { + i := sort.SearchInts(arr, x) + 1 + v, cnt := tree.query(i - 1) + tree.update(i, v+1, max(cnt, 1)) + } + _, ans := tree.query(m) + return ans +} \ No newline at end of file diff --git a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.java b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.java new file mode 100644 index 0000000000000..f25c65d9187c4 --- /dev/null +++ b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.java @@ -0,0 +1,55 @@ +class BinaryIndexedTree { + private int n; + private int[] c; + private int[] d; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + d = new int[n + 1]; + } + + public void update(int x, int v, int cnt) { + while (x <= n) { + if (c[x] < v) { + c[x] = v; + d[x] = cnt; + } else if (c[x] == v) { + d[x] += cnt; + } + x += x & -x; + } + } + + public int[] query(int x) { + int v = 0, cnt = 0; + while (x > 0) { + if (c[x] > v) { + v = c[x]; + cnt = d[x]; + } else if (c[x] == v) { + cnt += d[x]; + } + x -= x & -x; + } + return new int[] {v, cnt}; + } +} + +public class Solution { + public int findNumberOfLIS(int[] nums) { + // int[] arr = Arrays.stream(nums).distinct().sorted().toArray(); + int[] arr = nums.clone(); + Arrays.sort(arr); + int m = arr.length; + BinaryIndexedTree tree = new BinaryIndexedTree(m); + for (int x : nums) { + int i = Arrays.binarySearch(arr, x) + 1; + int[] t = tree.query(i - 1); + int v = t[0]; + int cnt = t[1]; + tree.update(i, v + 1, Math.max(cnt, 1)); + } + return tree.query(m)[1]; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.py b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.py new file mode 100644 index 0000000000000..c0fb4b6cd590b --- /dev/null +++ b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.py @@ -0,0 +1,39 @@ +class BinaryIndexedTree: + __slots__ = ["n", "c", "d"] + + def __init__(self, n): + self.n = n + self.c = [0] * (n + 1) + self.d = [0] * (n + 1) + + def update(self, x, v, cnt): + while x <= self.n: + if self.c[x] < v: + self.c[x] = v + self.d[x] = cnt + elif self.c[x] == v: + self.d[x] += cnt + x += x & -x + + def query(self, x): + v = cnt = 0 + while x: + if self.c[x] > v: + v = self.c[x] + cnt = self.d[x] + elif self.c[x] == v: + cnt += self.d[x] + x -= x & -x + return v, cnt + + +class Solution: + def findNumberOfLIS(self, nums: List[int]) -> int: + arr = sorted(set(nums)) + m = len(arr) + tree = BinaryIndexedTree(m) + for x in nums: + i = bisect_left(arr, x) + 1 + v, cnt = tree.query(i - 1) + tree.update(i, v + 1, max(cnt, 1)) + return tree.query(m)[1] diff --git a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.rs b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.rs new file mode 100644 index 0000000000000..ab8ada320a120 --- /dev/null +++ b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.rs @@ -0,0 +1,59 @@ +struct BinaryIndexedTree { + n: usize, + c: Vec, + d: Vec, +} + +impl BinaryIndexedTree { + fn new(n: usize) -> BinaryIndexedTree { + BinaryIndexedTree { + n, + c: vec![0; n + 1], + d: vec![0; n + 1], + } + } + + fn update(&mut self, x: usize, v: i32, cnt: i32) { + let mut x = x as usize; + while x <= self.n { + if self.c[x] < v { + self.c[x] = v; + self.d[x] = cnt; + } else if self.c[x] == v { + self.d[x] += cnt; + } + x += x & x.wrapping_neg(); + } + } + + fn query(&self, mut x: usize) -> (i32, i32) { + let (mut v, mut cnt) = (0, 0); + while x > 0 { + if self.c[x] > v { + v = self.c[x]; + cnt = self.d[x]; + } else if self.c[x] == v { + cnt += self.d[x]; + } + x -= x & x.wrapping_neg(); + } + (v, cnt) + } +} + +impl Solution { + pub fn find_number_of_lis(nums: Vec) -> i32 { + let mut arr: Vec = nums.iter().cloned().collect(); + arr.sort(); + let m = arr.len(); + let mut tree = BinaryIndexedTree::new(m); + for x in nums.iter() { + if let Ok(i) = arr.binary_search(x) { + let (v, cnt) = tree.query(i); + tree.update(i + 1, v + 1, cnt.max(1)); + } + } + let (_, ans) = tree.query(m); + ans + } +} diff --git a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.ts b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.ts new file mode 100644 index 0000000000000..02db626d34d85 --- /dev/null +++ b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.ts @@ -0,0 +1,63 @@ +class BinaryIndexedTree { + private n: number; + private c: number[]; + private d: number[]; + + constructor(n: number) { + this.n = n; + this.c = Array(n + 1).fill(0); + this.d = Array(n + 1).fill(0); + } + + update(x: number, v: number, cnt: number): void { + while (x <= this.n) { + if (this.c[x] < v) { + this.c[x] = v; + this.d[x] = cnt; + } else if (this.c[x] === v) { + this.d[x] += cnt; + } + x += x & -x; + } + } + + query(x: number): [number, number] { + let v = 0; + let cnt = 0; + while (x > 0) { + if (this.c[x] > v) { + v = this.c[x]; + cnt = this.d[x]; + } else if (this.c[x] === v) { + cnt += this.d[x]; + } + x -= x & -x; + } + return [v, cnt]; + } +} + +function findNumberOfLIS(nums: number[]): number { + const arr: number[] = [...new Set(nums)].sort((a, b) => a - b); + const m: number = arr.length; + const tree: BinaryIndexedTree = new BinaryIndexedTree(m); + const search = (x: number): number => { + let l = 0, + r = arr.length; + while (l < r) { + const mid = (l + r) >> 1; + if (arr[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l + 1; + }; + for (const x of nums) { + const i: number = search(x); + const [v, cnt]: [number, number] = tree.query(i - 1); + tree.update(i, v + 1, Math.max(cnt, 1)); + } + return tree.query(m)[1]; +} diff --git a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution.cpp b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution.cpp index f413eebad76d9..2deba37f27329 100644 --- a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution.cpp +++ b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution.cpp @@ -1,14 +1,14 @@ -class Solution { -public: - int findLengthOfLCIS(vector& nums) { - int ans = 1; - for (int i = 1, cnt = 1; i < nums.size(); ++i) { - if (nums[i - 1] < nums[i]) { - ans = max(ans, ++cnt); - } else { - cnt = 1; - } - } - return ans; - } +class Solution { +public: + int findLengthOfLCIS(vector& nums) { + int ans = 1; + for (int i = 1, cnt = 1; i < nums.size(); ++i) { + if (nums[i - 1] < nums[i]) { + ans = max(ans, ++cnt); + } else { + cnt = 1; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution.java b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution.java index e72c28d8909c6..e3fa7beec7628 100644 --- a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution.java +++ b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution.java @@ -1,13 +1,13 @@ -class Solution { - public int findLengthOfLCIS(int[] nums) { - int ans = 1; - for (int i = 1, cnt = 1; i < nums.length; ++i) { - if (nums[i - 1] < nums[i]) { - ans = Math.max(ans, ++cnt); - } else { - cnt = 1; - } - } - return ans; - } +class Solution { + public int findLengthOfLCIS(int[] nums) { + int ans = 1; + for (int i = 1, cnt = 1; i < nums.length; ++i) { + if (nums[i - 1] < nums[i]) { + ans = Math.max(ans, ++cnt); + } else { + cnt = 1; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution.php b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution.php index 0e86f33bb937c..b8861845a86e5 100644 --- a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution.php +++ b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution.php @@ -15,4 +15,4 @@ function findLengthOfLCIS($nums) { } return $ans; } -} \ No newline at end of file +} diff --git a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution.py b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution.py index f771487c8bb19..2f886ecfb158c 100644 --- a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution.py +++ b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def findLengthOfLCIS(self, nums: List[int]) -> int: - ans = cnt = 1 - for i, x in enumerate(nums[1:]): - if nums[i] < x: - cnt += 1 - ans = max(ans, cnt) - else: - cnt = 1 - return ans +class Solution: + def findLengthOfLCIS(self, nums: List[int]) -> int: + ans = cnt = 1 + for i, x in enumerate(nums[1:]): + if nums[i] < x: + cnt += 1 + ans = max(ans, cnt) + else: + cnt = 1 + return ans diff --git a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.cpp b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.cpp new file mode 100644 index 0000000000000..8b88ace6d66f9 --- /dev/null +++ b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int findLengthOfLCIS(vector& nums) { + int ans = 1; + int n = nums.size(); + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && nums[j - 1] < nums[j]) { + ++j; + } + ans = max(ans, j - i); + i = j; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.go b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.go new file mode 100644 index 0000000000000..37365724d0772 --- /dev/null +++ b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.go @@ -0,0 +1,13 @@ +func findLengthOfLCIS(nums []int) int { + ans := 1 + n := len(nums) + for i := 0; i < n; { + j := i + 1 + for j < n && nums[j-1] < nums[j] { + j++ + } + ans = max(ans, j-i) + i = j + } + return ans +} \ No newline at end of file diff --git a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.java b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.java new file mode 100644 index 0000000000000..420b2e0d8c86d --- /dev/null +++ b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public int findLengthOfLCIS(int[] nums) { + int ans = 1; + int n = nums.length; + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && nums[j - 1] < nums[j]) { + ++j; + } + ans = Math.max(ans, j - i); + i = j; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.php b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.php new file mode 100644 index 0000000000000..74d3867e0b72d --- /dev/null +++ b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.php @@ -0,0 +1,20 @@ +class Solution { + /** + * @param Integer[] $nums + * @return Integer + */ + function findLengthOfLCIS($nums) { + $ans = 1; + $n = count($nums); + $i = 0; + while ($i < $n) { + $j = $i + 1; + while ($j < $n && $nums[$j - 1] < $nums[$j]) { + $j++; + } + $ans = max($ans, $j - $i); + $i = $j; + } + return $ans; + } +} diff --git a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.py b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.py new file mode 100644 index 0000000000000..ce82e0052c333 --- /dev/null +++ b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def findLengthOfLCIS(self, nums: List[int]) -> int: + ans, n = 1, len(nums) + i = 0 + while i < n: + j = i + 1 + while j < n and nums[j - 1] < nums[j]: + j += 1 + ans = max(ans, j - i) + i = j + return ans diff --git a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.rs b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.rs new file mode 100644 index 0000000000000..658a9113f6464 --- /dev/null +++ b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn find_length_of_lcis(nums: Vec) -> i32 { + let mut ans = 1; + let n = nums.len(); + let mut i = 0; + while i < n { + let mut j = i + 1; + while j < n && nums[j - 1] < nums[j] { + j += 1; + } + ans = ans.max(j - i); + i = j; + } + ans as i32 + } +} diff --git a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.ts b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.ts new file mode 100644 index 0000000000000..b8db5c846b627 --- /dev/null +++ b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/Solution2.ts @@ -0,0 +1,13 @@ +function findLengthOfLCIS(nums: number[]): number { + let ans = 1; + const n = nums.length; + for (let i = 0; i < n; ) { + let j = i + 1; + while (j < n && nums[j - 1] < nums[j]) { + ++j; + } + ans = Math.max(ans, j - i); + i = j; + } + return ans; +} diff --git a/solution/0600-0699/0676.Implement Magic Dictionary/Solution.cpp b/solution/0600-0699/0676.Implement Magic Dictionary/Solution.cpp index a47678e780519..aa4bbd352d25b 100644 --- a/solution/0600-0699/0676.Implement Magic Dictionary/Solution.cpp +++ b/solution/0600-0699/0676.Implement Magic Dictionary/Solution.cpp @@ -1,72 +1,72 @@ -class Trie { -private: - Trie* children[26]; - bool isEnd = false; - -public: - Trie() { - fill(begin(children), end(children), nullptr); - } - - void insert(const string& w) { - Trie* node = this; - for (char c : w) { - int i = c - 'a'; - if (!node->children[i]) { - node->children[i] = new Trie(); - } - node = node->children[i]; - } - node->isEnd = true; - } - - bool search(const string& w) { - function dfs = [&](int i, Trie* node, int diff) { - if (i >= w.size()) { - return diff == 1 && node->isEnd; - } - int j = w[i] - 'a'; - if (node->children[j] && dfs(i + 1, node->children[j], diff)) { - return true; - } - if (diff == 0) { - for (int k = 0; k < 26; ++k) { - if (k != j && node->children[k]) { - if (dfs(i + 1, node->children[k], 1)) { - return true; - } - } - } - } - return false; - }; - return dfs(0, this, 0); - } -}; - -class MagicDictionary { -public: - MagicDictionary() { - trie = new Trie(); - } - - void buildDict(vector dictionary) { - for (auto& w : dictionary) { - trie->insert(w); - } - } - - bool search(string searchWord) { - return trie->search(searchWord); - } - -private: - Trie* trie; -}; - -/** - * Your MagicDictionary object will be instantiated and called as such: - * MagicDictionary* obj = new MagicDictionary(); - * obj->buildDict(dictionary); - * bool param_2 = obj->search(searchWord); +class Trie { +private: + Trie* children[26]; + bool isEnd = false; + +public: + Trie() { + fill(begin(children), end(children), nullptr); + } + + void insert(const string& w) { + Trie* node = this; + for (char c : w) { + int i = c - 'a'; + if (!node->children[i]) { + node->children[i] = new Trie(); + } + node = node->children[i]; + } + node->isEnd = true; + } + + bool search(const string& w) { + function dfs = [&](int i, Trie* node, int diff) { + if (i >= w.size()) { + return diff == 1 && node->isEnd; + } + int j = w[i] - 'a'; + if (node->children[j] && dfs(i + 1, node->children[j], diff)) { + return true; + } + if (diff == 0) { + for (int k = 0; k < 26; ++k) { + if (k != j && node->children[k]) { + if (dfs(i + 1, node->children[k], 1)) { + return true; + } + } + } + } + return false; + }; + return dfs(0, this, 0); + } +}; + +class MagicDictionary { +public: + MagicDictionary() { + trie = new Trie(); + } + + void buildDict(vector dictionary) { + for (auto& w : dictionary) { + trie->insert(w); + } + } + + bool search(string searchWord) { + return trie->search(searchWord); + } + +private: + Trie* trie; +}; + +/** + * Your MagicDictionary object will be instantiated and called as such: + * MagicDictionary* obj = new MagicDictionary(); + * obj->buildDict(dictionary); + * bool param_2 = obj->search(searchWord); */ \ No newline at end of file diff --git a/solution/0600-0699/0676.Implement Magic Dictionary/Solution.java b/solution/0600-0699/0676.Implement Magic Dictionary/Solution.java index 4f249d5b01aa0..ca85ba53209e9 100644 --- a/solution/0600-0699/0676.Implement Magic Dictionary/Solution.java +++ b/solution/0600-0699/0676.Implement Magic Dictionary/Solution.java @@ -1,66 +1,66 @@ -class Trie { - private Trie[] children = new Trie[26]; - private boolean isEnd; - - public void insert(String w) { - Trie node = this; - for (char c : w.toCharArray()) { - int i = c - 'a'; - if (node.children[i] == null) { - node.children[i] = new Trie(); - } - node = node.children[i]; - } - node.isEnd = true; - } - - public boolean search(String w) { - return dfs(w, 0, this, 0); - } - - private boolean dfs(String w, int i, Trie node, int diff) { - if (i == w.length()) { - return diff == 1 && node.isEnd; - } - int j = w.charAt(i) - 'a'; - if (node.children[j] != null) { - if (dfs(w, i + 1, node.children[j], diff)) { - return true; - } - } - if (diff == 0) { - for (int k = 0; k < 26; k++) { - if (k != j && node.children[k] != null) { - if (dfs(w, i + 1, node.children[k], 1)) { - return true; - } - } - } - } - return false; - } -} - -class MagicDictionary { - private Trie trie = new Trie(); - - public MagicDictionary() { - } - - public void buildDict(String[] dictionary) { - for (String w : dictionary) { - trie.insert(w); - } - } - - public boolean search(String searchWord) { - return trie.search(searchWord); - } -} - -/** - * Your MagicDictionary object will be instantiated and called as such: - * MagicDictionary obj = new MagicDictionary(); - * obj.buildDict(dictionary); - * boolean param_2 = obj.search(searchWord); +class Trie { + private Trie[] children = new Trie[26]; + private boolean isEnd; + + public void insert(String w) { + Trie node = this; + for (char c : w.toCharArray()) { + int i = c - 'a'; + if (node.children[i] == null) { + node.children[i] = new Trie(); + } + node = node.children[i]; + } + node.isEnd = true; + } + + public boolean search(String w) { + return dfs(w, 0, this, 0); + } + + private boolean dfs(String w, int i, Trie node, int diff) { + if (i == w.length()) { + return diff == 1 && node.isEnd; + } + int j = w.charAt(i) - 'a'; + if (node.children[j] != null) { + if (dfs(w, i + 1, node.children[j], diff)) { + return true; + } + } + if (diff == 0) { + for (int k = 0; k < 26; k++) { + if (k != j && node.children[k] != null) { + if (dfs(w, i + 1, node.children[k], 1)) { + return true; + } + } + } + } + return false; + } +} + +class MagicDictionary { + private Trie trie = new Trie(); + + public MagicDictionary() { + } + + public void buildDict(String[] dictionary) { + for (String w : dictionary) { + trie.insert(w); + } + } + + public boolean search(String searchWord) { + return trie.search(searchWord); + } +} + +/** + * Your MagicDictionary object will be instantiated and called as such: + * MagicDictionary obj = new MagicDictionary(); + * obj.buildDict(dictionary); + * boolean param_2 = obj.search(searchWord); */ \ No newline at end of file diff --git a/solution/0600-0699/0676.Implement Magic Dictionary/Solution.py b/solution/0600-0699/0676.Implement Magic Dictionary/Solution.py index 44dd0650cb285..b61a71619c054 100644 --- a/solution/0600-0699/0676.Implement Magic Dictionary/Solution.py +++ b/solution/0600-0699/0676.Implement Magic Dictionary/Solution.py @@ -1,44 +1,44 @@ -class Trie: - __slots__ = ["children", "is_end"] - - def __init__(self): - self.children = {} - self.is_end = False - - def insert(self, w: str) -> None: - node = self - for c in w: - if c not in node.children: - node.children[c] = Trie() - node = node.children[c] - node.is_end = True - - def search(self, w: str) -> bool: - def dfs(i: int, node: Trie, diff: int) -> bool: - if i == len(w): - return diff == 1 and node.is_end - if w[i] in node.children and dfs(i + 1, node.children[w[i]], diff): - return True - return diff == 0 and any( - dfs(i + 1, node.children[c], 1) for c in node.children if c != w[i] - ) - - return dfs(0, self, 0) - - -class MagicDictionary: - def __init__(self): - self.trie = Trie() - - def buildDict(self, dictionary: List[str]) -> None: - for w in dictionary: - self.trie.insert(w) - - def search(self, searchWord: str) -> bool: - return self.trie.search(searchWord) - - -# Your MagicDictionary object will be instantiated and called as such: -# obj = MagicDictionary() -# obj.buildDict(dictionary) -# param_2 = obj.search(searchWord) +class Trie: + __slots__ = ["children", "is_end"] + + def __init__(self): + self.children = {} + self.is_end = False + + def insert(self, w: str) -> None: + node = self + for c in w: + if c not in node.children: + node.children[c] = Trie() + node = node.children[c] + node.is_end = True + + def search(self, w: str) -> bool: + def dfs(i: int, node: Trie, diff: int) -> bool: + if i == len(w): + return diff == 1 and node.is_end + if w[i] in node.children and dfs(i + 1, node.children[w[i]], diff): + return True + return diff == 0 and any( + dfs(i + 1, node.children[c], 1) for c in node.children if c != w[i] + ) + + return dfs(0, self, 0) + + +class MagicDictionary: + def __init__(self): + self.trie = Trie() + + def buildDict(self, dictionary: List[str]) -> None: + for w in dictionary: + self.trie.insert(w) + + def search(self, searchWord: str) -> bool: + return self.trie.search(searchWord) + + +# Your MagicDictionary object will be instantiated and called as such: +# obj = MagicDictionary() +# obj.buildDict(dictionary) +# param_2 = obj.search(searchWord) diff --git a/solution/0600-0699/0676.Implement Magic Dictionary/Solution2.py b/solution/0600-0699/0676.Implement Magic Dictionary/Solution2.py new file mode 100644 index 0000000000000..b7c9051390d8b --- /dev/null +++ b/solution/0600-0699/0676.Implement Magic Dictionary/Solution2.py @@ -0,0 +1,48 @@ +class Trie: + __slots__ = ["children", "is_end"] + + def __init__(self): + self.children: [Trie | None] = [None] * 26 + self.is_end = False + + def insert(self, w: str) -> None: + node = self + for c in w: + idx = ord(c) - ord("a") + if node.children[idx] is None: + node.children[idx] = Trie() + node = node.children[idx] + node.is_end = True + + def search(self, w: str) -> bool: + def dfs(i: int, node: [Trie | None], diff: int) -> bool: + if i == len(w): + return diff == 1 and node.is_end + j = ord(w[i]) - ord("a") + if node.children[j] and dfs(i + 1, node.children[j], diff): + return True + return diff == 0 and any( + node.children[k] and dfs(i + 1, node.children[k], 1) + for k in range(26) + if k != j + ) + + return dfs(0, self, 0) + + +class MagicDictionary: + def __init__(self): + self.trie = Trie() + + def buildDict(self, dictionary: List[str]) -> None: + for w in dictionary: + self.trie.insert(w) + + def search(self, searchWord: str) -> bool: + return self.trie.search(searchWord) + + +# Your MagicDictionary object will be instantiated and called as such: +# obj = MagicDictionary() +# obj.buildDict(dictionary) +# param_2 = obj.search(searchWord) diff --git a/solution/0600-0699/0678.Valid Parenthesis String/Solution.cpp b/solution/0600-0699/0678.Valid Parenthesis String/Solution.cpp index 3a8c2b1c727de..20b5ba867bf40 100644 --- a/solution/0600-0699/0678.Valid Parenthesis String/Solution.cpp +++ b/solution/0600-0699/0678.Valid Parenthesis String/Solution.cpp @@ -1,26 +1,20 @@ class Solution { public: bool checkValidString(string s) { - int x = 0, n = s.size(); + int n = s.size(); + vector> dp(n, vector(n)); for (int i = 0; i < n; ++i) { - if (s[i] != ')') { - ++x; - } else if (x) { - --x; - } else { - return false; - } + dp[i][i] = s[i] == '*'; } - x = 0; - for (int i = n - 1; i >= 0; --i) { - if (s[i] != '(') { - ++x; - } else if (x) { - --x; - } else { - return false; + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + char a = s[i], b = s[j]; + dp[i][j] = (a == '(' || a == '*') && (b == '*' || b == ')') && (i + 1 == j || dp[i + 1][j - 1]); + for (int k = i; k < j && !dp[i][j]; ++k) { + dp[i][j] = dp[i][k] && dp[k + 1][j]; + } } } - return true; + return dp[0][n - 1]; } }; \ No newline at end of file diff --git a/solution/0600-0699/0678.Valid Parenthesis String/Solution.go b/solution/0600-0699/0678.Valid Parenthesis String/Solution.go index 04d7906f0cad7..1d61ea8b8f38c 100644 --- a/solution/0600-0699/0678.Valid Parenthesis String/Solution.go +++ b/solution/0600-0699/0678.Valid Parenthesis String/Solution.go @@ -1,23 +1,18 @@ func checkValidString(s string) bool { - x := 0 - for _, c := range s { - if c != ')' { - x++ - } else if x > 0 { - x-- - } else { - return false - } + n := len(s) + dp := make([][]bool, n) + for i := range dp { + dp[i] = make([]bool, n) + dp[i][i] = s[i] == '*' } - x = 0 - for i := len(s) - 1; i >= 0; i-- { - if s[i] != '(' { - x++ - } else if x > 0 { - x-- - } else { - return false + for i := n - 2; i >= 0; i-- { + for j := i + 1; j < n; j++ { + a, b := s[i], s[j] + dp[i][j] = (a == '(' || a == '*') && (b == '*' || b == ')') && (i+1 == j || dp[i+1][j-1]) + for k := i; k < j && !dp[i][j]; k++ { + dp[i][j] = dp[i][k] && dp[k+1][j] + } } } - return true + return dp[0][n-1] } \ No newline at end of file diff --git a/solution/0600-0699/0678.Valid Parenthesis String/Solution.java b/solution/0600-0699/0678.Valid Parenthesis String/Solution.java index d496006ebd93c..471cf7467ad32 100644 --- a/solution/0600-0699/0678.Valid Parenthesis String/Solution.java +++ b/solution/0600-0699/0678.Valid Parenthesis String/Solution.java @@ -1,26 +1,20 @@ class Solution { public boolean checkValidString(String s) { - int x = 0; int n = s.length(); + boolean[][] dp = new boolean[n][n]; for (int i = 0; i < n; ++i) { - if (s.charAt(i) != ')') { - ++x; - } else if (x > 0) { - --x; - } else { - return false; - } + dp[i][i] = s.charAt(i) == '*'; } - x = 0; - for (int i = n - 1; i >= 0; --i) { - if (s.charAt(i) != '(') { - ++x; - } else if (x > 0) { - --x; - } else { - return false; + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + char a = s.charAt(i), b = s.charAt(j); + dp[i][j] = (a == '(' || a == '*') && (b == '*' || b == ')') + && (i + 1 == j || dp[i + 1][j - 1]); + for (int k = i; k < j && !dp[i][j]; ++k) { + dp[i][j] = dp[i][k] && dp[k + 1][j]; + } } } - return true; + return dp[0][n - 1]; } } \ No newline at end of file diff --git a/solution/0600-0699/0678.Valid Parenthesis String/Solution.py b/solution/0600-0699/0678.Valid Parenthesis String/Solution.py index e5d695031df77..4dea8ac6762ac 100644 --- a/solution/0600-0699/0678.Valid Parenthesis String/Solution.py +++ b/solution/0600-0699/0678.Valid Parenthesis String/Solution.py @@ -1,19 +1,15 @@ class Solution: def checkValidString(self, s: str) -> bool: - x = 0 - for c in s: - if c in '(*': - x += 1 - elif x: - x -= 1 - else: - return False - x = 0 - for c in s[::-1]: - if c in '*)': - x += 1 - elif x: - x -= 1 - else: - return False - return True + n = len(s) + dp = [[False] * n for _ in range(n)] + for i, c in enumerate(s): + dp[i][i] = c == '*' + for i in range(n - 2, -1, -1): + for j in range(i + 1, n): + dp[i][j] = ( + s[i] in '(*' and s[j] in '*)' and (i + 1 == j or dp[i + 1][j - 1]) + ) + dp[i][j] = dp[i][j] or any( + dp[i][k] and dp[k + 1][j] for k in range(i, j) + ) + return dp[0][-1] diff --git a/solution/0600-0699/0678.Valid Parenthesis String/Solution2.cpp b/solution/0600-0699/0678.Valid Parenthesis String/Solution2.cpp new file mode 100644 index 0000000000000..3a8c2b1c727de --- /dev/null +++ b/solution/0600-0699/0678.Valid Parenthesis String/Solution2.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + bool checkValidString(string s) { + int x = 0, n = s.size(); + for (int i = 0; i < n; ++i) { + if (s[i] != ')') { + ++x; + } else if (x) { + --x; + } else { + return false; + } + } + x = 0; + for (int i = n - 1; i >= 0; --i) { + if (s[i] != '(') { + ++x; + } else if (x) { + --x; + } else { + return false; + } + } + return true; + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0678.Valid Parenthesis String/Solution2.go b/solution/0600-0699/0678.Valid Parenthesis String/Solution2.go new file mode 100644 index 0000000000000..04d7906f0cad7 --- /dev/null +++ b/solution/0600-0699/0678.Valid Parenthesis String/Solution2.go @@ -0,0 +1,23 @@ +func checkValidString(s string) bool { + x := 0 + for _, c := range s { + if c != ')' { + x++ + } else if x > 0 { + x-- + } else { + return false + } + } + x = 0 + for i := len(s) - 1; i >= 0; i-- { + if s[i] != '(' { + x++ + } else if x > 0 { + x-- + } else { + return false + } + } + return true +} \ No newline at end of file diff --git a/solution/0600-0699/0678.Valid Parenthesis String/Solution2.java b/solution/0600-0699/0678.Valid Parenthesis String/Solution2.java new file mode 100644 index 0000000000000..d496006ebd93c --- /dev/null +++ b/solution/0600-0699/0678.Valid Parenthesis String/Solution2.java @@ -0,0 +1,26 @@ +class Solution { + public boolean checkValidString(String s) { + int x = 0; + int n = s.length(); + for (int i = 0; i < n; ++i) { + if (s.charAt(i) != ')') { + ++x; + } else if (x > 0) { + --x; + } else { + return false; + } + } + x = 0; + for (int i = n - 1; i >= 0; --i) { + if (s.charAt(i) != '(') { + ++x; + } else if (x > 0) { + --x; + } else { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0678.Valid Parenthesis String/Solution2.py b/solution/0600-0699/0678.Valid Parenthesis String/Solution2.py new file mode 100644 index 0000000000000..e5d695031df77 --- /dev/null +++ b/solution/0600-0699/0678.Valid Parenthesis String/Solution2.py @@ -0,0 +1,19 @@ +class Solution: + def checkValidString(self, s: str) -> bool: + x = 0 + for c in s: + if c in '(*': + x += 1 + elif x: + x -= 1 + else: + return False + x = 0 + for c in s[::-1]: + if c in '*)': + x += 1 + elif x: + x -= 1 + else: + return False + return True diff --git a/solution/0600-0699/0679.24 Game/Solution.cpp b/solution/0600-0699/0679.24 Game/Solution.cpp index 80141c038774c..df6bd76be1527 100644 --- a/solution/0600-0699/0679.24 Game/Solution.cpp +++ b/solution/0600-0699/0679.24 Game/Solution.cpp @@ -1,58 +1,58 @@ -class Solution { -public: - bool judgePoint24(vector& cards) { - vector nums; - for (int num : cards) { - nums.push_back(static_cast(num)); - } - return dfs(nums); - } - -private: - const char ops[4] = {'+', '-', '*', '/'}; - - bool dfs(vector& nums) { - int n = nums.size(); - if (n == 1) { - return abs(nums[0] - 24) < 1e-6; - } - bool ok = false; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (i != j) { - vector nxt; - for (int k = 0; k < n; ++k) { - if (k != i && k != j) { - nxt.push_back(nums[k]); - } - } - for (char op : ops) { - switch (op) { - case '/': - if (nums[j] == 0) { - continue; - } - nxt.push_back(nums[i] / nums[j]); - break; - case '*': - nxt.push_back(nums[i] * nums[j]); - break; - case '+': - nxt.push_back(nums[i] + nums[j]); - break; - case '-': - nxt.push_back(nums[i] - nums[j]); - break; - } - ok |= dfs(nxt); - if (ok) { - return true; - } - nxt.pop_back(); - } - } - } - } - return ok; - } +class Solution { +public: + bool judgePoint24(vector& cards) { + vector nums; + for (int num : cards) { + nums.push_back(static_cast(num)); + } + return dfs(nums); + } + +private: + const char ops[4] = {'+', '-', '*', '/'}; + + bool dfs(vector& nums) { + int n = nums.size(); + if (n == 1) { + return abs(nums[0] - 24) < 1e-6; + } + bool ok = false; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (i != j) { + vector nxt; + for (int k = 0; k < n; ++k) { + if (k != i && k != j) { + nxt.push_back(nums[k]); + } + } + for (char op : ops) { + switch (op) { + case '/': + if (nums[j] == 0) { + continue; + } + nxt.push_back(nums[i] / nums[j]); + break; + case '*': + nxt.push_back(nums[i] * nums[j]); + break; + case '+': + nxt.push_back(nums[i] + nums[j]); + break; + case '-': + nxt.push_back(nums[i] - nums[j]); + break; + } + ok |= dfs(nxt); + if (ok) { + return true; + } + nxt.pop_back(); + } + } + } + } + return ok; + } }; \ No newline at end of file diff --git a/solution/0600-0699/0679.24 Game/Solution.java b/solution/0600-0699/0679.24 Game/Solution.java index b0877b96a0eff..071c8e4a0799b 100644 --- a/solution/0600-0699/0679.24 Game/Solution.java +++ b/solution/0600-0699/0679.24 Game/Solution.java @@ -1,56 +1,56 @@ -class Solution { - private final char[] ops = {'+', '-', '*', '/'}; - - public boolean judgePoint24(int[] cards) { - List nums = new ArrayList<>(); - for (int num : cards) { - nums.add((double) num); - } - return dfs(nums); - } - - private boolean dfs(List nums) { - int n = nums.size(); - if (n == 1) { - return Math.abs(nums.get(0) - 24) < 1e-6; - } - boolean ok = false; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (i != j) { - List nxt = new ArrayList<>(); - for (int k = 0; k < n; ++k) { - if (k != i && k != j) { - nxt.add(nums.get(k)); - } - } - for (char op : ops) { - switch (op) { - case '/' -> { - if (nums.get(j) == 0) { - continue; - } - nxt.add(nums.get(i) / nums.get(j)); - } - case '*' -> { - nxt.add(nums.get(i) * nums.get(j)); - } - case '+' -> { - nxt.add(nums.get(i) + nums.get(j)); - } - case '-' -> { - nxt.add(nums.get(i) - nums.get(j)); - } - } - ok |= dfs(nxt); - if (ok) { - return true; - } - nxt.remove(nxt.size() - 1); - } - } - } - } - return ok; - } +class Solution { + private final char[] ops = {'+', '-', '*', '/'}; + + public boolean judgePoint24(int[] cards) { + List nums = new ArrayList<>(); + for (int num : cards) { + nums.add((double) num); + } + return dfs(nums); + } + + private boolean dfs(List nums) { + int n = nums.size(); + if (n == 1) { + return Math.abs(nums.get(0) - 24) < 1e-6; + } + boolean ok = false; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (i != j) { + List nxt = new ArrayList<>(); + for (int k = 0; k < n; ++k) { + if (k != i && k != j) { + nxt.add(nums.get(k)); + } + } + for (char op : ops) { + switch (op) { + case '/' -> { + if (nums.get(j) == 0) { + continue; + } + nxt.add(nums.get(i) / nums.get(j)); + } + case '*' -> { + nxt.add(nums.get(i) * nums.get(j)); + } + case '+' -> { + nxt.add(nums.get(i) + nums.get(j)); + } + case '-' -> { + nxt.add(nums.get(i) - nums.get(j)); + } + } + ok |= dfs(nxt); + if (ok) { + return true; + } + nxt.remove(nxt.size() - 1); + } + } + } + } + return ok; + } } \ No newline at end of file diff --git a/solution/0600-0699/0679.24 Game/Solution.py b/solution/0600-0699/0679.24 Game/Solution.py index 3b4a267487737..d436f8b80cec4 100644 --- a/solution/0600-0699/0679.24 Game/Solution.py +++ b/solution/0600-0699/0679.24 Game/Solution.py @@ -1,32 +1,32 @@ -class Solution: - def judgePoint24(self, cards: List[int]) -> bool: - def dfs(nums: List[float]): - n = len(nums) - if n == 1: - if abs(nums[0] - 24) < 1e-6: - return True - return False - ok = False - for i in range(n): - for j in range(n): - if i != j: - nxt = [nums[k] for k in range(n) if k != i and k != j] - for op in ops: - match op: - case "/": - if nums[j] == 0: - continue - ok |= dfs(nxt + [nums[i] / nums[j]]) - case "*": - ok |= dfs(nxt + [nums[i] * nums[j]]) - case "+": - ok |= dfs(nxt + [nums[i] + nums[j]]) - case "-": - ok |= dfs(nxt + [nums[i] - nums[j]]) - if ok: - return True - return ok - - ops = ("+", "-", "*", "/") - nums = [float(x) for x in cards] - return dfs(nums) +class Solution: + def judgePoint24(self, cards: List[int]) -> bool: + def dfs(nums: List[float]): + n = len(nums) + if n == 1: + if abs(nums[0] - 24) < 1e-6: + return True + return False + ok = False + for i in range(n): + for j in range(n): + if i != j: + nxt = [nums[k] for k in range(n) if k != i and k != j] + for op in ops: + match op: + case "/": + if nums[j] == 0: + continue + ok |= dfs(nxt + [nums[i] / nums[j]]) + case "*": + ok |= dfs(nxt + [nums[i] * nums[j]]) + case "+": + ok |= dfs(nxt + [nums[i] + nums[j]]) + case "-": + ok |= dfs(nxt + [nums[i] - nums[j]]) + if ok: + return True + return ok + + ops = ("+", "-", "*", "/") + nums = [float(x) for x in cards] + return dfs(nums) diff --git a/solution/0600-0699/0680.Valid Palindrome II/Solution.cs b/solution/0600-0699/0680.Valid Palindrome II/Solution.cs index c2be831c40c29..98d69c111a128 100644 --- a/solution/0600-0699/0680.Valid Palindrome II/Solution.cs +++ b/solution/0600-0699/0680.Valid Palindrome II/Solution.cs @@ -21,4 +21,4 @@ private bool check(string s, int i, int j) { } return true; } -} \ No newline at end of file +} diff --git a/solution/0600-0699/0683.K Empty Slots/Solution.cpp b/solution/0600-0699/0683.K Empty Slots/Solution.cpp index c6c51e3a602cc..ce2403a51d04d 100644 --- a/solution/0600-0699/0683.K Empty Slots/Solution.cpp +++ b/solution/0600-0699/0683.K Empty Slots/Solution.cpp @@ -1,47 +1,47 @@ -class BinaryIndexedTree { -public: - int n; - vector c; - - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int delta) { - for (; x <= n; x += x & -x) { - c[x] += delta; - } - } - - int query(int x) { - int s = 0; - for (; x; x -= x & -x) { - s += c[x]; - } - return s; - } -}; - -class Solution { -public: - int kEmptySlots(vector& bulbs, int k) { - int n = bulbs.size(); - BinaryIndexedTree* tree = new BinaryIndexedTree(n); - bool vis[n + 1]; - memset(vis, false, sizeof(vis)); - for (int i = 1; i <= n; ++i) { - int x = bulbs[i - 1]; - tree->update(x, 1); - vis[x] = true; - int y = x - k - 1; - if (y > 0 && vis[y] && tree->query(x - 1) - tree->query(y) == 0) { - return i; - } - y = x + k + 1; - if (y <= n && vis[y] && tree->query(y - 1) - tree->query(x) == 0) { - return i; - } - } - return -1; - } +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + for (; x <= n; x += x & -x) { + c[x] += delta; + } + } + + int query(int x) { + int s = 0; + for (; x; x -= x & -x) { + s += c[x]; + } + return s; + } +}; + +class Solution { +public: + int kEmptySlots(vector& bulbs, int k) { + int n = bulbs.size(); + BinaryIndexedTree* tree = new BinaryIndexedTree(n); + bool vis[n + 1]; + memset(vis, false, sizeof(vis)); + for (int i = 1; i <= n; ++i) { + int x = bulbs[i - 1]; + tree->update(x, 1); + vis[x] = true; + int y = x - k - 1; + if (y > 0 && vis[y] && tree->query(x - 1) - tree->query(y) == 0) { + return i; + } + y = x + k + 1; + if (y <= n && vis[y] && tree->query(y - 1) - tree->query(x) == 0) { + return i; + } + } + return -1; + } }; \ No newline at end of file diff --git a/solution/0600-0699/0683.K Empty Slots/Solution.java b/solution/0600-0699/0683.K Empty Slots/Solution.java index 810e731ee256f..9c90df3887f27 100644 --- a/solution/0600-0699/0683.K Empty Slots/Solution.java +++ b/solution/0600-0699/0683.K Empty Slots/Solution.java @@ -1,45 +1,45 @@ -class Solution { - public int kEmptySlots(int[] bulbs, int k) { - int n = bulbs.length; - BinaryIndexedTree tree = new BinaryIndexedTree(n); - boolean[] vis = new boolean[n + 1]; - for (int i = 1; i <= n; ++i) { - int x = bulbs[i - 1]; - tree.update(x, 1); - vis[x] = true; - int y = x - k - 1; - if (y > 0 && vis[y] && tree.query(x - 1) - tree.query(y) == 0) { - return i; - } - y = x + k + 1; - if (y <= n && vis[y] && tree.query(y - 1) - tree.query(x) == 0) { - return i; - } - } - return -1; - } -} - -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - this.c = new int[n + 1]; - } - - public void update(int x, int delta) { - for (; x <= n; x += x & -x) { - c[x] += delta; - } - } - - public int query(int x) { - int s = 0; - for (; x > 0; x -= x & -x) { - s += c[x]; - } - return s; - } +class Solution { + public int kEmptySlots(int[] bulbs, int k) { + int n = bulbs.length; + BinaryIndexedTree tree = new BinaryIndexedTree(n); + boolean[] vis = new boolean[n + 1]; + for (int i = 1; i <= n; ++i) { + int x = bulbs[i - 1]; + tree.update(x, 1); + vis[x] = true; + int y = x - k - 1; + if (y > 0 && vis[y] && tree.query(x - 1) - tree.query(y) == 0) { + return i; + } + y = x + k + 1; + if (y <= n && vis[y] && tree.query(y - 1) - tree.query(x) == 0) { + return i; + } + } + return -1; + } +} + +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + this.c = new int[n + 1]; + } + + public void update(int x, int delta) { + for (; x <= n; x += x & -x) { + c[x] += delta; + } + } + + public int query(int x) { + int s = 0; + for (; x > 0; x -= x & -x) { + s += c[x]; + } + return s; + } } \ No newline at end of file diff --git a/solution/0600-0699/0683.K Empty Slots/Solution.py b/solution/0600-0699/0683.K Empty Slots/Solution.py index 4506d30a43a6d..46cccd760c7f0 100644 --- a/solution/0600-0699/0683.K Empty Slots/Solution.py +++ b/solution/0600-0699/0683.K Empty Slots/Solution.py @@ -1,33 +1,33 @@ -class BinaryIndexedTree: - def __init__(self, n): - self.n = n - self.c = [0] * (n + 1) - - def update(self, x, delta): - while x <= self.n: - self.c[x] += delta - x += x & -x - - def query(self, x): - s = 0 - while x: - s += self.c[x] - x -= x & -x - return s - - -class Solution: - def kEmptySlots(self, bulbs: List[int], k: int) -> int: - n = len(bulbs) - tree = BinaryIndexedTree(n) - vis = [False] * (n + 1) - for i, x in enumerate(bulbs, 1): - tree.update(x, 1) - vis[x] = True - y = x - k - 1 - if y > 0 and vis[y] and tree.query(x - 1) - tree.query(y) == 0: - return i - y = x + k + 1 - if y <= n and vis[y] and tree.query(y - 1) - tree.query(x) == 0: - return i - return -1 +class BinaryIndexedTree: + def __init__(self, n): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x, delta): + while x <= self.n: + self.c[x] += delta + x += x & -x + + def query(self, x): + s = 0 + while x: + s += self.c[x] + x -= x & -x + return s + + +class Solution: + def kEmptySlots(self, bulbs: List[int], k: int) -> int: + n = len(bulbs) + tree = BinaryIndexedTree(n) + vis = [False] * (n + 1) + for i, x in enumerate(bulbs, 1): + tree.update(x, 1) + vis[x] = True + y = x - k - 1 + if y > 0 and vis[y] and tree.query(x - 1) - tree.query(y) == 0: + return i + y = x + k + 1 + if y <= n and vis[y] and tree.query(y - 1) - tree.query(x) == 0: + return i + return -1 diff --git a/solution/0600-0699/0687.Longest Univalue Path/Solution.c b/solution/0600-0699/0687.Longest Univalue Path/Solution.c index 1358259069d3f..60269ed5a5196 100644 --- a/solution/0600-0699/0687.Longest Univalue Path/Solution.c +++ b/solution/0600-0699/0687.Longest Univalue Path/Solution.c @@ -29,4 +29,4 @@ int longestUnivaluePath(struct TreeNode* root) { int res = 0; dfs(root, root->val, &res); return res; -} +} \ No newline at end of file diff --git a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution.cpp b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution.cpp index 8baeba40d1770..a0596d0b2084d 100644 --- a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution.cpp +++ b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution.cpp @@ -1,46 +1,33 @@ class Solution { public: vector maxSumOfThreeSubarrays(vector& nums, int k) { - int n = nums.size(); - vector s(n + 1, 0); - for (int i = 0; i < n; ++i) { - s[i + 1] = s[i] + nums[i]; - } - - vector> pre(n, vector(2, 0)); - vector> suf(n, vector(2, 0)); - - for (int i = 0, t = 0, idx = 0; i < n - k + 1; ++i) { - int cur = s[i + k] - s[i]; - if (cur > t) { - pre[i + k - 1] = {cur, i}; - t = cur; - idx = i; - } else { - pre[i + k - 1] = {t, idx}; - } - } - - for (int i = n - k, t = 0, idx = 0; i >= 0; --i) { - int cur = s[i + k] - s[i]; - if (cur >= t) { - suf[i] = {cur, i}; - t = cur; - idx = i; - } else { - suf[i] = {t, idx}; - } - } - - vector ans; - for (int i = k, t = 0; i < n - 2 * k + 1; ++i) { - int cur = s[i + k] - s[i] + pre[i - 1][0] + suf[i + k][0]; - if (cur > t) { - ans = {pre[i - 1][1], i, suf[i + k][1]}; - t = cur; + vector ans(3); + int s = 0, s1 = 0, s2 = 0, s3 = 0; + int mx1 = 0, mx12 = 0; + int idx1 = 0, idx121 = 0, idx122 = 0; + for (int i = k * 2; i < nums.size(); ++i) { + s1 += nums[i - k * 2]; + s2 += nums[i - k]; + s3 += nums[i]; + if (i >= k * 3 - 1) { + if (s1 > mx1) { + mx1 = s1; + idx1 = i - k * 3 + 1; + } + if (mx1 + s2 > mx12) { + mx12 = mx1 + s2; + idx121 = idx1; + idx122 = i - k * 2 + 1; + } + if (mx12 + s3 > s) { + s = mx12 + s3; + ans = {idx121, idx122, i - k + 1}; + } + s1 -= nums[i - k * 3 + 1]; + s2 -= nums[i - k * 2 + 1]; + s3 -= nums[i - k + 1]; } } - return ans; } }; \ No newline at end of file diff --git a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution.go b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution.go index f42deecc50470..35ba3d2e5a2f2 100644 --- a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution.go +++ b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution.go @@ -1,40 +1,30 @@ -func maxSumOfThreeSubarrays(nums []int, k int) (ans []int) { - n := len(nums) - s := make([]int, n+1) - for i := 0; i < n; i++ { - s[i+1] = s[i] + nums[i] - } - - pre := make([][]int, n) - suf := make([][]int, n) - - for i, t, idx := 0, 0, 0; i < n-k+1; i++ { - cur := s[i+k] - s[i] - if cur > t { - pre[i+k-1] = []int{cur, i} - t, idx = cur, i - } else { - pre[i+k-1] = []int{t, idx} - } - } - - for i, t, idx := n-k, 0, 0; i >= 0; i-- { - cur := s[i+k] - s[i] - if cur >= t { - suf[i] = []int{cur, i} - t, idx = cur, i - } else { - suf[i] = []int{t, idx} - } - } - - for i, t := k, 0; i < n-2*k+1; i++ { - cur := s[i+k] - s[i] + pre[i-1][0] + suf[i+k][0] - if cur > t { - ans = []int{pre[i-1][1], i, suf[i+k][1]} - t = cur +func maxSumOfThreeSubarrays(nums []int, k int) []int { + ans := make([]int, 3) + s, s1, s2, s3 := 0, 0, 0, 0 + mx1, mx12 := 0, 0 + idx1, idx121, idx122 := 0, 0, 0 + for i := k * 2; i < len(nums); i++ { + s1 += nums[i-k*2] + s2 += nums[i-k] + s3 += nums[i] + if i >= k*3-1 { + if s1 > mx1 { + mx1 = s1 + idx1 = i - k*3 + 1 + } + if mx1+s2 > mx12 { + mx12 = mx1 + s2 + idx121 = idx1 + idx122 = i - k*2 + 1 + } + if mx12+s3 > s { + s = mx12 + s3 + ans = []int{idx121, idx122, i - k + 1} + } + s1 -= nums[i-k*3+1] + s2 -= nums[i-k*2+1] + s3 -= nums[i-k+1] } } - - return + return ans } \ No newline at end of file diff --git a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution.java b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution.java index 9143c7df011fe..2b02ca6b35c3c 100644 --- a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution.java +++ b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution.java @@ -1,38 +1,30 @@ class Solution { public int[] maxSumOfThreeSubarrays(int[] nums, int k) { - int n = nums.length; - int[] s = new int[n + 1]; - for (int i = 0; i < n; ++i) { - s[i + 1] = s[i] + nums[i]; - } - int[][] pre = new int[n][0]; - int[][] suf = new int[n][0]; - for (int i = 0, t = 0, idx = 0; i < n - k + 1; ++i) { - int cur = s[i + k] - s[i]; - if (cur > t) { - pre[i + k - 1] = new int[] {cur, i}; - t = cur; - idx = i; - } else { - pre[i + k - 1] = new int[] {t, idx}; - } - } - for (int i = n - k, t = 0, idx = 0; i >= 0; --i) { - int cur = s[i + k] - s[i]; - if (cur >= t) { - suf[i] = new int[] {cur, i}; - t = cur; - idx = i; - } else { - suf[i] = new int[] {t, idx}; - } - } - int[] ans = new int[0]; - for (int i = k, t = 0; i < n - 2 * k + 1; ++i) { - int cur = s[i + k] - s[i] + pre[i - 1][0] + suf[i + k][0]; - if (cur > t) { - ans = new int[] {pre[i - 1][1], i, suf[i + k][1]}; - t = cur; + int[] ans = new int[3]; + int s = 0, s1 = 0, s2 = 0, s3 = 0; + int mx1 = 0, mx12 = 0; + int idx1 = 0, idx121 = 0, idx122 = 0; + for (int i = k * 2; i < nums.length; ++i) { + s1 += nums[i - k * 2]; + s2 += nums[i - k]; + s3 += nums[i]; + if (i >= k * 3 - 1) { + if (s1 > mx1) { + mx1 = s1; + idx1 = i - k * 3 + 1; + } + if (mx1 + s2 > mx12) { + mx12 = mx1 + s2; + idx121 = idx1; + idx122 = i - k * 2 + 1; + } + if (mx12 + s3 > s) { + s = mx12 + s3; + ans = new int[] {idx121, idx122, i - k + 1}; + } + s1 -= nums[i - k * 3 + 1]; + s2 -= nums[i - k * 2 + 1]; + s3 -= nums[i - k + 1]; } } return ans; diff --git a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution.py b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution.py index fa1bd07acbdd9..be0a31f731688 100644 --- a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution.py +++ b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution.py @@ -1,27 +1,24 @@ class Solution: def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]: - n = len(nums) - s = list(accumulate(nums, initial=0)) - pre = [[] for _ in range(n)] - suf = [[] for _ in range(n)] - t = idx = 0 - for i in range(n - k + 1): - if (cur := s[i + k] - s[i]) > t: - pre[i + k - 1] = [cur, i] - t, idx = pre[i + k - 1] - else: - pre[i + k - 1] = [t, idx] - t = idx = 0 - for i in range(n - k, -1, -1): - if (cur := s[i + k] - s[i]) >= t: - suf[i] = [cur, i] - t, idx = suf[i] - else: - suf[i] = [t, idx] - t = 0 + s = s1 = s2 = s3 = 0 + mx1 = mx12 = 0 + idx1, idx12 = 0, () ans = [] - for i in range(k, n - 2 * k + 1): - if (cur := s[i + k] - s[i] + pre[i - 1][0] + suf[i + k][0]) > t: - ans = [pre[i - 1][1], i, suf[i + k][1]] - t = cur + for i in range(k * 2, len(nums)): + s1 += nums[i - k * 2] + s2 += nums[i - k] + s3 += nums[i] + if i >= k * 3 - 1: + if s1 > mx1: + mx1 = s1 + idx1 = i - k * 3 + 1 + if mx1 + s2 > mx12: + mx12 = mx1 + s2 + idx12 = (idx1, i - k * 2 + 1) + if mx12 + s3 > s: + s = mx12 + s3 + ans = [*idx12, i - k + 1] + s1 -= nums[i - k * 3 + 1] + s2 -= nums[i - k * 2 + 1] + s3 -= nums[i - k + 1] return ans diff --git a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution2.cpp b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution2.cpp new file mode 100644 index 0000000000000..8baeba40d1770 --- /dev/null +++ b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution2.cpp @@ -0,0 +1,46 @@ +class Solution { +public: + vector maxSumOfThreeSubarrays(vector& nums, int k) { + int n = nums.size(); + vector s(n + 1, 0); + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + + vector> pre(n, vector(2, 0)); + vector> suf(n, vector(2, 0)); + + for (int i = 0, t = 0, idx = 0; i < n - k + 1; ++i) { + int cur = s[i + k] - s[i]; + if (cur > t) { + pre[i + k - 1] = {cur, i}; + t = cur; + idx = i; + } else { + pre[i + k - 1] = {t, idx}; + } + } + + for (int i = n - k, t = 0, idx = 0; i >= 0; --i) { + int cur = s[i + k] - s[i]; + if (cur >= t) { + suf[i] = {cur, i}; + t = cur; + idx = i; + } else { + suf[i] = {t, idx}; + } + } + + vector ans; + for (int i = k, t = 0; i < n - 2 * k + 1; ++i) { + int cur = s[i + k] - s[i] + pre[i - 1][0] + suf[i + k][0]; + if (cur > t) { + ans = {pre[i - 1][1], i, suf[i + k][1]}; + t = cur; + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution2.go b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution2.go new file mode 100644 index 0000000000000..f42deecc50470 --- /dev/null +++ b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution2.go @@ -0,0 +1,40 @@ +func maxSumOfThreeSubarrays(nums []int, k int) (ans []int) { + n := len(nums) + s := make([]int, n+1) + for i := 0; i < n; i++ { + s[i+1] = s[i] + nums[i] + } + + pre := make([][]int, n) + suf := make([][]int, n) + + for i, t, idx := 0, 0, 0; i < n-k+1; i++ { + cur := s[i+k] - s[i] + if cur > t { + pre[i+k-1] = []int{cur, i} + t, idx = cur, i + } else { + pre[i+k-1] = []int{t, idx} + } + } + + for i, t, idx := n-k, 0, 0; i >= 0; i-- { + cur := s[i+k] - s[i] + if cur >= t { + suf[i] = []int{cur, i} + t, idx = cur, i + } else { + suf[i] = []int{t, idx} + } + } + + for i, t := k, 0; i < n-2*k+1; i++ { + cur := s[i+k] - s[i] + pre[i-1][0] + suf[i+k][0] + if cur > t { + ans = []int{pre[i-1][1], i, suf[i+k][1]} + t = cur + } + } + + return +} \ No newline at end of file diff --git a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution2.java b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution2.java new file mode 100644 index 0000000000000..9143c7df011fe --- /dev/null +++ b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution2.java @@ -0,0 +1,40 @@ +class Solution { + public int[] maxSumOfThreeSubarrays(int[] nums, int k) { + int n = nums.length; + int[] s = new int[n + 1]; + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + int[][] pre = new int[n][0]; + int[][] suf = new int[n][0]; + for (int i = 0, t = 0, idx = 0; i < n - k + 1; ++i) { + int cur = s[i + k] - s[i]; + if (cur > t) { + pre[i + k - 1] = new int[] {cur, i}; + t = cur; + idx = i; + } else { + pre[i + k - 1] = new int[] {t, idx}; + } + } + for (int i = n - k, t = 0, idx = 0; i >= 0; --i) { + int cur = s[i + k] - s[i]; + if (cur >= t) { + suf[i] = new int[] {cur, i}; + t = cur; + idx = i; + } else { + suf[i] = new int[] {t, idx}; + } + } + int[] ans = new int[0]; + for (int i = k, t = 0; i < n - 2 * k + 1; ++i) { + int cur = s[i + k] - s[i] + pre[i - 1][0] + suf[i + k][0]; + if (cur > t) { + ans = new int[] {pre[i - 1][1], i, suf[i + k][1]}; + t = cur; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution2.py b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution2.py new file mode 100644 index 0000000000000..fa1bd07acbdd9 --- /dev/null +++ b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/Solution2.py @@ -0,0 +1,27 @@ +class Solution: + def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]: + n = len(nums) + s = list(accumulate(nums, initial=0)) + pre = [[] for _ in range(n)] + suf = [[] for _ in range(n)] + t = idx = 0 + for i in range(n - k + 1): + if (cur := s[i + k] - s[i]) > t: + pre[i + k - 1] = [cur, i] + t, idx = pre[i + k - 1] + else: + pre[i + k - 1] = [t, idx] + t = idx = 0 + for i in range(n - k, -1, -1): + if (cur := s[i + k] - s[i]) >= t: + suf[i] = [cur, i] + t, idx = suf[i] + else: + suf[i] = [t, idx] + t = 0 + ans = [] + for i in range(k, n - 2 * k + 1): + if (cur := s[i + k] - s[i] + pre[i - 1][0] + suf[i + k][0]) > t: + ans = [pre[i - 1][1], i, suf[i + k][1]] + t = cur + return ans diff --git a/solution/0600-0699/0690.Employee Importance/Solution.java b/solution/0600-0699/0690.Employee Importance/Solution.java index 9c73a1aea36b0..42ca225c307ce 100644 --- a/solution/0600-0699/0690.Employee Importance/Solution.java +++ b/solution/0600-0699/0690.Employee Importance/Solution.java @@ -26,4 +26,4 @@ private int dfs(int id) { } return sum; } -} +} \ No newline at end of file diff --git a/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.cpp b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.cpp index 6e44e0223a205..3a97d822261ce 100644 --- a/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.cpp +++ b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.cpp @@ -1,7 +1,13 @@ class Solution { public: bool hasAlternatingBits(int n) { - n ^= (n >> 1); - return (n & ((long) n + 1)) == 0; + int prev = -1; + while (n) { + int curr = n & 1; + if (prev == curr) return false; + prev = curr; + n >>= 1; + } + return true; } }; \ No newline at end of file diff --git a/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.go b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.go index fb62e6edc35a5..b8d4566909de8 100644 --- a/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.go +++ b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.go @@ -1,4 +1,12 @@ func hasAlternatingBits(n int) bool { - n ^= (n >> 1) - return (n & (n + 1)) == 0 + prev := -1 + for n != 0 { + curr := n & 1 + if prev == curr { + return false + } + prev = curr + n >>= 1 + } + return true } \ No newline at end of file diff --git a/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.java b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.java index 17656a58893db..61f5fa2fb6fc8 100644 --- a/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.java +++ b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.java @@ -1,6 +1,14 @@ -class Solution { - public boolean hasAlternatingBits(int n) { - n ^= (n >> 1); - return (n & (n + 1)) == 0; - } +class Solution { + public boolean hasAlternatingBits(int n) { + int prev = -1; + while (n != 0) { + int curr = n & 1; + if (prev == curr) { + return false; + } + prev = curr; + n >>= 1; + } + return true; + } } \ No newline at end of file diff --git a/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.py b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.py index dc828384b567c..fed2d30c3f357 100644 --- a/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.py +++ b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.py @@ -1,4 +1,10 @@ -class Solution: - def hasAlternatingBits(self, n: int) -> bool: - n ^= n >> 1 - return (n & (n + 1)) == 0 +class Solution: + def hasAlternatingBits(self, n: int) -> bool: + prev = -1 + while n: + curr = n & 1 + if prev == curr: + return False + prev = curr + n >>= 1 + return True diff --git a/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.rs b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.rs index 81bad598e63a9..7708afd31155a 100644 --- a/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.rs +++ b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.rs @@ -1,6 +1,15 @@ impl Solution { - pub fn has_alternating_bits(n: i32) -> bool { - let t = n ^ (n >> 1); - (t & (t + 1)) == 0 + pub fn has_alternating_bits(mut n: i32) -> bool { + let u = n & 3; + if u != 1 && u != 2 { + return false; + } + while n != 0 { + if (n & 3) != u { + return false; + } + n >>= 2; + } + true } } diff --git a/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution2.cpp b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution2.cpp new file mode 100644 index 0000000000000..6e44e0223a205 --- /dev/null +++ b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution2.cpp @@ -0,0 +1,7 @@ +class Solution { +public: + bool hasAlternatingBits(int n) { + n ^= (n >> 1); + return (n & ((long) n + 1)) == 0; + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution2.go b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution2.go new file mode 100644 index 0000000000000..fb62e6edc35a5 --- /dev/null +++ b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution2.go @@ -0,0 +1,4 @@ +func hasAlternatingBits(n int) bool { + n ^= (n >> 1) + return (n & (n + 1)) == 0 +} \ No newline at end of file diff --git a/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution2.java b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution2.java new file mode 100644 index 0000000000000..34325336b732e --- /dev/null +++ b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution2.java @@ -0,0 +1,6 @@ +class Solution { + public boolean hasAlternatingBits(int n) { + n ^= (n >> 1); + return (n & (n + 1)) == 0; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution2.py b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution2.py new file mode 100644 index 0000000000000..4234424d15479 --- /dev/null +++ b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution2.py @@ -0,0 +1,4 @@ +class Solution: + def hasAlternatingBits(self, n: int) -> bool: + n ^= n >> 1 + return (n & (n + 1)) == 0 diff --git a/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution2.rs b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution2.rs new file mode 100644 index 0000000000000..81bad598e63a9 --- /dev/null +++ b/solution/0600-0699/0693.Binary Number with Alternating Bits/Solution2.rs @@ -0,0 +1,6 @@ +impl Solution { + pub fn has_alternating_bits(n: i32) -> bool { + let t = n ^ (n >> 1); + (t & (t + 1)) == 0 + } +} diff --git a/solution/0600-0699/0694.Number of Distinct Islands/Solution.cpp b/solution/0600-0699/0694.Number of Distinct Islands/Solution.cpp index 1a16d72904159..337c76caa75af 100644 --- a/solution/0600-0699/0694.Number of Distinct Islands/Solution.cpp +++ b/solution/0600-0699/0694.Number of Distinct Islands/Solution.cpp @@ -1,32 +1,32 @@ -class Solution { -public: - int numDistinctIslands(vector>& grid) { - unordered_set paths; - string path; - int m = grid.size(), n = grid[0].size(); - int dirs[5] = {-1, 0, 1, 0, -1}; - - function dfs = [&](int i, int j, int k) { - grid[i][j] = 0; - path += to_string(k); - for (int h = 1; h < 5; ++h) { - int x = i + dirs[h - 1], y = j + dirs[h]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y]) { - dfs(x, y, h); - } - } - path += to_string(k); - }; - - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j]) { - dfs(i, j, 0); - paths.insert(path); - path.clear(); - } - } - } - return paths.size(); - } +class Solution { +public: + int numDistinctIslands(vector>& grid) { + unordered_set paths; + string path; + int m = grid.size(), n = grid[0].size(); + int dirs[5] = {-1, 0, 1, 0, -1}; + + function dfs = [&](int i, int j, int k) { + grid[i][j] = 0; + path += to_string(k); + for (int h = 1; h < 5; ++h) { + int x = i + dirs[h - 1], y = j + dirs[h]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y]) { + dfs(x, y, h); + } + } + path += to_string(k); + }; + + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j]) { + dfs(i, j, 0); + paths.insert(path); + path.clear(); + } + } + } + return paths.size(); + } }; \ No newline at end of file diff --git a/solution/0600-0699/0694.Number of Distinct Islands/Solution.java b/solution/0600-0699/0694.Number of Distinct Islands/Solution.java index 79f2c6431e543..b7b261eb96b46 100644 --- a/solution/0600-0699/0694.Number of Distinct Islands/Solution.java +++ b/solution/0600-0699/0694.Number of Distinct Islands/Solution.java @@ -1,37 +1,37 @@ -class Solution { - private int m; - private int n; - private int[][] grid; - private StringBuilder path = new StringBuilder(); - - public int numDistinctIslands(int[][] grid) { - m = grid.length; - n = grid[0].length; - this.grid = grid; - Set paths = new HashSet<>(); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == 1) { - dfs(i, j, 0); - paths.add(path.toString()); - path.setLength(0); - } - } - } - return paths.size(); - } - - private void dfs(int i, int j, int k) { - grid[i][j] = 0; - path.append(k); - int[] dirs = {-1, 0, 1, 0, -1}; - for (int h = 1; h < 5; ++h) { - int x = i + dirs[h - 1]; - int y = j + dirs[h]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) { - dfs(x, y, h); - } - } - path.append(k); - } +class Solution { + private int m; + private int n; + private int[][] grid; + private StringBuilder path = new StringBuilder(); + + public int numDistinctIslands(int[][] grid) { + m = grid.length; + n = grid[0].length; + this.grid = grid; + Set paths = new HashSet<>(); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 1) { + dfs(i, j, 0); + paths.add(path.toString()); + path.setLength(0); + } + } + } + return paths.size(); + } + + private void dfs(int i, int j, int k) { + grid[i][j] = 0; + path.append(k); + int[] dirs = {-1, 0, 1, 0, -1}; + for (int h = 1; h < 5; ++h) { + int x = i + dirs[h - 1]; + int y = j + dirs[h]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) { + dfs(x, y, h); + } + } + path.append(k); + } } \ No newline at end of file diff --git a/solution/0600-0699/0694.Number of Distinct Islands/Solution.py b/solution/0600-0699/0694.Number of Distinct Islands/Solution.py index 50894e729bbbe..db2307c8cc22f 100644 --- a/solution/0600-0699/0694.Number of Distinct Islands/Solution.py +++ b/solution/0600-0699/0694.Number of Distinct Islands/Solution.py @@ -1,22 +1,22 @@ -class Solution: - def numDistinctIslands(self, grid: List[List[int]]) -> int: - def dfs(i: int, j: int, k: int): - grid[i][j] = 0 - path.append(str(k)) - dirs = (-1, 0, 1, 0, -1) - for h in range(1, 5): - x, y = i + dirs[h - 1], j + dirs[h] - if 0 <= x < m and 0 <= y < n and grid[x][y]: - dfs(x, y, h) - path.append(str(-k)) - - paths = set() - path = [] - m, n = len(grid), len(grid[0]) - for i, row in enumerate(grid): - for j, x in enumerate(row): - if x: - dfs(i, j, 0) - paths.add("".join(path)) - path.clear() - return len(paths) +class Solution: + def numDistinctIslands(self, grid: List[List[int]]) -> int: + def dfs(i: int, j: int, k: int): + grid[i][j] = 0 + path.append(str(k)) + dirs = (-1, 0, 1, 0, -1) + for h in range(1, 5): + x, y = i + dirs[h - 1], j + dirs[h] + if 0 <= x < m and 0 <= y < n and grid[x][y]: + dfs(x, y, h) + path.append(str(-k)) + + paths = set() + path = [] + m, n = len(grid), len(grid[0]) + for i, row in enumerate(grid): + for j, x in enumerate(row): + if x: + dfs(i, j, 0) + paths.add("".join(path)) + path.clear() + return len(paths) diff --git a/solution/0600-0699/0695.Max Area of Island/Solution.cpp b/solution/0600-0699/0695.Max Area of Island/Solution.cpp index ce3c17b6f64e3..6377276aa4e94 100644 --- a/solution/0600-0699/0695.Max Area of Island/Solution.cpp +++ b/solution/0600-0699/0695.Max Area of Island/Solution.cpp @@ -1,28 +1,28 @@ -class Solution { -public: - int maxAreaOfIsland(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - int dirs[5] = {-1, 0, 1, 0, -1}; - int ans = 0; - function dfs = [&](int i, int j) { - if (grid[i][j] == 0) { - return 0; - } - int ans = 1; - grid[i][j] = 0; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n) { - ans += dfs(x, y); - } - } - return ans; - }; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - ans = max(ans, dfs(i, j)); - } - } - return ans; - } +class Solution { +public: + int maxAreaOfIsland(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int dirs[5] = {-1, 0, 1, 0, -1}; + int ans = 0; + function dfs = [&](int i, int j) { + if (grid[i][j] == 0) { + return 0; + } + int ans = 1; + grid[i][j] = 0; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n) { + ans += dfs(x, y); + } + } + return ans; + }; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans = max(ans, dfs(i, j)); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0600-0699/0695.Max Area of Island/Solution.java b/solution/0600-0699/0695.Max Area of Island/Solution.java index 8250650f724f1..7e75932296920 100644 --- a/solution/0600-0699/0695.Max Area of Island/Solution.java +++ b/solution/0600-0699/0695.Max Area of Island/Solution.java @@ -1,34 +1,34 @@ -class Solution { - private int m; - private int n; - private int[][] grid; - - public int maxAreaOfIsland(int[][] grid) { - m = grid.length; - n = grid[0].length; - this.grid = grid; - int ans = 0; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - ans = Math.max(ans, dfs(i, j)); - } - } - return ans; - } - - private int dfs(int i, int j) { - if (grid[i][j] == 0) { - return 0; - } - int ans = 1; - grid[i][j] = 0; - int[] dirs = {-1, 0, 1, 0, -1}; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n) { - ans += dfs(x, y); - } - } - return ans; - } +class Solution { + private int m; + private int n; + private int[][] grid; + + public int maxAreaOfIsland(int[][] grid) { + m = grid.length; + n = grid[0].length; + this.grid = grid; + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans = Math.max(ans, dfs(i, j)); + } + } + return ans; + } + + private int dfs(int i, int j) { + if (grid[i][j] == 0) { + return 0; + } + int ans = 1; + grid[i][j] = 0; + int[] dirs = {-1, 0, 1, 0, -1}; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n) { + ans += dfs(x, y); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0600-0699/0695.Max Area of Island/Solution.py b/solution/0600-0699/0695.Max Area of Island/Solution.py index cbaf00bae009d..c94710af5bd22 100644 --- a/solution/0600-0699/0695.Max Area of Island/Solution.py +++ b/solution/0600-0699/0695.Max Area of Island/Solution.py @@ -1,16 +1,16 @@ -class Solution: - def maxAreaOfIsland(self, grid: List[List[int]]) -> int: - def dfs(i: int, j: int) -> int: - if grid[i][j] == 0: - return 0 - ans = 1 - grid[i][j] = 0 - dirs = (-1, 0, 1, 0, -1) - for a, b in pairwise(dirs): - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n: - ans += dfs(x, y) - return ans - - m, n = len(grid), len(grid[0]) - return max(dfs(i, j) for i in range(m) for j in range(n)) +class Solution: + def maxAreaOfIsland(self, grid: List[List[int]]) -> int: + def dfs(i: int, j: int) -> int: + if grid[i][j] == 0: + return 0 + ans = 1 + grid[i][j] = 0 + dirs = (-1, 0, 1, 0, -1) + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n: + ans += dfs(x, y) + return ans + + m, n = len(grid), len(grid[0]) + return max(dfs(i, j) for i in range(m) for j in range(n)) diff --git a/solution/0600-0699/0697.Degree of an Array/Solution.go b/solution/0600-0699/0697.Degree of an Array/Solution.go index 78ac336e12a76..9df5df341c6ff 100644 --- a/solution/0600-0699/0697.Degree of an Array/Solution.go +++ b/solution/0600-0699/0697.Degree of an Array/Solution.go @@ -1,52 +1,25 @@ -func findShortestSubArray(nums []int) (ans int) { - ans = 50000 - numsMap := make(map[int]int, len(nums)) - for _, num := range nums { - numsMap[num]++ - } - var maxDegree int - for _, num := range numsMap { - maxDegree = max(num, maxDegree) - } - degreeNums := getMaxDegreeElem(maxDegree, numsMap) - for _, num := range degreeNums { - f := findSubArray(num, nums) - ans = min(ans, f) - } - return -} - -func findSubArray(target int, nums []int) int { - start := getStartIdx(target, nums) - end := getEndIdx(target, nums) - return (end - start) + 1 -} - -func getStartIdx(target int, nums []int) (start int) { - for idx, num := range nums { - if num == target { - start = idx - break +func findShortestSubArray(nums []int) int { + cnt := map[int]int{} + left := map[int]int{} + right := map[int]int{} + var degree int + for i, v := range nums { + cnt[v]++ + if degree < cnt[v] { + degree = cnt[v] } - } - return start -} - -func getEndIdx(target int, nums []int) (end int) { - for i := len(nums) - 1; i > 0; i-- { - if nums[i] == target { - end = i - break + if _, ok := left[v]; !ok { + left[v] = i } + right[v] = i } - return -} - -func getMaxDegreeElem(maxDegree int, numsMap map[int]int) []int { - var ans []int - for key, value := range numsMap { - if value == maxDegree { - ans = append(ans, key) + ans := 100000 + for v, c := range cnt { + if c == degree { + t := right[v] - left[v] + 1 + if ans > t { + ans = t + } } } return ans diff --git a/solution/0600-0699/0697.Degree of an Array/Solution2.go b/solution/0600-0699/0697.Degree of an Array/Solution2.go new file mode 100644 index 0000000000000..78ac336e12a76 --- /dev/null +++ b/solution/0600-0699/0697.Degree of an Array/Solution2.go @@ -0,0 +1,53 @@ +func findShortestSubArray(nums []int) (ans int) { + ans = 50000 + numsMap := make(map[int]int, len(nums)) + for _, num := range nums { + numsMap[num]++ + } + var maxDegree int + for _, num := range numsMap { + maxDegree = max(num, maxDegree) + } + degreeNums := getMaxDegreeElem(maxDegree, numsMap) + for _, num := range degreeNums { + f := findSubArray(num, nums) + ans = min(ans, f) + } + return +} + +func findSubArray(target int, nums []int) int { + start := getStartIdx(target, nums) + end := getEndIdx(target, nums) + return (end - start) + 1 +} + +func getStartIdx(target int, nums []int) (start int) { + for idx, num := range nums { + if num == target { + start = idx + break + } + } + return start +} + +func getEndIdx(target int, nums []int) (end int) { + for i := len(nums) - 1; i > 0; i-- { + if nums[i] == target { + end = i + break + } + } + return +} + +func getMaxDegreeElem(maxDegree int, numsMap map[int]int) []int { + var ans []int + for key, value := range numsMap { + if value == maxDegree { + ans = append(ans, key) + } + } + return ans +} \ No newline at end of file diff --git a/solution/0600-0699/0698.Partition to K Equal Sum Subsets/Solution2.cpp b/solution/0600-0699/0698.Partition to K Equal Sum Subsets/Solution2.cpp new file mode 100644 index 0000000000000..27aa6624efacc --- /dev/null +++ b/solution/0600-0699/0698.Partition to K Equal Sum Subsets/Solution2.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + bool canPartitionKSubsets(vector& nums, int k) { + int s = accumulate(nums.begin(), nums.end(), 0); + if (s % k) { + return false; + } + s /= k; + sort(nums.begin(), nums.end()); + int n = nums.size(); + int mask = (1 << n) - 1; + vector f(1 << n); + function dfs; + dfs = [&](int state, int t) { + if (state == mask) { + return true; + } + if (f[state]) { + return f[state] == 1; + } + for (int i = 0; i < n; ++i) { + if (state >> i & 1) { + continue; + } + if (t + nums[i] > s) { + break; + } + if (dfs(state | 1 << i, (t + nums[i]) % s)) { + f[state] = 1; + return true; + } + } + f[state] = -1; + return false; + }; + return dfs(0, 0); + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0698.Partition to K Equal Sum Subsets/Solution2.go b/solution/0600-0699/0698.Partition to K Equal Sum Subsets/Solution2.go new file mode 100644 index 0000000000000..f6fe76ad4b96c --- /dev/null +++ b/solution/0600-0699/0698.Partition to K Equal Sum Subsets/Solution2.go @@ -0,0 +1,40 @@ +func canPartitionKSubsets(nums []int, k int) bool { + s := 0 + for _, v := range nums { + s += v + } + if s%k != 0 { + return false + } + s /= k + n := len(nums) + f := make([]int, 1<> i & 1) == 1 { + continue + } + if t+v > s { + break + } + if dfs(state|1<> i) & 1) == 1) { + continue; + } + if (t + nums[i] > s) { + break; + } + if (dfs(state | 1 << i, (t + nums[i]) % s)) { + f[state] = 1; + return true; + } + } + f[state] = -1; + return false; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0698.Partition to K Equal Sum Subsets/Solution2.py b/solution/0600-0699/0698.Partition to K Equal Sum Subsets/Solution2.py new file mode 100644 index 0000000000000..f35b99eca5146 --- /dev/null +++ b/solution/0600-0699/0698.Partition to K Equal Sum Subsets/Solution2.py @@ -0,0 +1,21 @@ +class Solution: + def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: + @cache + def dfs(state, t): + if state == mask: + return True + for i, v in enumerate(nums): + if (state >> i) & 1: + continue + if t + v > s: + break + if dfs(state | 1 << i, (t + v) % s): + return True + return False + + s, mod = divmod(sum(nums), k) + if mod: + return False + nums.sort() + mask = (1 << len(nums)) - 1 + return dfs(0, 0) diff --git a/solution/0600-0699/0698.Partition to K Equal Sum Subsets/Solution3.cpp b/solution/0600-0699/0698.Partition to K Equal Sum Subsets/Solution3.cpp new file mode 100644 index 0000000000000..74f3e3ed02713 --- /dev/null +++ b/solution/0600-0699/0698.Partition to K Equal Sum Subsets/Solution3.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + bool canPartitionKSubsets(vector& nums, int k) { + int s = accumulate(nums.begin(), nums.end(), 0); + if (s % k) { + return false; + } + s /= k; + sort(nums.begin(), nums.end()); + int n = nums.size(); + bool f[1 << n]; + int cur[1 << n]; + memset(f, false, sizeof(f)); + memset(cur, 0, sizeof(cur)); + f[0] = 1; + for (int i = 0; i < 1 << n; ++i) { + if (!f[i]) { + continue; + } + for (int j = 0; j < n; ++j) { + if (cur[i] + nums[j] > s) { + break; + } + if ((i >> j & 1) == 0) { + f[i | 1 << j] = true; + cur[i | 1 << j] = (cur[i] + nums[j]) % s; + } + } + } + return f[(1 << n) - 1]; + } +}; \ No newline at end of file diff --git a/solution/0600-0699/0698.Partition to K Equal Sum Subsets/Solution3.go b/solution/0600-0699/0698.Partition to K Equal Sum Subsets/Solution3.go new file mode 100644 index 0000000000000..4d18d8328256b --- /dev/null +++ b/solution/0600-0699/0698.Partition to K Equal Sum Subsets/Solution3.go @@ -0,0 +1,30 @@ +func canPartitionKSubsets(nums []int, k int) bool { + s := 0 + for _, x := range nums { + s += x + } + if s%k != 0 { + return false + } + s /= k + sort.Ints(nums) + n := len(nums) + f := make([]bool, 1< s { + break + } + if i>>j&1 == 0 { + f[i|1< s) { + break; + } + if ((i >> j & 1) == 0) { + cur[i | 1 << j] = (cur[i] + nums[j]) % s; + f[i | 1 << j] = true; + } + } + } + return f[(1 << n) - 1]; + } +} \ No newline at end of file diff --git a/solution/0600-0699/0698.Partition to K Equal Sum Subsets/Solution3.py b/solution/0600-0699/0698.Partition to K Equal Sum Subsets/Solution3.py new file mode 100644 index 0000000000000..08d0e32a79846 --- /dev/null +++ b/solution/0600-0699/0698.Partition to K Equal Sum Subsets/Solution3.py @@ -0,0 +1,22 @@ +class Solution: + def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: + s = sum(nums) + if s % k: + return False + s //= k + nums.sort() + n = len(nums) + f = [False] * (1 << n) + cur = [0] * (1 << n) + f[0] = True + for i in range(1 << n): + if not f[i]: + continue + for j in range(n): + if cur[i] + nums[j] > s: + break + if (i >> j & 1) == 0: + if not f[i | 1 << j]: + cur[i | 1 << j] = (cur[i] + nums[j]) % s + f[i | 1 << j] = True + return f[-1] diff --git a/solution/0700-0799/0701.Insert into a Binary Search Tree/Solution.java b/solution/0700-0799/0701.Insert into a Binary Search Tree/Solution.java index a4abb3d4e70a3..ce930076c394a 100644 --- a/solution/0700-0799/0701.Insert into a Binary Search Tree/Solution.java +++ b/solution/0700-0799/0701.Insert into a Binary Search Tree/Solution.java @@ -14,6 +14,7 @@ * } */ class Solution { + public TreeNode insertIntoBST(TreeNode root, int val) { if (root == null) { return new TreeNode(val); diff --git a/solution/0700-0799/0704.Binary Search/Solution2.rs b/solution/0700-0799/0704.Binary Search/Solution2.rs new file mode 100644 index 0000000000000..3fdbc947fad75 --- /dev/null +++ b/solution/0700-0799/0704.Binary Search/Solution2.rs @@ -0,0 +1,20 @@ +use std::cmp::Ordering; + +impl Solution { + fn binary_search(nums: Vec, target: i32, l: usize, r: usize) -> i32 { + if l == r { + return if nums[l] == target { l as i32 } else { -1 }; + } + let mid = (l + r) >> 1; + match nums[mid].cmp(&target) { + Ordering::Less => Self::binary_search(nums, target, mid + 1, r), + Ordering::Greater => Self::binary_search(nums, target, l, mid), + Ordering::Equal => mid as i32, + } + } + + pub fn search(nums: Vec, target: i32) -> i32 { + let r = nums.len() - 1; + Self::binary_search(nums, target, 0, r) + } +} diff --git a/solution/0700-0799/0705.Design HashSet/Solution2.cpp b/solution/0700-0799/0705.Design HashSet/Solution2.cpp new file mode 100644 index 0000000000000..8da3a098196f7 --- /dev/null +++ b/solution/0700-0799/0705.Design HashSet/Solution2.cpp @@ -0,0 +1,48 @@ +class MyHashSet { +private: + int size = 1000; + vector> data; + +public: + MyHashSet() + : data(size) { + } + + void add(int key) { + if (contains(key)) { + return; + } + int idx = hash(key); + data[idx].push_back(key); + } + + void remove(int key) { + if (!contains(key)) { + return; + } + int idx = hash(key); + data[idx].remove(key); + } + + bool contains(int key) { + int idx = hash(key); + for (auto it = data[idx].begin(); it != data[idx].end(); it++) { + if ((*it) == key) { + return true; + } + } + return false; + } + + int hash(int key) { + return key % size; + } +}; + +/** + * Your MyHashSet object will be instantiated and called as such: + * MyHashSet* obj = new MyHashSet(); + * obj->add(key); + * obj->remove(key); + * bool param_3 = obj->contains(key); + */ \ No newline at end of file diff --git a/solution/0700-0799/0705.Design HashSet/Solution2.go b/solution/0700-0799/0705.Design HashSet/Solution2.go new file mode 100644 index 0000000000000..7bab13c5e28a9 --- /dev/null +++ b/solution/0700-0799/0705.Design HashSet/Solution2.go @@ -0,0 +1,46 @@ +type MyHashSet struct { + data []list.List +} + +func Constructor() MyHashSet { + return MyHashSet{make([]list.List, 1000)} +} + +func (this *MyHashSet) Add(key int) { + if this.Contains(key) { + return + } + idx := this.hash(key) + this.data[idx].PushBack(key) +} + +func (this *MyHashSet) Remove(key int) { + idx := this.hash(key) + for e := this.data[idx].Front(); e != nil; e = e.Next() { + if e.Value.(int) == key { + this.data[idx].Remove(e) + } + } +} + +func (this *MyHashSet) Contains(key int) bool { + idx := this.hash(key) + for e := this.data[idx].Front(); e != nil; e = e.Next() { + if e.Value.(int) == key { + return true + } + } + return false +} + +func (this *MyHashSet) hash(key int) int { + return key % len(this.data) +} + +/** + * Your MyHashSet object will be instantiated and called as such: + * obj := Constructor(); + * obj.Add(key); + * obj.Remove(key); + * param_3 := obj.Contains(key); + */ \ No newline at end of file diff --git a/solution/0700-0799/0705.Design HashSet/Solution2.java b/solution/0700-0799/0705.Design HashSet/Solution2.java new file mode 100644 index 0000000000000..a568033581f79 --- /dev/null +++ b/solution/0700-0799/0705.Design HashSet/Solution2.java @@ -0,0 +1,51 @@ +class MyHashSet { + private static final int SIZE = 1000; + private LinkedList[] data; + + public MyHashSet() { + data = new LinkedList[SIZE]; + for (int i = 0; i < SIZE; ++i) { + data[i] = new LinkedList(); + } + } + + public void add(int key) { + if (contains(key)) { + return; + } + int idx = hash(key); + data[idx].addFirst(key); + } + + public void remove(int key) { + if (!contains(key)) { + return; + } + int idx = hash(key); + data[idx].remove(Integer.valueOf(key)); + } + + public boolean contains(int key) { + int idx = hash(key); + Iterator it = data[idx].iterator(); + while (it.hasNext()) { + Integer e = it.next(); + if (e == key) { + return true; + } + } + return false; + } + + private int hash(int key) { + return key % SIZE; + } +} + +/** + * Your MyHashSet object will be instantiated and called as such: + * MyHashSet obj = new MyHashSet(); + * obj.add(key); + * obj.remove(key); + * boolean param_3 = obj.contains(key); + */ \ No newline at end of file diff --git a/solution/0700-0799/0705.Design HashSet/Solution2.py b/solution/0700-0799/0705.Design HashSet/Solution2.py new file mode 100644 index 0000000000000..9432c49574bd6 --- /dev/null +++ b/solution/0700-0799/0705.Design HashSet/Solution2.py @@ -0,0 +1,30 @@ +class MyHashSet: + def __init__(self): + self.size = 1000 + self.data = [[] for _ in range(self.size)] + + def add(self, key: int) -> None: + if self.contains(key): + return + idx = self.hash(key) + self.data[idx].append(key) + + def remove(self, key: int) -> None: + if not self.contains(key): + return + idx = self.hash(key) + self.data[idx].remove(key) + + def contains(self, key: int) -> bool: + idx = self.hash(key) + return any(v == key for v in self.data[idx]) + + def hash(self, key) -> int: + return key % self.size + + +# Your MyHashSet object will be instantiated and called as such: +# obj = MyHashSet() +# obj.add(key) +# obj.remove(key) +# param_3 = obj.contains(key) diff --git a/solution/0700-0799/0706.Design HashMap/Solution.java b/solution/0700-0799/0706.Design HashMap/Solution.java index a46ccbd7e59f2..af508ca4c8383 100644 --- a/solution/0700-0799/0706.Design HashMap/Solution.java +++ b/solution/0700-0799/0706.Design HashMap/Solution.java @@ -1,27 +1,27 @@ -class MyHashMap { - private int[] data = new int[1000001]; - - public MyHashMap() { - Arrays.fill(data, -1); - } - - public void put(int key, int value) { - data[key] = value; - } - - public int get(int key) { - return data[key]; - } - - public void remove(int key) { - data[key] = -1; - } -} - -/** - * Your MyHashMap object will be instantiated and called as such: - * MyHashMap obj = new MyHashMap(); - * obj.put(key,value); - * int param_2 = obj.get(key); - * obj.remove(key); +class MyHashMap { + private int[] data = new int[1000001]; + + public MyHashMap() { + Arrays.fill(data, -1); + } + + public void put(int key, int value) { + data[key] = value; + } + + public int get(int key) { + return data[key]; + } + + public void remove(int key) { + data[key] = -1; + } +} + +/** + * Your MyHashMap object will be instantiated and called as such: + * MyHashMap obj = new MyHashMap(); + * obj.put(key,value); + * int param_2 = obj.get(key); + * obj.remove(key); */ \ No newline at end of file diff --git a/solution/0700-0799/0706.Design HashMap/Solution.py b/solution/0700-0799/0706.Design HashMap/Solution.py index c4b0413c170af..3b3cf51e57dfd 100644 --- a/solution/0700-0799/0706.Design HashMap/Solution.py +++ b/solution/0700-0799/0706.Design HashMap/Solution.py @@ -1,19 +1,19 @@ -class MyHashMap: - def __init__(self): - self.data = [-1] * 1000001 - - def put(self, key: int, value: int) -> None: - self.data[key] = value - - def get(self, key: int) -> int: - return self.data[key] - - def remove(self, key: int) -> None: - self.data[key] = -1 - - -# Your MyHashMap object will be instantiated and called as such: -# obj = MyHashMap() -# obj.put(key,value) -# param_2 = obj.get(key) -# obj.remove(key) +class MyHashMap: + def __init__(self): + self.data = [-1] * 1000001 + + def put(self, key: int, value: int) -> None: + self.data[key] = value + + def get(self, key: int) -> int: + return self.data[key] + + def remove(self, key: int) -> None: + self.data[key] = -1 + + +# Your MyHashMap object will be instantiated and called as such: +# obj = MyHashMap() +# obj.put(key,value) +# param_2 = obj.get(key) +# obj.remove(key) diff --git a/solution/0700-0799/0707.Design Linked List/Solution2.cpp b/solution/0700-0799/0707.Design Linked List/Solution2.cpp new file mode 100644 index 0000000000000..b7754711ddb7c --- /dev/null +++ b/solution/0700-0799/0707.Design Linked List/Solution2.cpp @@ -0,0 +1,75 @@ +class MyLinkedList { +private: + int e[1010], ne[1010]; + int head = -1, idx = 0, cnt = 0; + +public: + MyLinkedList() { + } + + int get(int index) { + if (index < 0 || index >= cnt) { + return -1; + } + int i = head; + while (index--) { + i = ne[i]; + } + return e[i]; + } + + void addAtHead(int val) { + e[idx] = val; + ne[idx] = head; + head = idx++; + ++cnt; + } + + void addAtTail(int val) { + addAtIndex(cnt, val); + } + + void addAtIndex(int index, int val) { + if (index > cnt) { + return; + } + if (index <= 0) { + addAtHead(val); + return; + } + int i = head; + while (--index) { + i = ne[i]; + } + e[idx] = val; + ne[idx] = ne[i]; + ne[i] = idx++; + ++cnt; + } + + void deleteAtIndex(int index) { + if (index < 0 || index >= cnt) { + return; + } + --cnt; + if (index == 0) { + head = ne[head]; + return; + } + int i = head; + while (--index) { + i = ne[i]; + } + ne[i] = ne[ne[i]]; + } +}; + +/** + * Your MyLinkedList object will be instantiated and called as such: + * MyLinkedList* obj = new MyLinkedList(); + * int param_1 = obj->get(index); + * obj->addAtHead(val); + * obj->addAtTail(val); + * obj->addAtIndex(index,val); + * obj->deleteAtIndex(index); + */ \ No newline at end of file diff --git a/solution/0700-0799/0707.Design Linked List/Solution2.go b/solution/0700-0799/0707.Design Linked List/Solution2.go new file mode 100644 index 0000000000000..a8f383f2a5262 --- /dev/null +++ b/solution/0700-0799/0707.Design Linked List/Solution2.go @@ -0,0 +1,81 @@ +type MyLinkedList struct { + e []int + ne []int + idx int + head int + cnt int +} + +func Constructor() MyLinkedList { + e := make([]int, 1010) + ne := make([]int, 1010) + return MyLinkedList{e, ne, 0, -1, 0} +} + +func (this *MyLinkedList) Get(index int) int { + if index < 0 || index >= this.cnt { + return -1 + } + i := this.head + for ; index > 0; index-- { + i = this.ne[i] + } + return this.e[i] +} + +func (this *MyLinkedList) AddAtHead(val int) { + this.e[this.idx] = val + this.ne[this.idx] = this.head + this.head = this.idx + this.idx++ + this.cnt++ +} + +func (this *MyLinkedList) AddAtTail(val int) { + this.AddAtIndex(this.cnt, val) +} + +func (this *MyLinkedList) AddAtIndex(index int, val int) { + if index > this.cnt { + return + } + if index <= 0 { + this.AddAtHead(val) + return + } + i := this.head + for ; index > 1; index-- { + i = this.ne[i] + } + this.e[this.idx] = val + this.ne[this.idx] = this.ne[i] + this.ne[i] = this.idx + this.idx++ + this.cnt++ +} + +func (this *MyLinkedList) DeleteAtIndex(index int) { + if index < 0 || index >= this.cnt { + return + } + this.cnt-- + if index == 0 { + this.head = this.ne[this.head] + return + } + i := this.head + for ; index > 1; index-- { + i = this.ne[i] + } + this.ne[i] = this.ne[this.ne[i]] +} + +/** + * Your MyLinkedList object will be instantiated and called as such: + * obj := Constructor(); + * param_1 := obj.Get(index); + * obj.AddAtHead(val); + * obj.AddAtTail(val); + * obj.AddAtIndex(index,val); + * obj.DeleteAtIndex(index); + */ \ No newline at end of file diff --git a/solution/0700-0799/0707.Design Linked List/Solution2.java b/solution/0700-0799/0707.Design Linked List/Solution2.java new file mode 100644 index 0000000000000..6effa326b5ef2 --- /dev/null +++ b/solution/0700-0799/0707.Design Linked List/Solution2.java @@ -0,0 +1,76 @@ +class MyLinkedList { + private int[] e = new int[1010]; + private int[] ne = new int[1010]; + private int head = -1; + private int idx; + private int cnt; + + public MyLinkedList() { + } + + public int get(int index) { + if (index < 0 || index >= cnt) { + return -1; + } + int i = head; + while (index-- > 0) { + i = ne[i]; + } + return e[i]; + } + + public void addAtHead(int val) { + e[idx] = val; + ne[idx] = head; + head = idx++; + ++cnt; + } + + public void addAtTail(int val) { + addAtIndex(cnt, val); + } + + public void addAtIndex(int index, int val) { + if (index > cnt) { + return; + } + if (index <= 0) { + addAtHead(val); + return; + } + int i = head; + while (--index > 0) { + i = ne[i]; + } + e[idx] = val; + ne[idx] = ne[i]; + ne[i] = idx++; + ++cnt; + } + + public void deleteAtIndex(int index) { + if (index < 0 || index >= cnt) { + return; + } + --cnt; + if (index == 0) { + head = ne[head]; + return; + } + int i = head; + while (--index > 0) { + i = ne[i]; + } + ne[i] = ne[ne[i]]; + } +} + +/** + * Your MyLinkedList object will be instantiated and called as such: + * MyLinkedList obj = new MyLinkedList(); + * int param_1 = obj.get(index); + * obj.addAtHead(val); + * obj.addAtTail(val); + * obj.addAtIndex(index,val); + * obj.deleteAtIndex(index); + */ \ No newline at end of file diff --git a/solution/0700-0799/0707.Design Linked List/Solution2.py b/solution/0700-0799/0707.Design Linked List/Solution2.py new file mode 100644 index 0000000000000..23c53dc0dd830 --- /dev/null +++ b/solution/0700-0799/0707.Design Linked List/Solution2.py @@ -0,0 +1,61 @@ +class MyLinkedList: + def __init__(self): + self.e = [0] * 1010 + self.ne = [0] * 1010 + self.idx = 0 + self.head = -1 + self.cnt = 0 + + def get(self, index: int) -> int: + if index < 0 or index >= self.cnt: + return -1 + i = self.head + for _ in range(index): + i = self.ne[i] + return self.e[i] + + def addAtHead(self, val: int) -> None: + self.e[self.idx] = val + self.ne[self.idx] = self.head + self.head = self.idx + self.idx += 1 + self.cnt += 1 + + def addAtTail(self, val: int) -> None: + self.addAtIndex(self.cnt, val) + + def addAtIndex(self, index: int, val: int) -> None: + if index > self.cnt: + return + if index <= 0: + self.addAtHead(val) + return + i = self.head + for _ in range(index - 1): + i = self.ne[i] + self.e[self.idx] = val + self.ne[self.idx] = self.ne[i] + self.ne[i] = self.idx + self.idx += 1 + self.cnt += 1 + + def deleteAtIndex(self, index: int) -> None: + if index < 0 or index >= self.cnt: + return -1 + self.cnt -= 1 + if index == 0: + self.head = self.ne[self.head] + return + i = self.head + for _ in range(index - 1): + i = self.ne[i] + self.ne[i] = self.ne[self.ne[i]] + + +# Your MyLinkedList object will be instantiated and called as such: +# obj = MyLinkedList() +# param_1 = obj.get(index) +# obj.addAtHead(val) +# obj.addAtTail(val) +# obj.addAtIndex(index,val) +# obj.deleteAtIndex(index) diff --git a/solution/0700-0799/0707.Design Linked List/Solution2.ts b/solution/0700-0799/0707.Design Linked List/Solution2.ts new file mode 100644 index 0000000000000..c0217e06f8951 --- /dev/null +++ b/solution/0700-0799/0707.Design Linked List/Solution2.ts @@ -0,0 +1,81 @@ +class MyLinkedList { + e: Array; + ne: Array; + idx: number; + head: number; + cnt: number; + + constructor() { + this.e = new Array(1010).fill(0); + this.ne = new Array(1010).fill(0); + this.head = -1; + this.idx = 0; + this.cnt = 0; + } + + get(index: number): number { + if (index < 0 || index >= this.cnt) { + return -1; + } + let i = this.head; + while (index--) { + i = this.ne[i]; + } + return this.e[i]; + } + + addAtHead(val: number): void { + this.e[this.idx] = val; + this.ne[this.idx] = this.head; + this.head = this.idx++; + this.cnt++; + } + + addAtTail(val: number): void { + this.addAtIndex(this.cnt, val); + } + + addAtIndex(index: number, val: number): void { + if (index > this.cnt) { + return; + } + if (index <= 0) { + this.addAtHead(val); + return; + } + let i = this.head; + while (--index) { + i = this.ne[i]; + } + this.e[this.idx] = val; + this.ne[this.idx] = this.ne[i]; + this.ne[i] = this.idx++; + this.cnt++; + } + + deleteAtIndex(index: number): void { + if (index < 0 || index >= this.cnt) { + return; + } + this.cnt--; + if (index == 0) { + this.head = this.ne[this.head]; + return; + } + let i = this.head; + while (--index) { + i = this.ne[i]; + } + this.ne[i] = this.ne[this.ne[i]]; + } +} + +/** + * Your MyLinkedList object will be instantiated and called as such: + * var obj = new MyLinkedList() + * var param_1 = obj.get(index) + * obj.addAtHead(val) + * obj.addAtTail(val) + * obj.addAtIndex(index,val) + * obj.deleteAtIndex(index) + */ diff --git a/solution/0700-0799/0708.Insert into a Sorted Circular Linked List/Solution.cpp b/solution/0700-0799/0708.Insert into a Sorted Circular Linked List/Solution.cpp index 84580318378eb..727ca056efbe2 100644 --- a/solution/0700-0799/0708.Insert into a Sorted Circular Linked List/Solution.cpp +++ b/solution/0700-0799/0708.Insert into a Sorted Circular Linked List/Solution.cpp @@ -1,40 +1,40 @@ -/* -// Definition for a Node. -class Node { -public: - int val; - Node* next; - - Node() {} - - Node(int _val) { - val = _val; - next = NULL; - } - - Node(int _val, Node* _next) { - val = _val; - next = _next; - } -}; -*/ - -class Solution { -public: - Node* insert(Node* head, int insertVal) { - Node* node = new Node(insertVal); - if (!head) { - node->next = node; - return node; - } - Node *prev = head, *curr = head->next; - while (curr != head) { - if ((prev->val <= insertVal && insertVal <= curr->val) || (prev->val > curr->val && (insertVal >= prev->val || insertVal <= curr->val))) break; - prev = curr; - curr = curr->next; - } - prev->next = node; - node->next = curr; - return head; - } +/* +// Definition for a Node. +class Node { +public: + int val; + Node* next; + + Node() {} + + Node(int _val) { + val = _val; + next = NULL; + } + + Node(int _val, Node* _next) { + val = _val; + next = _next; + } +}; +*/ + +class Solution { +public: + Node* insert(Node* head, int insertVal) { + Node* node = new Node(insertVal); + if (!head) { + node->next = node; + return node; + } + Node *prev = head, *curr = head->next; + while (curr != head) { + if ((prev->val <= insertVal && insertVal <= curr->val) || (prev->val > curr->val && (insertVal >= prev->val || insertVal <= curr->val))) break; + prev = curr; + curr = curr->next; + } + prev->next = node; + node->next = curr; + return head; + } }; \ No newline at end of file diff --git a/solution/0700-0799/0709.To Lower Case/Solution.c b/solution/0700-0799/0709.To Lower Case/Solution.c index c1b822ed6441b..4143e54531760 100644 --- a/solution/0700-0799/0709.To Lower Case/Solution.c +++ b/solution/0700-0799/0709.To Lower Case/Solution.c @@ -6,4 +6,4 @@ char* toLowerCase(char* s) { } } return s; -} +} \ No newline at end of file diff --git a/solution/0700-0799/0709.To Lower Case/Solution.rs b/solution/0700-0799/0709.To Lower Case/Solution.rs index 32c623942840e..68607a5c6cafd 100644 --- a/solution/0700-0799/0709.To Lower Case/Solution.rs +++ b/solution/0700-0799/0709.To Lower Case/Solution.rs @@ -1,8 +1,5 @@ impl Solution { pub fn to_lower_case(s: String) -> String { - s.as_bytes() - .iter() - .map(|&c| char::from(if c >= b'A' && c <= b'Z' { c | 32 } else { c })) - .collect() + s.to_ascii_lowercase() } } diff --git a/solution/0700-0799/0709.To Lower Case/Solution.ts b/solution/0700-0799/0709.To Lower Case/Solution.ts index 92ef077abca0c..e0e60bb82e64a 100644 --- a/solution/0700-0799/0709.To Lower Case/Solution.ts +++ b/solution/0700-0799/0709.To Lower Case/Solution.ts @@ -1,3 +1,3 @@ function toLowerCase(s: string): string { - return [...s].map(c => String.fromCharCode(c.charCodeAt(0) | 32)).join(''); + return s.toLowerCase(); } diff --git a/solution/0700-0799/0709.To Lower Case/Solution2.rs b/solution/0700-0799/0709.To Lower Case/Solution2.rs new file mode 100644 index 0000000000000..32c623942840e --- /dev/null +++ b/solution/0700-0799/0709.To Lower Case/Solution2.rs @@ -0,0 +1,8 @@ +impl Solution { + pub fn to_lower_case(s: String) -> String { + s.as_bytes() + .iter() + .map(|&c| char::from(if c >= b'A' && c <= b'Z' { c | 32 } else { c })) + .collect() + } +} diff --git a/solution/0700-0799/0709.To Lower Case/Solution2.ts b/solution/0700-0799/0709.To Lower Case/Solution2.ts new file mode 100644 index 0000000000000..92ef077abca0c --- /dev/null +++ b/solution/0700-0799/0709.To Lower Case/Solution2.ts @@ -0,0 +1,3 @@ +function toLowerCase(s: string): string { + return [...s].map(c => String.fromCharCode(c.charCodeAt(0) | 32)).join(''); +} diff --git a/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/Solution.cpp b/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/Solution.cpp index ee11cccb3e2ed..7590229bf2962 100644 --- a/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/Solution.cpp +++ b/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/Solution.cpp @@ -1,24 +1,24 @@ -class Solution { -public: - int minimumDeleteSum(string s1, string s2) { - int m = s1.size(), n = s2.size(); - int f[m + 1][n + 1]; - memset(f, 0, sizeof f); - for (int i = 1; i <= m; ++i) { - f[i][0] = f[i - 1][0] + s1[i - 1]; - } - for (int j = 1; j <= n; ++j) { - f[0][j] = f[0][j - 1] + s2[j - 1]; - } - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (s1[i - 1] == s2[j - 1]) { - f[i][j] = f[i - 1][j - 1]; - } else { - f[i][j] = min(f[i - 1][j] + s1[i - 1], f[i][j - 1] + s2[j - 1]); - } - } - } - return f[m][n]; - } +class Solution { +public: + int minimumDeleteSum(string s1, string s2) { + int m = s1.size(), n = s2.size(); + int f[m + 1][n + 1]; + memset(f, 0, sizeof f); + for (int i = 1; i <= m; ++i) { + f[i][0] = f[i - 1][0] + s1[i - 1]; + } + for (int j = 1; j <= n; ++j) { + f[0][j] = f[0][j - 1] + s2[j - 1]; + } + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (s1[i - 1] == s2[j - 1]) { + f[i][j] = f[i - 1][j - 1]; + } else { + f[i][j] = min(f[i - 1][j] + s1[i - 1], f[i][j - 1] + s2[j - 1]); + } + } + } + return f[m][n]; + } }; \ No newline at end of file diff --git a/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/Solution.java b/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/Solution.java index 4d85bc9aa77fe..86bab07ea12c0 100644 --- a/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/Solution.java +++ b/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/Solution.java @@ -1,23 +1,23 @@ -class Solution { - public int minimumDeleteSum(String s1, String s2) { - int m = s1.length(), n = s2.length(); - int[][] f = new int[m + 1][n + 1]; - for (int i = 1; i <= m; ++i) { - f[i][0] = f[i - 1][0] + s1.charAt(i - 1); - } - for (int j = 1; j <= n; ++j) { - f[0][j] = f[0][j - 1] + s2.charAt(j - 1); - } - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (s1.charAt(i - 1) == s2.charAt(j - 1)) { - f[i][j] = f[i - 1][j - 1]; - } else { - f[i][j] - = Math.min(f[i - 1][j] + s1.charAt(i - 1), f[i][j - 1] + s2.charAt(j - 1)); - } - } - } - return f[m][n]; - } +class Solution { + public int minimumDeleteSum(String s1, String s2) { + int m = s1.length(), n = s2.length(); + int[][] f = new int[m + 1][n + 1]; + for (int i = 1; i <= m; ++i) { + f[i][0] = f[i - 1][0] + s1.charAt(i - 1); + } + for (int j = 1; j <= n; ++j) { + f[0][j] = f[0][j - 1] + s2.charAt(j - 1); + } + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (s1.charAt(i - 1) == s2.charAt(j - 1)) { + f[i][j] = f[i - 1][j - 1]; + } else { + f[i][j] + = Math.min(f[i - 1][j] + s1.charAt(i - 1), f[i][j - 1] + s2.charAt(j - 1)); + } + } + } + return f[m][n]; + } } \ No newline at end of file diff --git a/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/Solution.py b/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/Solution.py index f6d45231535ca..6e4dafccc01cb 100644 --- a/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/Solution.py +++ b/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/Solution.py @@ -1,17 +1,17 @@ -class Solution: - def minimumDeleteSum(self, s1: str, s2: str) -> int: - m, n = len(s1), len(s2) - f = [[0] * (n + 1) for _ in range(m + 1)] - for i in range(1, m + 1): - f[i][0] = f[i - 1][0] + ord(s1[i - 1]) - for j in range(1, n + 1): - f[0][j] = f[0][j - 1] + ord(s2[j - 1]) - for i in range(1, m + 1): - for j in range(1, n + 1): - if s1[i - 1] == s2[j - 1]: - f[i][j] = f[i - 1][j - 1] - else: - f[i][j] = min( - f[i - 1][j] + ord(s1[i - 1]), f[i][j - 1] + ord(s2[j - 1]) - ) - return f[m][n] +class Solution: + def minimumDeleteSum(self, s1: str, s2: str) -> int: + m, n = len(s1), len(s2) + f = [[0] * (n + 1) for _ in range(m + 1)] + for i in range(1, m + 1): + f[i][0] = f[i - 1][0] + ord(s1[i - 1]) + for j in range(1, n + 1): + f[0][j] = f[0][j - 1] + ord(s2[j - 1]) + for i in range(1, m + 1): + for j in range(1, n + 1): + if s1[i - 1] == s2[j - 1]: + f[i][j] = f[i - 1][j - 1] + else: + f[i][j] = min( + f[i - 1][j] + ord(s1[i - 1]), f[i][j - 1] + ord(s2[j - 1]) + ) + return f[m][n] diff --git a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.cpp b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.cpp index cf0cf7a1608e9..0052306036dec 100644 --- a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.cpp +++ b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.cpp @@ -1,12 +1,12 @@ -class Solution { -public: - int numSubarrayProductLessThanK(vector& nums, int k) { - int ans = 0; - for (int i = 0, j = 0, s = 1; i < nums.size(); ++i) { - s *= nums[i]; - while (j <= i && s >= k) s /= nums[j++]; - ans += i - j + 1; - } - return ans; - } +class Solution { +public: + int numSubarrayProductLessThanK(vector& nums, int k) { + int ans = 0; + for (int i = 0, j = 0, s = 1; i < nums.size(); ++i) { + s *= nums[i]; + while (j <= i && s >= k) s /= nums[j++]; + ans += i - j + 1; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.cpp b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.cpp index edca7705b084e..75297b5a7849d 100644 --- a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.cpp +++ b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.cpp @@ -1,14 +1,24 @@ -class Solution { -public: - int maxProfit(vector& prices, int fee) { - int n = prices.size(); - int f[n][2]; - memset(f, 0, sizeof(f)); - f[0][1] = -prices[0]; - for (int i = 1; i < n; ++i) { - f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i] - fee); - f[i][1] = max(f[i - 1][1], f[i - 1][0] - prices[i]); - } - return f[n - 1][0]; - } +class Solution { +public: + int maxProfit(vector& prices, int fee) { + int n = prices.size(); + int f[n][2]; + memset(f, -1, sizeof(f)); + function dfs = [&](int i, int j) { + if (i >= prices.size()) { + return 0; + } + if (f[i][j] != -1) { + return f[i][j]; + } + int ans = dfs(i + 1, j); + if (j) { + ans = max(ans, prices[i] + dfs(i + 1, 0) - fee); + } else { + ans = max(ans, -prices[i] + dfs(i + 1, 1)); + } + return f[i][j] = ans; + }; + return dfs(0, 0); + } }; \ No newline at end of file diff --git a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.go b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.go index 6ae5c0730806f..6a5cda9185f2c 100644 --- a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.go +++ b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.go @@ -1,7 +1,25 @@ func maxProfit(prices []int, fee int) int { - f0, f1 := 0, -prices[0] - for _, x := range prices[1:] { - f0, f1 = max(f0, f1+x-fee), max(f1, f0-x) + n := len(prices) + f := make([][2]int, n) + for i := range f { + f[i] = [2]int{-1, -1} } - return f0 + var dfs func(i, j int) int + dfs = func(i, j int) int { + if i >= n { + return 0 + } + if f[i][j] != -1 { + return f[i][j] + } + ans := dfs(i+1, j) + if j > 0 { + ans = max(ans, prices[i]+dfs(i+1, 0)-fee) + } else { + ans = max(ans, -prices[i]+dfs(i+1, 1)) + } + f[i][j] = ans + return ans + } + return dfs(0, 0) } \ No newline at end of file diff --git a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.java b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.java index b64f2886af71c..e8bd021be97a9 100644 --- a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.java +++ b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.java @@ -1,11 +1,28 @@ -class Solution { - public int maxProfit(int[] prices, int fee) { - int f0 = 0, f1 = -prices[0]; - for (int i = 1; i < prices.length; ++i) { - int g0 = Math.max(f0, f1 + prices[i] - fee); - f1 = Math.max(f1, f0 - prices[i]); - f0 = g0; - } - return f0; - } +class Solution { + private Integer[][] f; + private int[] prices; + private int fee; + + public int maxProfit(int[] prices, int fee) { + f = new Integer[prices.length][2]; + this.prices = prices; + this.fee = fee; + return dfs(0, 0); + } + + private int dfs(int i, int j) { + if (i >= prices.length) { + return 0; + } + if (f[i][j] != null) { + return f[i][j]; + } + int ans = dfs(i + 1, j); + if (j > 0) { + ans = Math.max(ans, prices[i] + dfs(i + 1, 0) - fee); + } else { + ans = Math.max(ans, -prices[i] + dfs(i + 1, 1)); + } + return f[i][j] = ans; + } } \ No newline at end of file diff --git a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.py b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.py index 837a8ef2fda62..8df6b9c82568d 100644 --- a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.py +++ b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.py @@ -1,6 +1,14 @@ -class Solution: - def maxProfit(self, prices: List[int], fee: int) -> int: - f0, f1 = 0, -prices[0] - for x in prices[1:]: - f0, f1 = max(f0, f1 + x - fee), max(f1, f0 - x) - return f0 +class Solution: + def maxProfit(self, prices: List[int], fee: int) -> int: + @cache + def dfs(i: int, j: int) -> int: + if i >= len(prices): + return 0 + ans = dfs(i + 1, j) + if j: + ans = max(ans, prices[i] + dfs(i + 1, 0) - fee) + else: + ans = max(ans, -prices[i] + dfs(i + 1, 1)) + return ans + + return dfs(0, 0) diff --git a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.ts b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.ts index e460a4b7a184f..bb22aaae593ab 100644 --- a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.ts +++ b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.ts @@ -1,8 +1,20 @@ function maxProfit(prices: number[], fee: number): number { const n = prices.length; - let [f0, f1] = [0, -prices[0]]; - for (const x of prices.slice(1)) { - [f0, f1] = [Math.max(f0, f1 + x - fee), Math.max(f1, f0 - x)]; - } - return f0; + const f: number[][] = Array.from({ length: n }, () => [-1, -1]); + const dfs = (i: number, j: number): number => { + if (i >= n) { + return 0; + } + if (f[i][j] !== -1) { + return f[i][j]; + } + let ans = dfs(i + 1, j); + if (j) { + ans = Math.max(ans, prices[i] + dfs(i + 1, 0) - fee); + } else { + ans = Math.max(ans, -prices[i] + dfs(i + 1, 1)); + } + return (f[i][j] = ans); + }; + return dfs(0, 0); } diff --git a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution2.cpp b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution2.cpp new file mode 100644 index 0000000000000..d3259a3a8114e --- /dev/null +++ b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int maxProfit(vector& prices, int fee) { + int n = prices.size(); + int f[n][2]; + memset(f, 0, sizeof(f)); + f[0][1] = -prices[0]; + for (int i = 1; i < n; ++i) { + f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i] - fee); + f[i][1] = max(f[i - 1][1], f[i - 1][0] - prices[i]); + } + return f[n - 1][0]; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution2.go b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution2.go new file mode 100644 index 0000000000000..f153a7d1b759a --- /dev/null +++ b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution2.go @@ -0,0 +1,10 @@ +func maxProfit(prices []int, fee int) int { + n := len(prices) + f := make([][2]int, n) + f[0][1] = -prices[0] + for i := 1; i < n; i++ { + f[i][0] = max(f[i-1][0], f[i-1][1]+prices[i]-fee) + f[i][1] = max(f[i-1][1], f[i-1][0]-prices[i]) + } + return f[n-1][0] +} \ No newline at end of file diff --git a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution2.java b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution2.java new file mode 100644 index 0000000000000..fdc2a25acdb34 --- /dev/null +++ b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution2.java @@ -0,0 +1,12 @@ +class Solution { + public int maxProfit(int[] prices, int fee) { + int n = prices.length; + int[][] f = new int[n][2]; + f[0][1] = -prices[0]; + for (int i = 1; i < n; ++i) { + f[i][0] = Math.max(f[i - 1][0], f[i - 1][1] + prices[i] - fee); + f[i][1] = Math.max(f[i - 1][1], f[i - 1][0] - prices[i]); + } + return f[n - 1][0]; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution2.py b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution2.py new file mode 100644 index 0000000000000..0a5215f9f41d3 --- /dev/null +++ b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def maxProfit(self, prices: List[int], fee: int) -> int: + n = len(prices) + f = [[0] * 2 for _ in range(n)] + f[0][1] = -prices[0] + for i in range(1, n): + f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i] - fee) + f[i][1] = max(f[i - 1][1], f[i - 1][0] - prices[i]) + return f[n - 1][0] diff --git a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution2.ts b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution2.ts new file mode 100644 index 0000000000000..ff093fd529c98 --- /dev/null +++ b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution2.ts @@ -0,0 +1,10 @@ +function maxProfit(prices: number[], fee: number): number { + const n = prices.length; + const f: number[][] = Array.from({ length: n }, () => [0, 0]); + f[0][1] = -prices[0]; + for (let i = 1; i < n; ++i) { + f[i][0] = Math.max(f[i - 1][0], f[i - 1][1] + prices[i] - fee); + f[i][1] = Math.max(f[i - 1][1], f[i - 1][0] - prices[i]); + } + return f[n - 1][0]; +} diff --git a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution3.cpp b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution3.cpp new file mode 100644 index 0000000000000..985cf2aadd810 --- /dev/null +++ b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution3.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int maxProfit(vector& prices, int fee) { + int f0 = 0, f1 = -prices[0]; + for (int i = 1; i < prices.size(); ++i) { + int g0 = max(f0, f1 + prices[i] - fee); + f1 = max(f1, f0 - prices[i]); + f0 = g0; + } + return f0; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution3.go b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution3.go new file mode 100644 index 0000000000000..6ae5c0730806f --- /dev/null +++ b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution3.go @@ -0,0 +1,7 @@ +func maxProfit(prices []int, fee int) int { + f0, f1 := 0, -prices[0] + for _, x := range prices[1:] { + f0, f1 = max(f0, f1+x-fee), max(f1, f0-x) + } + return f0 +} \ No newline at end of file diff --git a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution3.java b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution3.java new file mode 100644 index 0000000000000..93282146ca2f1 --- /dev/null +++ b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution3.java @@ -0,0 +1,11 @@ +class Solution { + public int maxProfit(int[] prices, int fee) { + int f0 = 0, f1 = -prices[0]; + for (int i = 1; i < prices.length; ++i) { + int g0 = Math.max(f0, f1 + prices[i] - fee); + f1 = Math.max(f1, f0 - prices[i]); + f0 = g0; + } + return f0; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution3.py b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution3.py new file mode 100644 index 0000000000000..fd72ebabf8ea8 --- /dev/null +++ b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution3.py @@ -0,0 +1,6 @@ +class Solution: + def maxProfit(self, prices: List[int], fee: int) -> int: + f0, f1 = 0, -prices[0] + for x in prices[1:]: + f0, f1 = max(f0, f1 + x - fee), max(f1, f0 - x) + return f0 diff --git a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution3.ts b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution3.ts new file mode 100644 index 0000000000000..e460a4b7a184f --- /dev/null +++ b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution3.ts @@ -0,0 +1,8 @@ +function maxProfit(prices: number[], fee: number): number { + const n = prices.length; + let [f0, f1] = [0, -prices[0]]; + for (const x of prices.slice(1)) { + [f0, f1] = [Math.max(f0, f1 + x - fee), Math.max(f1, f0 - x)]; + } + return f0; +} diff --git a/solution/0700-0799/0715.Range Module/Solution.cpp b/solution/0700-0799/0715.Range Module/Solution.cpp index 60f9f0019f31e..727c4709f5082 100644 --- a/solution/0700-0799/0715.Range Module/Solution.cpp +++ b/solution/0700-0799/0715.Range Module/Solution.cpp @@ -1,124 +1,124 @@ -template -class CachedObj { -public: - void* operator new(size_t s) { - if (!head) { - T* a = new T[SIZE]; - for (size_t i = 0; i < SIZE; ++i) - add(a + i); - } - T* p = head; - head = head->CachedObj::next; - return p; - } - void operator delete(void* p, size_t) { - if (p) add(static_cast(p)); - } - virtual ~CachedObj() {} - -protected: - T* next; - -private: - static T* head; - static const size_t SIZE; - static void add(T* p) { - p->CachedObj::next = head; - head = p; - } -}; -template -T* CachedObj::head = 0; -template -const size_t CachedObj::SIZE = 10000; -class Node : public CachedObj { -public: - Node* left; - Node* right; - int add; - bool v; -}; - -class SegmentTree { -private: - Node* root; - -public: - SegmentTree() { - root = new Node(); - } - - void modify(int left, int right, int v) { - modify(left, right, v, 1, 1e9, root); - } - - void modify(int left, int right, int v, int l, int r, Node* node) { - if (l >= left && r <= right) { - node->v = v == 1; - node->add = v; - return; - } - pushdown(node); - int mid = (l + r) >> 1; - if (left <= mid) modify(left, right, v, l, mid, node->left); - if (right > mid) modify(left, right, v, mid + 1, r, node->right); - pushup(node); - } - - bool query(int left, int right) { - return query(left, right, 1, 1e9, root); - } - - bool query(int left, int right, int l, int r, Node* node) { - if (l >= left && r <= right) return node->v; - pushdown(node); - int mid = (l + r) >> 1; - bool v = true; - if (left <= mid) v = v && query(left, right, l, mid, node->left); - if (right > mid) v = v && query(left, right, mid + 1, r, node->right); - return v; - } - - void pushup(Node* node) { - node->v = node->left && node->left->v && node->right && node->right->v; - } - - void pushdown(Node* node) { - if (!node->left) node->left = new Node(); - if (!node->right) node->right = new Node(); - if (node->add) { - node->left->add = node->right->add = node->add; - node->left->v = node->right->v = node->add == 1; - node->add = 0; - } - } -}; - -class RangeModule { -public: - SegmentTree* tree; - - RangeModule() { - tree = new SegmentTree(); - } - - void addRange(int left, int right) { - tree->modify(left, right - 1, 1); - } - - bool queryRange(int left, int right) { - return tree->query(left, right - 1); - } - - void removeRange(int left, int right) { - tree->modify(left, right - 1, -1); - } -}; - -/** - * Your RangeModule object will be instantiated and called as such: - * RangeModule* obj = new RangeModule(); - * obj->addRange(left,right); - * bool param_2 = obj->queryRange(left,right); - * obj->removeRange(left,right); +template +class CachedObj { +public: + void* operator new(size_t s) { + if (!head) { + T* a = new T[SIZE]; + for (size_t i = 0; i < SIZE; ++i) + add(a + i); + } + T* p = head; + head = head->CachedObj::next; + return p; + } + void operator delete(void* p, size_t) { + if (p) add(static_cast(p)); + } + virtual ~CachedObj() {} + +protected: + T* next; + +private: + static T* head; + static const size_t SIZE; + static void add(T* p) { + p->CachedObj::next = head; + head = p; + } +}; +template +T* CachedObj::head = 0; +template +const size_t CachedObj::SIZE = 10000; +class Node : public CachedObj { +public: + Node* left; + Node* right; + int add; + bool v; +}; + +class SegmentTree { +private: + Node* root; + +public: + SegmentTree() { + root = new Node(); + } + + void modify(int left, int right, int v) { + modify(left, right, v, 1, 1e9, root); + } + + void modify(int left, int right, int v, int l, int r, Node* node) { + if (l >= left && r <= right) { + node->v = v == 1; + node->add = v; + return; + } + pushdown(node); + int mid = (l + r) >> 1; + if (left <= mid) modify(left, right, v, l, mid, node->left); + if (right > mid) modify(left, right, v, mid + 1, r, node->right); + pushup(node); + } + + bool query(int left, int right) { + return query(left, right, 1, 1e9, root); + } + + bool query(int left, int right, int l, int r, Node* node) { + if (l >= left && r <= right) return node->v; + pushdown(node); + int mid = (l + r) >> 1; + bool v = true; + if (left <= mid) v = v && query(left, right, l, mid, node->left); + if (right > mid) v = v && query(left, right, mid + 1, r, node->right); + return v; + } + + void pushup(Node* node) { + node->v = node->left && node->left->v && node->right && node->right->v; + } + + void pushdown(Node* node) { + if (!node->left) node->left = new Node(); + if (!node->right) node->right = new Node(); + if (node->add) { + node->left->add = node->right->add = node->add; + node->left->v = node->right->v = node->add == 1; + node->add = 0; + } + } +}; + +class RangeModule { +public: + SegmentTree* tree; + + RangeModule() { + tree = new SegmentTree(); + } + + void addRange(int left, int right) { + tree->modify(left, right - 1, 1); + } + + bool queryRange(int left, int right) { + return tree->query(left, right - 1); + } + + void removeRange(int left, int right) { + tree->modify(left, right - 1, -1); + } +}; + +/** + * Your RangeModule object will be instantiated and called as such: + * RangeModule* obj = new RangeModule(); + * obj->addRange(left,right); + * bool param_2 = obj->queryRange(left,right); + * obj->removeRange(left,right); */ \ No newline at end of file diff --git a/solution/0700-0799/0715.Range Module/Solution.java b/solution/0700-0799/0715.Range Module/Solution.java index 03f7daa325731..1314b3fde08ab 100644 --- a/solution/0700-0799/0715.Range Module/Solution.java +++ b/solution/0700-0799/0715.Range Module/Solution.java @@ -1,101 +1,101 @@ -class Node { - Node left; - Node right; - int add; - boolean v; -} - -class SegmentTree { - private Node root = new Node(); - - public SegmentTree() { - } - - public void modify(int left, int right, int v) { - modify(left, right, v, 1, (int) 1e9, root); - } - - public void modify(int left, int right, int v, int l, int r, Node node) { - if (l >= left && r <= right) { - node.v = v == 1; - node.add = v; - return; - } - pushdown(node); - int mid = (l + r) >> 1; - if (left <= mid) { - modify(left, right, v, l, mid, node.left); - } - if (right > mid) { - modify(left, right, v, mid + 1, r, node.right); - } - pushup(node); - } - - public boolean query(int left, int right) { - return query(left, right, 1, (int) 1e9, root); - } - - public boolean query(int left, int right, int l, int r, Node node) { - if (l >= left && r <= right) { - return node.v; - } - pushdown(node); - int mid = (l + r) >> 1; - boolean v = true; - if (left <= mid) { - v = v && query(left, right, l, mid, node.left); - } - if (right > mid) { - v = v && query(left, right, mid + 1, r, node.right); - } - return v; - } - - public void pushup(Node node) { - node.v = node.left != null && node.left.v && node.right != null && node.right.v; - } - - public void pushdown(Node node) { - if (node.left == null) { - node.left = new Node(); - } - if (node.right == null) { - node.right = new Node(); - } - if (node.add != 0) { - node.left.add = node.add; - node.right.add = node.add; - node.left.v = node.add == 1; - node.right.v = node.add == 1; - node.add = 0; - } - } -} - -class RangeModule { - private SegmentTree tree = new SegmentTree(); - - public RangeModule() { - } - - public void addRange(int left, int right) { - tree.modify(left, right - 1, 1); - } - - public boolean queryRange(int left, int right) { - return tree.query(left, right - 1); - } - - public void removeRange(int left, int right) { - tree.modify(left, right - 1, -1); - } -} - -/** - * Your RangeModule object will be instantiated and called as such: - * RangeModule obj = new RangeModule(); - * obj.addRange(left,right); - * boolean param_2 = obj.queryRange(left,right); - * obj.removeRange(left,right); +class Node { + Node left; + Node right; + int add; + boolean v; +} + +class SegmentTree { + private Node root = new Node(); + + public SegmentTree() { + } + + public void modify(int left, int right, int v) { + modify(left, right, v, 1, (int) 1e9, root); + } + + public void modify(int left, int right, int v, int l, int r, Node node) { + if (l >= left && r <= right) { + node.v = v == 1; + node.add = v; + return; + } + pushdown(node); + int mid = (l + r) >> 1; + if (left <= mid) { + modify(left, right, v, l, mid, node.left); + } + if (right > mid) { + modify(left, right, v, mid + 1, r, node.right); + } + pushup(node); + } + + public boolean query(int left, int right) { + return query(left, right, 1, (int) 1e9, root); + } + + public boolean query(int left, int right, int l, int r, Node node) { + if (l >= left && r <= right) { + return node.v; + } + pushdown(node); + int mid = (l + r) >> 1; + boolean v = true; + if (left <= mid) { + v = v && query(left, right, l, mid, node.left); + } + if (right > mid) { + v = v && query(left, right, mid + 1, r, node.right); + } + return v; + } + + public void pushup(Node node) { + node.v = node.left != null && node.left.v && node.right != null && node.right.v; + } + + public void pushdown(Node node) { + if (node.left == null) { + node.left = new Node(); + } + if (node.right == null) { + node.right = new Node(); + } + if (node.add != 0) { + node.left.add = node.add; + node.right.add = node.add; + node.left.v = node.add == 1; + node.right.v = node.add == 1; + node.add = 0; + } + } +} + +class RangeModule { + private SegmentTree tree = new SegmentTree(); + + public RangeModule() { + } + + public void addRange(int left, int right) { + tree.modify(left, right - 1, 1); + } + + public boolean queryRange(int left, int right) { + return tree.query(left, right - 1); + } + + public void removeRange(int left, int right) { + tree.modify(left, right - 1, -1); + } +} + +/** + * Your RangeModule object will be instantiated and called as such: + * RangeModule obj = new RangeModule(); + * obj.addRange(left,right); + * boolean param_2 = obj.queryRange(left,right); + * obj.removeRange(left,right); */ \ No newline at end of file diff --git a/solution/0700-0799/0715.Range Module/Solution.py b/solution/0700-0799/0715.Range Module/Solution.py index 69b27d0c6d4e6..59f53fe78c294 100644 --- a/solution/0700-0799/0715.Range Module/Solution.py +++ b/solution/0700-0799/0715.Range Module/Solution.py @@ -1,83 +1,83 @@ -class Node: - __slots__ = ['left', 'right', 'add', 'v'] - - def __init__(self): - self.left = None - self.right = None - self.add = 0 - self.v = False - - -class SegmentTree: - __slots__ = ['root'] - - def __init__(self): - self.root = Node() - - def modify(self, left, right, v, l=1, r=int(1e9), node=None): - if node is None: - node = self.root - if l >= left and r <= right: - if v == 1: - node.add = 1 - node.v = True - else: - node.add = -1 - node.v = False - return - self.pushdown(node) - mid = (l + r) >> 1 - if left <= mid: - self.modify(left, right, v, l, mid, node.left) - if right > mid: - self.modify(left, right, v, mid + 1, r, node.right) - self.pushup(node) - - def query(self, left, right, l=1, r=int(1e9), node=None): - if node is None: - node = self.root - if l >= left and r <= right: - return node.v - self.pushdown(node) - mid = (l + r) >> 1 - v = True - if left <= mid: - v = v and self.query(left, right, l, mid, node.left) - if right > mid: - v = v and self.query(left, right, mid + 1, r, node.right) - return v - - def pushup(self, node): - node.v = bool(node.left and node.left.v and node.right and node.right.v) - - def pushdown(self, node): - if node.left is None: - node.left = Node() - if node.right is None: - node.right = Node() - if node.add: - node.left.add = node.right.add = node.add - node.left.v = node.add == 1 - node.right.v = node.add == 1 - node.add = 0 - - -class RangeModule: - def __init__(self): - self.tree = SegmentTree() - - def addRange(self, left: int, right: int) -> None: - self.tree.modify(left, right - 1, 1) - - def queryRange(self, left: int, right: int) -> bool: - return self.tree.query(left, right - 1) - - def removeRange(self, left: int, right: int) -> None: - self.tree.modify(left, right - 1, -1) - - -# Your RangeModule object will be instantiated and called as such: -# obj = RangeModule() -# obj.addRange(left,right) -# param_2 = obj.queryRange(left,right) -# obj.removeRange(left,right) +class Node: + __slots__ = ['left', 'right', 'add', 'v'] + + def __init__(self): + self.left = None + self.right = None + self.add = 0 + self.v = False + + +class SegmentTree: + __slots__ = ['root'] + + def __init__(self): + self.root = Node() + + def modify(self, left, right, v, l=1, r=int(1e9), node=None): + if node is None: + node = self.root + if l >= left and r <= right: + if v == 1: + node.add = 1 + node.v = True + else: + node.add = -1 + node.v = False + return + self.pushdown(node) + mid = (l + r) >> 1 + if left <= mid: + self.modify(left, right, v, l, mid, node.left) + if right > mid: + self.modify(left, right, v, mid + 1, r, node.right) + self.pushup(node) + + def query(self, left, right, l=1, r=int(1e9), node=None): + if node is None: + node = self.root + if l >= left and r <= right: + return node.v + self.pushdown(node) + mid = (l + r) >> 1 + v = True + if left <= mid: + v = v and self.query(left, right, l, mid, node.left) + if right > mid: + v = v and self.query(left, right, mid + 1, r, node.right) + return v + + def pushup(self, node): + node.v = bool(node.left and node.left.v and node.right and node.right.v) + + def pushdown(self, node): + if node.left is None: + node.left = Node() + if node.right is None: + node.right = Node() + if node.add: + node.left.add = node.right.add = node.add + node.left.v = node.add == 1 + node.right.v = node.add == 1 + node.add = 0 + + +class RangeModule: + def __init__(self): + self.tree = SegmentTree() + + def addRange(self, left: int, right: int) -> None: + self.tree.modify(left, right - 1, 1) + + def queryRange(self, left: int, right: int) -> bool: + return self.tree.query(left, right - 1) + + def removeRange(self, left: int, right: int) -> None: + self.tree.modify(left, right - 1, -1) + + +# Your RangeModule object will be instantiated and called as such: +# obj = RangeModule() +# obj.addRange(left,right) +# param_2 = obj.queryRange(left,right) +# obj.removeRange(left,right) diff --git a/solution/0700-0799/0721.Accounts Merge/Solution.java b/solution/0700-0799/0721.Accounts Merge/Solution.java new file mode 100644 index 0000000000000..3fbd05ffc0c63 --- /dev/null +++ b/solution/0700-0799/0721.Accounts Merge/Solution.java @@ -0,0 +1,48 @@ +class Solution { + private int[] p; + + public List> accountsMerge(List> accounts) { + int n = accounts.size(); + p = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + } + Map emailId = new HashMap<>(); + for (int i = 0; i < n; ++i) { + List account = accounts.get(i); + String name = account.get(0); + for (int j = 1; j < account.size(); ++j) { + String email = account.get(j); + if (emailId.containsKey(email)) { + p[find(i)] = find(emailId.get(email)); + } else { + emailId.put(email, i); + } + } + } + Map> mp = new HashMap<>(); + for (int i = 0; i < n; ++i) { + List account = accounts.get(i); + for (int j = 1; j < account.size(); ++j) { + String email = account.get(j); + mp.computeIfAbsent(find(i), k -> new HashSet<>()).add(email); + } + } + List> res = new ArrayList<>(); + for (Map.Entry> entry : mp.entrySet()) { + List t = new LinkedList<>(); + t.addAll(entry.getValue()); + Collections.sort(t); + t.add(0, accounts.get(entry.getKey()).get(0)); + res.add(t); + } + return res; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0722.Remove Comments/Solution.cpp b/solution/0700-0799/0722.Remove Comments/Solution.cpp index 5321b36e51c63..24028013a6f6f 100644 --- a/solution/0700-0799/0722.Remove Comments/Solution.cpp +++ b/solution/0700-0799/0722.Remove Comments/Solution.cpp @@ -1,33 +1,33 @@ -class Solution { -public: - vector removeComments(vector& source) { - vector ans; - string t; - bool blockComment = false; - for (auto& s : source) { - int m = s.size(); - for (int i = 0; i < m; ++i) { - if (blockComment) { - if (i + 1 < m && s[i] == '*' && s[i + 1] == '/') { - blockComment = false; - ++i; - } - } else { - if (i + 1 < m && s[i] == '/' && s[i + 1] == '*') { - blockComment = true; - ++i; - } else if (i + 1 < m && s[i] == '/' && s[i + 1] == '/') { - break; - } else { - t.push_back(s[i]); - } - } - } - if (!blockComment && !t.empty()) { - ans.emplace_back(t); - t.clear(); - } - } - return ans; - } +class Solution { +public: + vector removeComments(vector& source) { + vector ans; + string t; + bool blockComment = false; + for (auto& s : source) { + int m = s.size(); + for (int i = 0; i < m; ++i) { + if (blockComment) { + if (i + 1 < m && s[i] == '*' && s[i + 1] == '/') { + blockComment = false; + ++i; + } + } else { + if (i + 1 < m && s[i] == '/' && s[i + 1] == '*') { + blockComment = true; + ++i; + } else if (i + 1 < m && s[i] == '/' && s[i + 1] == '/') { + break; + } else { + t.push_back(s[i]); + } + } + } + if (!blockComment && !t.empty()) { + ans.emplace_back(t); + t.clear(); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0700-0799/0722.Remove Comments/Solution.java b/solution/0700-0799/0722.Remove Comments/Solution.java index 65f1aaacd2b18..255b2f3d32202 100644 --- a/solution/0700-0799/0722.Remove Comments/Solution.java +++ b/solution/0700-0799/0722.Remove Comments/Solution.java @@ -1,32 +1,32 @@ -class Solution { - public List removeComments(String[] source) { - List ans = new ArrayList<>(); - StringBuilder sb = new StringBuilder(); - boolean blockComment = false; - for (String s : source) { - int m = s.length(); - for (int i = 0; i < m; ++i) { - if (blockComment) { - if (i + 1 < m && s.charAt(i) == '*' && s.charAt(i + 1) == '/') { - blockComment = false; - ++i; - } - } else { - if (i + 1 < m && s.charAt(i) == '/' && s.charAt(i + 1) == '*') { - blockComment = true; - ++i; - } else if (i + 1 < m && s.charAt(i) == '/' && s.charAt(i + 1) == '/') { - break; - } else { - sb.append(s.charAt(i)); - } - } - } - if (!blockComment && sb.length() > 0) { - ans.add(sb.toString()); - sb.setLength(0); - } - } - return ans; - } +class Solution { + public List removeComments(String[] source) { + List ans = new ArrayList<>(); + StringBuilder sb = new StringBuilder(); + boolean blockComment = false; + for (String s : source) { + int m = s.length(); + for (int i = 0; i < m; ++i) { + if (blockComment) { + if (i + 1 < m && s.charAt(i) == '*' && s.charAt(i + 1) == '/') { + blockComment = false; + ++i; + } + } else { + if (i + 1 < m && s.charAt(i) == '/' && s.charAt(i + 1) == '*') { + blockComment = true; + ++i; + } else if (i + 1 < m && s.charAt(i) == '/' && s.charAt(i + 1) == '/') { + break; + } else { + sb.append(s.charAt(i)); + } + } + } + if (!blockComment && sb.length() > 0) { + ans.add(sb.toString()); + sb.setLength(0); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0700-0799/0722.Remove Comments/Solution.py b/solution/0700-0799/0722.Remove Comments/Solution.py index bb321fa4f5a04..8b3a1e3b428c4 100644 --- a/solution/0700-0799/0722.Remove Comments/Solution.py +++ b/solution/0700-0799/0722.Remove Comments/Solution.py @@ -1,25 +1,25 @@ -class Solution: - def removeComments(self, source: List[str]) -> List[str]: - ans = [] - t = [] - block_comment = False - for s in source: - i, m = 0, len(s) - while i < m: - if block_comment: - if i + 1 < m and s[i : i + 2] == "*/": - block_comment = False - i += 1 - else: - if i + 1 < m and s[i : i + 2] == "/*": - block_comment = True - i += 1 - elif i + 1 < m and s[i : i + 2] == "//": - break - else: - t.append(s[i]) - i += 1 - if not block_comment and t: - ans.append("".join(t)) - t.clear() - return ans +class Solution: + def removeComments(self, source: List[str]) -> List[str]: + ans = [] + t = [] + block_comment = False + for s in source: + i, m = 0, len(s) + while i < m: + if block_comment: + if i + 1 < m and s[i : i + 2] == "*/": + block_comment = False + i += 1 + else: + if i + 1 < m and s[i : i + 2] == "/*": + block_comment = True + i += 1 + elif i + 1 < m and s[i : i + 2] == "//": + break + else: + t.append(s[i]) + i += 1 + if not block_comment and t: + ans.append("".join(t)) + t.clear() + return ans diff --git a/solution/0700-0799/0727.Minimum Window Subsequence/Solution.cpp b/solution/0700-0799/0727.Minimum Window Subsequence/Solution.cpp index 5efa4d8f2c9db..40d081043a05b 100644 --- a/solution/0700-0799/0727.Minimum Window Subsequence/Solution.cpp +++ b/solution/0700-0799/0727.Minimum Window Subsequence/Solution.cpp @@ -1,28 +1,28 @@ -class Solution { -public: - string minWindow(string s1, string s2) { - int m = s1.size(), n = s2.size(); - int f[m + 1][n + 1]; - memset(f, 0, sizeof(f)); - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (s1[i - 1] == s2[j - 1]) { - f[i][j] = j == 1 ? i : f[i - 1][j - 1]; - } else { - f[i][j] = f[i - 1][j]; - } - } - } - int p = 0, k = m + 1; - for (int i = 1; i <= m; ++i) { - if (s1[i - 1] == s2[n - 1] && f[i][n]) { - int j = f[i][n] - 1; - if (i - j < k) { - k = i - j; - p = j; - } - } - } - return k > m ? "" : s1.substr(p, k); - } +class Solution { +public: + string minWindow(string s1, string s2) { + int m = s1.size(), n = s2.size(); + int f[m + 1][n + 1]; + memset(f, 0, sizeof(f)); + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (s1[i - 1] == s2[j - 1]) { + f[i][j] = j == 1 ? i : f[i - 1][j - 1]; + } else { + f[i][j] = f[i - 1][j]; + } + } + } + int p = 0, k = m + 1; + for (int i = 1; i <= m; ++i) { + if (s1[i - 1] == s2[n - 1] && f[i][n]) { + int j = f[i][n] - 1; + if (i - j < k) { + k = i - j; + p = j; + } + } + } + return k > m ? "" : s1.substr(p, k); + } }; \ No newline at end of file diff --git a/solution/0700-0799/0727.Minimum Window Subsequence/Solution.java b/solution/0700-0799/0727.Minimum Window Subsequence/Solution.java index c8815f114dd30..397e1f2084766 100644 --- a/solution/0700-0799/0727.Minimum Window Subsequence/Solution.java +++ b/solution/0700-0799/0727.Minimum Window Subsequence/Solution.java @@ -1,26 +1,26 @@ -class Solution { - public String minWindow(String s1, String s2) { - int m = s1.length(), n = s2.length(); - int[][] f = new int[m + 1][n + 1]; - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (s1.charAt(i - 1) == s2.charAt(j - 1)) { - f[i][j] = j == 1 ? i : f[i - 1][j - 1]; - } else { - f[i][j] = f[i - 1][j]; - } - } - } - int p = 0, k = m + 1; - for (int i = 1; i <= m; ++i) { - if (s1.charAt(i - 1) == s2.charAt(n - 1) && f[i][n] > 0) { - int j = f[i][n] - 1; - if (i - j < k) { - k = i - j; - p = j; - } - } - } - return k > m ? "" : s1.substring(p, p + k); - } +class Solution { + public String minWindow(String s1, String s2) { + int m = s1.length(), n = s2.length(); + int[][] f = new int[m + 1][n + 1]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (s1.charAt(i - 1) == s2.charAt(j - 1)) { + f[i][j] = j == 1 ? i : f[i - 1][j - 1]; + } else { + f[i][j] = f[i - 1][j]; + } + } + } + int p = 0, k = m + 1; + for (int i = 1; i <= m; ++i) { + if (s1.charAt(i - 1) == s2.charAt(n - 1) && f[i][n] > 0) { + int j = f[i][n] - 1; + if (i - j < k) { + k = i - j; + p = j; + } + } + } + return k > m ? "" : s1.substring(p, p + k); + } } \ No newline at end of file diff --git a/solution/0700-0799/0727.Minimum Window Subsequence/Solution.py b/solution/0700-0799/0727.Minimum Window Subsequence/Solution.py index b35b66aeed34f..cbef67b090d6b 100644 --- a/solution/0700-0799/0727.Minimum Window Subsequence/Solution.py +++ b/solution/0700-0799/0727.Minimum Window Subsequence/Solution.py @@ -1,18 +1,18 @@ -class Solution: - def minWindow(self, s1: str, s2: str) -> str: - m, n = len(s1), len(s2) - f = [[0] * (n + 1) for _ in range(m + 1)] - for i, a in enumerate(s1, 1): - for j, b in enumerate(s2, 1): - if a == b: - f[i][j] = i if j == 1 else f[i - 1][j - 1] - else: - f[i][j] = f[i - 1][j] - p, k = 0, m + 1 - for i, a in enumerate(s1, 1): - if a == s2[n - 1] and f[i][n]: - j = f[i][n] - 1 - if i - j < k: - k = i - j - p = j - return "" if k > m else s1[p : p + k] +class Solution: + def minWindow(self, s1: str, s2: str) -> str: + m, n = len(s1), len(s2) + f = [[0] * (n + 1) for _ in range(m + 1)] + for i, a in enumerate(s1, 1): + for j, b in enumerate(s2, 1): + if a == b: + f[i][j] = i if j == 1 else f[i - 1][j - 1] + else: + f[i][j] = f[i - 1][j] + p, k = 0, m + 1 + for i, a in enumerate(s1, 1): + if a == s2[n - 1] and f[i][n]: + j = f[i][n] - 1 + if i - j < k: + k = i - j + p = j + return "" if k > m else s1[p : p + k] diff --git a/solution/0700-0799/0728.Self Dividing Numbers/Solution.cpp b/solution/0700-0799/0728.Self Dividing Numbers/Solution.cpp index 1bdad0aca71f4..6ec7bb5bedc2a 100644 --- a/solution/0700-0799/0728.Self Dividing Numbers/Solution.cpp +++ b/solution/0700-0799/0728.Self Dividing Numbers/Solution.cpp @@ -1,18 +1,18 @@ -class Solution { -public: - vector selfDividingNumbers(int left, int right) { - vector ans; - for (int i = left; i <= right; ++i) - if (check(i)) - ans.push_back(i); - return ans; - } - - bool check(int num) { - for (int t = num; t; t /= 10) { - int x = t % 10; - if (x == 0 || num % x) return false; - } - return true; - } +class Solution { +public: + vector selfDividingNumbers(int left, int right) { + vector ans; + for (int i = left; i <= right; ++i) + if (check(i)) + ans.push_back(i); + return ans; + } + + bool check(int num) { + for (int t = num; t; t /= 10) { + int x = t % 10; + if (x == 0 || num % x) return false; + } + return true; + } }; \ No newline at end of file diff --git a/solution/0700-0799/0728.Self Dividing Numbers/Solution.java b/solution/0700-0799/0728.Self Dividing Numbers/Solution.java index 08125ad383927..141289f1646a0 100644 --- a/solution/0700-0799/0728.Self Dividing Numbers/Solution.java +++ b/solution/0700-0799/0728.Self Dividing Numbers/Solution.java @@ -1,21 +1,21 @@ -class Solution { - public List selfDividingNumbers(int left, int right) { - List ans = new ArrayList<>(); - for (int i = left; i <= right; ++i) { - if (check(i)) { - ans.add(i); - } - } - return ans; - } - - private boolean check(int num) { - for (int t = num; t != 0; t /= 10) { - int x = t % 10; - if (x == 0 || num % x != 0) { - return false; - } - } - return true; - } +class Solution { + public List selfDividingNumbers(int left, int right) { + List ans = new ArrayList<>(); + for (int i = left; i <= right; ++i) { + if (check(i)) { + ans.add(i); + } + } + return ans; + } + + private boolean check(int num) { + for (int t = num; t != 0; t /= 10) { + int x = t % 10; + if (x == 0 || num % x != 0) { + return false; + } + } + return true; + } } \ No newline at end of file diff --git a/solution/0700-0799/0728.Self Dividing Numbers/Solution.py b/solution/0700-0799/0728.Self Dividing Numbers/Solution.py index 43f982ef2e9e0..1016c35e412a8 100644 --- a/solution/0700-0799/0728.Self Dividing Numbers/Solution.py +++ b/solution/0700-0799/0728.Self Dividing Numbers/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def selfDividingNumbers(self, left: int, right: int) -> List[int]: - return [ - num - for num in range(left, right + 1) - if all(i != '0' and num % int(i) == 0 for i in str(num)) - ] +class Solution: + def selfDividingNumbers(self, left: int, right: int) -> List[int]: + return [ + num + for num in range(left, right + 1) + if all(i != '0' and num % int(i) == 0 for i in str(num)) + ] diff --git a/solution/0700-0799/0729.My Calendar I/Solution.cpp b/solution/0700-0799/0729.My Calendar I/Solution.cpp index 8c83456ecc38c..cbc395d669f2c 100644 --- a/solution/0700-0799/0729.My Calendar I/Solution.cpp +++ b/solution/0700-0799/0729.My Calendar I/Solution.cpp @@ -1,28 +1,28 @@ -class MyCalendar { -public: - map m; - - MyCalendar() { - } - - bool book(int start, int end) { - ++m[start]; - --m[end]; - int s = 0; - for (auto& [k, v] : m) { - s += v; - if (s > 1) { - --m[start]; - ++m[end]; - return false; - } - } - return true; - } -}; - -/** - * Your MyCalendar object will be instantiated and called as such: - * MyCalendar* obj = new MyCalendar(); - * bool param_1 = obj->book(start,end); +class MyCalendar { +public: + map m; + + MyCalendar() { + } + + bool book(int start, int end) { + ++m[start]; + --m[end]; + int s = 0; + for (auto& [k, v] : m) { + s += v; + if (s > 1) { + --m[start]; + ++m[end]; + return false; + } + } + return true; + } +}; + +/** + * Your MyCalendar object will be instantiated and called as such: + * MyCalendar* obj = new MyCalendar(); + * bool param_1 = obj->book(start,end); */ \ No newline at end of file diff --git a/solution/0700-0799/0729.My Calendar I/Solution.java b/solution/0700-0799/0729.My Calendar I/Solution.java index 8f66a7bdf5599..3d04816dc4b2e 100644 --- a/solution/0700-0799/0729.My Calendar I/Solution.java +++ b/solution/0700-0799/0729.My Calendar I/Solution.java @@ -25,4 +25,4 @@ public boolean book(int start, int end) { /** * Your MyCalendar object will be instantiated and called as such: MyCalendar * obj = new MyCalendar(); boolean param_1 = obj.book(start,end); - */ + */ \ No newline at end of file diff --git a/solution/0700-0799/0731.My Calendar II/Solution.py b/solution/0700-0799/0731.My Calendar II/Solution.py index d927d4d0f4d80..1944c9e7d7c79 100644 --- a/solution/0700-0799/0731.My Calendar II/Solution.py +++ b/solution/0700-0799/0731.My Calendar II/Solution.py @@ -1,23 +1,23 @@ -from sortedcontainers import SortedDict - - -class MyCalendarTwo: - def __init__(self): - self.sd = SortedDict() - - def book(self, start: int, end: int) -> bool: - self.sd[start] = self.sd.get(start, 0) + 1 - self.sd[end] = self.sd.get(end, 0) - 1 - s = 0 - for v in self.sd.values(): - s += v - if s > 2: - self.sd[start] -= 1 - self.sd[end] += 1 - return False - return True - - -# Your MyCalendarTwo object will be instantiated and called as such: -# obj = MyCalendarTwo() -# param_1 = obj.book(start,end) +from sortedcontainers import SortedDict + + +class MyCalendarTwo: + def __init__(self): + self.sd = SortedDict() + + def book(self, start: int, end: int) -> bool: + self.sd[start] = self.sd.get(start, 0) + 1 + self.sd[end] = self.sd.get(end, 0) - 1 + s = 0 + for v in self.sd.values(): + s += v + if s > 2: + self.sd[start] -= 1 + self.sd[end] += 1 + return False + return True + + +# Your MyCalendarTwo object will be instantiated and called as such: +# obj = MyCalendarTwo() +# param_1 = obj.book(start,end) diff --git a/solution/0700-0799/0731.My Calendar II/Solution2.cpp b/solution/0700-0799/0731.My Calendar II/Solution2.cpp new file mode 100644 index 0000000000000..47110e6e8afc7 --- /dev/null +++ b/solution/0700-0799/0731.My Calendar II/Solution2.cpp @@ -0,0 +1,97 @@ +class Node { +public: + Node* left; + Node* right; + int l; + int r; + int mid; + int v; + int add; + + Node(int l, int r) { + this->l = l; + this->r = r; + this->mid = (l + r) >> 1; + this->left = this->right = nullptr; + v = add = 0; + } +}; + +class SegmentTree { +private: + Node* root; + +public: + SegmentTree() { + root = new Node(1, 1e9 + 1); + } + + void modify(int l, int r, int v) { + modify(l, r, v, root); + } + + void modify(int l, int r, int v, Node* node) { + if (l > r) return; + if (node->l >= l && node->r <= r) { + node->v += v; + node->add += v; + return; + } + pushdown(node); + if (l <= node->mid) modify(l, r, v, node->left); + if (r > node->mid) modify(l, r, v, node->right); + pushup(node); + } + + int query(int l, int r) { + return query(l, r, root); + } + + int query(int l, int r, Node* node) { + if (l > r) return 0; + if (node->l >= l && node->r <= r) return node->v; + pushdown(node); + int v = 0; + if (l <= node->mid) v = max(v, query(l, r, node->left)); + if (r > node->mid) v = max(v, query(l, r, node->right)); + return v; + } + + void pushup(Node* node) { + node->v = max(node->left->v, node->right->v); + } + + void pushdown(Node* node) { + if (!node->left) node->left = new Node(node->l, node->mid); + if (!node->right) node->right = new Node(node->mid + 1, node->r); + if (node->add) { + Node* left = node->left; + Node* right = node->right; + left->v += node->add; + right->v += node->add; + left->add += node->add; + right->add += node->add; + node->add = 0; + } + } +}; + +class MyCalendarTwo { +public: + SegmentTree* tree = new SegmentTree(); + + MyCalendarTwo() { + } + + bool book(int start, int end) { + if (tree->query(start + 1, end) >= 2) return false; + tree->modify(start + 1, end, 1); + return true; + } +}; + +/** + * Your MyCalendarTwo object will be instantiated and called as such: + * MyCalendarTwo* obj = new MyCalendarTwo(); + * bool param_1 = obj->book(start,end); + */ \ No newline at end of file diff --git a/solution/0700-0799/0731.My Calendar II/Solution2.go b/solution/0700-0799/0731.My Calendar II/Solution2.go new file mode 100644 index 0000000000000..32cab0ad93397 --- /dev/null +++ b/solution/0700-0799/0731.My Calendar II/Solution2.go @@ -0,0 +1,103 @@ +type node struct { + left *node + right *node + l, mid, r int + v, add int +} + +func newNode(l, r int) *node { + return &node{ + l: l, + r: r, + mid: int(uint(l+r) >> 1), + } +} + +type segmentTree struct { + root *node +} + +func newSegmentTree() *segmentTree { + return &segmentTree{ + root: newNode(1, 1e9+1), + } +} + +func (t *segmentTree) modify(l, r, v int, n *node) { + if l > r { + return + } + if n.l >= l && n.r <= r { + n.v += v + n.add += v + return + } + t.pushdown(n) + if l <= n.mid { + t.modify(l, r, v, n.left) + } + if r > n.mid { + t.modify(l, r, v, n.right) + } + t.pushup(n) +} + +func (t *segmentTree) query(l, r int, n *node) int { + if l > r { + return 0 + } + if n.l >= l && n.r <= r { + return n.v + } + t.pushdown(n) + v := 0 + if l <= n.mid { + v = max(v, t.query(l, r, n.left)) + } + if r > n.mid { + v = max(v, t.query(l, r, n.right)) + } + return v +} + +func (t *segmentTree) pushup(n *node) { + n.v = max(n.left.v, n.right.v) +} + +func (t *segmentTree) pushdown(n *node) { + if n.left == nil { + n.left = newNode(n.l, n.mid) + } + if n.right == nil { + n.right = newNode(n.mid+1, n.r) + } + if n.add != 0 { + n.left.add += n.add + n.right.add += n.add + n.left.v += n.add + n.right.v += n.add + n.add = 0 + } +} + +type MyCalendarTwo struct { + tree *segmentTree +} + +func Constructor() MyCalendarTwo { + return MyCalendarTwo{newSegmentTree()} +} + +func (this *MyCalendarTwo) Book(start int, end int) bool { + if this.tree.query(start+1, end, this.tree.root) >= 2 { + return false + } + this.tree.modify(start+1, end, 1, this.tree.root) + return true +} + +/** + * Your MyCalendarTwo object will be instantiated and called as such: + * obj := Constructor(); + * param_1 := obj.Book(start,end); + */ \ No newline at end of file diff --git a/solution/0700-0799/0731.My Calendar II/Solution2.java b/solution/0700-0799/0731.My Calendar II/Solution2.java new file mode 100644 index 0000000000000..f77e48f08772d --- /dev/null +++ b/solution/0700-0799/0731.My Calendar II/Solution2.java @@ -0,0 +1,108 @@ +class Node { + Node left; + Node right; + int l; + int r; + int mid; + int v; + int add; + public Node(int l, int r) { + this.l = l; + this.r = r; + this.mid = (l + r) >> 1; + } +} + +class SegmentTree { + private Node root = new Node(1, (int) 1e9 + 1); + + public SegmentTree() { + } + + public void modify(int l, int r, int v) { + modify(l, r, v, root); + } + + public void modify(int l, int r, int v, Node node) { + if (l > r) { + return; + } + if (node.l >= l && node.r <= r) { + node.v += v; + node.add += v; + return; + } + pushdown(node); + if (l <= node.mid) { + modify(l, r, v, node.left); + } + if (r > node.mid) { + modify(l, r, v, node.right); + } + pushup(node); + } + + public int query(int l, int r) { + return query(l, r, root); + } + + public int query(int l, int r, Node node) { + if (l > r) { + return 0; + } + if (node.l >= l && node.r <= r) { + return node.v; + } + pushdown(node); + int v = 0; + if (l <= node.mid) { + v = Math.max(v, query(l, r, node.left)); + } + if (r > node.mid) { + v = Math.max(v, query(l, r, node.right)); + } + return v; + } + + public void pushup(Node node) { + node.v = Math.max(node.left.v, node.right.v); + } + + public void pushdown(Node node) { + if (node.left == null) { + node.left = new Node(node.l, node.mid); + } + if (node.right == null) { + node.right = new Node(node.mid + 1, node.r); + } + if (node.add != 0) { + Node left = node.left, right = node.right; + left.add += node.add; + right.add += node.add; + left.v += node.add; + right.v += node.add; + node.add = 0; + } + } +} + +class MyCalendarTwo { + private SegmentTree tree = new SegmentTree(); + + public MyCalendarTwo() { + } + + public boolean book(int start, int end) { + if (tree.query(start + 1, end) >= 2) { + return false; + } + tree.modify(start + 1, end, 1); + return true; + } +} + +/** + * Your MyCalendarTwo object will be instantiated and called as such: + * MyCalendarTwo obj = new MyCalendarTwo(); + * boolean param_1 = obj.book(start,end); + */ \ No newline at end of file diff --git a/solution/0700-0799/0731.My Calendar II/Solution2.py b/solution/0700-0799/0731.My Calendar II/Solution2.py new file mode 100644 index 0000000000000..dd5797afe62fd --- /dev/null +++ b/solution/0700-0799/0731.My Calendar II/Solution2.py @@ -0,0 +1,76 @@ +class Node: + def __init__(self, l, r): + self.left = None + self.right = None + self.l = l + self.r = r + self.mid = (l + r) >> 1 + self.v = 0 + self.add = 0 + + +class SegmentTree: + def __init__(self): + self.root = Node(1, int(1e9 + 1)) + + def modify(self, l, r, v, node=None): + if l > r: + return + if node is None: + node = self.root + if node.l >= l and node.r <= r: + node.v += v + node.add += v + return + self.pushdown(node) + if l <= node.mid: + self.modify(l, r, v, node.left) + if r > node.mid: + self.modify(l, r, v, node.right) + self.pushup(node) + + def query(self, l, r, node=None): + if l > r: + return 0 + if node is None: + node = self.root + if node.l >= l and node.r <= r: + return node.v + self.pushdown(node) + v = 0 + if l <= node.mid: + v = max(v, self.query(l, r, node.left)) + if r > node.mid: + v = max(v, self.query(l, r, node.right)) + return v + + def pushup(self, node): + node.v = max(node.left.v, node.right.v) + + def pushdown(self, node): + if node.left is None: + node.left = Node(node.l, node.mid) + if node.right is None: + node.right = Node(node.mid + 1, node.r) + if node.add: + node.left.v += node.add + node.right.v += node.add + node.left.add += node.add + node.right.add += node.add + node.add = 0 + + +class MyCalendarTwo: + def __init__(self): + self.tree = SegmentTree() + + def book(self, start: int, end: int) -> bool: + if self.tree.query(start + 1, end) >= 2: + return False + self.tree.modify(start + 1, end, 1) + return True + + +# Your MyCalendarTwo object will be instantiated and called as such: +# obj = MyCalendarTwo() +# param_1 = obj.book(start,end) diff --git a/solution/0700-0799/0732.My Calendar III/Solution.cpp b/solution/0700-0799/0732.My Calendar III/Solution.cpp index c98f72a193afd..9a6b54976d6d0 100644 --- a/solution/0700-0799/0732.My Calendar III/Solution.cpp +++ b/solution/0700-0799/0732.My Calendar III/Solution.cpp @@ -1,97 +1,97 @@ -class Node { -public: - Node* left; - Node* right; - int l; - int r; - int mid; - int v; - int add; - - Node(int l, int r) { - this->l = l; - this->r = r; - this->mid = (l + r) >> 1; - this->left = this->right = nullptr; - v = add = 0; - } -}; - -class SegmentTree { -private: - Node* root; - -public: - SegmentTree() { - root = new Node(1, 1e9 + 1); - } - - void modify(int l, int r, int v) { - modify(l, r, v, root); - } - - void modify(int l, int r, int v, Node* node) { - if (l > r) return; - if (node->l >= l && node->r <= r) { - node->v += v; - node->add += v; - return; - } - pushdown(node); - if (l <= node->mid) modify(l, r, v, node->left); - if (r > node->mid) modify(l, r, v, node->right); - pushup(node); - } - - int query(int l, int r) { - return query(l, r, root); - } - - int query(int l, int r, Node* node) { - if (l > r) return 0; - if (node->l >= l && node->r <= r) return node->v; - pushdown(node); - int v = 0; - if (l <= node->mid) v = max(v, query(l, r, node->left)); - if (r > node->mid) v = max(v, query(l, r, node->right)); - return v; - } - - void pushup(Node* node) { - node->v = max(node->left->v, node->right->v); - } - - void pushdown(Node* node) { - if (!node->left) node->left = new Node(node->l, node->mid); - if (!node->right) node->right = new Node(node->mid + 1, node->r); - if (node->add) { - Node* left = node->left; - Node* right = node->right; - left->v += node->add; - right->v += node->add; - left->add += node->add; - right->add += node->add; - node->add = 0; - } - } -}; - -class MyCalendarThree { -public: - SegmentTree* tree; - - MyCalendarThree() { - tree = new SegmentTree(); - } - - int book(int start, int end) { - tree->modify(start + 1, end, 1); - return tree->query(1, 1e9 + 1); - } -}; - -/** - * Your MyCalendarThree object will be instantiated and called as such: - * MyCalendarThree* obj = new MyCalendarThree(); - * int param_1 = obj->book(start,end); +class Node { +public: + Node* left; + Node* right; + int l; + int r; + int mid; + int v; + int add; + + Node(int l, int r) { + this->l = l; + this->r = r; + this->mid = (l + r) >> 1; + this->left = this->right = nullptr; + v = add = 0; + } +}; + +class SegmentTree { +private: + Node* root; + +public: + SegmentTree() { + root = new Node(1, 1e9 + 1); + } + + void modify(int l, int r, int v) { + modify(l, r, v, root); + } + + void modify(int l, int r, int v, Node* node) { + if (l > r) return; + if (node->l >= l && node->r <= r) { + node->v += v; + node->add += v; + return; + } + pushdown(node); + if (l <= node->mid) modify(l, r, v, node->left); + if (r > node->mid) modify(l, r, v, node->right); + pushup(node); + } + + int query(int l, int r) { + return query(l, r, root); + } + + int query(int l, int r, Node* node) { + if (l > r) return 0; + if (node->l >= l && node->r <= r) return node->v; + pushdown(node); + int v = 0; + if (l <= node->mid) v = max(v, query(l, r, node->left)); + if (r > node->mid) v = max(v, query(l, r, node->right)); + return v; + } + + void pushup(Node* node) { + node->v = max(node->left->v, node->right->v); + } + + void pushdown(Node* node) { + if (!node->left) node->left = new Node(node->l, node->mid); + if (!node->right) node->right = new Node(node->mid + 1, node->r); + if (node->add) { + Node* left = node->left; + Node* right = node->right; + left->v += node->add; + right->v += node->add; + left->add += node->add; + right->add += node->add; + node->add = 0; + } + } +}; + +class MyCalendarThree { +public: + SegmentTree* tree; + + MyCalendarThree() { + tree = new SegmentTree(); + } + + int book(int start, int end) { + tree->modify(start + 1, end, 1); + return tree->query(1, 1e9 + 1); + } +}; + +/** + * Your MyCalendarThree object will be instantiated and called as such: + * MyCalendarThree* obj = new MyCalendarThree(); + * int param_1 = obj->book(start,end); */ \ No newline at end of file diff --git a/solution/0700-0799/0732.My Calendar III/Solution.java b/solution/0700-0799/0732.My Calendar III/Solution.java index 53cb31205e589..3e35484a44d75 100644 --- a/solution/0700-0799/0732.My Calendar III/Solution.java +++ b/solution/0700-0799/0732.My Calendar III/Solution.java @@ -1,105 +1,105 @@ -class Node { - Node left; - Node right; - int l; - int r; - int mid; - int v; - int add; - public Node(int l, int r) { - this.l = l; - this.r = r; - this.mid = (l + r) >> 1; - } -} - -class SegmentTree { - private Node root = new Node(1, (int) 1e9 + 1); - - public SegmentTree() { - } - - public void modify(int l, int r, int v) { - modify(l, r, v, root); - } - - public void modify(int l, int r, int v, Node node) { - if (l > r) { - return; - } - if (node.l >= l && node.r <= r) { - node.v += v; - node.add += v; - return; - } - pushdown(node); - if (l <= node.mid) { - modify(l, r, v, node.left); - } - if (r > node.mid) { - modify(l, r, v, node.right); - } - pushup(node); - } - - public int query(int l, int r) { - return query(l, r, root); - } - - public int query(int l, int r, Node node) { - if (l > r) { - return 0; - } - if (node.l >= l && node.r <= r) { - return node.v; - } - pushdown(node); - int v = 0; - if (l <= node.mid) { - v = Math.max(v, query(l, r, node.left)); - } - if (r > node.mid) { - v = Math.max(v, query(l, r, node.right)); - } - return v; - } - - public void pushup(Node node) { - node.v = Math.max(node.left.v, node.right.v); - } - - public void pushdown(Node node) { - if (node.left == null) { - node.left = new Node(node.l, node.mid); - } - if (node.right == null) { - node.right = new Node(node.mid + 1, node.r); - } - if (node.add != 0) { - Node left = node.left, right = node.right; - left.add += node.add; - right.add += node.add; - left.v += node.add; - right.v += node.add; - node.add = 0; - } - } -} - -class MyCalendarThree { - private SegmentTree tree = new SegmentTree(); - - public MyCalendarThree() { - } - - public int book(int start, int end) { - tree.modify(start + 1, end, 1); - return tree.query(1, (int) 1e9 + 1); - } -} - -/** - * Your MyCalendarThree object will be instantiated and called as such: - * MyCalendarThree obj = new MyCalendarThree(); - * int param_1 = obj.book(start,end); +class Node { + Node left; + Node right; + int l; + int r; + int mid; + int v; + int add; + public Node(int l, int r) { + this.l = l; + this.r = r; + this.mid = (l + r) >> 1; + } +} + +class SegmentTree { + private Node root = new Node(1, (int) 1e9 + 1); + + public SegmentTree() { + } + + public void modify(int l, int r, int v) { + modify(l, r, v, root); + } + + public void modify(int l, int r, int v, Node node) { + if (l > r) { + return; + } + if (node.l >= l && node.r <= r) { + node.v += v; + node.add += v; + return; + } + pushdown(node); + if (l <= node.mid) { + modify(l, r, v, node.left); + } + if (r > node.mid) { + modify(l, r, v, node.right); + } + pushup(node); + } + + public int query(int l, int r) { + return query(l, r, root); + } + + public int query(int l, int r, Node node) { + if (l > r) { + return 0; + } + if (node.l >= l && node.r <= r) { + return node.v; + } + pushdown(node); + int v = 0; + if (l <= node.mid) { + v = Math.max(v, query(l, r, node.left)); + } + if (r > node.mid) { + v = Math.max(v, query(l, r, node.right)); + } + return v; + } + + public void pushup(Node node) { + node.v = Math.max(node.left.v, node.right.v); + } + + public void pushdown(Node node) { + if (node.left == null) { + node.left = new Node(node.l, node.mid); + } + if (node.right == null) { + node.right = new Node(node.mid + 1, node.r); + } + if (node.add != 0) { + Node left = node.left, right = node.right; + left.add += node.add; + right.add += node.add; + left.v += node.add; + right.v += node.add; + node.add = 0; + } + } +} + +class MyCalendarThree { + private SegmentTree tree = new SegmentTree(); + + public MyCalendarThree() { + } + + public int book(int start, int end) { + tree.modify(start + 1, end, 1); + return tree.query(1, (int) 1e9 + 1); + } +} + +/** + * Your MyCalendarThree object will be instantiated and called as such: + * MyCalendarThree obj = new MyCalendarThree(); + * int param_1 = obj.book(start,end); */ \ No newline at end of file diff --git a/solution/0700-0799/0732.My Calendar III/Solution.py b/solution/0700-0799/0732.My Calendar III/Solution.py index ac5aee8ce85d5..ba577eb3924cd 100644 --- a/solution/0700-0799/0732.My Calendar III/Solution.py +++ b/solution/0700-0799/0732.My Calendar III/Solution.py @@ -1,74 +1,74 @@ -class Node: - def __init__(self, l, r): - self.left = None - self.right = None - self.l = l - self.r = r - self.mid = (l + r) >> 1 - self.v = 0 - self.add = 0 - - -class SegmentTree: - def __init__(self): - self.root = Node(1, int(1e9 + 1)) - - def modify(self, l, r, v, node=None): - if l > r: - return - if node is None: - node = self.root - if node.l >= l and node.r <= r: - node.v += v - node.add += v - return - self.pushdown(node) - if l <= node.mid: - self.modify(l, r, v, node.left) - if r > node.mid: - self.modify(l, r, v, node.right) - self.pushup(node) - - def query(self, l, r, node=None): - if l > r: - return 0 - if node is None: - node = self.root - if node.l >= l and node.r <= r: - return node.v - self.pushdown(node) - v = 0 - if l <= node.mid: - v = max(v, self.query(l, r, node.left)) - if r > node.mid: - v = max(v, self.query(l, r, node.right)) - return v - - def pushup(self, node): - node.v = max(node.left.v, node.right.v) - - def pushdown(self, node): - if node.left is None: - node.left = Node(node.l, node.mid) - if node.right is None: - node.right = Node(node.mid + 1, node.r) - if node.add: - node.left.v += node.add - node.right.v += node.add - node.left.add += node.add - node.right.add += node.add - node.add = 0 - - -class MyCalendarThree: - def __init__(self): - self.tree = SegmentTree() - - def book(self, start: int, end: int) -> int: - self.tree.modify(start + 1, end, 1) - return self.tree.query(1, int(1e9 + 1)) - - -# Your MyCalendarThree object will be instantiated and called as such: -# obj = MyCalendarThree() -# param_1 = obj.book(start,end) +class Node: + def __init__(self, l, r): + self.left = None + self.right = None + self.l = l + self.r = r + self.mid = (l + r) >> 1 + self.v = 0 + self.add = 0 + + +class SegmentTree: + def __init__(self): + self.root = Node(1, int(1e9 + 1)) + + def modify(self, l, r, v, node=None): + if l > r: + return + if node is None: + node = self.root + if node.l >= l and node.r <= r: + node.v += v + node.add += v + return + self.pushdown(node) + if l <= node.mid: + self.modify(l, r, v, node.left) + if r > node.mid: + self.modify(l, r, v, node.right) + self.pushup(node) + + def query(self, l, r, node=None): + if l > r: + return 0 + if node is None: + node = self.root + if node.l >= l and node.r <= r: + return node.v + self.pushdown(node) + v = 0 + if l <= node.mid: + v = max(v, self.query(l, r, node.left)) + if r > node.mid: + v = max(v, self.query(l, r, node.right)) + return v + + def pushup(self, node): + node.v = max(node.left.v, node.right.v) + + def pushdown(self, node): + if node.left is None: + node.left = Node(node.l, node.mid) + if node.right is None: + node.right = Node(node.mid + 1, node.r) + if node.add: + node.left.v += node.add + node.right.v += node.add + node.left.add += node.add + node.right.add += node.add + node.add = 0 + + +class MyCalendarThree: + def __init__(self): + self.tree = SegmentTree() + + def book(self, start: int, end: int) -> int: + self.tree.modify(start + 1, end, 1) + return self.tree.query(1, int(1e9 + 1)) + + +# Your MyCalendarThree object will be instantiated and called as such: +# obj = MyCalendarThree() +# param_1 = obj.book(start,end) diff --git a/solution/0700-0799/0733.Flood Fill/Solution2.cpp b/solution/0700-0799/0733.Flood Fill/Solution2.cpp new file mode 100644 index 0000000000000..2425f5a5e6722 --- /dev/null +++ b/solution/0700-0799/0733.Flood Fill/Solution2.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + vector> floodFill(vector>& image, int sr, int sc, int color) { + if (image[sr][sc] == color) return image; + int oc = image[sr][sc]; + image[sr][sc] = color; + queue> q; + q.push({sr, sc}); + int dirs[5] = {-1, 0, 1, 0, -1}; + while (!q.empty()) { + auto [a, b] = q.front(); + q.pop(); + for (int k = 0; k < 4; ++k) { + int x = a + dirs[k]; + int y = b + dirs[k + 1]; + if (x >= 0 && x < image.size() && y >= 0 && y < image[0].size() && image[x][y] == oc) { + q.push({x, y}); + image[x][y] = color; + } + } + } + return image; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0733.Flood Fill/Solution2.go b/solution/0700-0799/0733.Flood Fill/Solution2.go new file mode 100644 index 0000000000000..ab81d5392ab0e --- /dev/null +++ b/solution/0700-0799/0733.Flood Fill/Solution2.go @@ -0,0 +1,21 @@ +func floodFill(image [][]int, sr int, sc int, color int) [][]int { + if image[sr][sc] == color { + return image + } + oc := image[sr][sc] + q := [][]int{[]int{sr, sc}} + image[sr][sc] = color + dirs := []int{-1, 0, 1, 0, -1} + for len(q) > 0 { + p := q[0] + q = q[1:] + for k := 0; k < 4; k++ { + x, y := p[0]+dirs[k], p[1]+dirs[k+1] + if x >= 0 && x < len(image) && y >= 0 && y < len(image[0]) && image[x][y] == oc { + q = append(q, []int{x, y}) + image[x][y] = color + } + } + } + return image +} \ No newline at end of file diff --git a/solution/0700-0799/0733.Flood Fill/Solution2.java b/solution/0700-0799/0733.Flood Fill/Solution2.java new file mode 100644 index 0000000000000..a2ffacec32728 --- /dev/null +++ b/solution/0700-0799/0733.Flood Fill/Solution2.java @@ -0,0 +1,25 @@ +class Solution { + public int[][] floodFill(int[][] image, int sr, int sc, int color) { + if (image[sr][sc] == color) { + return image; + } + Deque q = new ArrayDeque<>(); + q.offer(new int[] {sr, sc}); + int oc = image[sr][sc]; + image[sr][sc] = color; + int[] dirs = {-1, 0, 1, 0, -1}; + while (!q.isEmpty()) { + int[] p = q.poll(); + int i = p[0], j = p[1]; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < image.length && y >= 0 && y < image[0].length + && image[x][y] == oc) { + q.offer(new int[] {x, y}); + image[x][y] = color; + } + } + } + return image; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0733.Flood Fill/Solution2.py b/solution/0700-0799/0733.Flood Fill/Solution2.py new file mode 100644 index 0000000000000..d6384d418afed --- /dev/null +++ b/solution/0700-0799/0733.Flood Fill/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def floodFill( + self, image: List[List[int]], sr: int, sc: int, color: int + ) -> List[List[int]]: + if image[sr][sc] == color: + return image + q = deque([(sr, sc)]) + oc = image[sr][sc] + image[sr][sc] = color + dirs = (-1, 0, 1, 0, -1) + while q: + i, j = q.popleft() + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < len(image) and 0 <= y < len(image[0]) and image[x][y] == oc: + q.append((x, y)) + image[x][y] = color + return image diff --git a/solution/0700-0799/0735.Asteroid Collision/Solution.cpp b/solution/0700-0799/0735.Asteroid Collision/Solution.cpp index 768f03fc6a28c..b0f72d73376ad 100644 --- a/solution/0700-0799/0735.Asteroid Collision/Solution.cpp +++ b/solution/0700-0799/0735.Asteroid Collision/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - vector asteroidCollision(vector& asteroids) { - vector stk; - for (int x : asteroids) { - if (x > 0) { - stk.push_back(x); - } else { - while (stk.size() && stk.back() > 0 && stk.back() < -x) { - stk.pop_back(); - } - if (stk.size() && stk.back() == -x) { - stk.pop_back(); - } else if (stk.empty() || stk.back() < 0) { - stk.push_back(x); - } - } - } - return stk; - } +class Solution { +public: + vector asteroidCollision(vector& asteroids) { + vector stk; + for (int x : asteroids) { + if (x > 0) { + stk.push_back(x); + } else { + while (stk.size() && stk.back() > 0 && stk.back() < -x) { + stk.pop_back(); + } + if (stk.size() && stk.back() == -x) { + stk.pop_back(); + } else if (stk.empty() || stk.back() < 0) { + stk.push_back(x); + } + } + } + return stk; + } }; \ No newline at end of file diff --git a/solution/0700-0799/0735.Asteroid Collision/Solution.java b/solution/0700-0799/0735.Asteroid Collision/Solution.java index 2482fab648a88..a7fe353b8ae41 100644 --- a/solution/0700-0799/0735.Asteroid Collision/Solution.java +++ b/solution/0700-0799/0735.Asteroid Collision/Solution.java @@ -1,20 +1,20 @@ -class Solution { - public int[] asteroidCollision(int[] asteroids) { - Deque stk = new ArrayDeque<>(); - for (int x : asteroids) { - if (x > 0) { - stk.offerLast(x); - } else { - while (!stk.isEmpty() && stk.peekLast() > 0 && stk.peekLast() < -x) { - stk.pollLast(); - } - if (!stk.isEmpty() && stk.peekLast() == -x) { - stk.pollLast(); - } else if (stk.isEmpty() || stk.peekLast() < 0) { - stk.offerLast(x); - } - } - } - return stk.stream().mapToInt(Integer::valueOf).toArray(); - } +class Solution { + public int[] asteroidCollision(int[] asteroids) { + Deque stk = new ArrayDeque<>(); + for (int x : asteroids) { + if (x > 0) { + stk.offerLast(x); + } else { + while (!stk.isEmpty() && stk.peekLast() > 0 && stk.peekLast() < -x) { + stk.pollLast(); + } + if (!stk.isEmpty() && stk.peekLast() == -x) { + stk.pollLast(); + } else if (stk.isEmpty() || stk.peekLast() < 0) { + stk.offerLast(x); + } + } + } + return stk.stream().mapToInt(Integer::valueOf).toArray(); + } } \ No newline at end of file diff --git a/solution/0700-0799/0735.Asteroid Collision/Solution.py b/solution/0700-0799/0735.Asteroid Collision/Solution.py index 01660c5098ec8..1049a39e6c463 100644 --- a/solution/0700-0799/0735.Asteroid Collision/Solution.py +++ b/solution/0700-0799/0735.Asteroid Collision/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def asteroidCollision(self, asteroids: List[int]) -> List[int]: - stk = [] - for x in asteroids: - if x > 0: - stk.append(x) - else: - while stk and stk[-1] > 0 and stk[-1] < -x: - stk.pop() - if stk and stk[-1] == -x: - stk.pop() - elif not stk or stk[-1] < 0: - stk.append(x) - return stk +class Solution: + def asteroidCollision(self, asteroids: List[int]) -> List[int]: + stk = [] + for x in asteroids: + if x > 0: + stk.append(x) + else: + while stk and stk[-1] > 0 and stk[-1] < -x: + stk.pop() + if stk and stk[-1] == -x: + stk.pop() + elif not stk or stk[-1] < 0: + stk.append(x) + return stk diff --git a/solution/0700-0799/0739.Daily Temperatures/Solution2.cpp b/solution/0700-0799/0739.Daily Temperatures/Solution2.cpp new file mode 100644 index 0000000000000..3ad97088685ab --- /dev/null +++ b/solution/0700-0799/0739.Daily Temperatures/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + vector dailyTemperatures(vector& temperatures) { + int n = temperatures.size(); + vector ans(n); + stack stk; + for (int i = n - 1; ~i; --i) { + while (!stk.empty() && temperatures[stk.top()] <= temperatures[i]) stk.pop(); + if (!stk.empty()) ans[i] = stk.top() - i; + stk.push(i); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0739.Daily Temperatures/Solution2.go b/solution/0700-0799/0739.Daily Temperatures/Solution2.go new file mode 100644 index 0000000000000..ff6cf7e4efb4f --- /dev/null +++ b/solution/0700-0799/0739.Daily Temperatures/Solution2.go @@ -0,0 +1,15 @@ +func dailyTemperatures(temperatures []int) []int { + n := len(temperatures) + ans := make([]int, n) + var stk []int + for i := n - 1; i >= 0; i-- { + for len(stk) > 0 && temperatures[stk[len(stk)-1]] <= temperatures[i] { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + ans[i] = stk[len(stk)-1] - i + } + stk = append(stk, i) + } + return ans +} \ No newline at end of file diff --git a/solution/0700-0799/0739.Daily Temperatures/Solution2.java b/solution/0700-0799/0739.Daily Temperatures/Solution2.java new file mode 100644 index 0000000000000..7eda02cd99b08 --- /dev/null +++ b/solution/0700-0799/0739.Daily Temperatures/Solution2.java @@ -0,0 +1,17 @@ +class Solution { + public int[] dailyTemperatures(int[] temperatures) { + int n = temperatures.length; + Deque stk = new ArrayDeque<>(); + int[] ans = new int[n]; + for (int i = n - 1; i >= 0; --i) { + while (!stk.isEmpty() && temperatures[stk.peek()] <= temperatures[i]) { + stk.pop(); + } + if (!stk.isEmpty()) { + ans[i] = stk.peek() - i; + } + stk.push(i); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0739.Daily Temperatures/Solution2.py b/solution/0700-0799/0739.Daily Temperatures/Solution2.py new file mode 100644 index 0000000000000..e5a9ba4f87332 --- /dev/null +++ b/solution/0700-0799/0739.Daily Temperatures/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def dailyTemperatures(self, temperatures: List[int]) -> List[int]: + n = len(temperatures) + stk = [] + ans = [0] * n + for i in range(n - 1, -1, -1): + while stk and temperatures[stk[-1]] <= temperatures[i]: + stk.pop() + if stk: + ans[i] = stk[-1] - i + stk.append(i) + return ans diff --git a/solution/0700-0799/0740.Delete and Earn/Solution.java b/solution/0700-0799/0740.Delete and Earn/Solution.java index cd80bc55a8870..6fe0718a72568 100644 --- a/solution/0700-0799/0740.Delete and Earn/Solution.java +++ b/solution/0700-0799/0740.Delete and Earn/Solution.java @@ -1,4 +1,4 @@ -public class Solution { +class Solution { public int deleteAndEarn(int[] nums) { if (nums.length == 0) { return 0; @@ -20,4 +20,4 @@ public int deleteAndEarn(int[] nums) { } return Math.max(select[maxV], nonSelect[maxV]); } -} +} \ No newline at end of file diff --git a/solution/0700-0799/0741.Cherry Pickup/Solution.cpp b/solution/0700-0799/0741.Cherry Pickup/Solution.cpp index d0d3ba8ef70ab..ff7787c75acd2 100644 --- a/solution/0700-0799/0741.Cherry Pickup/Solution.cpp +++ b/solution/0700-0799/0741.Cherry Pickup/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - int cherryPickup(vector>& grid) { - int n = grid.size(); - vector>> dp(n << 1, vector>(n, vector(n, -1e9))); - dp[0][0][0] = grid[0][0]; - for (int k = 1; k < n * 2 - 1; ++k) { - for (int i1 = 0; i1 < n; ++i1) { - for (int i2 = 0; i2 < n; ++i2) { - int j1 = k - i1, j2 = k - i2; - if (j1 < 0 || j1 >= n || j2 < 0 || j2 >= n || grid[i1][j1] == -1 || grid[i2][j2] == -1) continue; - int t = grid[i1][j1]; - if (i1 != i2) t += grid[i2][j2]; - for (int x1 = i1 - 1; x1 <= i1; ++x1) - for (int x2 = i2 - 1; x2 <= i2; ++x2) - if (x1 >= 0 && x2 >= 0) - dp[k][i1][i2] = max(dp[k][i1][i2], dp[k - 1][x1][x2] + t); - } - } - } - return max(0, dp[n * 2 - 2][n - 1][n - 1]); - } +class Solution { +public: + int cherryPickup(vector>& grid) { + int n = grid.size(); + vector>> dp(n << 1, vector>(n, vector(n, -1e9))); + dp[0][0][0] = grid[0][0]; + for (int k = 1; k < n * 2 - 1; ++k) { + for (int i1 = 0; i1 < n; ++i1) { + for (int i2 = 0; i2 < n; ++i2) { + int j1 = k - i1, j2 = k - i2; + if (j1 < 0 || j1 >= n || j2 < 0 || j2 >= n || grid[i1][j1] == -1 || grid[i2][j2] == -1) continue; + int t = grid[i1][j1]; + if (i1 != i2) t += grid[i2][j2]; + for (int x1 = i1 - 1; x1 <= i1; ++x1) + for (int x2 = i2 - 1; x2 <= i2; ++x2) + if (x1 >= 0 && x2 >= 0) + dp[k][i1][i2] = max(dp[k][i1][i2], dp[k - 1][x1][x2] + t); + } + } + } + return max(0, dp[n * 2 - 2][n - 1][n - 1]); + } }; \ No newline at end of file diff --git a/solution/0700-0799/0741.Cherry Pickup/Solution.java b/solution/0700-0799/0741.Cherry Pickup/Solution.java index c2e431dfcdaa1..9dcaf672261b0 100644 --- a/solution/0700-0799/0741.Cherry Pickup/Solution.java +++ b/solution/0700-0799/0741.Cherry Pickup/Solution.java @@ -1,31 +1,31 @@ -class Solution { - public int cherryPickup(int[][] grid) { - int n = grid.length; - int[][][] dp = new int[n * 2][n][n]; - dp[0][0][0] = grid[0][0]; - for (int k = 1; k < n * 2 - 1; ++k) { - for (int i1 = 0; i1 < n; ++i1) { - for (int i2 = 0; i2 < n; ++i2) { - int j1 = k - i1, j2 = k - i2; - dp[k][i1][i2] = Integer.MIN_VALUE; - if (j1 < 0 || j1 >= n || j2 < 0 || j2 >= n || grid[i1][j1] == -1 - || grid[i2][j2] == -1) { - continue; - } - int t = grid[i1][j1]; - if (i1 != i2) { - t += grid[i2][j2]; - } - for (int x1 = i1 - 1; x1 <= i1; ++x1) { - for (int x2 = i2 - 1; x2 <= i2; ++x2) { - if (x1 >= 0 && x2 >= 0) { - dp[k][i1][i2] = Math.max(dp[k][i1][i2], dp[k - 1][x1][x2] + t); - } - } - } - } - } - } - return Math.max(0, dp[n * 2 - 2][n - 1][n - 1]); - } +class Solution { + public int cherryPickup(int[][] grid) { + int n = grid.length; + int[][][] dp = new int[n * 2][n][n]; + dp[0][0][0] = grid[0][0]; + for (int k = 1; k < n * 2 - 1; ++k) { + for (int i1 = 0; i1 < n; ++i1) { + for (int i2 = 0; i2 < n; ++i2) { + int j1 = k - i1, j2 = k - i2; + dp[k][i1][i2] = Integer.MIN_VALUE; + if (j1 < 0 || j1 >= n || j2 < 0 || j2 >= n || grid[i1][j1] == -1 + || grid[i2][j2] == -1) { + continue; + } + int t = grid[i1][j1]; + if (i1 != i2) { + t += grid[i2][j2]; + } + for (int x1 = i1 - 1; x1 <= i1; ++x1) { + for (int x2 = i2 - 1; x2 <= i2; ++x2) { + if (x1 >= 0 && x2 >= 0) { + dp[k][i1][i2] = Math.max(dp[k][i1][i2], dp[k - 1][x1][x2] + t); + } + } + } + } + } + } + return Math.max(0, dp[n * 2 - 2][n - 1][n - 1]); + } } \ No newline at end of file diff --git a/solution/0700-0799/0741.Cherry Pickup/Solution.py b/solution/0700-0799/0741.Cherry Pickup/Solution.py index cff08b80e56c5..460c3373d03fa 100644 --- a/solution/0700-0799/0741.Cherry Pickup/Solution.py +++ b/solution/0700-0799/0741.Cherry Pickup/Solution.py @@ -1,26 +1,26 @@ -class Solution: - def cherryPickup(self, grid: List[List[int]]) -> int: - n = len(grid) - dp = [[[-inf] * n for _ in range(n)] for _ in range((n << 1) - 1)] - dp[0][0][0] = grid[0][0] - for k in range(1, (n << 1) - 1): - for i1 in range(n): - for i2 in range(n): - j1, j2 = k - i1, k - i2 - if ( - not 0 <= j1 < n - or not 0 <= j2 < n - or grid[i1][j1] == -1 - or grid[i2][j2] == -1 - ): - continue - t = grid[i1][j1] - if i1 != i2: - t += grid[i2][j2] - for x1 in range(i1 - 1, i1 + 1): - for x2 in range(i2 - 1, i2 + 1): - if x1 >= 0 and x2 >= 0: - dp[k][i1][i2] = max( - dp[k][i1][i2], dp[k - 1][x1][x2] + t - ) - return max(0, dp[-1][-1][-1]) +class Solution: + def cherryPickup(self, grid: List[List[int]]) -> int: + n = len(grid) + dp = [[[-inf] * n for _ in range(n)] for _ in range((n << 1) - 1)] + dp[0][0][0] = grid[0][0] + for k in range(1, (n << 1) - 1): + for i1 in range(n): + for i2 in range(n): + j1, j2 = k - i1, k - i2 + if ( + not 0 <= j1 < n + or not 0 <= j2 < n + or grid[i1][j1] == -1 + or grid[i2][j2] == -1 + ): + continue + t = grid[i1][j1] + if i1 != i2: + t += grid[i2][j2] + for x1 in range(i1 - 1, i1 + 1): + for x2 in range(i2 - 1, i2 + 1): + if x1 >= 0 and x2 >= 0: + dp[k][i1][i2] = max( + dp[k][i1][i2], dp[k - 1][x1][x2] + t + ) + return max(0, dp[-1][-1][-1]) diff --git a/solution/0700-0799/0743.Network Delay Time/Solution.go b/solution/0700-0799/0743.Network Delay Time/Solution.go index 01149a8fe0de9..490c5c75cc7a0 100644 --- a/solution/0700-0799/0743.Network Delay Time/Solution.go +++ b/solution/0700-0799/0743.Network Delay Time/Solution.go @@ -1,54 +1,33 @@ -const Inf = 0x3f3f3f3f - -type pair struct { - first int - second int -} - -var _ heap.Interface = (*pairs)(nil) - -type pairs []pair - -func (a pairs) Len() int { return len(a) } -func (a pairs) Less(i int, j int) bool { - return a[i].first < a[j].first || a[i].first == a[j].first && a[i].second < a[j].second -} -func (a pairs) Swap(i int, j int) { a[i], a[j] = a[j], a[i] } -func (a *pairs) Push(x any) { *a = append(*a, x.(pair)) } -func (a *pairs) Pop() any { l := len(*a); t := (*a)[l-1]; *a = (*a)[:l-1]; return t } - func networkDelayTime(times [][]int, n int, k int) int { - graph := make([]pairs, n) - for _, time := range times { - from, to, time := time[0]-1, time[1]-1, time[2] - graph[from] = append(graph[from], pair{to, time}) - } - - dis := make([]int, n) - for i := range dis { - dis[i] = Inf - } - dis[k-1] = 0 - + const inf = 0x3f3f + dist := make([]int, n) vis := make([]bool, n) - h := make(pairs, 0) - heap.Push(&h, pair{0, k - 1}) - for len(h) > 0 { - from := heap.Pop(&h).(pair).second - if vis[from] { - continue + g := make([][]int, n) + for i := range dist { + dist[i] = inf + g[i] = make([]int, n) + for j := range g[i] { + g[i][j] = inf } - vis[from] = true - for _, e := range graph[from] { - to, d := e.first, dis[from]+e.second - if d < dis[to] { - dis[to] = d - heap.Push(&h, pair{d, to}) + } + for _, t := range times { + g[t[0]-1][t[1]-1] = t[2] + } + dist[k-1] = 0 + for i := 0; i < n; i++ { + t := -1 + for j := 0; j < n; j++ { + if !vis[j] && (t == -1 || dist[t] > dist[j]) { + t = j } } + vis[t] = true + for j := 0; j < n; j++ { + dist[j] = min(dist[j], dist[t]+g[t][j]) + } } - ans := slices.Max(dis) - if ans == Inf { + ans := slices.Max(dist) + if ans == inf { return -1 } return ans diff --git a/solution/0700-0799/0743.Network Delay Time/Solution.java b/solution/0700-0799/0743.Network Delay Time/Solution.java index bbbf70725b8a4..941e7ae1c3099 100644 --- a/solution/0700-0799/0743.Network Delay Time/Solution.java +++ b/solution/0700-0799/0743.Network Delay Time/Solution.java @@ -1,34 +1,33 @@ class Solution { - private static final int N = 110; private static final int INF = 0x3f3f; public int networkDelayTime(int[][] times, int n, int k) { - int[][] g = new int[N][N]; - for (int i = 0; i < N; ++i) { + int[][] g = new int[n][n]; + int[] dist = new int[n]; + boolean[] vis = new boolean[n]; + for (int i = 0; i < n; ++i) { + dist[i] = INF; Arrays.fill(g[i], INF); } - for (int[] e : times) { - g[e[0]][e[1]] = e[2]; + for (int[] t : times) { + g[t[0] - 1][t[1] - 1] = t[2]; } - int[] dist = new int[N]; - Arrays.fill(dist, INF); - dist[k] = 0; - boolean[] vis = new boolean[N]; + dist[k - 1] = 0; for (int i = 0; i < n; ++i) { int t = -1; - for (int j = 1; j <= n; ++j) { + for (int j = 0; j < n; ++j) { if (!vis[j] && (t == -1 || dist[t] > dist[j])) { t = j; } } vis[t] = true; - for (int j = 1; j <= n; ++j) { + for (int j = 0; j < n; ++j) { dist[j] = Math.min(dist[j], dist[t] + g[t][j]); } } int ans = 0; - for (int i = 1; i <= n; ++i) { - ans = Math.max(ans, dist[i]); + for (int d : dist) { + ans = Math.max(ans, d); } return ans == INF ? -1 : ans; } diff --git a/solution/0700-0799/0743.Network Delay Time/Solution.py b/solution/0700-0799/0743.Network Delay Time/Solution.py index 009bea471b470..16047a5d66c35 100644 --- a/solution/0700-0799/0743.Network Delay Time/Solution.py +++ b/solution/0700-0799/0743.Network Delay Time/Solution.py @@ -1,17 +1,19 @@ class Solution: def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: INF = 0x3F3F - g = defaultdict(list) - for u, v, w in times: - g[u - 1].append((v - 1, w)) dist = [INF] * n + vis = [False] * n + g = [[INF] * n for _ in range(n)] + for u, v, w in times: + g[u - 1][v - 1] = w dist[k - 1] = 0 - q = [(0, k - 1)] - while q: - _, u = heappop(q) - for v, w in g[u]: - if dist[v] > dist[u] + w: - dist[v] = dist[u] + w - heappush(q, (dist[v], v)) + for _ in range(n): + t = -1 + for j in range(n): + if not vis[j] and (t == -1 or dist[t] > dist[j]): + t = j + vis[t] = True + for j in range(n): + dist[j] = min(dist[j], dist[t] + g[t][j]) ans = max(dist) return -1 if ans == INF else ans diff --git a/solution/0700-0799/0743.Network Delay Time/Solution2.cpp b/solution/0700-0799/0743.Network Delay Time/Solution2.cpp new file mode 100644 index 0000000000000..5aa9582036770 --- /dev/null +++ b/solution/0700-0799/0743.Network Delay Time/Solution2.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + const int inf = 0x3f3f; + + int networkDelayTime(vector>& times, int n, int k) { + vector>> g(n); + for (auto& t : times) g[t[0] - 1].push_back({t[1] - 1, t[2]}); + vector dist(n, inf); + dist[k - 1] = 0; + priority_queue, vector>, greater>> q; + q.push({0, k - 1}); + while (!q.empty()) { + auto p = q.top(); + q.pop(); + int u = p[1]; + for (auto& ne : g[u]) { + int v = ne[0], w = ne[1]; + if (dist[v] > dist[u] + w) { + dist[v] = dist[u] + w; + q.push({dist[v], v}); + } + } + } + int ans = *max_element(dist.begin(), dist.end()); + return ans == inf ? -1 : ans; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0743.Network Delay Time/Solution2.go b/solution/0700-0799/0743.Network Delay Time/Solution2.go new file mode 100644 index 0000000000000..01149a8fe0de9 --- /dev/null +++ b/solution/0700-0799/0743.Network Delay Time/Solution2.go @@ -0,0 +1,55 @@ +const Inf = 0x3f3f3f3f + +type pair struct { + first int + second int +} + +var _ heap.Interface = (*pairs)(nil) + +type pairs []pair + +func (a pairs) Len() int { return len(a) } +func (a pairs) Less(i int, j int) bool { + return a[i].first < a[j].first || a[i].first == a[j].first && a[i].second < a[j].second +} +func (a pairs) Swap(i int, j int) { a[i], a[j] = a[j], a[i] } +func (a *pairs) Push(x any) { *a = append(*a, x.(pair)) } +func (a *pairs) Pop() any { l := len(*a); t := (*a)[l-1]; *a = (*a)[:l-1]; return t } + +func networkDelayTime(times [][]int, n int, k int) int { + graph := make([]pairs, n) + for _, time := range times { + from, to, time := time[0]-1, time[1]-1, time[2] + graph[from] = append(graph[from], pair{to, time}) + } + + dis := make([]int, n) + for i := range dis { + dis[i] = Inf + } + dis[k-1] = 0 + + vis := make([]bool, n) + h := make(pairs, 0) + heap.Push(&h, pair{0, k - 1}) + for len(h) > 0 { + from := heap.Pop(&h).(pair).second + if vis[from] { + continue + } + vis[from] = true + for _, e := range graph[from] { + to, d := e.first, dis[from]+e.second + if d < dis[to] { + dis[to] = d + heap.Push(&h, pair{d, to}) + } + } + } + ans := slices.Max(dis) + if ans == Inf { + return -1 + } + return ans +} \ No newline at end of file diff --git a/solution/0700-0799/0743.Network Delay Time/Solution2.java b/solution/0700-0799/0743.Network Delay Time/Solution2.java new file mode 100644 index 0000000000000..86ca85e907949 --- /dev/null +++ b/solution/0700-0799/0743.Network Delay Time/Solution2.java @@ -0,0 +1,34 @@ +class Solution { + private static final int INF = 0x3f3f; + + public int networkDelayTime(int[][] times, int n, int k) { + List[] g = new List[n]; + int[] dist = new int[n]; + for (int i = 0; i < n; ++i) { + dist[i] = INF; + g[i] = new ArrayList<>(); + } + for (int[] t : times) { + g[t[0] - 1].add(new int[] {t[1] - 1, t[2]}); + } + dist[k - 1] = 0; + PriorityQueue q = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); + q.offer(new int[] {0, k - 1}); + while (!q.isEmpty()) { + int[] p = q.poll(); + int u = p[1]; + for (int[] ne : g[u]) { + int v = ne[0], w = ne[1]; + if (dist[v] > dist[u] + w) { + dist[v] = dist[u] + w; + q.offer(new int[] {dist[v], v}); + } + } + } + int ans = 0; + for (int d : dist) { + ans = Math.max(ans, d); + } + return ans == INF ? -1 : ans; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0743.Network Delay Time/Solution2.py b/solution/0700-0799/0743.Network Delay Time/Solution2.py new file mode 100644 index 0000000000000..009bea471b470 --- /dev/null +++ b/solution/0700-0799/0743.Network Delay Time/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: + INF = 0x3F3F + g = defaultdict(list) + for u, v, w in times: + g[u - 1].append((v - 1, w)) + dist = [INF] * n + dist[k - 1] = 0 + q = [(0, k - 1)] + while q: + _, u = heappop(q) + for v, w in g[u]: + if dist[v] > dist[u] + w: + dist[v] = dist[u] + w + heappush(q, (dist[v], v)) + ans = max(dist) + return -1 if ans == INF else ans diff --git a/solution/0700-0799/0743.Network Delay Time/Solution3.cpp b/solution/0700-0799/0743.Network Delay Time/Solution3.cpp new file mode 100644 index 0000000000000..ce256623dcf49 --- /dev/null +++ b/solution/0700-0799/0743.Network Delay Time/Solution3.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int inf = 0x3f3f; + + int networkDelayTime(vector>& times, int n, int k) { + vector dist(n, inf); + dist[k - 1] = 0; + for (int i = 0; i < n; ++i) { + vector backup = dist; + for (auto& e : times) { + int u = e[0] - 1, v = e[1] - 1, w = e[2]; + dist[v] = min(dist[v], backup[u] + w); + } + } + int ans = *max_element(dist.begin(), dist.end()); + return ans == inf ? -1 : ans; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0743.Network Delay Time/Solution3.go b/solution/0700-0799/0743.Network Delay Time/Solution3.go new file mode 100644 index 0000000000000..002be604aa819 --- /dev/null +++ b/solution/0700-0799/0743.Network Delay Time/Solution3.go @@ -0,0 +1,21 @@ +func networkDelayTime(times [][]int, n int, k int) int { + const inf = 0x3f3f + dist := make([]int, n) + backup := make([]int, n) + for i := range dist { + dist[i] = inf + } + dist[k-1] = 0 + for i := 0; i < n; i++ { + copy(backup, dist) + for _, e := range times { + u, v, w := e[0]-1, e[1]-1, e[2] + dist[v] = min(dist[v], backup[u]+w) + } + } + ans := slices.Max(dist) + if ans == inf { + return -1 + } + return ans +} \ No newline at end of file diff --git a/solution/0700-0799/0743.Network Delay Time/Solution3.java b/solution/0700-0799/0743.Network Delay Time/Solution3.java new file mode 100644 index 0000000000000..5a961ad640e68 --- /dev/null +++ b/solution/0700-0799/0743.Network Delay Time/Solution3.java @@ -0,0 +1,22 @@ +class Solution { + private static final int INF = 0x3f3f; + + public int networkDelayTime(int[][] times, int n, int k) { + int[] dist = new int[n]; + int[] backup = new int[n]; + Arrays.fill(dist, INF); + dist[k - 1] = 0; + for (int i = 0; i < n; ++i) { + System.arraycopy(dist, 0, backup, 0, n); + for (int[] t : times) { + int u = t[0] - 1, v = t[1] - 1, w = t[2]; + dist[v] = Math.min(dist[v], backup[u] + w); + } + } + int ans = 0; + for (int i = 0; i < n; ++i) { + ans = Math.max(ans, dist[i]); + } + return ans == INF ? -1 : ans; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0743.Network Delay Time/Solution3.py b/solution/0700-0799/0743.Network Delay Time/Solution3.py new file mode 100644 index 0000000000000..768e9dc2e85df --- /dev/null +++ b/solution/0700-0799/0743.Network Delay Time/Solution3.py @@ -0,0 +1,11 @@ +class Solution: + def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: + INF = 0x3F3F + dist = [INF] * n + dist[k - 1] = 0 + for _ in range(n): + backup = dist[:] + for u, v, w in times: + dist[v - 1] = min(dist[v - 1], dist[u - 1] + w) + ans = max(dist) + return -1 if ans == INF else ans diff --git a/solution/0700-0799/0743.Network Delay Time/Solution4.cpp b/solution/0700-0799/0743.Network Delay Time/Solution4.cpp new file mode 100644 index 0000000000000..7bd884c23db07 --- /dev/null +++ b/solution/0700-0799/0743.Network Delay Time/Solution4.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + const int inf = 0x3f3f; + + int networkDelayTime(vector>& times, int n, int k) { + vector dist(n, inf); + vector>> g(n); + for (auto& e : times) { + int u = e[0] - 1, v = e[1] - 1, w = e[2]; + g[u].push_back({v, w}); + } + vector vis(n); + --k; + queue q{{k}}; + vis[k] = true; + dist[k] = 0; + while (!q.empty()) { + int u = q.front(); + q.pop(); + vis[u] = false; + for (auto& ne : g[u]) { + int v = ne[0], w = ne[1]; + if (dist[v] > dist[u] + w) { + dist[v] = dist[u] + w; + if (!vis[v]) { + q.push(v); + vis[v] = true; + } + } + } + } + int ans = *max_element(dist.begin(), dist.end()); + return ans == inf ? -1 : ans; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0743.Network Delay Time/Solution4.go b/solution/0700-0799/0743.Network Delay Time/Solution4.go new file mode 100644 index 0000000000000..ccf75347f03e4 --- /dev/null +++ b/solution/0700-0799/0743.Network Delay Time/Solution4.go @@ -0,0 +1,37 @@ +func networkDelayTime(times [][]int, n int, k int) int { + const inf = 0x3f3f + dist := make([]int, n) + vis := make([]bool, n) + g := make([][][]int, n) + for i := range dist { + dist[i] = inf + } + for _, t := range times { + u, v, w := t[0]-1, t[1]-1, t[2] + g[u] = append(g[u], []int{v, w}) + } + k-- + dist[k] = 0 + q := []int{k} + vis[k] = true + for len(q) > 0 { + u := q[0] + q = q[1:] + vis[u] = false + for _, ne := range g[u] { + v, w := ne[0], ne[1] + if dist[v] > dist[u]+w { + dist[v] = dist[u] + w + if !vis[v] { + q = append(q, v) + vis[v] = true + } + } + } + } + ans := slices.Max(dist) + if ans == inf { + return -1 + } + return ans +} \ No newline at end of file diff --git a/solution/0700-0799/0743.Network Delay Time/Solution4.java b/solution/0700-0799/0743.Network Delay Time/Solution4.java new file mode 100644 index 0000000000000..a9465a8cb408e --- /dev/null +++ b/solution/0700-0799/0743.Network Delay Time/Solution4.java @@ -0,0 +1,41 @@ +class Solution { + private static final int INF = 0x3f3f; + + public int networkDelayTime(int[][] times, int n, int k) { + int[] dist = new int[n]; + boolean[] vis = new boolean[n]; + List[] g = new List[n]; + for (int i = 0; i < n; ++i) { + dist[i] = INF; + g[i] = new ArrayList<>(); + } + for (int[] t : times) { + int u = t[0] - 1, v = t[1] - 1, w = t[2]; + g[u].add(new int[] {v, w}); + } + --k; + dist[k] = 0; + Deque q = new ArrayDeque<>(); + q.offer(k); + vis[k] = true; + while (!q.isEmpty()) { + int u = q.poll(); + vis[u] = false; + for (int[] ne : g[u]) { + int v = ne[0], w = ne[1]; + if (dist[v] > dist[u] + w) { + dist[v] = dist[u] + w; + if (!vis[v]) { + q.offer(v); + vis[v] = true; + } + } + } + } + int ans = 0; + for (int i = 0; i < n; ++i) { + ans = Math.max(ans, dist[i]); + } + return ans == INF ? -1 : ans; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0743.Network Delay Time/Solution4.py b/solution/0700-0799/0743.Network Delay Time/Solution4.py new file mode 100644 index 0000000000000..ef237bd6aa19e --- /dev/null +++ b/solution/0700-0799/0743.Network Delay Time/Solution4.py @@ -0,0 +1,23 @@ +class Solution: + def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: + INF = 0x3F3F + dist = [INF] * n + vis = [False] * n + g = defaultdict(list) + for u, v, w in times: + g[u - 1].append((v - 1, w)) + k -= 1 + dist[k] = 0 + q = deque([k]) + vis[k] = True + while q: + u = q.popleft() + vis[u] = False + for v, w in g[u]: + if dist[v] > dist[u] + w: + dist[v] = dist[u] + w + if not vis[v]: + q.append(v) + vis[v] = True + ans = max(dist) + return -1 if ans == INF else ans diff --git a/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/Solution.php b/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/Solution.php index fba59065af972..52a60ac3d165b 100644 --- a/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/Solution.php +++ b/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/Solution.php @@ -21,4 +21,4 @@ function nextGreatestLetter($letters, $target) { return $letters[$left]; } } -} \ No newline at end of file +} diff --git a/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/Solution.rs b/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/Solution.rs index 5812277f023ce..13f53f2c7b4f3 100644 --- a/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/Solution.rs +++ b/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/Solution.rs @@ -1,16 +1,8 @@ impl Solution { pub fn next_greatest_letter(letters: Vec, target: char) -> char { - let n = letters.len(); - let mut left = 0; - let mut right = n; - while left < right { - let mid = left + (right - left) / 2; - if letters[mid] > target { - right = mid; - } else { - left = mid + 1; - } - } - letters[left % n] + *letters + .iter() + .find(|&&c| c > target) + .unwrap_or(&letters[0]) } } diff --git a/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/Solution2.rs b/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/Solution2.rs new file mode 100644 index 0000000000000..5812277f023ce --- /dev/null +++ b/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/Solution2.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn next_greatest_letter(letters: Vec, target: char) -> char { + let n = letters.len(); + let mut left = 0; + let mut right = n; + while left < right { + let mid = left + (right - left) / 2; + if letters[mid] > target { + right = mid; + } else { + left = mid + 1; + } + } + letters[left % n] + } +} diff --git a/solution/0700-0799/0745.Prefix and Suffix Search/Solution.go b/solution/0700-0799/0745.Prefix and Suffix Search/Solution.go index b18fc3b0a7533..a7da1e80948d9 100644 --- a/solution/0700-0799/0745.Prefix and Suffix Search/Solution.go +++ b/solution/0700-0799/0745.Prefix and Suffix Search/Solution.go @@ -1,79 +1,29 @@ -type Trie struct { - children [26]*Trie - indexes []int -} - -func newTrie() *Trie { - return &Trie{indexes: []int{}} -} -func (this *Trie) insert(word string, i int) { - node := this - for _, c := range word { - idx := c - 'a' - if node.children[idx] == nil { - node.children[idx] = newTrie() - } - node = node.children[idx] - node.indexes = append(node.indexes, i) - } -} - -func (this *Trie) search(pref string) []int { - node := this - for _, c := range pref { - idx := c - 'a' - if node.children[idx] == nil { - return []int{} - } - node = node.children[idx] - } - return node.indexes -} - type WordFilter struct { - p *Trie - s *Trie + d map[string]int } func Constructor(words []string) WordFilter { - p := newTrie() - s := newTrie() - for i, w := range words { - p.insert(w, i) - s.insert(reverse(w), i) + d := map[string]int{} + for k, w := range words { + n := len(w) + for i := 0; i <= n; i++ { + a := w[:i] + for j := 0; j <= n; j++ { + b := w[j:] + d[a+"."+b] = k + } + } } - return WordFilter{p, s} + return WordFilter{d} } func (this *WordFilter) F(pref string, suff string) int { - a := this.p.search(pref) - b := this.s.search(reverse(suff)) - if len(a) == 0 || len(b) == 0 { - return -1 - } - i, j := len(a)-1, len(b)-1 - for i >= 0 && j >= 0 { - if a[i] == b[j] { - return a[i] - } - if a[i] > b[j] { - i-- - } else { - j-- - } + if v, ok := this.d[pref+"."+suff]; ok { + return v } return -1 } -func reverse(w string) string { - ww := []byte(w) - for i, j := 0, len(w)-1; i < j; i++ { - ww[i], ww[j] = ww[j], ww[i] - j-- - } - return string(ww) -} - /** * Your WordFilter object will be instantiated and called as such: * obj := Constructor(words); diff --git a/solution/0700-0799/0745.Prefix and Suffix Search/Solution.java b/solution/0700-0799/0745.Prefix and Suffix Search/Solution.java index fc017ff1b3e9c..eeeff51838cec 100644 --- a/solution/0700-0799/0745.Prefix and Suffix Search/Solution.java +++ b/solution/0700-0799/0745.Prefix and Suffix Search/Solution.java @@ -1,64 +1,22 @@ -class Trie { - Trie[] children = new Trie[26]; - List indexes = new ArrayList<>(); - - void insert(String word, int i) { - Trie node = this; - for (char c : word.toCharArray()) { - c -= 'a'; - if (node.children[c] == null) { - node.children[c] = new Trie(); - } - node = node.children[c]; - node.indexes.add(i); - } - } - - List search(String pref) { - Trie node = this; - for (char c : pref.toCharArray()) { - c -= 'a'; - if (node.children[c] == null) { - return Collections.emptyList(); - } - node = node.children[c]; - } - return node.indexes; - } -} - class WordFilter { - private Trie p = new Trie(); - private Trie s = new Trie(); + private Map d = new HashMap<>(); public WordFilter(String[] words) { - for (int i = 0; i < words.length; ++i) { - String w = words[i]; - p.insert(w, i); - s.insert(new StringBuilder(w).reverse().toString(), i); + for (int k = 0; k < words.length; ++k) { + String w = words[k]; + int n = w.length(); + for (int i = 0; i <= n; ++i) { + String a = w.substring(0, i); + for (int j = 0; j <= n; ++j) { + String b = w.substring(j); + d.put(a + "." + b, k); + } + } } } public int f(String pref, String suff) { - suff = new StringBuilder(suff).reverse().toString(); - List a = p.search(pref); - List b = s.search(suff); - if (a.isEmpty() || b.isEmpty()) { - return -1; - } - int i = a.size() - 1, j = b.size() - 1; - while (i >= 0 && j >= 0) { - int c = a.get(i), d = b.get(j); - if (c == d) { - return c; - } - if (c > d) { - --i; - } else { - --j; - } - } - return -1; + return d.getOrDefault(pref + "." + suff, -1); } } diff --git a/solution/0700-0799/0745.Prefix and Suffix Search/Solution.py b/solution/0700-0799/0745.Prefix and Suffix Search/Solution.py index aa40653fa602c..99ea413387ea1 100644 --- a/solution/0700-0799/0745.Prefix and Suffix Search/Solution.py +++ b/solution/0700-0799/0745.Prefix and Suffix Search/Solution.py @@ -1,49 +1,16 @@ -class Trie: - def __init__(self): - self.children = [None] * 26 - self.indexes = [] - - def insert(self, word, i): - node = self - for c in word: - idx = ord(c) - ord("a") - if node.children[idx] is None: - node.children[idx] = Trie() - node = node.children[idx] - node.indexes.append(i) - - def search(self, pref): - node = self - for c in pref: - idx = ord(c) - ord("a") - if node.children[idx] is None: - return [] - node = node.children[idx] - return node.indexes - - class WordFilter: def __init__(self, words: List[str]): - self.p = Trie() - self.s = Trie() - for i, w in enumerate(words): - self.p.insert(w, i) - self.s.insert(w[::-1], i) + self.d = {} + for k, w in enumerate(words): + n = len(w) + for i in range(n + 1): + a = w[:i] + for j in range(n + 1): + b = w[j:] + self.d[(a, b)] = k def f(self, pref: str, suff: str) -> int: - a = self.p.search(pref) - b = self.s.search(suff[::-1]) - if not a or not b: - return -1 - i, j = len(a) - 1, len(b) - 1 - while ~i and ~j: - if a[i] == b[j]: - return a[i] - if a[i] > b[j]: - i -= 1 - else: - j -= 1 - return -1 + return self.d.get((pref, suff), -1) # Your WordFilter object will be instantiated and called as such: diff --git a/solution/0700-0799/0745.Prefix and Suffix Search/Solution2.go b/solution/0700-0799/0745.Prefix and Suffix Search/Solution2.go new file mode 100644 index 0000000000000..b18fc3b0a7533 --- /dev/null +++ b/solution/0700-0799/0745.Prefix and Suffix Search/Solution2.go @@ -0,0 +1,81 @@ +type Trie struct { + children [26]*Trie + indexes []int +} + +func newTrie() *Trie { + return &Trie{indexes: []int{}} +} +func (this *Trie) insert(word string, i int) { + node := this + for _, c := range word { + idx := c - 'a' + if node.children[idx] == nil { + node.children[idx] = newTrie() + } + node = node.children[idx] + node.indexes = append(node.indexes, i) + } +} + +func (this *Trie) search(pref string) []int { + node := this + for _, c := range pref { + idx := c - 'a' + if node.children[idx] == nil { + return []int{} + } + node = node.children[idx] + } + return node.indexes +} + +type WordFilter struct { + p *Trie + s *Trie +} + +func Constructor(words []string) WordFilter { + p := newTrie() + s := newTrie() + for i, w := range words { + p.insert(w, i) + s.insert(reverse(w), i) + } + return WordFilter{p, s} +} + +func (this *WordFilter) F(pref string, suff string) int { + a := this.p.search(pref) + b := this.s.search(reverse(suff)) + if len(a) == 0 || len(b) == 0 { + return -1 + } + i, j := len(a)-1, len(b)-1 + for i >= 0 && j >= 0 { + if a[i] == b[j] { + return a[i] + } + if a[i] > b[j] { + i-- + } else { + j-- + } + } + return -1 +} + +func reverse(w string) string { + ww := []byte(w) + for i, j := 0, len(w)-1; i < j; i++ { + ww[i], ww[j] = ww[j], ww[i] + j-- + } + return string(ww) +} + +/** + * Your WordFilter object will be instantiated and called as such: + * obj := Constructor(words); + * param_1 := obj.F(pref,suff); + */ \ No newline at end of file diff --git a/solution/0700-0799/0745.Prefix and Suffix Search/Solution2.java b/solution/0700-0799/0745.Prefix and Suffix Search/Solution2.java new file mode 100644 index 0000000000000..fc017ff1b3e9c --- /dev/null +++ b/solution/0700-0799/0745.Prefix and Suffix Search/Solution2.java @@ -0,0 +1,69 @@ +class Trie { + Trie[] children = new Trie[26]; + List indexes = new ArrayList<>(); + + void insert(String word, int i) { + Trie node = this; + for (char c : word.toCharArray()) { + c -= 'a'; + if (node.children[c] == null) { + node.children[c] = new Trie(); + } + node = node.children[c]; + node.indexes.add(i); + } + } + + List search(String pref) { + Trie node = this; + for (char c : pref.toCharArray()) { + c -= 'a'; + if (node.children[c] == null) { + return Collections.emptyList(); + } + node = node.children[c]; + } + return node.indexes; + } +} + +class WordFilter { + private Trie p = new Trie(); + private Trie s = new Trie(); + + public WordFilter(String[] words) { + for (int i = 0; i < words.length; ++i) { + String w = words[i]; + p.insert(w, i); + s.insert(new StringBuilder(w).reverse().toString(), i); + } + } + + public int f(String pref, String suff) { + suff = new StringBuilder(suff).reverse().toString(); + List a = p.search(pref); + List b = s.search(suff); + if (a.isEmpty() || b.isEmpty()) { + return -1; + } + int i = a.size() - 1, j = b.size() - 1; + while (i >= 0 && j >= 0) { + int c = a.get(i), d = b.get(j); + if (c == d) { + return c; + } + if (c > d) { + --i; + } else { + --j; + } + } + return -1; + } +} + +/** + * Your WordFilter object will be instantiated and called as such: + * WordFilter obj = new WordFilter(words); + * int param_1 = obj.f(pref,suff); + */ \ No newline at end of file diff --git a/solution/0700-0799/0745.Prefix and Suffix Search/Solution2.py b/solution/0700-0799/0745.Prefix and Suffix Search/Solution2.py new file mode 100644 index 0000000000000..aa40653fa602c --- /dev/null +++ b/solution/0700-0799/0745.Prefix and Suffix Search/Solution2.py @@ -0,0 +1,51 @@ +class Trie: + def __init__(self): + self.children = [None] * 26 + self.indexes = [] + + def insert(self, word, i): + node = self + for c in word: + idx = ord(c) - ord("a") + if node.children[idx] is None: + node.children[idx] = Trie() + node = node.children[idx] + node.indexes.append(i) + + def search(self, pref): + node = self + for c in pref: + idx = ord(c) - ord("a") + if node.children[idx] is None: + return [] + node = node.children[idx] + return node.indexes + + +class WordFilter: + def __init__(self, words: List[str]): + self.p = Trie() + self.s = Trie() + for i, w in enumerate(words): + self.p.insert(w, i) + self.s.insert(w[::-1], i) + + def f(self, pref: str, suff: str) -> int: + a = self.p.search(pref) + b = self.s.search(suff[::-1]) + if not a or not b: + return -1 + i, j = len(a) - 1, len(b) - 1 + while ~i and ~j: + if a[i] == b[j]: + return a[i] + if a[i] > b[j]: + i -= 1 + else: + j -= 1 + return -1 + + +# Your WordFilter object will be instantiated and called as such: +# obj = WordFilter(words) +# param_1 = obj.f(pref,suff) diff --git a/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.cpp b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.cpp index 3e83bd9c0896d..16a0e8f681057 100644 --- a/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.cpp +++ b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.cpp @@ -1,12 +1,11 @@ -class Solution { -public: - int minCostClimbingStairs(vector& cost) { - int f = 0, g = 0; - for (int i = 2; i <= cost.size(); ++i) { - int gg = min(f + cost[i - 2], g + cost[i - 1]); - f = g; - g = gg; - } - return g; - } +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + int n = cost.size(); + vector f(n + 1); + for (int i = 2; i <= n; ++i) { + f[i] = min(f[i - 2] + cost[i - 2], f[i - 1] + cost[i - 1]); + } + return f[n]; + } }; \ No newline at end of file diff --git a/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.go b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.go index 24764a4c60f57..97ce4e397a98e 100644 --- a/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.go +++ b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.go @@ -1,7 +1,8 @@ func minCostClimbingStairs(cost []int) int { - var f, g int + n := len(cost) + f := make([]int, n+1) for i := 2; i <= n; i++ { - f, g = g, min(f+cost[i-2], g+cost[i-1]) + f[i] = min(f[i-1]+cost[i-1], f[i-2]+cost[i-2]) } - return g + return f[n] } \ No newline at end of file diff --git a/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.java b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.java index 78e778bcf49d3..c69c7d7398fe7 100644 --- a/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.java +++ b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.java @@ -1,11 +1,10 @@ -class Solution { - public int minCostClimbingStairs(int[] cost) { - int f = 0, g = 0; - for (int i = 2; i <= cost.length; ++i) { - int gg = Math.min(f + cost[i - 2], g + cost[i - 1]); - f = g; - g = gg; - } - return g; - } +class Solution { + public int minCostClimbingStairs(int[] cost) { + int n = cost.length; + int[] f = new int[n + 1]; + for (int i = 2; i <= n; ++i) { + f[i] = Math.min(f[i - 2] + cost[i - 2], f[i - 1] + cost[i - 1]); + } + return f[n]; + } } \ No newline at end of file diff --git a/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.py b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.py index ae51a443d9f8e..3c29d129b947b 100644 --- a/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.py +++ b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.py @@ -1,6 +1,7 @@ -class Solution: - def minCostClimbingStairs(self, cost: List[int]) -> int: - f = g = 0 - for i in range(2, len(cost) + 1): - f, g = g, min(f + cost[i - 2], g + cost[i - 1]) - return g +class Solution: + def minCostClimbingStairs(self, cost: List[int]) -> int: + n = len(cost) + f = [0] * (n + 1) + for i in range(2, n + 1): + f[i] = min(f[i - 2] + cost[i - 2], f[i - 1] + cost[i - 1]) + return f[n] diff --git a/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.rs b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.rs index 5d62ffd744c5c..82eb36fc1ec4b 100644 --- a/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.rs +++ b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.rs @@ -1,11 +1,10 @@ impl Solution { pub fn min_cost_climbing_stairs(cost: Vec) -> i32 { - let (mut f, mut g) = (0, 0); - for i in 2..=cost.len() { - let gg = std::cmp::min(f + cost[i - 2], g + cost[i - 1]); - f = g; - g = gg; + let n = cost.len(); + let mut f = vec![0; n + 1]; + for i in 2..=n { + f[i] = std::cmp::min(f[i - 2] + cost[i - 2], f[i - 1] + cost[i - 1]); } - g + f[n] } } diff --git a/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.ts b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.ts index dc38fa0f3da7f..7c51ae65fec4f 100644 --- a/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.ts +++ b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution.ts @@ -1,7 +1,8 @@ function minCostClimbingStairs(cost: number[]): number { - let [f, g] = [0, 0]; - for (let i = 2; i <= cost.length; ++i) { - [f, g] = [g, Math.min(f + cost[i - 2], g + cost[i - 1])]; + const n = cost.length; + const f: number[] = Array(n + 1).fill(0); + for (let i = 2; i <= n; ++i) { + f[i] = Math.min(f[i - 1] + cost[i - 1], f[i - 2] + cost[i - 2]); } - return g; + return f[n]; } diff --git a/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.cpp b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.cpp new file mode 100644 index 0000000000000..8add5acdee316 --- /dev/null +++ b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + int f = 0, g = 0; + for (int i = 2; i <= cost.size(); ++i) { + int gg = min(f + cost[i - 2], g + cost[i - 1]); + f = g; + g = gg; + } + return g; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.go b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.go new file mode 100644 index 0000000000000..24764a4c60f57 --- /dev/null +++ b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.go @@ -0,0 +1,7 @@ +func minCostClimbingStairs(cost []int) int { + var f, g int + for i := 2; i <= n; i++ { + f, g = g, min(f+cost[i-2], g+cost[i-1]) + } + return g +} \ No newline at end of file diff --git a/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.java b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.java new file mode 100644 index 0000000000000..87e58dc41de5d --- /dev/null +++ b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.java @@ -0,0 +1,11 @@ +class Solution { + public int minCostClimbingStairs(int[] cost) { + int f = 0, g = 0; + for (int i = 2; i <= cost.length; ++i) { + int gg = Math.min(f + cost[i - 2], g + cost[i - 1]); + f = g; + g = gg; + } + return g; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.py b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.py new file mode 100644 index 0000000000000..bc756e0b55d92 --- /dev/null +++ b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.py @@ -0,0 +1,6 @@ +class Solution: + def minCostClimbingStairs(self, cost: List[int]) -> int: + f = g = 0 + for i in range(2, len(cost) + 1): + f, g = g, min(f + cost[i - 2], g + cost[i - 1]) + return g diff --git a/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.rs b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.rs new file mode 100644 index 0000000000000..5d62ffd744c5c --- /dev/null +++ b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn min_cost_climbing_stairs(cost: Vec) -> i32 { + let (mut f, mut g) = (0, 0); + for i in 2..=cost.len() { + let gg = std::cmp::min(f + cost[i - 2], g + cost[i - 1]); + f = g; + g = gg; + } + g + } +} diff --git a/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.ts b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.ts new file mode 100644 index 0000000000000..2b133cba36647 --- /dev/null +++ b/solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.ts @@ -0,0 +1,8 @@ +function minCostClimbingStairs(cost: number[]): number { + let a = 0, + b = 0; + for (let i = 1; i < cost.length; ++i) { + [a, b] = [b, Math.min(a + cost[i - 1], b + cost[i])]; + } + return b; +} diff --git a/solution/0700-0799/0747.Largest Number At Least Twice of Others/Solution.cpp b/solution/0700-0799/0747.Largest Number At Least Twice of Others/Solution.cpp index 6f58941b1b216..efc581070a1e0 100644 --- a/solution/0700-0799/0747.Largest Number At Least Twice of Others/Solution.cpp +++ b/solution/0700-0799/0747.Largest Number At Least Twice of Others/Solution.cpp @@ -1,18 +1,18 @@ -class Solution { -public: - int dominantIndex(vector& nums) { - int n = nums.size(); - int k = 0; - for (int i = 0; i < n; ++i) { - if (nums[k] < nums[i]) { - k = i; - } - } - for (int i = 0; i < n; ++i) { - if (k != i && nums[k] < nums[i] * 2) { - return -1; - } - } - return k; - } +class Solution { +public: + int dominantIndex(vector& nums) { + int n = nums.size(); + int k = 0; + for (int i = 0; i < n; ++i) { + if (nums[k] < nums[i]) { + k = i; + } + } + for (int i = 0; i < n; ++i) { + if (k != i && nums[k] < nums[i] * 2) { + return -1; + } + } + return k; + } }; \ No newline at end of file diff --git a/solution/0700-0799/0747.Largest Number At Least Twice of Others/Solution.java b/solution/0700-0799/0747.Largest Number At Least Twice of Others/Solution.java index 1ba2fe8e8acbb..5bcc022388560 100644 --- a/solution/0700-0799/0747.Largest Number At Least Twice of Others/Solution.java +++ b/solution/0700-0799/0747.Largest Number At Least Twice of Others/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public int dominantIndex(int[] nums) { - int n = nums.length; - int k = 0; - for (int i = 0; i < n; ++i) { - if (nums[k] < nums[i]) { - k = i; - } - } - for (int i = 0; i < n; ++i) { - if (k != i && nums[k] < nums[i] * 2) { - return -1; - } - } - return k; - } +class Solution { + public int dominantIndex(int[] nums) { + int n = nums.length; + int k = 0; + for (int i = 0; i < n; ++i) { + if (nums[k] < nums[i]) { + k = i; + } + } + for (int i = 0; i < n; ++i) { + if (k != i && nums[k] < nums[i] * 2) { + return -1; + } + } + return k; + } } \ No newline at end of file diff --git a/solution/0700-0799/0747.Largest Number At Least Twice of Others/Solution.py b/solution/0700-0799/0747.Largest Number At Least Twice of Others/Solution.py index 3c23b293c01f8..2b51e03b88c69 100644 --- a/solution/0700-0799/0747.Largest Number At Least Twice of Others/Solution.py +++ b/solution/0700-0799/0747.Largest Number At Least Twice of Others/Solution.py @@ -1,4 +1,4 @@ -class Solution: - def dominantIndex(self, nums: List[int]) -> int: - x, y = nlargest(2, nums) - return nums.index(x) if x >= 2 * y else -1 +class Solution: + def dominantIndex(self, nums: List[int]) -> int: + x, y = nlargest(2, nums) + return nums.index(x) if x >= 2 * y else -1 diff --git a/solution/0700-0799/0748.Shortest Completing Word/Solution.cpp b/solution/0700-0799/0748.Shortest Completing Word/Solution.cpp index c79c78bd37d6b..83c2aa9241763 100644 --- a/solution/0700-0799/0748.Shortest Completing Word/Solution.cpp +++ b/solution/0700-0799/0748.Shortest Completing Word/Solution.cpp @@ -1,32 +1,32 @@ -class Solution { -public: - string shortestCompletingWord(string licensePlate, vector& words) { - int cnt[26]{}; - for (char& c : licensePlate) { - if (isalpha(c)) { - ++cnt[tolower(c) - 'a']; - } - } - string ans; - for (auto& w : words) { - if (ans.size() && ans.size() <= w.size()) { - continue; - } - int t[26]{}; - for (char& c : w) { - ++t[c - 'a']; - } - bool ok = true; - for (int i = 0; i < 26; ++i) { - if (cnt[i] > t[i]) { - ok = false; - break; - } - } - if (ok) { - ans = w; - } - } - return ans; - } +class Solution { +public: + string shortestCompletingWord(string licensePlate, vector& words) { + int cnt[26]{}; + for (char& c : licensePlate) { + if (isalpha(c)) { + ++cnt[tolower(c) - 'a']; + } + } + string ans; + for (auto& w : words) { + if (ans.size() && ans.size() <= w.size()) { + continue; + } + int t[26]{}; + for (char& c : w) { + ++t[c - 'a']; + } + bool ok = true; + for (int i = 0; i < 26; ++i) { + if (cnt[i] > t[i]) { + ok = false; + break; + } + } + if (ok) { + ans = w; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0700-0799/0748.Shortest Completing Word/Solution.java b/solution/0700-0799/0748.Shortest Completing Word/Solution.java index 1338440a8bdcb..de4a60810660e 100644 --- a/solution/0700-0799/0748.Shortest Completing Word/Solution.java +++ b/solution/0700-0799/0748.Shortest Completing Word/Solution.java @@ -1,32 +1,32 @@ -class Solution { - public String shortestCompletingWord(String licensePlate, String[] words) { - int[] cnt = new int[26]; - for (int i = 0; i < licensePlate.length(); ++i) { - char c = licensePlate.charAt(i); - if (Character.isLetter(c)) { - cnt[Character.toLowerCase(c) - 'a']++; - } - } - String ans = ""; - for (String w : words) { - if (!ans.isEmpty() && w.length() >= ans.length()) { - continue; - } - int[] t = new int[26]; - for (int i = 0; i < w.length(); ++i) { - t[w.charAt(i) - 'a']++; - } - boolean ok = true; - for (int i = 0; i < 26; ++i) { - if (t[i] < cnt[i]) { - ok = false; - break; - } - } - if (ok) { - ans = w; - } - } - return ans; - } +class Solution { + public String shortestCompletingWord(String licensePlate, String[] words) { + int[] cnt = new int[26]; + for (int i = 0; i < licensePlate.length(); ++i) { + char c = licensePlate.charAt(i); + if (Character.isLetter(c)) { + cnt[Character.toLowerCase(c) - 'a']++; + } + } + String ans = ""; + for (String w : words) { + if (!ans.isEmpty() && w.length() >= ans.length()) { + continue; + } + int[] t = new int[26]; + for (int i = 0; i < w.length(); ++i) { + t[w.charAt(i) - 'a']++; + } + boolean ok = true; + for (int i = 0; i < 26; ++i) { + if (t[i] < cnt[i]) { + ok = false; + break; + } + } + if (ok) { + ans = w; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0700-0799/0748.Shortest Completing Word/Solution.py b/solution/0700-0799/0748.Shortest Completing Word/Solution.py index 02452f1fad5e5..968a189b1272a 100644 --- a/solution/0700-0799/0748.Shortest Completing Word/Solution.py +++ b/solution/0700-0799/0748.Shortest Completing Word/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: - cnt = Counter(c.lower() for c in licensePlate if c.isalpha()) - ans = None - for w in words: - if ans and len(w) >= len(ans): - continue - t = Counter(w) - if all(v <= t[c] for c, v in cnt.items()): - ans = w - return ans +class Solution: + def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: + cnt = Counter(c.lower() for c in licensePlate if c.isalpha()) + ans = None + for w in words: + if ans and len(w) >= len(ans): + continue + t = Counter(w) + if all(v <= t[c] for c, v in cnt.items()): + ans = w + return ans diff --git a/solution/0700-0799/0750.Number Of Corner Rectangles/Solution.cpp b/solution/0700-0799/0750.Number Of Corner Rectangles/Solution.cpp index edcf872d928ab..720ae16515893 100644 --- a/solution/0700-0799/0750.Number Of Corner Rectangles/Solution.cpp +++ b/solution/0700-0799/0750.Number Of Corner Rectangles/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - int countCornerRectangles(vector>& grid) { - int n = grid[0].size(); - int ans = 0; - map, int> cnt; - for (auto& row : grid) { - for (int i = 0; i < n; ++i) { - if (row[i]) { - for (int j = i + 1; j < n; ++j) { - if (row[j]) { - ans += cnt[{i, j}]; - ++cnt[{i, j}]; - } - } - } - } - } - return ans; - } +class Solution { +public: + int countCornerRectangles(vector>& grid) { + int n = grid[0].size(); + int ans = 0; + map, int> cnt; + for (auto& row : grid) { + for (int i = 0; i < n; ++i) { + if (row[i]) { + for (int j = i + 1; j < n; ++j) { + if (row[j]) { + ans += cnt[{i, j}]; + ++cnt[{i, j}]; + } + } + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0700-0799/0750.Number Of Corner Rectangles/Solution.java b/solution/0700-0799/0750.Number Of Corner Rectangles/Solution.java index 0faa65a72974b..901b993fa64f4 100644 --- a/solution/0700-0799/0750.Number Of Corner Rectangles/Solution.java +++ b/solution/0700-0799/0750.Number Of Corner Rectangles/Solution.java @@ -1,21 +1,21 @@ -class Solution { - public int countCornerRectangles(int[][] grid) { - int n = grid[0].length; - int ans = 0; - Map, Integer> cnt = new HashMap<>(); - for (var row : grid) { - for (int i = 0; i < n; ++i) { - if (row[i] == 1) { - for (int j = i + 1; j < n; ++j) { - if (row[j] == 1) { - List t = List.of(i, j); - ans += cnt.getOrDefault(t, 0); - cnt.merge(t, 1, Integer::sum); - } - } - } - } - } - return ans; - } +class Solution { + public int countCornerRectangles(int[][] grid) { + int n = grid[0].length; + int ans = 0; + Map, Integer> cnt = new HashMap<>(); + for (var row : grid) { + for (int i = 0; i < n; ++i) { + if (row[i] == 1) { + for (int j = i + 1; j < n; ++j) { + if (row[j] == 1) { + List t = List.of(i, j); + ans += cnt.getOrDefault(t, 0); + cnt.merge(t, 1, Integer::sum); + } + } + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0700-0799/0750.Number Of Corner Rectangles/Solution.py b/solution/0700-0799/0750.Number Of Corner Rectangles/Solution.py index e0075d27420f7..f7516c63de2aa 100644 --- a/solution/0700-0799/0750.Number Of Corner Rectangles/Solution.py +++ b/solution/0700-0799/0750.Number Of Corner Rectangles/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def countCornerRectangles(self, grid: List[List[int]]) -> int: - ans = 0 - cnt = Counter() - n = len(grid[0]) - for row in grid: - for i, c1 in enumerate(row): - if c1: - for j in range(i + 1, n): - if row[j]: - ans += cnt[(i, j)] - cnt[(i, j)] += 1 - return ans +class Solution: + def countCornerRectangles(self, grid: List[List[int]]) -> int: + ans = 0 + cnt = Counter() + n = len(grid[0]) + for row in grid: + for i, c1 in enumerate(row): + if c1: + for j in range(i + 1, n): + if row[j]: + ans += cnt[(i, j)] + cnt[(i, j)] += 1 + return ans diff --git a/solution/0700-0799/0752.Open the Lock/Solution.cpp b/solution/0700-0799/0752.Open the Lock/Solution.cpp index fa7f9fd2990c0..e28c49d01bddc 100644 --- a/solution/0700-0799/0752.Open the Lock/Solution.cpp +++ b/solution/0700-0799/0752.Open the Lock/Solution.cpp @@ -1,42 +1,24 @@ class Solution { public: - unordered_set s; - string start; - string target; - int openLock(vector& deadends, string target) { - if (target == "0000") return 0; - for (auto d : deadends) s.insert(d); + unordered_set s(deadends.begin(), deadends.end()); if (s.count("0000")) return -1; - this->start = "0000"; - this->target = target; - return bfs(); - } - - int bfs() { - unordered_map m1; - unordered_map m2; - m1[start] = 0; - m2[target] = 0; - queue q1{{start}}; - queue q2{{target}}; - while (!q1.empty() && !q2.empty()) { - int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); - if (t != -1) return t; - } - return -1; - } - - int extend(unordered_map& m1, unordered_map& m2, queue& q) { - for (int n = q.size(); n > 0; --n) { - string p = q.front(); - int step = m1[p]; - q.pop(); - for (string t : next(p)) { - if (s.count(t) || m1.count(t)) continue; - if (m2.count(t)) return step + 1 + m2[t]; - m1[t] = step + 1; - q.push(t); + if (target == "0000") return 0; + queue q{{"0000"}}; + s.insert("0000"); + int ans = 0; + while (!q.empty()) { + ++ans; + for (int n = q.size(); n > 0; --n) { + string p = q.front(); + q.pop(); + for (string t : next(p)) { + if (target == t) return ans; + if (!s.count(t)) { + q.push(t); + s.insert(t); + } + } } } return -1; diff --git a/solution/0700-0799/0752.Open the Lock/Solution.go b/solution/0700-0799/0752.Open the Lock/Solution.go index 81541a9386304..61f138e9340c4 100644 --- a/solution/0700-0799/0752.Open the Lock/Solution.go +++ b/solution/0700-0799/0752.Open the Lock/Solution.go @@ -9,6 +9,9 @@ func openLock(deadends []string, target string) int { if s["0000"] { return -1 } + q := []string{"0000"} + s["0000"] = true + ans := 0 next := func(t string) []string { s := []byte(t) var res []string @@ -27,47 +30,21 @@ func openLock(deadends []string, target string) int { } return res } - - extend := func(m1, m2 map[string]int, q *[]string) int { - for n := len(*q); n > 0; n-- { - p := (*q)[0] - *q = (*q)[1:] - step, _ := m1[p] + for len(q) > 0 { + ans++ + for n := len(q); n > 0; n-- { + p := q[0] + q = q[1:] for _, t := range next(p) { - if s[t] { - continue + if target == t { + return ans } - if _, ok := m1[t]; ok { - continue + if !s[t] { + q = append(q, t) + s[t] = true } - if v, ok := m2[t]; ok { - return step + 1 + v - } - m1[t] = step + 1 - *q = append(*q, t) } } - return -1 - } - - bfs := func() int { - q1 := []string{"0000"} - q2 := []string{target} - m1 := map[string]int{"0000": 0} - m2 := map[string]int{target: 0} - for len(q1) > 0 && len(q2) > 0 { - t := -1 - if len(q1) <= len(q2) { - t = extend(m1, m2, &q1) - } else { - t = extend(m2, m1, &q2) - } - if t != -1 { - return t - } - } - return -1 } - - return bfs() + return -1 } \ No newline at end of file diff --git a/solution/0700-0799/0752.Open the Lock/Solution.java b/solution/0700-0799/0752.Open the Lock/Solution.java index 580da54af3f1c..f2b3d8753690f 100644 --- a/solution/0700-0799/0752.Open the Lock/Solution.java +++ b/solution/0700-0799/0752.Open the Lock/Solution.java @@ -1,54 +1,29 @@ class Solution { - private String start; - private String target; - private Set s = new HashSet<>(); - public int openLock(String[] deadends, String target) { if ("0000".equals(target)) { return 0; } - start = "0000"; - this.target = target; - for (String d : deadends) { - s.add(d); - } - if (s.contains(start)) { + Set s = new HashSet<>(Arrays.asList(deadends)); + if (s.contains("0000")) { return -1; } - return bfs(); - } - - private int bfs() { - Map m1 = new HashMap<>(); - Map m2 = new HashMap<>(); - Deque q1 = new ArrayDeque<>(); - Deque q2 = new ArrayDeque<>(); - m1.put(start, 0); - m2.put(target, 0); - q1.offer(start); - q2.offer(target); - while (!q1.isEmpty() && !q2.isEmpty()) { - int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); - if (t != -1) { - return t; - } - } - return -1; - } - - private int extend(Map m1, Map m2, Deque q) { - for (int n = q.size(); n > 0; --n) { - String p = q.poll(); - int step = m1.get(p); - for (String t : next(p)) { - if (m1.containsKey(t) || s.contains(t)) { - continue; - } - if (m2.containsKey(t)) { - return step + 1 + m2.get(t); + Deque q = new ArrayDeque<>(); + q.offer("0000"); + s.add("0000"); + int ans = 0; + while (!q.isEmpty()) { + ++ans; + for (int n = q.size(); n > 0; --n) { + String p = q.poll(); + for (String t : next(p)) { + if (target.equals(t)) { + return ans; + } + if (!s.contains(t)) { + q.offer(t); + s.add(t); + } } - m1.put(t, step + 1); - q.offer(t); } } return -1; diff --git a/solution/0700-0799/0752.Open the Lock/Solution.py b/solution/0700-0799/0752.Open the Lock/Solution.py index 49074767707c2..650d7757d7db7 100644 --- a/solution/0700-0799/0752.Open the Lock/Solution.py +++ b/solution/0700-0799/0752.Open the Lock/Solution.py @@ -1,42 +1,33 @@ -class Solution: - def openLock(self, deadends: List[str], target: str) -> int: - def next(s): - res = [] - s = list(s) - for i in range(4): - c = s[i] - s[i] = '9' if c == '0' else str(int(c) - 1) - res.append(''.join(s)) - s[i] = '0' if c == '9' else str(int(c) + 1) - res.append(''.join(s)) - s[i] = c - return res - - def extend(m1, m2, q): - for _ in range(len(q)): - p = q.popleft() - step = m1[p] - for t in next(p): - if t in s or t in m1: - continue - if t in m2: - return step + 1 + m2[t] - m1[t] = step + 1 - q.append(t) - return -1 - - def bfs(): - m1, m2 = {"0000": 0}, {target: 0} - q1, q2 = deque([('0000')]), deque([(target)]) - while q1 and q2: - t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) - if t != -1: - return t - return -1 - - if target == '0000': - return 0 - s = set(deadends) - if '0000' in s: - return -1 - return bfs() +class Solution: + def openLock(self, deadends: List[str], target: str) -> int: + def next(s): + res = [] + s = list(s) + for i in range(4): + c = s[i] + s[i] = '9' if c == '0' else str(int(c) - 1) + res.append(''.join(s)) + s[i] = '0' if c == '9' else str(int(c) + 1) + res.append(''.join(s)) + s[i] = c + return res + + if target == '0000': + return 0 + s = set(deadends) + if '0000' in s: + return -1 + q = deque([('0000')]) + s.add('0000') + ans = 0 + while q: + ans += 1 + for _ in range(len(q)): + p = q.popleft() + for t in next(p): + if t == target: + return ans + if t not in s: + q.append(t) + s.add(t) + return -1 diff --git a/solution/0700-0799/0752.Open the Lock/Solution2.cpp b/solution/0700-0799/0752.Open the Lock/Solution2.cpp new file mode 100644 index 0000000000000..fa7f9fd2990c0 --- /dev/null +++ b/solution/0700-0799/0752.Open the Lock/Solution2.cpp @@ -0,0 +1,57 @@ +class Solution { +public: + unordered_set s; + string start; + string target; + + int openLock(vector& deadends, string target) { + if (target == "0000") return 0; + for (auto d : deadends) s.insert(d); + if (s.count("0000")) return -1; + this->start = "0000"; + this->target = target; + return bfs(); + } + + int bfs() { + unordered_map m1; + unordered_map m2; + m1[start] = 0; + m2[target] = 0; + queue q1{{start}}; + queue q2{{target}}; + while (!q1.empty() && !q2.empty()) { + int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); + if (t != -1) return t; + } + return -1; + } + + int extend(unordered_map& m1, unordered_map& m2, queue& q) { + for (int n = q.size(); n > 0; --n) { + string p = q.front(); + int step = m1[p]; + q.pop(); + for (string t : next(p)) { + if (s.count(t) || m1.count(t)) continue; + if (m2.count(t)) return step + 1 + m2[t]; + m1[t] = step + 1; + q.push(t); + } + } + return -1; + } + + vector next(string& t) { + vector res; + for (int i = 0; i < 4; ++i) { + char c = t[i]; + t[i] = c == '0' ? '9' : (char) (c - 1); + res.push_back(t); + t[i] = c == '9' ? '0' : (char) (c + 1); + res.push_back(t); + t[i] = c; + } + return res; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0752.Open the Lock/Solution2.go b/solution/0700-0799/0752.Open the Lock/Solution2.go new file mode 100644 index 0000000000000..81541a9386304 --- /dev/null +++ b/solution/0700-0799/0752.Open the Lock/Solution2.go @@ -0,0 +1,73 @@ +func openLock(deadends []string, target string) int { + if target == "0000" { + return 0 + } + s := make(map[string]bool) + for _, d := range deadends { + s[d] = true + } + if s["0000"] { + return -1 + } + next := func(t string) []string { + s := []byte(t) + var res []string + for i, b := range s { + s[i] = b - 1 + if s[i] < '0' { + s[i] = '9' + } + res = append(res, string(s)) + s[i] = b + 1 + if s[i] > '9' { + s[i] = '0' + } + res = append(res, string(s)) + s[i] = b + } + return res + } + + extend := func(m1, m2 map[string]int, q *[]string) int { + for n := len(*q); n > 0; n-- { + p := (*q)[0] + *q = (*q)[1:] + step, _ := m1[p] + for _, t := range next(p) { + if s[t] { + continue + } + if _, ok := m1[t]; ok { + continue + } + if v, ok := m2[t]; ok { + return step + 1 + v + } + m1[t] = step + 1 + *q = append(*q, t) + } + } + return -1 + } + + bfs := func() int { + q1 := []string{"0000"} + q2 := []string{target} + m1 := map[string]int{"0000": 0} + m2 := map[string]int{target: 0} + for len(q1) > 0 && len(q2) > 0 { + t := -1 + if len(q1) <= len(q2) { + t = extend(m1, m2, &q1) + } else { + t = extend(m2, m1, &q2) + } + if t != -1 { + return t + } + } + return -1 + } + + return bfs() +} \ No newline at end of file diff --git a/solution/0700-0799/0752.Open the Lock/Solution2.java b/solution/0700-0799/0752.Open the Lock/Solution2.java new file mode 100644 index 0000000000000..580da54af3f1c --- /dev/null +++ b/solution/0700-0799/0752.Open the Lock/Solution2.java @@ -0,0 +1,70 @@ +class Solution { + private String start; + private String target; + private Set s = new HashSet<>(); + + public int openLock(String[] deadends, String target) { + if ("0000".equals(target)) { + return 0; + } + start = "0000"; + this.target = target; + for (String d : deadends) { + s.add(d); + } + if (s.contains(start)) { + return -1; + } + return bfs(); + } + + private int bfs() { + Map m1 = new HashMap<>(); + Map m2 = new HashMap<>(); + Deque q1 = new ArrayDeque<>(); + Deque q2 = new ArrayDeque<>(); + m1.put(start, 0); + m2.put(target, 0); + q1.offer(start); + q2.offer(target); + while (!q1.isEmpty() && !q2.isEmpty()) { + int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); + if (t != -1) { + return t; + } + } + return -1; + } + + private int extend(Map m1, Map m2, Deque q) { + for (int n = q.size(); n > 0; --n) { + String p = q.poll(); + int step = m1.get(p); + for (String t : next(p)) { + if (m1.containsKey(t) || s.contains(t)) { + continue; + } + if (m2.containsKey(t)) { + return step + 1 + m2.get(t); + } + m1.put(t, step + 1); + q.offer(t); + } + } + return -1; + } + + private List next(String t) { + List res = new ArrayList<>(); + char[] chars = t.toCharArray(); + for (int i = 0; i < 4; ++i) { + char c = chars[i]; + chars[i] = c == '0' ? '9' : (char) (c - 1); + res.add(String.valueOf(chars)); + chars[i] = c == '9' ? '0' : (char) (c + 1); + res.add(String.valueOf(chars)); + chars[i] = c; + } + return res; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0752.Open the Lock/Solution2.py b/solution/0700-0799/0752.Open the Lock/Solution2.py new file mode 100644 index 0000000000000..6a623bcf80b3b --- /dev/null +++ b/solution/0700-0799/0752.Open the Lock/Solution2.py @@ -0,0 +1,42 @@ +class Solution: + def openLock(self, deadends: List[str], target: str) -> int: + def next(s): + res = [] + s = list(s) + for i in range(4): + c = s[i] + s[i] = '9' if c == '0' else str(int(c) - 1) + res.append(''.join(s)) + s[i] = '0' if c == '9' else str(int(c) + 1) + res.append(''.join(s)) + s[i] = c + return res + + def extend(m1, m2, q): + for _ in range(len(q)): + p = q.popleft() + step = m1[p] + for t in next(p): + if t in s or t in m1: + continue + if t in m2: + return step + 1 + m2[t] + m1[t] = step + 1 + q.append(t) + return -1 + + def bfs(): + m1, m2 = {"0000": 0}, {target: 0} + q1, q2 = deque([('0000')]), deque([(target)]) + while q1 and q2: + t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) + if t != -1: + return t + return -1 + + if target == '0000': + return 0 + s = set(deadends) + if '0000' in s: + return -1 + return bfs() diff --git a/solution/0700-0799/0752.Open the Lock/Solution3.cpp b/solution/0700-0799/0752.Open the Lock/Solution3.cpp new file mode 100644 index 0000000000000..143248ce51776 --- /dev/null +++ b/solution/0700-0799/0752.Open the Lock/Solution3.cpp @@ -0,0 +1,60 @@ +class Solution { +public: + string target; + + int openLock(vector& deadends, string target) { + if (target == "0000") return 0; + unordered_set s(deadends.begin(), deadends.end()); + if (s.count("0000")) return -1; + string start = "0000"; + this->target = target; + typedef pair PIS; + priority_queue, greater> q; + unordered_map dist; + dist[start] = 0; + q.push({f(start), start}); + while (!q.empty()) { + PIS t = q.top(); + q.pop(); + string state = t.second; + int step = dist[state]; + if (state == target) return step; + for (string& t : next(state)) { + if (s.count(t)) continue; + if (!dist.count(t) || dist[t] > step + 1) { + dist[t] = step + 1; + q.push({step + 1 + f(t), t}); + } + } + } + return -1; + } + + int f(string s) { + int ans = 0; + for (int i = 0; i < 4; ++i) { + int a = s[i] - '0'; + int b = target[i] - '0'; + if (a < b) { + int t = a; + a = b; + b = t; + } + ans += min(b - a, a + 10 - b); + } + return ans; + } + + vector next(string& t) { + vector res; + for (int i = 0; i < 4; ++i) { + char c = t[i]; + t[i] = c == '0' ? '9' : (char) (c - 1); + res.push_back(t); + t[i] = c == '9' ? '0' : (char) (c + 1); + res.push_back(t); + t[i] = c; + } + return res; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0752.Open the Lock/Solution3.java b/solution/0700-0799/0752.Open the Lock/Solution3.java new file mode 100644 index 0000000000000..fce7bf4ad199e --- /dev/null +++ b/solution/0700-0799/0752.Open the Lock/Solution3.java @@ -0,0 +1,69 @@ +class Solution { + private String target; + + public int openLock(String[] deadends, String target) { + if ("0000".equals(target)) { + return 0; + } + String start = "0000"; + this.target = target; + Set s = new HashSet<>(); + for (String d : deadends) { + s.add(d); + } + if (s.contains(start)) { + return -1; + } + PriorityQueue> q + = new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)); + q.offer(new Pair<>(f(start), start)); + Map dist = new HashMap<>(); + dist.put(start, 0); + while (!q.isEmpty()) { + String state = q.poll().getValue(); + int step = dist.get(state); + if (target.equals(state)) { + return step; + } + for (String t : next(state)) { + if (s.contains(t)) { + continue; + } + if (!dist.containsKey(t) || dist.get(t) > step + 1) { + dist.put(t, step + 1); + q.offer(new Pair<>(step + 1 + f(t), t)); + } + } + } + return -1; + } + + private int f(String s) { + int ans = 0; + for (int i = 0; i < 4; ++i) { + int a = s.charAt(i) - '0'; + int b = target.charAt(i) - '0'; + if (a > b) { + int t = a; + a = b; + b = a; + } + ans += Math.min(b - a, a + 10 - b); + } + return ans; + } + + private List next(String t) { + List res = new ArrayList<>(); + char[] chars = t.toCharArray(); + for (int i = 0; i < 4; ++i) { + char c = chars[i]; + chars[i] = c == '0' ? '9' : (char) (c - 1); + res.add(String.valueOf(chars)); + chars[i] = c == '9' ? '0' : (char) (c + 1); + res.add(String.valueOf(chars)); + chars[i] = c; + } + return res; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0752.Open the Lock/Solution3.py b/solution/0700-0799/0752.Open the Lock/Solution3.py new file mode 100644 index 0000000000000..f1810dbe61f45 --- /dev/null +++ b/solution/0700-0799/0752.Open the Lock/Solution3.py @@ -0,0 +1,43 @@ +class Solution: + def openLock(self, deadends: List[str], target: str) -> int: + def next(s): + res = [] + s = list(s) + for i in range(4): + c = s[i] + s[i] = '9' if c == '0' else str(int(c) - 1) + res.append(''.join(s)) + s[i] = '0' if c == '9' else str(int(c) + 1) + res.append(''.join(s)) + s[i] = c + return res + + def f(s): + ans = 0 + for i in range(4): + a = ord(s[i]) - ord('0') + b = ord(target[i]) - ord('0') + if a > b: + a, b = b, a + ans += min(b - a, a + 10 - b) + return ans + + if target == '0000': + return 0 + s = set(deadends) + if '0000' in s: + return -1 + start = '0000' + q = [(f(start), start)] + dist = {start: 0} + while q: + _, state = heappop(q) + if state == target: + return dist[state] + for t in next(state): + if t in s: + continue + if t not in dist or dist[t] > dist[state] + 1: + dist[t] = dist[state] + 1 + heappush(q, (dist[t] + f(t), t)) + return -1 diff --git a/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/Solution.cpp b/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/Solution.cpp index 6b727c39ae5f8..22f56882e59fe 100644 --- a/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/Solution.cpp +++ b/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/Solution.cpp @@ -1,9 +1,9 @@ -class Solution { -public: - int countPrimeSetBits(int left, int right) { - unordered_set primes{2, 3, 5, 7, 11, 13, 17, 19}; - int ans = 0; - for (int i = left; i <= right; ++i) ans += primes.count(__builtin_popcount(i)); - return ans; - } +class Solution { +public: + int countPrimeSetBits(int left, int right) { + unordered_set primes{2, 3, 5, 7, 11, 13, 17, 19}; + int ans = 0; + for (int i = left; i <= right; ++i) ans += primes.count(__builtin_popcount(i)); + return ans; + } }; \ No newline at end of file diff --git a/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/Solution.java b/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/Solution.java index 01a19101742ab..e077462844255 100644 --- a/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/Solution.java +++ b/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/Solution.java @@ -1,13 +1,13 @@ -class Solution { - private static Set primes = Set.of(2, 3, 5, 7, 11, 13, 17, 19); - - public int countPrimeSetBits(int left, int right) { - int ans = 0; - for (int i = left; i <= right; ++i) { - if (primes.contains(Integer.bitCount(i))) { - ++ans; - } - } - return ans; - } +class Solution { + private static Set primes = Set.of(2, 3, 5, 7, 11, 13, 17, 19); + + public int countPrimeSetBits(int left, int right) { + int ans = 0; + for (int i = left; i <= right; ++i) { + if (primes.contains(Integer.bitCount(i))) { + ++ans; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/Solution.py b/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/Solution.py index 0b94b2e9c0788..1905d4333a59e 100644 --- a/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/Solution.py +++ b/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/Solution.py @@ -1,4 +1,4 @@ -class Solution: - def countPrimeSetBits(self, left: int, right: int) -> int: - primes = {2, 3, 5, 7, 11, 13, 17, 19} - return sum(i.bit_count() in primes for i in range(left, right + 1)) +class Solution: + def countPrimeSetBits(self, left: int, right: int) -> int: + primes = {2, 3, 5, 7, 11, 13, 17, 19} + return sum(i.bit_count() in primes for i in range(left, right + 1)) diff --git a/solution/0700-0799/0763.Partition Labels/Solution.cpp b/solution/0700-0799/0763.Partition Labels/Solution.cpp index f3bfe865bebfb..3fc5c2bbb21e6 100644 --- a/solution/0700-0799/0763.Partition Labels/Solution.cpp +++ b/solution/0700-0799/0763.Partition Labels/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - vector partitionLabels(string s) { - int last[26] = {0}; - int n = s.size(); - for (int i = 0; i < n; ++i) { - last[s[i] - 'a'] = i; - } - vector ans; - int mx = 0, j = 0; - for (int i = 0; i < n; ++i) { - mx = max(mx, last[s[i] - 'a']); - if (mx == i) { - ans.push_back(i - j + 1); - j = i + 1; - } - } - return ans; - } +class Solution { +public: + vector partitionLabels(string s) { + int last[26] = {0}; + int n = s.size(); + for (int i = 0; i < n; ++i) { + last[s[i] - 'a'] = i; + } + vector ans; + int mx = 0, j = 0; + for (int i = 0; i < n; ++i) { + mx = max(mx, last[s[i] - 'a']); + if (mx == i) { + ans.push_back(i - j + 1); + j = i + 1; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0700-0799/0763.Partition Labels/Solution.cs b/solution/0700-0799/0763.Partition Labels/Solution.cs index 448e4d91bbca7..83c586fac1386 100644 --- a/solution/0700-0799/0763.Partition Labels/Solution.cs +++ b/solution/0700-0799/0763.Partition Labels/Solution.cs @@ -1,18 +1,18 @@ -public class Solution { - public IList PartitionLabels(string s) { - int[] last = new int[26]; - int n = s.Length; - for (int i = 0; i < n; i++) { - last[s[i] - 'a'] = i; - } - IList ans = new List(); - for (int i = 0, j = 0, mx = 0; i < n; ++i) { - mx = Math.Max(mx, last[s[i] - 'a']); - if (mx == i) { - ans.Add(i - j + 1); - j = i + 1; - } - } - return ans; - } -} \ No newline at end of file +public class Solution { + public IList PartitionLabels(string s) { + int[] last = new int[26]; + int n = s.Length; + for (int i = 0; i < n; i++) { + last[s[i] - 'a'] = i; + } + IList ans = new List(); + for (int i = 0, j = 0, mx = 0; i < n; ++i) { + mx = Math.Max(mx, last[s[i] - 'a']); + if (mx == i) { + ans.Add(i - j + 1); + j = i + 1; + } + } + return ans; + } +} diff --git a/solution/0700-0799/0763.Partition Labels/Solution.java b/solution/0700-0799/0763.Partition Labels/Solution.java index 159761cc06b10..bb2f937fe22b4 100644 --- a/solution/0700-0799/0763.Partition Labels/Solution.java +++ b/solution/0700-0799/0763.Partition Labels/Solution.java @@ -1,19 +1,19 @@ -class Solution { - public List partitionLabels(String s) { - int[] last = new int[26]; - int n = s.length(); - for (int i = 0; i < n; ++i) { - last[s.charAt(i) - 'a'] = i; - } - List ans = new ArrayList<>(); - int mx = 0, j = 0; - for (int i = 0; i < n; ++i) { - mx = Math.max(mx, last[s.charAt(i) - 'a']); - if (mx == i) { - ans.add(i - j + 1); - j = i + 1; - } - } - return ans; - } +class Solution { + public List partitionLabels(String s) { + int[] last = new int[26]; + int n = s.length(); + for (int i = 0; i < n; ++i) { + last[s.charAt(i) - 'a'] = i; + } + List ans = new ArrayList<>(); + int mx = 0, j = 0; + for (int i = 0; i < n; ++i) { + mx = Math.max(mx, last[s.charAt(i) - 'a']); + if (mx == i) { + ans.add(i - j + 1); + j = i + 1; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0700-0799/0763.Partition Labels/Solution.py b/solution/0700-0799/0763.Partition Labels/Solution.py index 479940dcf8ea2..3c1b77de11e08 100644 --- a/solution/0700-0799/0763.Partition Labels/Solution.py +++ b/solution/0700-0799/0763.Partition Labels/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def partitionLabels(self, s: str) -> List[int]: - last = {c: i for i, c in enumerate(s)} - mx = j = 0 - ans = [] - for i, c in enumerate(s): - mx = max(mx, last[c]) - if mx == i: - ans.append(i - j + 1) - j = i + 1 - return ans +class Solution: + def partitionLabels(self, s: str) -> List[int]: + last = {c: i for i, c in enumerate(s)} + mx = j = 0 + ans = [] + for i, c in enumerate(s): + mx = max(mx, last[c]) + if mx == i: + ans.append(i - j + 1) + j = i + 1 + return ans diff --git a/solution/0700-0799/0765.Couples Holding Hands/Solution.cpp b/solution/0700-0799/0765.Couples Holding Hands/Solution.cpp index 84aba753f2cd9..cd4ee3c17f8e4 100644 --- a/solution/0700-0799/0765.Couples Holding Hands/Solution.cpp +++ b/solution/0700-0799/0765.Couples Holding Hands/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - int minSwapsCouples(vector& row) { - int n = row.size() / 2; - int p[n]; - iota(p, p + n, 0); - function find = [&](int x) -> int { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - }; - for (int i = 0; i < n << 1; i += 2) { - int a = row[i] >> 1, b = row[i + 1] >> 1; - p[find(a)] = find(b); - } - int ans = n; - for (int i = 0; i < n; ++i) { - ans -= i == find(i); - } - return ans; - } +class Solution { +public: + int minSwapsCouples(vector& row) { + int n = row.size() / 2; + int p[n]; + iota(p, p + n, 0); + function find = [&](int x) -> int { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + }; + for (int i = 0; i < n << 1; i += 2) { + int a = row[i] >> 1, b = row[i + 1] >> 1; + p[find(a)] = find(b); + } + int ans = n; + for (int i = 0; i < n; ++i) { + ans -= i == find(i); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0700-0799/0765.Couples Holding Hands/Solution.cs b/solution/0700-0799/0765.Couples Holding Hands/Solution.cs index 12729d77dd2b2..6ad5d97a994a8 100644 --- a/solution/0700-0799/0765.Couples Holding Hands/Solution.cs +++ b/solution/0700-0799/0765.Couples Holding Hands/Solution.cs @@ -1,30 +1,30 @@ -public class Solution { - private int[] p; - - public int MinSwapsCouples(int[] row) { - int n = row.Length >> 1; - p = new int[n]; - for (int i = 0; i < n; ++i) { - p[i] = i; - } - for (int i = 0; i < n << 1; i += 2) { - int a = row[i] >> 1; - int b = row[i + 1] >> 1; - p[find(a)] = find(b); - } - int ans = n; - for (int i = 0; i < n; ++i) { - if (p[i] == i) { - --ans; - } - } - return ans; - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } -} \ No newline at end of file +public class Solution { + private int[] p; + + public int MinSwapsCouples(int[] row) { + int n = row.Length >> 1; + p = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + } + for (int i = 0; i < n << 1; i += 2) { + int a = row[i] >> 1; + int b = row[i + 1] >> 1; + p[find(a)] = find(b); + } + int ans = n; + for (int i = 0; i < n; ++i) { + if (p[i] == i) { + --ans; + } + } + return ans; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} diff --git a/solution/0700-0799/0765.Couples Holding Hands/Solution.java b/solution/0700-0799/0765.Couples Holding Hands/Solution.java index 18e3dd48fd9ff..516ed3983286a 100644 --- a/solution/0700-0799/0765.Couples Holding Hands/Solution.java +++ b/solution/0700-0799/0765.Couples Holding Hands/Solution.java @@ -1,29 +1,29 @@ -class Solution { - private int[] p; - - public int minSwapsCouples(int[] row) { - int n = row.length >> 1; - p = new int[n]; - for (int i = 0; i < n; ++i) { - p[i] = i; - } - for (int i = 0; i < n << 1; i += 2) { - int a = row[i] >> 1, b = row[i + 1] >> 1; - p[find(a)] = find(b); - } - int ans = n; - for (int i = 0; i < n; ++i) { - if (i == find(i)) { - --ans; - } - } - return ans; - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } +class Solution { + private int[] p; + + public int minSwapsCouples(int[] row) { + int n = row.length >> 1; + p = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + } + for (int i = 0; i < n << 1; i += 2) { + int a = row[i] >> 1, b = row[i + 1] >> 1; + p[find(a)] = find(b); + } + int ans = n; + for (int i = 0; i < n; ++i) { + if (i == find(i)) { + --ans; + } + } + return ans; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } } \ No newline at end of file diff --git a/solution/0700-0799/0765.Couples Holding Hands/Solution.py b/solution/0700-0799/0765.Couples Holding Hands/Solution.py index d966f99679b31..bcbef2ca6092f 100644 --- a/solution/0700-0799/0765.Couples Holding Hands/Solution.py +++ b/solution/0700-0799/0765.Couples Holding Hands/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def minSwapsCouples(self, row: List[int]) -> int: - def find(x: int) -> int: - if p[x] != x: - p[x] = find(p[x]) - return p[x] - - n = len(row) >> 1 - p = list(range(n)) - for i in range(0, len(row), 2): - a, b = row[i] >> 1, row[i + 1] >> 1 - p[find(a)] = find(b) - return n - sum(i == find(i) for i in range(n)) +class Solution: + def minSwapsCouples(self, row: List[int]) -> int: + def find(x: int) -> int: + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + n = len(row) >> 1 + p = list(range(n)) + for i in range(0, len(row), 2): + a, b = row[i] >> 1, row[i + 1] >> 1 + p[find(a)] = find(b) + return n - sum(i == find(i) for i in range(n)) diff --git a/solution/0700-0799/0767.Reorganize String/Solution2.cpp b/solution/0700-0799/0767.Reorganize String/Solution2.cpp new file mode 100644 index 0000000000000..6cd877a09121a --- /dev/null +++ b/solution/0700-0799/0767.Reorganize String/Solution2.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + string reorganizeString(string s) { + return rearrangeString(s, 2); + } + + string rearrangeString(string s, int k) { + unordered_map cnt; + for (char c : s) ++cnt[c]; + priority_queue> pq; + for (auto& [c, v] : cnt) pq.push({v, c}); + queue> q; + string ans; + while (!pq.empty()) { + auto [v, c] = pq.top(); + pq.pop(); + ans += c; + q.push({v - 1, c}); + if (q.size() >= k) { + auto p = q.front(); + q.pop(); + if (p.first) { + pq.push(p); + } + } + } + return ans.size() == s.size() ? ans : ""; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0767.Reorganize String/Solution2.go b/solution/0700-0799/0767.Reorganize String/Solution2.go new file mode 100644 index 0000000000000..dab3d41928909 --- /dev/null +++ b/solution/0700-0799/0767.Reorganize String/Solution2.go @@ -0,0 +1,49 @@ +func reorganizeString(s string) string { + return rearrangeString(s, 2) +} + +func rearrangeString(s string, k int) string { + cnt := map[byte]int{} + for i := range s { + cnt[s[i]]++ + } + pq := hp{} + for c, v := range cnt { + heap.Push(&pq, pair{v, c}) + } + ans := []byte{} + q := []pair{} + for len(pq) > 0 { + p := heap.Pop(&pq).(pair) + v, c := p.v, p.c + ans = append(ans, c) + q = append(q, pair{v - 1, c}) + if len(q) >= k { + p = q[0] + q = q[1:] + if p.v > 0 { + heap.Push(&pq, p) + } + } + } + if len(ans) == len(s) { + return string(ans) + } + return "" +} + +type pair struct { + v int + c byte +} + +type hp []pair + +func (h hp) Len() int { return len(h) } +func (h hp) Less(i, j int) bool { + a, b := h[i], h[j] + return a.v > b.v +} +func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } +func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } \ No newline at end of file diff --git a/solution/0700-0799/0767.Reorganize String/Solution2.java b/solution/0700-0799/0767.Reorganize String/Solution2.java new file mode 100644 index 0000000000000..6959c81003eeb --- /dev/null +++ b/solution/0700-0799/0767.Reorganize String/Solution2.java @@ -0,0 +1,34 @@ +class Solution { + public String reorganizeString(String s) { + return rearrangeString(s, 2); + } + + public String rearrangeString(String s, int k) { + int n = s.length(); + int[] cnt = new int[26]; + for (char c : s.toCharArray()) { + ++cnt[c - 'a']; + } + PriorityQueue pq = new PriorityQueue<>((a, b) -> b[0] - a[0]); + for (int i = 0; i < 26; ++i) { + if (cnt[i] > 0) { + pq.offer(new int[] {cnt[i], i}); + } + } + Deque q = new ArrayDeque<>(); + StringBuilder ans = new StringBuilder(); + while (!pq.isEmpty()) { + var p = pq.poll(); + int v = p[0], c = p[1]; + ans.append((char) ('a' + c)); + q.offer(new int[] {v - 1, c}); + if (q.size() >= k) { + p = q.pollFirst(); + if (p[0] > 0) { + pq.offer(p); + } + } + } + return ans.length() == n ? ans.toString() : ""; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0767.Reorganize String/Solution2.py b/solution/0700-0799/0767.Reorganize String/Solution2.py new file mode 100644 index 0000000000000..2962cfbf234de --- /dev/null +++ b/solution/0700-0799/0767.Reorganize String/Solution2.py @@ -0,0 +1,19 @@ +class Solution: + def reorganizeString(self, s: str) -> str: + return self.rearrangeString(s, 2) + + def rearrangeString(self, s: str, k: int) -> str: + h = [(-v, c) for c, v in Counter(s).items()] + heapify(h) + q = deque() + ans = [] + while h: + v, c = heappop(h) + v *= -1 + ans.append(c) + q.append((v - 1, c)) + if len(q) >= k: + w, c = q.popleft() + if w: + heappush(h, (-w, c)) + return "" if len(ans) != len(s) else "".join(ans) diff --git a/solution/0700-0799/0769.Max Chunks To Make Sorted/Solution.c b/solution/0700-0799/0769.Max Chunks To Make Sorted/Solution.c index 1f8ca793093d6..8cb564843f83c 100644 --- a/solution/0700-0799/0769.Max Chunks To Make Sorted/Solution.c +++ b/solution/0700-0799/0769.Max Chunks To Make Sorted/Solution.c @@ -10,4 +10,4 @@ int maxChunksToSorted(int* arr, int arrSize) { } } return res; -} +} \ No newline at end of file diff --git a/solution/0700-0799/0769.Max Chunks To Make Sorted/Solution2.cpp b/solution/0700-0799/0769.Max Chunks To Make Sorted/Solution2.cpp new file mode 100644 index 0000000000000..08f2834084546 --- /dev/null +++ b/solution/0700-0799/0769.Max Chunks To Make Sorted/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int maxChunksToSorted(vector& arr) { + stack stk; + for (int v : arr) { + if (stk.empty() || v >= stk.top()) { + stk.push(v); + } else { + int mx = stk.top(); + stk.pop(); + while (!stk.empty() && stk.top() > v) { + stk.pop(); + } + stk.push(mx); + } + } + return stk.size(); + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0769.Max Chunks To Make Sorted/Solution2.go b/solution/0700-0799/0769.Max Chunks To Make Sorted/Solution2.go new file mode 100644 index 0000000000000..7e47512a8939e --- /dev/null +++ b/solution/0700-0799/0769.Max Chunks To Make Sorted/Solution2.go @@ -0,0 +1,16 @@ +func maxChunksToSorted(arr []int) int { + stk := []int{} + for _, v := range arr { + if len(stk) == 0 || v >= stk[len(stk)-1] { + stk = append(stk, v) + } else { + mx := stk[len(stk)-1] + stk = stk[:len(stk)-1] + for len(stk) > 0 && stk[len(stk)-1] > v { + stk = stk[:len(stk)-1] + } + stk = append(stk, mx) + } + } + return len(stk) +} \ No newline at end of file diff --git a/solution/0700-0799/0769.Max Chunks To Make Sorted/Solution2.java b/solution/0700-0799/0769.Max Chunks To Make Sorted/Solution2.java new file mode 100644 index 0000000000000..84c74b922b556 --- /dev/null +++ b/solution/0700-0799/0769.Max Chunks To Make Sorted/Solution2.java @@ -0,0 +1,17 @@ +class Solution { + public int maxChunksToSorted(int[] arr) { + Deque stk = new ArrayDeque<>(); + for (int v : arr) { + if (stk.isEmpty() || v >= stk.peek()) { + stk.push(v); + } else { + int mx = stk.pop(); + while (!stk.isEmpty() && stk.peek() > v) { + stk.pop(); + } + stk.push(mx); + } + } + return stk.size(); + } +} \ No newline at end of file diff --git a/solution/0700-0799/0769.Max Chunks To Make Sorted/Solution2.py b/solution/0700-0799/0769.Max Chunks To Make Sorted/Solution2.py new file mode 100644 index 0000000000000..136132d699aad --- /dev/null +++ b/solution/0700-0799/0769.Max Chunks To Make Sorted/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def maxChunksToSorted(self, arr: List[int]) -> int: + stk = [] + for v in arr: + if not stk or v >= stk[-1]: + stk.append(v) + else: + mx = stk.pop() + while stk and stk[-1] > v: + stk.pop() + stk.append(mx) + return len(stk) diff --git a/solution/0700-0799/0771.Jewels and Stones/Solution.c b/solution/0700-0799/0771.Jewels and Stones/Solution.c index 4a0a79a7be67b..fa51af012743d 100644 --- a/solution/0700-0799/0771.Jewels and Stones/Solution.c +++ b/solution/0700-0799/0771.Jewels and Stones/Solution.c @@ -8,4 +8,4 @@ int numJewelsInStones(char* jewels, char* stones) { set[stones[i]] && ans++; } return ans; -} +} \ No newline at end of file diff --git a/solution/0700-0799/0773.Sliding Puzzle/Solution.cpp b/solution/0700-0799/0773.Sliding Puzzle/Solution.cpp index bc21ba79c6567..af31b0fe648f2 100644 --- a/solution/0700-0799/0773.Sliding Puzzle/Solution.cpp +++ b/solution/0700-0799/0773.Sliding Puzzle/Solution.cpp @@ -1,64 +1,72 @@ class Solution { public: - int m = 2; - int n = 3; - int slidingPuzzle(vector>& board) { - string start, seq; + string start = gets(board); string end = "123450"; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - start += char(board[i][j] + '0'); - if (board[i][j] != 0) seq += char(board[i][j] + '0'); - } - } - if (!check(seq)) return -1; - typedef pair PIS; - priority_queue, greater> q; - unordered_map dist; - dist[start] = 0; - q.push({f(start), start}); - vector dirs = {-1, 0, 1, 0, -1}; + if (start == end) return 0; + unordered_set vis; + vis.insert(start); + queue q{{start}}; + int ans = 0; while (!q.empty()) { - PIS t = q.top(); - q.pop(); - string state = t.second; - int step = dist[state]; - if (state == end) return step; - int p1 = state.find('0'); - int i = p1 / n, j = p1 % n; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x < 0 || x >= m || y < 0 || y >= n) continue; - int p2 = x * n + y; - swap(state[p1], state[p2]); - if (!dist.count(state) || dist[state] > step + 1) { - dist[state] = step + 1; - q.push({step + 1 + f(state), state}); + ++ans; + for (int n = q.size(); n > 0; --n) { + string x = q.front(); + q.pop(); + setb(x, board); + for (string y : next(board)) { + if (y == end) return ans; + if (!vis.count(y)) { + vis.insert(y); + q.push(y); + } } - swap(state[p1], state[p2]); } } return -1; } - bool check(string s) { - int n = s.size(); - int cnt = 0; - for (int i = 0; i < n; ++i) - for (int j = i; j < n; ++j) - if (s[i] > s[j]) - ++cnt; - return cnt % 2 == 0; + string gets(vector>& board) { + string s = ""; + for (int i = 0; i < 2; ++i) + for (int j = 0; j < 3; ++j) + s.push_back('0' + board[i][j]); + return s; } - int f(string s) { - int ans = 0; - for (int i = 0; i < m * n; ++i) { - if (s[i] == '0') continue; - int num = s[i] - '1'; - ans += abs(num / n - i / n) + abs(num % n - i % n); + void setb(string s, vector>& board) { + for (int i = 0; i < 2; ++i) + for (int j = 0; j < 3; ++j) + board[i][j] = s[i * 3 + j] - '0'; + } + + vector next(vector>& board) { + vector res; + auto p = find0(board); + int i = p.first, j = p.second; + vector dirs = {-1, 0, 1, 0, -1}; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < 2 && y >= 0 && y < 3) { + swap(i, j, x, y, board); + res.push_back(gets(board)); + swap(i, j, x, y, board); + } } - return ans; + return res; + } + + void swap(int i, int j, int x, int y, vector>& board) { + int t = board[i][j]; + board[i][j] = board[x][y]; + board[x][y] = t; + } + + pair find0(vector>& board) { + for (int i = 0; i < 2; ++i) + for (int j = 0; j < 3; ++j) + if (board[i][j] == 0) + return {i, j}; + return {0, 0}; } }; \ No newline at end of file diff --git a/solution/0700-0799/0773.Sliding Puzzle/Solution.java b/solution/0700-0799/0773.Sliding Puzzle/Solution.java index e01478a59cb02..4d1cf7ccaf44c 100644 --- a/solution/0700-0799/0773.Sliding Puzzle/Solution.java +++ b/solution/0700-0799/0773.Sliding Puzzle/Solution.java @@ -1,81 +1,86 @@ class Solution { - private int m = 2; - private int n = 3; + private String[] t = new String[6]; + private int[][] board; public int slidingPuzzle(int[][] board) { - String start = ""; + this.board = board; + String start = gets(); String end = "123450"; - String seq = ""; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - start += board[i][j]; - if (board[i][j] != 0) { - seq += board[i][j]; - } - } - } - if (!check(seq)) { - return -1; + if (end.equals(start)) { + return 0; } - PriorityQueue> q - = new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)); - Map dist = new HashMap<>(); - dist.put(start, 0); - q.offer(new Pair<>(f(start), start)); - int[] dirs = {-1, 0, 1, 0, -1}; + Set vis = new HashSet<>(); + Deque q = new ArrayDeque<>(); + q.offer(start); + vis.add(start); + int ans = 0; while (!q.isEmpty()) { - String state = q.poll().getValue(); - int step = dist.get(state); - if (end.equals(state)) { - return step; - } - int p1 = state.indexOf("0"); - int i = p1 / n, j = p1 % n; - char[] s = state.toCharArray(); - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n) { - int p2 = x * n + y; - swap(s, p1, p2); - String next = String.valueOf(s); - if (!dist.containsKey(next) || dist.get(next) > step + 1) { - dist.put(next, step + 1); - q.offer(new Pair<>(step + 1 + f(next), next)); + ++ans; + for (int n = q.size(); n > 0; --n) { + String x = q.poll(); + setb(x); + for (String y : next()) { + if (y.equals(end)) { + return ans; + } + if (!vis.contains(y)) { + vis.add(y); + q.offer(y); } - swap(s, p1, p2); } } } return -1; } - private void swap(char[] arr, int i, int j) { - char t = arr[i]; - arr[i] = arr[j]; - arr[j] = t; + private String gets() { + for (int i = 0; i < 2; ++i) { + for (int j = 0; j < 3; ++j) { + t[i * 3 + j] = String.valueOf(board[i][j]); + } + } + return String.join("", t); } - private int f(String s) { - int ans = 0; - for (int i = 0; i < m * n; ++i) { - if (s.charAt(i) != '0') { - int num = s.charAt(i) - '1'; - ans += Math.abs(i / n - num / n) + Math.abs(i % n - num % n); + private void setb(String s) { + for (int i = 0; i < 2; ++i) { + for (int j = 0; j < 3; ++j) { + board[i][j] = s.charAt(i * 3 + j) - '0'; } } - return ans; } - private boolean check(String s) { - int n = s.length(); - int cnt = 0; - for (int i = 0; i < n; ++i) { - for (int j = i + 1; j < n; ++j) { - if (s.charAt(i) > s.charAt(j)) { - ++cnt; + private int[] find0() { + for (int i = 0; i < 2; ++i) { + for (int j = 0; j < 3; ++j) { + if (board[i][j] == 0) { + return new int[] {i, j}; } } } - return cnt % 2 == 0; + return new int[] {0, 0}; + } + + private List next() { + int[] p = find0(); + int i = p[0], j = p[1]; + int[] dirs = {-1, 0, 1, 0, -1}; + List res = new ArrayList<>(); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k]; + int y = j + dirs[k + 1]; + if (x >= 0 && x < 2 && y >= 0 && y < 3) { + swap(i, j, x, y); + res.add(gets()); + swap(i, j, x, y); + } + } + return res; + } + + private void swap(int i, int j, int x, int y) { + int t = board[i][j]; + board[i][j] = board[x][y]; + board[x][y] = t; } } \ No newline at end of file diff --git a/solution/0700-0799/0773.Sliding Puzzle/Solution.py b/solution/0700-0799/0773.Sliding Puzzle/Solution.py index 282a305c2f27f..897f9d185a622 100644 --- a/solution/0700-0799/0773.Sliding Puzzle/Solution.py +++ b/solution/0700-0799/0773.Sliding Puzzle/Solution.py @@ -1,46 +1,45 @@ class Solution: def slidingPuzzle(self, board: List[List[int]]) -> int: - m, n = 2, 3 - seq = [] - start, end = '', '123450' - for i in range(m): - for j in range(n): - if board[i][j] != 0: - seq.append(board[i][j]) - start += str(board[i][j]) + t = [None] * 6 - def check(seq): - n = len(seq) - cnt = sum(seq[i] > seq[j] for i in range(n) for j in range(i, n)) - return cnt % 2 == 0 + def gets(): + for i in range(2): + for j in range(3): + t[i * 3 + j] = str(board[i][j]) + return ''.join(t) - def f(s): - ans = 0 - for i in range(m * n): - if s[i] != '0': - num = ord(s[i]) - ord('1') - ans += abs(i // n - num // n) + abs(i % n - num % n) - return ans + def setb(s): + for i in range(2): + for j in range(3): + board[i][j] = int(s[i * 3 + j]) - if not check(seq): - return -1 - q = [(f(start), start)] - dist = {start: 0} - while q: - _, state = heappop(q) - if state == end: - return dist[state] - p1 = state.index('0') - i, j = p1 // n, p1 % n - s = list(state) + def f(): + res = [] + i, j = next((i, j) for i in range(2) for j in range(3) if board[i][j] == 0) for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]: x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n: - p2 = x * n + y - s[p1], s[p2] = s[p2], s[p1] - next = ''.join(s) - s[p1], s[p2] = s[p2], s[p1] - if next not in dist or dist[next] > dist[state] + 1: - dist[next] = dist[state] + 1 - heappush(q, (dist[next] + f(next), next)) + if 0 <= x < 2 and 0 <= y < 3: + board[i][j], board[x][y] = board[x][y], board[i][j] + res.append(gets()) + board[i][j], board[x][y] = board[x][y], board[i][j] + return res + + start = gets() + end = "123450" + if start == end: + return 0 + vis = {start} + q = deque([(start)]) + ans = 0 + while q: + ans += 1 + for _ in range(len(q)): + x = q.popleft() + setb(x) + for y in f(): + if y == end: + return ans + if y not in vis: + vis.add(y) + q.append(y) return -1 diff --git a/solution/0700-0799/0773.Sliding Puzzle/Solution2.cpp b/solution/0700-0799/0773.Sliding Puzzle/Solution2.cpp new file mode 100644 index 0000000000000..bc21ba79c6567 --- /dev/null +++ b/solution/0700-0799/0773.Sliding Puzzle/Solution2.cpp @@ -0,0 +1,64 @@ +class Solution { +public: + int m = 2; + int n = 3; + + int slidingPuzzle(vector>& board) { + string start, seq; + string end = "123450"; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + start += char(board[i][j] + '0'); + if (board[i][j] != 0) seq += char(board[i][j] + '0'); + } + } + if (!check(seq)) return -1; + typedef pair PIS; + priority_queue, greater> q; + unordered_map dist; + dist[start] = 0; + q.push({f(start), start}); + vector dirs = {-1, 0, 1, 0, -1}; + while (!q.empty()) { + PIS t = q.top(); + q.pop(); + string state = t.second; + int step = dist[state]; + if (state == end) return step; + int p1 = state.find('0'); + int i = p1 / n, j = p1 % n; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x < 0 || x >= m || y < 0 || y >= n) continue; + int p2 = x * n + y; + swap(state[p1], state[p2]); + if (!dist.count(state) || dist[state] > step + 1) { + dist[state] = step + 1; + q.push({step + 1 + f(state), state}); + } + swap(state[p1], state[p2]); + } + } + return -1; + } + + bool check(string s) { + int n = s.size(); + int cnt = 0; + for (int i = 0; i < n; ++i) + for (int j = i; j < n; ++j) + if (s[i] > s[j]) + ++cnt; + return cnt % 2 == 0; + } + + int f(string s) { + int ans = 0; + for (int i = 0; i < m * n; ++i) { + if (s[i] == '0') continue; + int num = s[i] - '1'; + ans += abs(num / n - i / n) + abs(num % n - i % n); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0773.Sliding Puzzle/Solution2.java b/solution/0700-0799/0773.Sliding Puzzle/Solution2.java new file mode 100644 index 0000000000000..e01478a59cb02 --- /dev/null +++ b/solution/0700-0799/0773.Sliding Puzzle/Solution2.java @@ -0,0 +1,81 @@ +class Solution { + private int m = 2; + private int n = 3; + + public int slidingPuzzle(int[][] board) { + String start = ""; + String end = "123450"; + String seq = ""; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + start += board[i][j]; + if (board[i][j] != 0) { + seq += board[i][j]; + } + } + } + if (!check(seq)) { + return -1; + } + PriorityQueue> q + = new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)); + Map dist = new HashMap<>(); + dist.put(start, 0); + q.offer(new Pair<>(f(start), start)); + int[] dirs = {-1, 0, 1, 0, -1}; + while (!q.isEmpty()) { + String state = q.poll().getValue(); + int step = dist.get(state); + if (end.equals(state)) { + return step; + } + int p1 = state.indexOf("0"); + int i = p1 / n, j = p1 % n; + char[] s = state.toCharArray(); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n) { + int p2 = x * n + y; + swap(s, p1, p2); + String next = String.valueOf(s); + if (!dist.containsKey(next) || dist.get(next) > step + 1) { + dist.put(next, step + 1); + q.offer(new Pair<>(step + 1 + f(next), next)); + } + swap(s, p1, p2); + } + } + } + return -1; + } + + private void swap(char[] arr, int i, int j) { + char t = arr[i]; + arr[i] = arr[j]; + arr[j] = t; + } + + private int f(String s) { + int ans = 0; + for (int i = 0; i < m * n; ++i) { + if (s.charAt(i) != '0') { + int num = s.charAt(i) - '1'; + ans += Math.abs(i / n - num / n) + Math.abs(i % n - num % n); + } + } + return ans; + } + + private boolean check(String s) { + int n = s.length(); + int cnt = 0; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + if (s.charAt(i) > s.charAt(j)) { + ++cnt; + } + } + } + return cnt % 2 == 0; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0773.Sliding Puzzle/Solution2.py b/solution/0700-0799/0773.Sliding Puzzle/Solution2.py new file mode 100644 index 0000000000000..282a305c2f27f --- /dev/null +++ b/solution/0700-0799/0773.Sliding Puzzle/Solution2.py @@ -0,0 +1,46 @@ +class Solution: + def slidingPuzzle(self, board: List[List[int]]) -> int: + m, n = 2, 3 + seq = [] + start, end = '', '123450' + for i in range(m): + for j in range(n): + if board[i][j] != 0: + seq.append(board[i][j]) + start += str(board[i][j]) + + def check(seq): + n = len(seq) + cnt = sum(seq[i] > seq[j] for i in range(n) for j in range(i, n)) + return cnt % 2 == 0 + + def f(s): + ans = 0 + for i in range(m * n): + if s[i] != '0': + num = ord(s[i]) - ord('1') + ans += abs(i // n - num // n) + abs(i % n - num % n) + return ans + + if not check(seq): + return -1 + q = [(f(start), start)] + dist = {start: 0} + while q: + _, state = heappop(q) + if state == end: + return dist[state] + p1 = state.index('0') + i, j = p1 // n, p1 % n + s = list(state) + for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]: + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n: + p2 = x * n + y + s[p1], s[p2] = s[p2], s[p1] + next = ''.join(s) + s[p1], s[p2] = s[p2], s[p1] + if next not in dist or dist[next] > dist[state] + 1: + dist[next] = dist[state] + 1 + heappush(q, (dist[next] + f(next), next)) + return -1 diff --git a/solution/0700-0799/0775.Global and Local Inversions/Solution2.cpp b/solution/0700-0799/0775.Global and Local Inversions/Solution2.cpp new file mode 100644 index 0000000000000..c97f4e03aec16 --- /dev/null +++ b/solution/0700-0799/0775.Global and Local Inversions/Solution2.cpp @@ -0,0 +1,41 @@ +class BinaryIndexedTree { +public: + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + int query(int x) { + int s = 0; + while (x) { + s += c[x]; + x -= x & -x; + } + return s; + } + +private: + int n; + vector c; +}; + +class Solution { +public: + bool isIdealPermutation(vector& nums) { + int n = nums.size(); + BinaryIndexedTree tree(n); + long cnt = 0; + for (int i = 0; i < n && ~cnt; ++i) { + cnt += (i < n - 1 && nums[i] > nums[i + 1]); + cnt -= (i - tree.query(nums[i])); + tree.update(nums[i] + 1, 1); + } + return cnt == 0; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0775.Global and Local Inversions/Solution2.go b/solution/0700-0799/0775.Global and Local Inversions/Solution2.go new file mode 100644 index 0000000000000..a1b017ed08ff3 --- /dev/null +++ b/solution/0700-0799/0775.Global and Local Inversions/Solution2.go @@ -0,0 +1,42 @@ +func isIdealPermutation(nums []int) bool { + n := len(nums) + tree := newBinaryIndexedTree(n) + cnt := 0 + for i, v := range nums { + if i < n-1 && v > nums[i+1] { + cnt++ + } + cnt -= (i - tree.query(v)) + if cnt < 0 { + break + } + tree.update(v+1, 1) + } + return cnt == 0 +} + +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) BinaryIndexedTree { + c := make([]int, n+1) + return BinaryIndexedTree{n, c} +} + +func (this BinaryIndexedTree) update(x, delta int) { + for x <= this.n { + this.c[x] += delta + x += x & -x + } +} + +func (this BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= x & -x + } + return s +} \ No newline at end of file diff --git a/solution/0700-0799/0775.Global and Local Inversions/Solution2.java b/solution/0700-0799/0775.Global and Local Inversions/Solution2.java new file mode 100644 index 0000000000000..4a5a2b73b9bf9 --- /dev/null +++ b/solution/0700-0799/0775.Global and Local Inversions/Solution2.java @@ -0,0 +1,39 @@ +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +} + +class Solution { + public boolean isIdealPermutation(int[] nums) { + int n = nums.length; + BinaryIndexedTree tree = new BinaryIndexedTree(n); + int cnt = 0; + for (int i = 0; i < n && cnt >= 0; ++i) { + cnt += (i < n - 1 && nums[i] > nums[i + 1] ? 1 : 0); + cnt -= (i - tree.query(nums[i])); + tree.update(nums[i] + 1, 1); + } + return cnt == 0; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0775.Global and Local Inversions/Solution2.py b/solution/0700-0799/0775.Global and Local Inversions/Solution2.py new file mode 100644 index 0000000000000..4a544efd62d23 --- /dev/null +++ b/solution/0700-0799/0775.Global and Local Inversions/Solution2.py @@ -0,0 +1,30 @@ +class BinaryIndexedTree: + def __init__(self, n): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x, delta): + while x <= self.n: + self.c[x] += delta + x += x & -x + + def query(self, x): + s = 0 + while x: + s += self.c[x] + x -= x & -x + return s + + +class Solution: + def isIdealPermutation(self, nums: List[int]) -> bool: + n = len(nums) + tree = BinaryIndexedTree(n) + cnt = 0 + for i, v in enumerate(nums): + cnt += i < n - 1 and v > nums[i + 1] + cnt -= i - tree.query(v) + if cnt < 0: + return False + tree.update(v + 1, 1) + return True diff --git a/solution/0700-0799/0779.K-th Symbol in Grammar/Solution.cpp b/solution/0700-0799/0779.K-th Symbol in Grammar/Solution.cpp index df82777399bba..6da9879ab132c 100644 --- a/solution/0700-0799/0779.K-th Symbol in Grammar/Solution.cpp +++ b/solution/0700-0799/0779.K-th Symbol in Grammar/Solution.cpp @@ -1,6 +1,8 @@ class Solution { public: int kthGrammar(int n, int k) { - return __builtin_popcount(k - 1) & 1; + if (n == 1) return 0; + if (k <= (1 << (n - 2))) return kthGrammar(n - 1, k); + return kthGrammar(n - 1, k - (1 << (n - 2))) ^ 1; } }; \ No newline at end of file diff --git a/solution/0700-0799/0779.K-th Symbol in Grammar/Solution.go b/solution/0700-0799/0779.K-th Symbol in Grammar/Solution.go index c7a816d7605d0..d18afaf08f5ca 100644 --- a/solution/0700-0799/0779.K-th Symbol in Grammar/Solution.go +++ b/solution/0700-0799/0779.K-th Symbol in Grammar/Solution.go @@ -1,3 +1,9 @@ func kthGrammar(n int, k int) int { - return bits.OnesCount(uint(k-1)) & 1 + if n == 1 { + return 0 + } + if k <= (1 << (n - 2)) { + return kthGrammar(n-1, k) + } + return kthGrammar(n-1, k-(1<<(n-2))) ^ 1 } \ No newline at end of file diff --git a/solution/0700-0799/0779.K-th Symbol in Grammar/Solution.java b/solution/0700-0799/0779.K-th Symbol in Grammar/Solution.java index 9b7b8fcfa901d..04080d7abc67c 100644 --- a/solution/0700-0799/0779.K-th Symbol in Grammar/Solution.java +++ b/solution/0700-0799/0779.K-th Symbol in Grammar/Solution.java @@ -1,5 +1,11 @@ class Solution { public int kthGrammar(int n, int k) { - return Integer.bitCount(k - 1) & 1; + if (n == 1) { + return 0; + } + if (k <= (1 << (n - 2))) { + return kthGrammar(n - 1, k); + } + return kthGrammar(n - 1, k - (1 << (n - 2))) ^ 1; } } \ No newline at end of file diff --git a/solution/0700-0799/0779.K-th Symbol in Grammar/Solution.py b/solution/0700-0799/0779.K-th Symbol in Grammar/Solution.py index d0e5953bca11f..7122a6093708c 100644 --- a/solution/0700-0799/0779.K-th Symbol in Grammar/Solution.py +++ b/solution/0700-0799/0779.K-th Symbol in Grammar/Solution.py @@ -1,3 +1,7 @@ class Solution: def kthGrammar(self, n: int, k: int) -> int: - return (k - 1).bit_count() & 1 + if n == 1: + return 0 + if k <= (1 << (n - 2)): + return self.kthGrammar(n - 1, k) + return self.kthGrammar(n - 1, k - (1 << (n - 2))) ^ 1 diff --git a/solution/0700-0799/0779.K-th Symbol in Grammar/Solution2.cpp b/solution/0700-0799/0779.K-th Symbol in Grammar/Solution2.cpp new file mode 100644 index 0000000000000..df82777399bba --- /dev/null +++ b/solution/0700-0799/0779.K-th Symbol in Grammar/Solution2.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + int kthGrammar(int n, int k) { + return __builtin_popcount(k - 1) & 1; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0779.K-th Symbol in Grammar/Solution2.go b/solution/0700-0799/0779.K-th Symbol in Grammar/Solution2.go new file mode 100644 index 0000000000000..c7a816d7605d0 --- /dev/null +++ b/solution/0700-0799/0779.K-th Symbol in Grammar/Solution2.go @@ -0,0 +1,3 @@ +func kthGrammar(n int, k int) int { + return bits.OnesCount(uint(k-1)) & 1 +} \ No newline at end of file diff --git a/solution/0700-0799/0779.K-th Symbol in Grammar/Solution2.java b/solution/0700-0799/0779.K-th Symbol in Grammar/Solution2.java new file mode 100644 index 0000000000000..9b7b8fcfa901d --- /dev/null +++ b/solution/0700-0799/0779.K-th Symbol in Grammar/Solution2.java @@ -0,0 +1,5 @@ +class Solution { + public int kthGrammar(int n, int k) { + return Integer.bitCount(k - 1) & 1; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0779.K-th Symbol in Grammar/Solution2.py b/solution/0700-0799/0779.K-th Symbol in Grammar/Solution2.py new file mode 100644 index 0000000000000..d0e5953bca11f --- /dev/null +++ b/solution/0700-0799/0779.K-th Symbol in Grammar/Solution2.py @@ -0,0 +1,3 @@ +class Solution: + def kthGrammar(self, n: int, k: int) -> int: + return (k - 1).bit_count() & 1 diff --git a/solution/0700-0799/0780.Reaching Points/Solution.cpp b/solution/0700-0799/0780.Reaching Points/Solution.cpp index 717fa4413b93b..6843e939c4b35 100644 --- a/solution/0700-0799/0780.Reaching Points/Solution.cpp +++ b/solution/0700-0799/0780.Reaching Points/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - bool reachingPoints(int sx, int sy, int tx, int ty) { - while (tx > sx && ty > sy && tx != ty) { - if (tx > ty) - tx %= ty; - else - ty %= tx; - } - if (tx == sx && ty == sy) return true; - if (tx == sx) return ty > sy && (ty - sy) % tx == 0; - if (ty == sy) return tx > sx && (tx - sx) % ty == 0; - return false; - } +class Solution { +public: + bool reachingPoints(int sx, int sy, int tx, int ty) { + while (tx > sx && ty > sy && tx != ty) { + if (tx > ty) + tx %= ty; + else + ty %= tx; + } + if (tx == sx && ty == sy) return true; + if (tx == sx) return ty > sy && (ty - sy) % tx == 0; + if (ty == sy) return tx > sx && (tx - sx) % ty == 0; + return false; + } }; \ No newline at end of file diff --git a/solution/0700-0799/0780.Reaching Points/Solution.java b/solution/0700-0799/0780.Reaching Points/Solution.java index 10d0a9d01645b..3e3754e06bd26 100644 --- a/solution/0700-0799/0780.Reaching Points/Solution.java +++ b/solution/0700-0799/0780.Reaching Points/Solution.java @@ -1,21 +1,21 @@ -class Solution { - public boolean reachingPoints(int sx, int sy, int tx, int ty) { - while (tx > sx && ty > sy && tx != ty) { - if (tx > ty) { - tx %= ty; - } else { - ty %= tx; - } - } - if (tx == sx && ty == sy) { - return true; - } - if (tx == sx) { - return ty > sy && (ty - sy) % tx == 0; - } - if (ty == sy) { - return tx > sx && (tx - sx) % ty == 0; - } - return false; - } +class Solution { + public boolean reachingPoints(int sx, int sy, int tx, int ty) { + while (tx > sx && ty > sy && tx != ty) { + if (tx > ty) { + tx %= ty; + } else { + ty %= tx; + } + } + if (tx == sx && ty == sy) { + return true; + } + if (tx == sx) { + return ty > sy && (ty - sy) % tx == 0; + } + if (ty == sy) { + return tx > sx && (tx - sx) % ty == 0; + } + return false; + } } \ No newline at end of file diff --git a/solution/0700-0799/0780.Reaching Points/Solution.py b/solution/0700-0799/0780.Reaching Points/Solution.py index deffb58c5083e..e3ae7ba7e5fcd 100644 --- a/solution/0700-0799/0780.Reaching Points/Solution.py +++ b/solution/0700-0799/0780.Reaching Points/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool: - while tx > sx and ty > sy and tx != ty: - if tx > ty: - tx %= ty - else: - ty %= tx - if tx == sx and ty == sy: - return True - if tx == sx: - return ty > sy and (ty - sy) % tx == 0 - if ty == sy: - return tx > sx and (tx - sx) % ty == 0 - return False +class Solution: + def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool: + while tx > sx and ty > sy and tx != ty: + if tx > ty: + tx %= ty + else: + ty %= tx + if tx == sx and ty == sy: + return True + if tx == sx: + return ty > sy and (ty - sy) % tx == 0 + if ty == sy: + return tx > sx and (tx - sx) % ty == 0 + return False diff --git a/solution/0700-0799/0784.Letter Case Permutation/Solution2.cpp b/solution/0700-0799/0784.Letter Case Permutation/Solution2.cpp new file mode 100644 index 0000000000000..e92edc5464a79 --- /dev/null +++ b/solution/0700-0799/0784.Letter Case Permutation/Solution2.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + vector letterCasePermutation(string s) { + int n = 0; + for (char c : s) + if (isalpha(c)) ++n; + vector ans; + for (int i = 0; i < 1 << n; ++i) { + int j = 0; + string t; + for (char c : s) { + if (isalpha(c)) { + c = (i >> j & 1) ? tolower(c) : toupper(c); + ++j; + } + t += c; + } + ans.emplace_back(t); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0784.Letter Case Permutation/Solution2.go b/solution/0700-0799/0784.Letter Case Permutation/Solution2.go new file mode 100644 index 0000000000000..d0334a2a8b5dd --- /dev/null +++ b/solution/0700-0799/0784.Letter Case Permutation/Solution2.go @@ -0,0 +1,25 @@ +func letterCasePermutation(s string) (ans []string) { + n := 0 + for _, c := range s { + if c >= 'A' { + n++ + } + } + for i := 0; i < 1<= 'A' { + if ((i >> j) & 1) == 1 { + c = unicode.ToLower(c) + } else { + c = unicode.ToUpper(c) + } + j++ + } + t = append(t, c) + } + ans = append(ans, string(t)) + } + return ans +} \ No newline at end of file diff --git a/solution/0700-0799/0784.Letter Case Permutation/Solution2.java b/solution/0700-0799/0784.Letter Case Permutation/Solution2.java new file mode 100644 index 0000000000000..9dc4bce98a634 --- /dev/null +++ b/solution/0700-0799/0784.Letter Case Permutation/Solution2.java @@ -0,0 +1,25 @@ +class Solution { + public List letterCasePermutation(String s) { + int n = 0; + for (int i = 0; i < s.length(); ++i) { + if (s.charAt(i) >= 'A') { + ++n; + } + } + List ans = new ArrayList<>(); + for (int i = 0; i < 1 << n; ++i) { + int j = 0; + StringBuilder t = new StringBuilder(); + for (int k = 0; k < s.length(); ++k) { + char x = s.charAt(k); + if (x >= 'A') { + x = ((i >> j) & 1) == 1 ? Character.toLowerCase(x) : Character.toUpperCase(x); + ++j; + } + t.append(x); + } + ans.add(t.toString()); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0784.Letter Case Permutation/Solution2.py b/solution/0700-0799/0784.Letter Case Permutation/Solution2.py new file mode 100644 index 0000000000000..73f5a068ad6df --- /dev/null +++ b/solution/0700-0799/0784.Letter Case Permutation/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def letterCasePermutation(self, s: str) -> List[str]: + ans = [] + n = sum(c.isalpha() for c in s) + for i in range(1 << n): + j, t = 0, [] + for c in s: + if c.isalpha(): + c = c.lower() if (i >> j) & 1 else c.upper() + j += 1 + t.append(c) + ans.append(''.join(t)) + return ans diff --git a/solution/0700-0799/0785.Is Graph Bipartite/Solution.ts b/solution/0700-0799/0785.Is Graph Bipartite/Solution.ts index bad47a9afb815..88692c15ebc97 100644 --- a/solution/0700-0799/0785.Is Graph Bipartite/Solution.ts +++ b/solution/0700-0799/0785.Is Graph Bipartite/Solution.ts @@ -1,6 +1,7 @@ function isBipartite(graph: number[][]): boolean { const n = graph.length; let valid = true; + // 0 未遍历, 1 红色标记, 2 绿色标记 let colors = new Array(n).fill(0); function dfs(idx: number, color: number, graph: number[][]) { colors[idx] = color; diff --git a/solution/0700-0799/0785.Is Graph Bipartite/Solution2.cpp b/solution/0700-0799/0785.Is Graph Bipartite/Solution2.cpp new file mode 100644 index 0000000000000..73ab8a67cc3a2 --- /dev/null +++ b/solution/0700-0799/0785.Is Graph Bipartite/Solution2.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + vector p; + + bool isBipartite(vector>& graph) { + int n = graph.size(); + p.resize(n); + for (int i = 0; i < n; ++i) p[i] = i; + for (int u = 0; u < n; ++u) { + auto& g = graph[u]; + for (int v : g) { + if (find(u) == find(v)) return 0; + p[find(v)] = find(g[0]); + } + } + return 1; + } + + int find(int x) { + if (p[x] != x) p[x] = find(p[x]); + return p[x]; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0785.Is Graph Bipartite/Solution2.go b/solution/0700-0799/0785.Is Graph Bipartite/Solution2.go new file mode 100644 index 0000000000000..f52ba18b0283d --- /dev/null +++ b/solution/0700-0799/0785.Is Graph Bipartite/Solution2.go @@ -0,0 +1,23 @@ +func isBipartite(graph [][]int) bool { + n := len(graph) + p := make([]int, n) + for i := range p { + p[i] = i + } + var find func(x int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + for u, g := range graph { + for _, v := range g { + if find(u) == find(v) { + return false + } + p[find(v)] = find(g[0]) + } + } + return true +} \ No newline at end of file diff --git a/solution/0700-0799/0785.Is Graph Bipartite/Solution2.java b/solution/0700-0799/0785.Is Graph Bipartite/Solution2.java new file mode 100644 index 0000000000000..f40f2a480dbf7 --- /dev/null +++ b/solution/0700-0799/0785.Is Graph Bipartite/Solution2.java @@ -0,0 +1,28 @@ +class Solution { + private int[] p; + + public boolean isBipartite(int[][] graph) { + int n = graph.length; + p = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + } + for (int u = 0; u < n; ++u) { + int[] g = graph[u]; + for (int v : g) { + if (find(u) == find(v)) { + return false; + } + p[find(v)] = find(g[0]); + } + } + return true; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0785.Is Graph Bipartite/Solution2.py b/solution/0700-0799/0785.Is Graph Bipartite/Solution2.py new file mode 100644 index 0000000000000..32761a802ef55 --- /dev/null +++ b/solution/0700-0799/0785.Is Graph Bipartite/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def isBipartite(self, graph: List[List[int]]) -> bool: + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + p = list(range(len(graph))) + for u, g in enumerate(graph): + for v in g: + if find(u) == find(v): + return False + p[find(v)] = find(g[0]) + return True diff --git a/solution/0700-0799/0785.Is Graph Bipartite/Solution2.rs b/solution/0700-0799/0785.Is Graph Bipartite/Solution2.rs new file mode 100644 index 0000000000000..574f7c1e9d66c --- /dev/null +++ b/solution/0700-0799/0785.Is Graph Bipartite/Solution2.rs @@ -0,0 +1,46 @@ +impl Solution { + #[allow(dead_code)] + pub fn is_bipartite(graph: Vec>) -> bool { + let n = graph.len(); + let mut disjoint_set: Vec = vec![0; n]; + // Initialize the disjoint set + for i in 0..n { + disjoint_set[i] = i; + } + + // Traverse the graph + for i in 0..n { + if graph[i].is_empty() { + continue; + } + let first = graph[i][0] as usize; + for v in &graph[i] { + let v = *v as usize; + let i_p = Self::find(i, &mut disjoint_set); + let v_p = Self::find(v, &mut disjoint_set); + if i_p == v_p { + return false; + } + // Otherwise, union the node + Self::union(first, v, &mut disjoint_set); + } + } + + true + } + + #[allow(dead_code)] + fn find(x: usize, d_set: &mut Vec) -> usize { + if d_set[x] != x { + d_set[x] = Self::find(d_set[x], d_set); + } + d_set[x] + } + + #[allow(dead_code)] + fn union(x: usize, y: usize, d_set: &mut Vec) { + let p_x = Self::find(x, d_set); + let p_y = Self::find(y, d_set); + d_set[p_x] = p_y; + } +} diff --git a/solution/0700-0799/0785.Is Graph Bipartite/Solution2.ts b/solution/0700-0799/0785.Is Graph Bipartite/Solution2.ts new file mode 100644 index 0000000000000..76b038b2ffe62 --- /dev/null +++ b/solution/0700-0799/0785.Is Graph Bipartite/Solution2.ts @@ -0,0 +1,22 @@ +function isBipartite(graph: number[][]): boolean { + const n = graph.length; + let p = new Array(n); + for (let i = 0; i < n; ++i) { + p[i] = i; + } + function find(x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + for (let u = 0; u < n; ++u) { + for (let v of graph[u]) { + if (find(u) == find(v)) { + return false; + } + p[find(v)] = find(graph[u][0]); + } + } + return true; +} diff --git a/solution/0700-0799/0786.K-th Smallest Prime Fraction/Solution.cpp b/solution/0700-0799/0786.K-th Smallest Prime Fraction/Solution.cpp index 1e21f4539f531..b35b068c55a5b 100644 --- a/solution/0700-0799/0786.K-th Smallest Prime Fraction/Solution.cpp +++ b/solution/0700-0799/0786.K-th Smallest Prime Fraction/Solution.cpp @@ -19,4 +19,4 @@ class Solution { } return {arr[pq.top().first], arr[pq.top().second]}; } -}; +}; \ No newline at end of file diff --git a/solution/0700-0799/0786.K-th Smallest Prime Fraction/Solution.java b/solution/0700-0799/0786.K-th Smallest Prime Fraction/Solution.java index 9769ab58b19b0..718180f89166d 100644 --- a/solution/0700-0799/0786.K-th Smallest Prime Fraction/Solution.java +++ b/solution/0700-0799/0786.K-th Smallest Prime Fraction/Solution.java @@ -30,4 +30,4 @@ public int compareTo(Object o) { return x * ((Frac) o).y - ((Frac) o).x * y; } } -} +} \ No newline at end of file diff --git a/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution.cpp b/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution.cpp index f370447f4e397..dc6ed94c4da45 100644 --- a/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution.cpp +++ b/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution.cpp @@ -1,17 +1,17 @@ -class Solution { -public: - int findCheapestPrice(int n, vector>& flights, int src, int dst, int k) { - const int inf = 0x3f3f3f3f; - vector dist(n, inf); - vector backup; - dist[src] = 0; - for (int i = 0; i < k + 1; ++i) { - backup = dist; - for (auto& e : flights) { - int f = e[0], t = e[1], p = e[2]; - dist[t] = min(dist[t], backup[f] + p); - } - } - return dist[dst] == inf ? -1 : dist[dst]; - } +class Solution { +public: + int findCheapestPrice(int n, vector>& flights, int src, int dst, int k) { + const int inf = 0x3f3f3f3f; + vector dist(n, inf); + vector backup; + dist[src] = 0; + for (int i = 0; i < k + 1; ++i) { + backup = dist; + for (auto& e : flights) { + int f = e[0], t = e[1], p = e[2]; + dist[t] = min(dist[t], backup[f] + p); + } + } + return dist[dst] == inf ? -1 : dist[dst]; + } }; \ No newline at end of file diff --git a/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution.java b/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution.java index b70a9ace2a6a4..4eb0e6c6d79e9 100644 --- a/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution.java +++ b/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution.java @@ -1,18 +1,18 @@ -class Solution { - private static final int INF = 0x3f3f3f3f; - - public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { - int[] dist = new int[n]; - int[] backup = new int[n]; - Arrays.fill(dist, INF); - dist[src] = 0; - for (int i = 0; i < k + 1; ++i) { - System.arraycopy(dist, 0, backup, 0, n); - for (int[] e : flights) { - int f = e[0], t = e[1], p = e[2]; - dist[t] = Math.min(dist[t], backup[f] + p); - } - } - return dist[dst] == INF ? -1 : dist[dst]; - } +class Solution { + private static final int INF = 0x3f3f3f3f; + + public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { + int[] dist = new int[n]; + int[] backup = new int[n]; + Arrays.fill(dist, INF); + dist[src] = 0; + for (int i = 0; i < k + 1; ++i) { + System.arraycopy(dist, 0, backup, 0, n); + for (int[] e : flights) { + int f = e[0], t = e[1], p = e[2]; + dist[t] = Math.min(dist[t], backup[f] + p); + } + } + return dist[dst] == INF ? -1 : dist[dst]; + } } \ No newline at end of file diff --git a/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution.py b/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution.py index 530f0831e03d2..ea6f8c590677f 100644 --- a/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution.py +++ b/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def findCheapestPrice( - self, n: int, flights: List[List[int]], src: int, dst: int, k: int - ) -> int: - INF = 0x3F3F3F3F - dist = [INF] * n - dist[src] = 0 - for _ in range(k + 1): - backup = dist.copy() - for f, t, p in flights: - dist[t] = min(dist[t], backup[f] + p) - return -1 if dist[dst] == INF else dist[dst] +class Solution: + def findCheapestPrice( + self, n: int, flights: List[List[int]], src: int, dst: int, k: int + ) -> int: + INF = 0x3F3F3F3F + dist = [INF] * n + dist[src] = 0 + for _ in range(k + 1): + backup = dist.copy() + for f, t, p in flights: + dist[t] = min(dist[t], backup[f] + p) + return -1 if dist[dst] == INF else dist[dst] diff --git a/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution2.cpp b/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution2.cpp new file mode 100644 index 0000000000000..b1cd3ccfac564 --- /dev/null +++ b/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution2.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + vector> memo; + vector> g; + int dst; + int inf = 1e6; + + int findCheapestPrice(int n, vector>& flights, int src, int dst, int k) { + n += 10; + memo.resize(n, vector(n, -1)); + g.resize(n, vector(n)); + for (auto& e : flights) g[e[0]][e[1]] = e[2]; + this->dst = dst; + int ans = dfs(src, k + 1); + return ans >= inf ? -1 : ans; + } + + int dfs(int u, int k) { + if (memo[u][k] != -1) return memo[u][k]; + if (u == dst) return 0; + if (k <= 0) return inf; + int ans = inf; + for (int v = 0; v < g[u].size(); ++v) + if (g[u][v] > 0) + ans = min(ans, dfs(v, k - 1) + g[u][v]); + memo[u][k] = ans; + return memo[u][k]; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution2.go b/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution2.go new file mode 100644 index 0000000000000..6f01da730774a --- /dev/null +++ b/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution2.go @@ -0,0 +1,42 @@ +func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int { + n += 10 + memo := make([][]int, n) + g := make([][]int, n) + for i := range memo { + memo[i] = make([]int, n) + g[i] = make([]int, n) + for j := range memo[i] { + memo[i][j] = -1 + } + } + + for _, e := range flights { + g[e[0]][e[1]] = e[2] + } + inf := int(1e6) + var dfs func(u, k int) int + dfs = func(u, k int) int { + if memo[u][k] != -1 { + return memo[u][k] + } + if u == dst { + return 0 + } + if k <= 0 { + return inf + } + ans := inf + for v, p := range g[u] { + if p > 0 { + ans = min(ans, dfs(v, k-1)+p) + } + } + memo[u][k] = ans + return ans + } + ans := dfs(src, k+1) + if ans >= inf { + return -1 + } + return ans +} \ No newline at end of file diff --git a/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution2.java b/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution2.java new file mode 100644 index 0000000000000..d399cfb0d7993 --- /dev/null +++ b/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution2.java @@ -0,0 +1,41 @@ +class Solution { + private int[][] memo; + private int[][] g; + private int dst; + private static final int INF = (int) 1e6; + + public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { + n += 10; + memo = new int[n][n]; + for (int i = 0; i < n; ++i) { + Arrays.fill(memo[i], -1); + } + g = new int[n][n]; + for (int[] e : flights) { + g[e[0]][e[1]] = e[2]; + } + this.dst = dst; + int ans = dfs(src, k + 1); + return ans >= INF ? -1 : ans; + } + + private int dfs(int u, int k) { + if (memo[u][k] != -1) { + return memo[u][k]; + } + if (u == dst) { + return 0; + } + if (k <= 0) { + return INF; + } + int ans = INF; + for (int v = 0; v < g[u].length; ++v) { + if (g[u][v] > 0) { + ans = Math.min(ans, dfs(v, k - 1) + g[u][v]); + } + } + memo[u][k] = ans; + return ans; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution2.py b/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution2.py new file mode 100644 index 0000000000000..fe577a753ccac --- /dev/null +++ b/solution/0700-0799/0787.Cheapest Flights Within K Stops/Solution2.py @@ -0,0 +1,21 @@ +class Solution: + def findCheapestPrice( + self, n: int, flights: List[List[int]], src: int, dst: int, k: int + ) -> int: + @cache + def dfs(u, k): + if u == dst: + return 0 + if k <= 0: + return inf + k -= 1 + ans = inf + for v, p in g[u]: + ans = min(ans, dfs(v, k) + p) + return ans + + g = defaultdict(list) + for u, v, p in flights: + g[u].append((v, p)) + ans = dfs(src, k + 1) + return -1 if ans >= inf else ans diff --git a/solution/0700-0799/0788.Rotated Digits/Solution.cpp b/solution/0700-0799/0788.Rotated Digits/Solution.cpp index c066f45eccf3f..8505024081f2f 100644 --- a/solution/0700-0799/0788.Rotated Digits/Solution.cpp +++ b/solution/0700-0799/0788.Rotated Digits/Solution.cpp @@ -1,38 +1,27 @@ class Solution { public: - int a[6]; - int dp[6][2]; + const vector d = {0, 1, 5, -1, -1, 2, 9, -1, 8, 6}; int rotatedDigits(int n) { - memset(dp, -1, sizeof dp); - int len = 0; - while (n) { - a[++len] = n % 10; - n /= 10; + int ans = 0; + for (int i = 1; i <= n; ++i) { + ans += check(i); } - return dfs(len, 0, true); + return ans; } - int dfs(int pos, int ok, bool limit) { - if (pos <= 0) { - return ok; - } - if (!limit && dp[pos][ok] != -1) { - return dp[pos][ok]; - } - int up = limit ? a[pos] : 9; - int ans = 0; - for (int i = 0; i <= up; ++i) { - if (i == 0 || i == 1 || i == 8) { - ans += dfs(pos - 1, ok, limit && i == up); - } - if (i == 2 || i == 5 || i == 6 || i == 9) { - ans += dfs(pos - 1, 1, limit && i == up); + bool check(int x) { + int y = 0, t = x; + int k = 1; + while (t) { + int v = t % 10; + if (d[v] == -1) { + return false; } + y = d[v] * k + y; + k *= 10; + t /= 10; } - if (!limit) { - dp[pos][ok] = ans; - } - return ans; + return x != y; } }; \ No newline at end of file diff --git a/solution/0700-0799/0788.Rotated Digits/Solution.go b/solution/0700-0799/0788.Rotated Digits/Solution.go index 065c3e74e40c4..978eb7c529521 100644 --- a/solution/0700-0799/0788.Rotated Digits/Solution.go +++ b/solution/0700-0799/0788.Rotated Digits/Solution.go @@ -1,42 +1,23 @@ func rotatedDigits(n int) int { - a := make([]int, 6) - dp := make([][2]int, 6) - for i := range a { - dp[i] = [2]int{-1, -1} - } - l := 0 - for n > 0 { - l++ - a[l] = n % 10 - n /= 10 - } - - var dfs func(int, int, bool) int - dfs = func(pos, ok int, limit bool) int { - if pos <= 0 { - return ok - } - if !limit && dp[pos][ok] != -1 { - return dp[pos][ok] - } - up := 9 - if limit { - up = a[pos] - } - ans := 0 - for i := 0; i <= up; i++ { - if i == 0 || i == 1 || i == 8 { - ans += dfs(pos-1, ok, limit && i == up) - } - if i == 2 || i == 5 || i == 6 || i == 9 { - ans += dfs(pos-1, 1, limit && i == up) + d := []int{0, 1, 5, -1, -1, 2, 9, -1, 8, 6} + check := func(x int) bool { + y, t := 0, x + k := 1 + for ; t > 0; t /= 10 { + v := t % 10 + if d[v] == -1 { + return false } + y = d[v]*k + y + k *= 10 } - if !limit { - dp[pos][ok] = ans + return x != y + } + ans := 0 + for i := 1; i <= n; i++ { + if check(i) { + ans++ } - return ans } - - return dfs(l, 0, true) + return ans } \ No newline at end of file diff --git a/solution/0700-0799/0788.Rotated Digits/Solution.java b/solution/0700-0799/0788.Rotated Digits/Solution.java index 3c7068f5cc1f1..82ec4cc40ef2c 100644 --- a/solution/0700-0799/0788.Rotated Digits/Solution.java +++ b/solution/0700-0799/0788.Rotated Digits/Solution.java @@ -1,39 +1,28 @@ class Solution { - private int[] a = new int[6]; - private int[][] dp = new int[6][2]; + private int[] d = new int[] {0, 1, 5, -1, -1, 2, 9, -1, 8, 6}; public int rotatedDigits(int n) { - int len = 0; - for (var e : dp) { - Arrays.fill(e, -1); - } - while (n > 0) { - a[++len] = n % 10; - n /= 10; + int ans = 0; + for (int i = 1; i <= n; ++i) { + if (check(i)) { + ++ans; + } } - return dfs(len, 0, true); + return ans; } - private int dfs(int pos, int ok, boolean limit) { - if (pos <= 0) { - return ok; - } - if (!limit && dp[pos][ok] != -1) { - return dp[pos][ok]; - } - int up = limit ? a[pos] : 9; - int ans = 0; - for (int i = 0; i <= up; ++i) { - if (i == 0 || i == 1 || i == 8) { - ans += dfs(pos - 1, ok, limit && i == up); - } - if (i == 2 || i == 5 || i == 6 || i == 9) { - ans += dfs(pos - 1, 1, limit && i == up); + private boolean check(int x) { + int y = 0, t = x; + int k = 1; + while (t > 0) { + int v = t % 10; + if (d[v] == -1) { + return false; } + y = d[v] * k + y; + k *= 10; + t /= 10; } - if (!limit) { - dp[pos][ok] = ans; - } - return ans; + return x != y; } } \ No newline at end of file diff --git a/solution/0700-0799/0788.Rotated Digits/Solution.py b/solution/0700-0799/0788.Rotated Digits/Solution.py index 14e41e6f35aa0..1885c67a88e4f 100644 --- a/solution/0700-0799/0788.Rotated Digits/Solution.py +++ b/solution/0700-0799/0788.Rotated Digits/Solution.py @@ -1,22 +1,16 @@ class Solution: def rotatedDigits(self, n: int) -> int: - @cache - def dfs(pos, ok, limit): - if pos <= 0: - return ok - up = a[pos] if limit else 9 - ans = 0 - for i in range(up + 1): - if i in (0, 1, 8): - ans += dfs(pos - 1, ok, limit and i == up) - if i in (2, 5, 6, 9): - ans += dfs(pos - 1, 1, limit and i == up) - return ans + def check(x): + y, t = 0, x + k = 1 + while t: + v = t % 10 + if d[v] == -1: + return False + y = d[v] * k + y + k *= 10 + t //= 10 + return x != y - a = [0] * 6 - l = 1 - while n: - a[l] = n % 10 - n //= 10 - l += 1 - return dfs(l, 0, True) + d = [0, 1, 5, -1, -1, 2, 9, -1, 8, 6] + return sum(check(i) for i in range(1, n + 1)) diff --git a/solution/0700-0799/0788.Rotated Digits/Solution2.cpp b/solution/0700-0799/0788.Rotated Digits/Solution2.cpp new file mode 100644 index 0000000000000..c066f45eccf3f --- /dev/null +++ b/solution/0700-0799/0788.Rotated Digits/Solution2.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + int a[6]; + int dp[6][2]; + + int rotatedDigits(int n) { + memset(dp, -1, sizeof dp); + int len = 0; + while (n) { + a[++len] = n % 10; + n /= 10; + } + return dfs(len, 0, true); + } + + int dfs(int pos, int ok, bool limit) { + if (pos <= 0) { + return ok; + } + if (!limit && dp[pos][ok] != -1) { + return dp[pos][ok]; + } + int up = limit ? a[pos] : 9; + int ans = 0; + for (int i = 0; i <= up; ++i) { + if (i == 0 || i == 1 || i == 8) { + ans += dfs(pos - 1, ok, limit && i == up); + } + if (i == 2 || i == 5 || i == 6 || i == 9) { + ans += dfs(pos - 1, 1, limit && i == up); + } + } + if (!limit) { + dp[pos][ok] = ans; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0788.Rotated Digits/Solution2.go b/solution/0700-0799/0788.Rotated Digits/Solution2.go new file mode 100644 index 0000000000000..065c3e74e40c4 --- /dev/null +++ b/solution/0700-0799/0788.Rotated Digits/Solution2.go @@ -0,0 +1,42 @@ +func rotatedDigits(n int) int { + a := make([]int, 6) + dp := make([][2]int, 6) + for i := range a { + dp[i] = [2]int{-1, -1} + } + l := 0 + for n > 0 { + l++ + a[l] = n % 10 + n /= 10 + } + + var dfs func(int, int, bool) int + dfs = func(pos, ok int, limit bool) int { + if pos <= 0 { + return ok + } + if !limit && dp[pos][ok] != -1 { + return dp[pos][ok] + } + up := 9 + if limit { + up = a[pos] + } + ans := 0 + for i := 0; i <= up; i++ { + if i == 0 || i == 1 || i == 8 { + ans += dfs(pos-1, ok, limit && i == up) + } + if i == 2 || i == 5 || i == 6 || i == 9 { + ans += dfs(pos-1, 1, limit && i == up) + } + } + if !limit { + dp[pos][ok] = ans + } + return ans + } + + return dfs(l, 0, true) +} \ No newline at end of file diff --git a/solution/0700-0799/0788.Rotated Digits/Solution2.java b/solution/0700-0799/0788.Rotated Digits/Solution2.java new file mode 100644 index 0000000000000..3c7068f5cc1f1 --- /dev/null +++ b/solution/0700-0799/0788.Rotated Digits/Solution2.java @@ -0,0 +1,39 @@ +class Solution { + private int[] a = new int[6]; + private int[][] dp = new int[6][2]; + + public int rotatedDigits(int n) { + int len = 0; + for (var e : dp) { + Arrays.fill(e, -1); + } + while (n > 0) { + a[++len] = n % 10; + n /= 10; + } + return dfs(len, 0, true); + } + + private int dfs(int pos, int ok, boolean limit) { + if (pos <= 0) { + return ok; + } + if (!limit && dp[pos][ok] != -1) { + return dp[pos][ok]; + } + int up = limit ? a[pos] : 9; + int ans = 0; + for (int i = 0; i <= up; ++i) { + if (i == 0 || i == 1 || i == 8) { + ans += dfs(pos - 1, ok, limit && i == up); + } + if (i == 2 || i == 5 || i == 6 || i == 9) { + ans += dfs(pos - 1, 1, limit && i == up); + } + } + if (!limit) { + dp[pos][ok] = ans; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0788.Rotated Digits/Solution2.py b/solution/0700-0799/0788.Rotated Digits/Solution2.py new file mode 100644 index 0000000000000..14e41e6f35aa0 --- /dev/null +++ b/solution/0700-0799/0788.Rotated Digits/Solution2.py @@ -0,0 +1,22 @@ +class Solution: + def rotatedDigits(self, n: int) -> int: + @cache + def dfs(pos, ok, limit): + if pos <= 0: + return ok + up = a[pos] if limit else 9 + ans = 0 + for i in range(up + 1): + if i in (0, 1, 8): + ans += dfs(pos - 1, ok, limit and i == up) + if i in (2, 5, 6, 9): + ans += dfs(pos - 1, 1, limit and i == up) + return ans + + a = [0] * 6 + l = 1 + while n: + a[l] = n % 10 + n //= 10 + l += 1 + return dfs(l, 0, True) diff --git a/solution/0700-0799/0790.Domino and Tromino Tiling/Solution2.py b/solution/0700-0799/0790.Domino and Tromino Tiling/Solution2.py new file mode 100644 index 0000000000000..39bb58c8e9dcc --- /dev/null +++ b/solution/0700-0799/0790.Domino and Tromino Tiling/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def numTilings(self, n: int) -> int: + f = [1, 0, 0, 0] + mod = 10**9 + 7 + for i in range(1, n + 1): + g = [0] * 4 + g[0] = (f[0] + f[1] + f[2] + f[3]) % mod + g[1] = (f[2] + f[3]) % mod + g[2] = (f[1] + f[3]) % mod + g[3] = f[0] + f = g + return f[0] diff --git a/solution/0700-0799/0791.Custom Sort String/Solution.cpp b/solution/0700-0799/0791.Custom Sort String/Solution.cpp index feda9b3263e21..befbfa055a1cd 100644 --- a/solution/0700-0799/0791.Custom Sort String/Solution.cpp +++ b/solution/0700-0799/0791.Custom Sort String/Solution.cpp @@ -1,13 +1,9 @@ class Solution { public: string customSortString(string order, string s) { - int cnt[26] = {0}; - for (char& c : s) ++cnt[c - 'a']; - string ans; - for (char& c : order) - while (cnt[c - 'a']-- > 0) ans += c; - for (int i = 0; i < 26; ++i) - if (cnt[i] > 0) ans += string(cnt[i], i + 'a'); - return ans; + int d[26] = {0}; + for (int i = 0; i < order.size(); ++i) d[order[i] - 'a'] = i; + sort(s.begin(), s.end(), [&](auto a, auto b) { return d[a - 'a'] < d[b - 'a']; }); + return s; } }; \ No newline at end of file diff --git a/solution/0700-0799/0791.Custom Sort String/Solution.go b/solution/0700-0799/0791.Custom Sort String/Solution.go index c4455f701540a..d7897167f9c2b 100644 --- a/solution/0700-0799/0791.Custom Sort String/Solution.go +++ b/solution/0700-0799/0791.Custom Sort String/Solution.go @@ -1,19 +1,9 @@ func customSortString(order string, s string) string { - cnt := [26]int{} - for _, c := range s { - cnt[c-'a']++ + d := [26]int{} + for i := range order { + d[order[i]-'a'] = i } - ans := []rune{} - for _, c := range order { - for cnt[c-'a'] > 0 { - ans = append(ans, c) - cnt[c-'a']-- - } - } - for i, v := range cnt { - for j := 0; j < v; j++ { - ans = append(ans, rune('a'+i)) - } - } - return string(ans) + cs := []byte(s) + sort.Slice(cs, func(i, j int) bool { return d[cs[i]-'a'] < d[cs[j]-'a'] }) + return string(cs) } \ No newline at end of file diff --git a/solution/0700-0799/0791.Custom Sort String/Solution.java b/solution/0700-0799/0791.Custom Sort String/Solution.java index f8c0b8c30160e..049f73cc86cf4 100644 --- a/solution/0700-0799/0791.Custom Sort String/Solution.java +++ b/solution/0700-0799/0791.Custom Sort String/Solution.java @@ -1,21 +1,14 @@ class Solution { public String customSortString(String order, String s) { - int[] cnt = new int[26]; - for (int i = 0; i < s.length(); ++i) { - ++cnt[s.charAt(i) - 'a']; - } - StringBuilder ans = new StringBuilder(); + int[] d = new int[26]; for (int i = 0; i < order.length(); ++i) { - char c = order.charAt(i); - while (cnt[c - 'a']-- > 0) { - ans.append(c); - } + d[order.charAt(i) - 'a'] = i; } - for (int i = 0; i < 26; ++i) { - while (cnt[i]-- > 0) { - ans.append((char) ('a' + i)); - } + List cs = new ArrayList<>(); + for (int i = 0; i < s.length(); ++i) { + cs.add(s.charAt(i)); } - return ans.toString(); + cs.sort((a, b) -> d[a - 'a'] - d[b - 'a']); + return cs.stream().map(String::valueOf).collect(Collectors.joining()); } } \ No newline at end of file diff --git a/solution/0700-0799/0791.Custom Sort String/Solution.py b/solution/0700-0799/0791.Custom Sort String/Solution.py index 5afd25898ee6c..da83bb32cdcc9 100644 --- a/solution/0700-0799/0791.Custom Sort String/Solution.py +++ b/solution/0700-0799/0791.Custom Sort String/Solution.py @@ -1,10 +1,4 @@ class Solution: def customSortString(self, order: str, s: str) -> str: - cnt = Counter(s) - ans = [] - for c in order: - ans.append(c * cnt[c]) - cnt[c] = 0 - for c, v in cnt.items(): - ans.append(c * v) - return ''.join(ans) + d = {c: i for i, c in enumerate(order)} + return ''.join(sorted(s, key=lambda x: d.get(x, 0))) diff --git a/solution/0700-0799/0791.Custom Sort String/Solution.rs b/solution/0700-0799/0791.Custom Sort String/Solution.rs index 6ec7d3f7e68ea..488f21a12dafa 100644 --- a/solution/0700-0799/0791.Custom Sort String/Solution.rs +++ b/solution/0700-0799/0791.Custom Sort String/Solution.rs @@ -1,21 +1,14 @@ impl Solution { pub fn custom_sort_string(order: String, s: String) -> String { - let mut count = [0; 26]; - for c in s.as_bytes() { - count[(c - b'a') as usize] += 1; + let n = order.len(); + let mut d = [n; 26]; + for (i, c) in order.as_bytes().iter().enumerate() { + d[(c - b'a') as usize] = i; } - let mut ans = String::new(); - for c in order.as_bytes() { - for _ in 0..count[(c - b'a') as usize] { - ans.push(char::from(*c)); - } - count[(c - b'a') as usize] = 0; - } - for i in 0..count.len() { - for _ in 0..count[i] { - ans.push(char::from(b'a' + (i as u8))); - } - } - ans + let mut ans = s.chars().collect::>(); + ans.sort_by(|&a, &b| + d[((a as u8) - ('a' as u8)) as usize].cmp(&d[((b as u8) - ('a' as u8)) as usize]) + ); + ans.into_iter().collect() } } diff --git a/solution/0700-0799/0791.Custom Sort String/Solution.ts b/solution/0700-0799/0791.Custom Sort String/Solution.ts index c7a2bd68b06cd..ad01792fbfb38 100644 --- a/solution/0700-0799/0791.Custom Sort String/Solution.ts +++ b/solution/0700-0799/0791.Custom Sort String/Solution.ts @@ -1,18 +1,9 @@ function customSortString(order: string, s: string): string { const toIndex = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); - const count = new Array(26).fill(0); - for (const c of s) { - count[toIndex(c)]++; + const n = order.length; + const d = new Array(26).fill(n); + for (let i = 0; i < n; i++) { + d[toIndex(order[i])] = i; } - const ans: string[] = []; - for (const c of order) { - const i = toIndex(c); - ans.push(c.repeat(count[i])); - count[i] = 0; - } - for (let i = 0; i < 26; i++) { - if (!count[i]) continue; - ans.push(String.fromCharCode('a'.charCodeAt(0) + i).repeat(count[i])); - } - return ans.join(''); + return [...s].sort((a, b) => d[toIndex(a)] - d[toIndex(b)]).join(''); } diff --git a/solution/0700-0799/0791.Custom Sort String/Solution2.cpp b/solution/0700-0799/0791.Custom Sort String/Solution2.cpp new file mode 100644 index 0000000000000..feda9b3263e21 --- /dev/null +++ b/solution/0700-0799/0791.Custom Sort String/Solution2.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + string customSortString(string order, string s) { + int cnt[26] = {0}; + for (char& c : s) ++cnt[c - 'a']; + string ans; + for (char& c : order) + while (cnt[c - 'a']-- > 0) ans += c; + for (int i = 0; i < 26; ++i) + if (cnt[i] > 0) ans += string(cnt[i], i + 'a'); + return ans; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0791.Custom Sort String/Solution2.go b/solution/0700-0799/0791.Custom Sort String/Solution2.go new file mode 100644 index 0000000000000..c4455f701540a --- /dev/null +++ b/solution/0700-0799/0791.Custom Sort String/Solution2.go @@ -0,0 +1,19 @@ +func customSortString(order string, s string) string { + cnt := [26]int{} + for _, c := range s { + cnt[c-'a']++ + } + ans := []rune{} + for _, c := range order { + for cnt[c-'a'] > 0 { + ans = append(ans, c) + cnt[c-'a']-- + } + } + for i, v := range cnt { + for j := 0; j < v; j++ { + ans = append(ans, rune('a'+i)) + } + } + return string(ans) +} \ No newline at end of file diff --git a/solution/0700-0799/0791.Custom Sort String/Solution2.java b/solution/0700-0799/0791.Custom Sort String/Solution2.java new file mode 100644 index 0000000000000..f8c0b8c30160e --- /dev/null +++ b/solution/0700-0799/0791.Custom Sort String/Solution2.java @@ -0,0 +1,21 @@ +class Solution { + public String customSortString(String order, String s) { + int[] cnt = new int[26]; + for (int i = 0; i < s.length(); ++i) { + ++cnt[s.charAt(i) - 'a']; + } + StringBuilder ans = new StringBuilder(); + for (int i = 0; i < order.length(); ++i) { + char c = order.charAt(i); + while (cnt[c - 'a']-- > 0) { + ans.append(c); + } + } + for (int i = 0; i < 26; ++i) { + while (cnt[i]-- > 0) { + ans.append((char) ('a' + i)); + } + } + return ans.toString(); + } +} \ No newline at end of file diff --git a/solution/0700-0799/0791.Custom Sort String/Solution2.py b/solution/0700-0799/0791.Custom Sort String/Solution2.py new file mode 100644 index 0000000000000..5afd25898ee6c --- /dev/null +++ b/solution/0700-0799/0791.Custom Sort String/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def customSortString(self, order: str, s: str) -> str: + cnt = Counter(s) + ans = [] + for c in order: + ans.append(c * cnt[c]) + cnt[c] = 0 + for c, v in cnt.items(): + ans.append(c * v) + return ''.join(ans) diff --git a/solution/0700-0799/0791.Custom Sort String/Solution2.rs b/solution/0700-0799/0791.Custom Sort String/Solution2.rs new file mode 100644 index 0000000000000..6ec7d3f7e68ea --- /dev/null +++ b/solution/0700-0799/0791.Custom Sort String/Solution2.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn custom_sort_string(order: String, s: String) -> String { + let mut count = [0; 26]; + for c in s.as_bytes() { + count[(c - b'a') as usize] += 1; + } + let mut ans = String::new(); + for c in order.as_bytes() { + for _ in 0..count[(c - b'a') as usize] { + ans.push(char::from(*c)); + } + count[(c - b'a') as usize] = 0; + } + for i in 0..count.len() { + for _ in 0..count[i] { + ans.push(char::from(b'a' + (i as u8))); + } + } + ans + } +} diff --git a/solution/0700-0799/0791.Custom Sort String/Solution2.ts b/solution/0700-0799/0791.Custom Sort String/Solution2.ts new file mode 100644 index 0000000000000..c7a2bd68b06cd --- /dev/null +++ b/solution/0700-0799/0791.Custom Sort String/Solution2.ts @@ -0,0 +1,18 @@ +function customSortString(order: string, s: string): string { + const toIndex = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); + const count = new Array(26).fill(0); + for (const c of s) { + count[toIndex(c)]++; + } + const ans: string[] = []; + for (const c of order) { + const i = toIndex(c); + ans.push(c.repeat(count[i])); + count[i] = 0; + } + for (let i = 0; i < 26; i++) { + if (!count[i]) continue; + ans.push(String.fromCharCode('a'.charCodeAt(0) + i).repeat(count[i])); + } + return ans.join(''); +} diff --git a/solution/0700-0799/0792.Number of Matching Subsequences/Solution.cpp b/solution/0700-0799/0792.Number of Matching Subsequences/Solution.cpp index 5b7c935ee5491..a5817dcf38c2b 100644 --- a/solution/0700-0799/0792.Number of Matching Subsequences/Solution.cpp +++ b/solution/0700-0799/0792.Number of Matching Subsequences/Solution.cpp @@ -1,18 +1,18 @@ class Solution { public: int numMatchingSubseq(string s, vector& words) { - vector>> d(26); - for (int i = 0; i < words.size(); ++i) d[words[i][0] - 'a'].emplace(i, 0); + vector> d(26); + for (auto& w : words) d[w[0] - 'a'].emplace(w); int ans = 0; for (char& c : s) { auto& q = d[c - 'a']; - for (int t = q.size(); t; --t) { - auto [i, j] = q.front(); + for (int k = q.size(); k; --k) { + auto t = q.front(); q.pop(); - if (++j == words[i].size()) + if (t.size() == 1) ++ans; else - d[words[i][j] - 'a'].emplace(i, j); + d[t[1] - 'a'].emplace(t.substr(1)); } } return ans; diff --git a/solution/0700-0799/0792.Number of Matching Subsequences/Solution.go b/solution/0700-0799/0792.Number of Matching Subsequences/Solution.go index dc3389125844a..561f13f274fcc 100644 --- a/solution/0700-0799/0792.Number of Matching Subsequences/Solution.go +++ b/solution/0700-0799/0792.Number of Matching Subsequences/Solution.go @@ -1,18 +1,16 @@ func numMatchingSubseq(s string, words []string) (ans int) { - type pair struct{ i, j int } - d := [26][]pair{} - for i, w := range words { - d[w[0]-'a'] = append(d[w[0]-'a'], pair{i, 0}) + d := [26][]string{} + for _, w := range words { + d[w[0]-'a'] = append(d[w[0]-'a'], w) } for _, c := range s { q := d[c-'a'] d[c-'a'] = nil - for _, p := range q { - i, j := p.i, p.j+1 - if j == len(words[i]) { + for _, t := range q { + if len(t) == 1 { ans++ } else { - d[words[i][j]-'a'] = append(d[words[i][j]-'a'], pair{i, j}) + d[t[1]-'a'] = append(d[t[1]-'a'], t[1:]) } } } diff --git a/solution/0700-0799/0792.Number of Matching Subsequences/Solution.java b/solution/0700-0799/0792.Number of Matching Subsequences/Solution.java index 14f82380fafd7..db74bb51c6fbe 100644 --- a/solution/0700-0799/0792.Number of Matching Subsequences/Solution.java +++ b/solution/0700-0799/0792.Number of Matching Subsequences/Solution.java @@ -1,20 +1,19 @@ class Solution { public int numMatchingSubseq(String s, String[] words) { - Deque[] d = new Deque[26]; + Deque[] d = new Deque[26]; Arrays.setAll(d, k -> new ArrayDeque<>()); - for (int i = 0; i < words.length; ++i) { - d[words[i].charAt(0) - 'a'].offer(new int[] {i, 0}); + for (String w : words) { + d[w.charAt(0) - 'a'].add(w); } int ans = 0; for (char c : s.toCharArray()) { var q = d[c - 'a']; - for (int t = q.size(); t > 0; --t) { - var p = q.pollFirst(); - int i = p[0], j = p[1] + 1; - if (j == words[i].length()) { + for (int k = q.size(); k > 0; --k) { + String t = q.pollFirst(); + if (t.length() == 1) { ++ans; } else { - d[words[i].charAt(j) - 'a'].offer(new int[] {i, j}); + d[t.charAt(1) - 'a'].offer(t.substring(1)); } } } diff --git a/solution/0700-0799/0792.Number of Matching Subsequences/Solution.py b/solution/0700-0799/0792.Number of Matching Subsequences/Solution.py index 43740ea1701a7..105ea0fbe8692 100644 --- a/solution/0700-0799/0792.Number of Matching Subsequences/Solution.py +++ b/solution/0700-0799/0792.Number of Matching Subsequences/Solution.py @@ -1,15 +1,14 @@ class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: d = defaultdict(deque) - for i, w in enumerate(words): - d[w[0]].append((i, 0)) + for w in words: + d[w[0]].append(w) ans = 0 for c in s: for _ in range(len(d[c])): - i, j = d[c].popleft() - j += 1 - if j == len(words[i]): + t = d[c].popleft() + if len(t) == 1: ans += 1 else: - d[words[i][j]].append((i, j)) + d[t[1]].append(t[1:]) return ans diff --git a/solution/0700-0799/0792.Number of Matching Subsequences/Solution2.cpp b/solution/0700-0799/0792.Number of Matching Subsequences/Solution2.cpp new file mode 100644 index 0000000000000..5b7c935ee5491 --- /dev/null +++ b/solution/0700-0799/0792.Number of Matching Subsequences/Solution2.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int numMatchingSubseq(string s, vector& words) { + vector>> d(26); + for (int i = 0; i < words.size(); ++i) d[words[i][0] - 'a'].emplace(i, 0); + int ans = 0; + for (char& c : s) { + auto& q = d[c - 'a']; + for (int t = q.size(); t; --t) { + auto [i, j] = q.front(); + q.pop(); + if (++j == words[i].size()) + ++ans; + else + d[words[i][j] - 'a'].emplace(i, j); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0792.Number of Matching Subsequences/Solution2.go b/solution/0700-0799/0792.Number of Matching Subsequences/Solution2.go new file mode 100644 index 0000000000000..dc3389125844a --- /dev/null +++ b/solution/0700-0799/0792.Number of Matching Subsequences/Solution2.go @@ -0,0 +1,20 @@ +func numMatchingSubseq(s string, words []string) (ans int) { + type pair struct{ i, j int } + d := [26][]pair{} + for i, w := range words { + d[w[0]-'a'] = append(d[w[0]-'a'], pair{i, 0}) + } + for _, c := range s { + q := d[c-'a'] + d[c-'a'] = nil + for _, p := range q { + i, j := p.i, p.j+1 + if j == len(words[i]) { + ans++ + } else { + d[words[i][j]-'a'] = append(d[words[i][j]-'a'], pair{i, j}) + } + } + } + return +} \ No newline at end of file diff --git a/solution/0700-0799/0792.Number of Matching Subsequences/Solution2.java b/solution/0700-0799/0792.Number of Matching Subsequences/Solution2.java new file mode 100644 index 0000000000000..14f82380fafd7 --- /dev/null +++ b/solution/0700-0799/0792.Number of Matching Subsequences/Solution2.java @@ -0,0 +1,23 @@ +class Solution { + public int numMatchingSubseq(String s, String[] words) { + Deque[] d = new Deque[26]; + Arrays.setAll(d, k -> new ArrayDeque<>()); + for (int i = 0; i < words.length; ++i) { + d[words[i].charAt(0) - 'a'].offer(new int[] {i, 0}); + } + int ans = 0; + for (char c : s.toCharArray()) { + var q = d[c - 'a']; + for (int t = q.size(); t > 0; --t) { + var p = q.pollFirst(); + int i = p[0], j = p[1] + 1; + if (j == words[i].length()) { + ++ans; + } else { + d[words[i].charAt(j) - 'a'].offer(new int[] {i, j}); + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0792.Number of Matching Subsequences/Solution2.py b/solution/0700-0799/0792.Number of Matching Subsequences/Solution2.py new file mode 100644 index 0000000000000..43740ea1701a7 --- /dev/null +++ b/solution/0700-0799/0792.Number of Matching Subsequences/Solution2.py @@ -0,0 +1,15 @@ +class Solution: + def numMatchingSubseq(self, s: str, words: List[str]) -> int: + d = defaultdict(deque) + for i, w in enumerate(words): + d[w[0]].append((i, 0)) + ans = 0 + for c in s: + for _ in range(len(d[c])): + i, j = d[c].popleft() + j += 1 + if j == len(words[i]): + ans += 1 + else: + d[words[i][j]].append((i, j)) + return ans diff --git a/solution/0700-0799/0792.Number of Matching Subsequences/Solution3.cpp b/solution/0700-0799/0792.Number of Matching Subsequences/Solution3.cpp new file mode 100644 index 0000000000000..5b1a3a9b9b7e2 --- /dev/null +++ b/solution/0700-0799/0792.Number of Matching Subsequences/Solution3.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int numMatchingSubseq(string s, vector& words) { + vector> d(26); + for (int i = 0; i < s.size(); ++i) d[s[i] - 'a'].emplace_back(i); + int ans = 0; + auto check = [&](string& w) { + int i = -1; + for (char& c : w) { + auto& t = d[c - 'a']; + int j = upper_bound(t.begin(), t.end(), i) - t.begin(); + if (j == t.size()) return false; + i = t[j]; + } + return true; + }; + for (auto& w : words) ans += check(w); + return ans; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0792.Number of Matching Subsequences/Solution3.go b/solution/0700-0799/0792.Number of Matching Subsequences/Solution3.go new file mode 100644 index 0000000000000..ea1f7d9313930 --- /dev/null +++ b/solution/0700-0799/0792.Number of Matching Subsequences/Solution3.go @@ -0,0 +1,24 @@ +func numMatchingSubseq(s string, words []string) (ans int) { + d := [26][]int{} + for i, c := range s { + d[c-'a'] = append(d[c-'a'], i) + } + check := func(w string) bool { + i := -1 + for _, c := range w { + t := d[c-'a'] + j := sort.SearchInts(t, i+1) + if j == len(t) { + return false + } + i = t[j] + } + return true + } + for _, w := range words { + if check(w) { + ans++ + } + } + return +} \ No newline at end of file diff --git a/solution/0700-0799/0792.Number of Matching Subsequences/Solution3.java b/solution/0700-0799/0792.Number of Matching Subsequences/Solution3.java new file mode 100644 index 0000000000000..3b223a9cb781d --- /dev/null +++ b/solution/0700-0799/0792.Number of Matching Subsequences/Solution3.java @@ -0,0 +1,43 @@ +class Solution { + private List[] d = new List[26]; + + public int numMatchingSubseq(String s, String[] words) { + Arrays.setAll(d, k -> new ArrayList<>()); + for (int i = 0; i < s.length(); ++i) { + d[s.charAt(i) - 'a'].add(i); + } + int ans = 0; + for (String w : words) { + if (check(w)) { + ++ans; + } + } + return ans; + } + + private boolean check(String w) { + int i = -1; + for (int k = 0; k < w.length(); ++k) { + int c = w.charAt(k) - 'a'; + int j = search(d[c], i); + if (j == d[c].size()) { + return false; + } + i = d[c].get(j); + } + return true; + } + + private int search(List t, int x) { + int left = 0, right = t.size(); + while (left < right) { + int mid = (left + right) >> 1; + if (t.get(mid) > x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0792.Number of Matching Subsequences/Solution3.py b/solution/0700-0799/0792.Number of Matching Subsequences/Solution3.py new file mode 100644 index 0000000000000..96c77cc424210 --- /dev/null +++ b/solution/0700-0799/0792.Number of Matching Subsequences/Solution3.py @@ -0,0 +1,15 @@ +class Solution: + def numMatchingSubseq(self, s: str, words: List[str]) -> int: + def check(w): + i = -1 + for c in w: + j = bisect_right(d[c], i) + if j == len(d[c]): + return False + i = d[c][j] + return True + + d = defaultdict(list) + for i, c in enumerate(s): + d[c].append(i) + return sum(check(w) for w in words) diff --git a/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/Solution2.cpp b/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/Solution2.cpp new file mode 100644 index 0000000000000..f18e1a6b08b76 --- /dev/null +++ b/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/Solution2.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int numSubarrayBoundedMax(vector& nums, int left, int right) { + int n = nums.size(); + vector l(n, -1); + vector r(n, n); + stack stk; + for (int i = 0; i < n; ++i) { + int v = nums[i]; + while (!stk.empty() && nums[stk.top()] <= v) stk.pop(); + if (!stk.empty()) l[i] = stk.top(); + stk.push(i); + } + stk = stack(); + for (int i = n - 1; ~i; --i) { + int v = nums[i]; + while (!stk.empty() && nums[stk.top()] < v) stk.pop(); + if (!stk.empty()) r[i] = stk.top(); + stk.push(i); + } + int ans = 0; + for (int i = 0; i < n; ++i) { + if (left <= nums[i] && nums[i] <= right) { + ans += (i - l[i]) * (r[i] - i); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/Solution2.go b/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/Solution2.go new file mode 100644 index 0000000000000..4609df5238a0e --- /dev/null +++ b/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/Solution2.go @@ -0,0 +1,35 @@ +func numSubarrayBoundedMax(nums []int, left int, right int) (ans int) { + n := len(nums) + l := make([]int, n) + r := make([]int, n) + for i := range l { + l[i], r[i] = -1, n + } + stk := []int{} + for i, v := range nums { + for len(stk) > 0 && nums[stk[len(stk)-1]] <= v { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + l[i] = stk[len(stk)-1] + } + stk = append(stk, i) + } + stk = []int{} + for i := n - 1; i >= 0; i-- { + v := nums[i] + for len(stk) > 0 && nums[stk[len(stk)-1]] < v { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + r[i] = stk[len(stk)-1] + } + stk = append(stk, i) + } + for i, v := range nums { + if left <= v && v <= right { + ans += (i - l[i]) * (r[i] - i) + } + } + return +} \ No newline at end of file diff --git a/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/Solution2.java b/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/Solution2.java new file mode 100644 index 0000000000000..d621f4836b8ca --- /dev/null +++ b/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/Solution2.java @@ -0,0 +1,38 @@ +class Solution { + public int numSubarrayBoundedMax(int[] nums, int left, int right) { + int n = nums.length; + int[] l = new int[n]; + int[] r = new int[n]; + Arrays.fill(l, -1); + Arrays.fill(r, n); + Deque stk = new ArrayDeque<>(); + for (int i = 0; i < n; ++i) { + int v = nums[i]; + while (!stk.isEmpty() && nums[stk.peek()] <= v) { + stk.pop(); + } + if (!stk.isEmpty()) { + l[i] = stk.peek(); + } + stk.push(i); + } + stk.clear(); + for (int i = n - 1; i >= 0; --i) { + int v = nums[i]; + while (!stk.isEmpty() && nums[stk.peek()] < v) { + stk.pop(); + } + if (!stk.isEmpty()) { + r[i] = stk.peek(); + } + stk.push(i); + } + int ans = 0; + for (int i = 0; i < n; ++i) { + if (left <= nums[i] && nums[i] <= right) { + ans += (i - l[i]) * (r[i] - i); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/Solution2.py b/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/Solution2.py new file mode 100644 index 0000000000000..90c506f0df4a1 --- /dev/null +++ b/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/Solution2.py @@ -0,0 +1,21 @@ +class Solution: + def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int: + n = len(nums) + l, r = [-1] * n, [n] * n + stk = [] + for i, v in enumerate(nums): + while stk and nums[stk[-1]] <= v: + stk.pop() + if stk: + l[i] = stk[-1] + stk.append(i) + stk = [] + for i in range(n - 1, -1, -1): + while stk and nums[stk[-1]] < nums[i]: + stk.pop() + if stk: + r[i] = stk[-1] + stk.append(i) + return sum( + (i - l[i]) * (r[i] - i) for i, v in enumerate(nums) if left <= v <= right + ) diff --git a/solution/0700-0799/0796.Rotate String/Solution.cpp b/solution/0700-0799/0796.Rotate String/Solution.cpp index 8a1f02eaa7b54..a7c7c99ccb8b5 100644 --- a/solution/0700-0799/0796.Rotate String/Solution.cpp +++ b/solution/0700-0799/0796.Rotate String/Solution.cpp @@ -1,6 +1,6 @@ -class Solution { -public: - bool rotateString(string s, string goal) { - return s.size() == goal.size() && strstr((s + s).data(), goal.data()); - } +class Solution { +public: + bool rotateString(string s, string goal) { + return s.size() == goal.size() && strstr((s + s).data(), goal.data()); + } }; \ No newline at end of file diff --git a/solution/0700-0799/0796.Rotate String/Solution.java b/solution/0700-0799/0796.Rotate String/Solution.java index a157fce1e8338..4dbbdf7e39a98 100644 --- a/solution/0700-0799/0796.Rotate String/Solution.java +++ b/solution/0700-0799/0796.Rotate String/Solution.java @@ -1,5 +1,5 @@ -class Solution { - public boolean rotateString(String s, String goal) { - return s.length() == goal.length() && (s + s).contains(goal); - } +class Solution { + public boolean rotateString(String s, String goal) { + return s.length() == goal.length() && (s + s).contains(goal); + } } \ No newline at end of file diff --git a/solution/0700-0799/0796.Rotate String/Solution.php b/solution/0700-0799/0796.Rotate String/Solution.php index 7a46068181c23..f1233304963b9 100644 --- a/solution/0700-0799/0796.Rotate String/Solution.php +++ b/solution/0700-0799/0796.Rotate String/Solution.php @@ -7,4 +7,4 @@ class Solution { function rotateString($s, $goal) { return strlen($goal) === strlen($s) && strpos($s . $s, $goal) !== false; } -} \ No newline at end of file +} diff --git a/solution/0700-0799/0796.Rotate String/Solution.py b/solution/0700-0799/0796.Rotate String/Solution.py index b47c432471e67..6775f23652854 100644 --- a/solution/0700-0799/0796.Rotate String/Solution.py +++ b/solution/0700-0799/0796.Rotate String/Solution.py @@ -1,3 +1,3 @@ -class Solution: - def rotateString(self, s: str, goal: str) -> bool: - return len(s) == len(goal) and goal in s + s +class Solution: + def rotateString(self, s: str, goal: str) -> bool: + return len(s) == len(goal) and goal in s + s diff --git a/solution/0700-0799/0797.All Paths From Source to Target/Solution.cpp b/solution/0700-0799/0797.All Paths From Source to Target/Solution.cpp index fcd84fdf595fd..f8c547dc931b9 100644 --- a/solution/0700-0799/0797.All Paths From Source to Target/Solution.cpp +++ b/solution/0700-0799/0797.All Paths From Source to Target/Solution.cpp @@ -1,4 +1,4 @@ -class Solution { +class Solution { public: vector> graph; vector> ans; diff --git a/solution/0700-0799/0797.All Paths From Source to Target/Solution.java b/solution/0700-0799/0797.All Paths From Source to Target/Solution.java index 52363078fe30f..6aca92b863a4d 100644 --- a/solution/0700-0799/0797.All Paths From Source to Target/Solution.java +++ b/solution/0700-0799/0797.All Paths From Source to Target/Solution.java @@ -19,4 +19,4 @@ public List> allPathsSourceTarget(int[][] graph) { } return ans; } -} +} \ No newline at end of file diff --git a/solution/0700-0799/0797.All Paths From Source to Target/Solution2.java b/solution/0700-0799/0797.All Paths From Source to Target/Solution2.java new file mode 100644 index 0000000000000..23a8e79016100 --- /dev/null +++ b/solution/0700-0799/0797.All Paths From Source to Target/Solution2.java @@ -0,0 +1,26 @@ +class Solution { + private List> ans; + private int[][] graph; + + public List> allPathsSourceTarget(int[][] graph) { + ans = new ArrayList<>(); + this.graph = graph; + List t = new ArrayList<>(); + t.add(0); + dfs(t); + return ans; + } + + private void dfs(List t) { + int cur = t.get(t.size() - 1); + if (cur == graph.length - 1) { + ans.add(new ArrayList<>(t)); + return; + } + for (int v : graph[cur]) { + t.add(v); + dfs(t); + t.remove(t.size() - 1); + } + } +} \ No newline at end of file diff --git a/solution/0700-0799/0797.All Paths From Source to Target/Solution2.py b/solution/0700-0799/0797.All Paths From Source to Target/Solution2.py new file mode 100644 index 0000000000000..529788750b874 --- /dev/null +++ b/solution/0700-0799/0797.All Paths From Source to Target/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: + def dfs(t): + if t[-1] == len(graph) - 1: + ans.append(t[:]) + return + for v in graph[t[-1]]: + t.append(v) + dfs(t) + t.pop() + + ans = [] + dfs([0]) + return ans diff --git a/solution/0700-0799/0799.Champagne Tower/Solution2.cpp b/solution/0700-0799/0799.Champagne Tower/Solution2.cpp new file mode 100644 index 0000000000000..8b00d1b2facfd --- /dev/null +++ b/solution/0700-0799/0799.Champagne Tower/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + double champagneTower(int poured, int query_row, int query_glass) { + double f[101] = {(double) poured}; + double g[101]; + for (int i = 1; i <= query_row; ++i) { + memset(g, 0, sizeof g); + for (int j = 0; j < i; ++j) { + if (f[j] > 1) { + double half = (f[j] - 1) / 2.0; + g[j] += half; + g[j + 1] += half; + } + } + memcpy(f, g, sizeof g); + } + return min(1.0, f[query_glass]); + } +}; \ No newline at end of file diff --git a/solution/0700-0799/0799.Champagne Tower/Solution2.go b/solution/0700-0799/0799.Champagne Tower/Solution2.go new file mode 100644 index 0000000000000..de5b4d9561893 --- /dev/null +++ b/solution/0700-0799/0799.Champagne Tower/Solution2.go @@ -0,0 +1,15 @@ +func champagneTower(poured int, query_row int, query_glass int) float64 { + f := []float64{float64(poured)} + for i := 1; i <= query_row; i++ { + g := make([]float64, i+1) + for j, v := range f { + if v > 1 { + half := (v - 1) / 2.0 + g[j] += half + g[j+1] += half + } + } + f = g + } + return math.Min(1, f[query_glass]) +} \ No newline at end of file diff --git a/solution/0700-0799/0799.Champagne Tower/Solution2.java b/solution/0700-0799/0799.Champagne Tower/Solution2.java new file mode 100644 index 0000000000000..c7e7a11937b3c --- /dev/null +++ b/solution/0700-0799/0799.Champagne Tower/Solution2.java @@ -0,0 +1,17 @@ +class Solution { + public double champagneTower(int poured, int query_row, int query_glass) { + double[] f = {poured}; + for (int i = 1; i <= query_row; ++i) { + double[] g = new double[i + 1]; + for (int j = 0; j < i; ++j) { + if (f[j] > 1) { + double half = (f[j] - 1) / 2.0; + g[j] += half; + g[j + 1] += half; + } + } + f = g; + } + return Math.min(1, f[query_glass]); + } +} \ No newline at end of file diff --git a/solution/0700-0799/0799.Champagne Tower/Solution2.py b/solution/0700-0799/0799.Champagne Tower/Solution2.py new file mode 100644 index 0000000000000..3bcd4a2f031fe --- /dev/null +++ b/solution/0700-0799/0799.Champagne Tower/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: + f = [poured] + for i in range(1, query_row + 1): + g = [0] * (i + 1) + for j, v in enumerate(f): + if v > 1: + half = (v - 1) / 2 + g[j] += half + g[j + 1] += half + f = g + return min(1, f[query_glass]) diff --git a/solution/0800-0899/0802.Find Eventual Safe States/Solution.cpp b/solution/0800-0899/0802.Find Eventual Safe States/Solution.cpp index 4cba32551e75e..a8b37e19bbf6f 100644 --- a/solution/0800-0899/0802.Find Eventual Safe States/Solution.cpp +++ b/solution/0800-0899/0802.Find Eventual Safe States/Solution.cpp @@ -1,22 +1,24 @@ class Solution { public: - vector color; - vector eventualSafeNodes(vector>& graph) { int n = graph.size(); - color.assign(n, 0); + vector indeg(n); + vector> rg(n); + queue q; + for (int i = 0; i < n; ++i) { + for (int j : graph[i]) rg[j].push_back(i); + indeg[i] = graph[i].size(); + if (indeg[i] == 0) q.push(i); + } + while (!q.empty()) { + int i = q.front(); + q.pop(); + for (int j : rg[i]) + if (--indeg[j] == 0) q.push(j); + } vector ans; for (int i = 0; i < n; ++i) - if (dfs(i, graph)) ans.push_back(i); + if (indeg[i] == 0) ans.push_back(i); return ans; } - - bool dfs(int i, vector>& g) { - if (color[i]) return color[i] == 2; - color[i] = 1; - for (int j : g[i]) - if (!dfs(j, g)) return false; - color[i] = 2; - return true; - } }; \ No newline at end of file diff --git a/solution/0800-0899/0802.Find Eventual Safe States/Solution.go b/solution/0800-0899/0802.Find Eventual Safe States/Solution.go index fb44b8be6c5fa..962f4c817e290 100644 --- a/solution/0800-0899/0802.Find Eventual Safe States/Solution.go +++ b/solution/0800-0899/0802.Find Eventual Safe States/Solution.go @@ -1,23 +1,30 @@ func eventualSafeNodes(graph [][]int) []int { n := len(graph) - color := make([]int, n) - var dfs func(int) bool - dfs = func(i int) bool { - if color[i] > 0 { - return color[i] == 2 + indeg := make([]int, n) + rg := make([][]int, n) + q := []int{} + for i, vs := range graph { + for _, j := range vs { + rg[j] = append(rg[j], i) } - color[i] = 1 - for _, j := range graph[i] { - if !dfs(j) { - return false + indeg[i] = len(vs) + if indeg[i] == 0 { + q = append(q, i) + } + } + for len(q) > 0 { + i := q[0] + q = q[1:] + for _, j := range rg[i] { + indeg[j]-- + if indeg[j] == 0 { + q = append(q, j) } } - color[i] = 2 - return true } ans := []int{} - for i := range graph { - if dfs(i) { + for i, v := range indeg { + if v == 0 { ans = append(ans, i) } } diff --git a/solution/0800-0899/0802.Find Eventual Safe States/Solution.java b/solution/0800-0899/0802.Find Eventual Safe States/Solution.java index 4c189c8deded4..31bf06ee66737 100644 --- a/solution/0800-0899/0802.Find Eventual Safe States/Solution.java +++ b/solution/0800-0899/0802.Find Eventual Safe States/Solution.java @@ -1,31 +1,33 @@ class Solution { - private int[] color; - private int[][] g; - public List eventualSafeNodes(int[][] graph) { int n = graph.length; - color = new int[n]; - g = graph; - List ans = new ArrayList<>(); + int[] indeg = new int[n]; + List[] rg = new List[n]; + Arrays.setAll(rg, k -> new ArrayList<>()); + Deque q = new ArrayDeque<>(); for (int i = 0; i < n; ++i) { - if (dfs(i)) { - ans.add(i); + for (int j : graph[i]) { + rg[j].add(i); + } + indeg[i] = graph[i].length; + if (indeg[i] == 0) { + q.offer(i); } } - return ans; - } - - private boolean dfs(int i) { - if (color[i] > 0) { - return color[i] == 2; + while (!q.isEmpty()) { + int i = q.pollFirst(); + for (int j : rg[i]) { + if (--indeg[j] == 0) { + q.offer(j); + } + } } - color[i] = 1; - for (int j : g[i]) { - if (!dfs(j)) { - return false; + List ans = new ArrayList<>(); + for (int i = 0; i < n; ++i) { + if (indeg[i] == 0) { + ans.add(i); } } - color[i] = 2; - return true; + return ans; } } \ No newline at end of file diff --git a/solution/0800-0899/0802.Find Eventual Safe States/Solution.js b/solution/0800-0899/0802.Find Eventual Safe States/Solution.js index 6dbc2f3035285..59f346eb18e50 100644 --- a/solution/0800-0899/0802.Find Eventual Safe States/Solution.js +++ b/solution/0800-0899/0802.Find Eventual Safe States/Solution.js @@ -4,23 +4,29 @@ */ var eventualSafeNodes = function (graph) { const n = graph.length; - const color = new Array(n).fill(0); - function dfs(i) { - if (color[i]) { - return color[i] == 2; + const rg = new Array(n).fill(0).map(() => new Array()); + const indeg = new Array(n).fill(0); + const q = []; + for (let i = 0; i < n; ++i) { + for (let j of graph[i]) { + rg[j].push(i); + } + indeg[i] = graph[i].length; + if (indeg[i] == 0) { + q.push(i); } - color[i] = 1; - for (const j of graph[i]) { - if (!dfs(j)) { - return false; + } + while (q.length) { + const i = q.shift(); + for (let j of rg[i]) { + if (--indeg[j] == 0) { + q.push(j); } } - color[i] = 2; - return true; } let ans = []; for (let i = 0; i < n; ++i) { - if (dfs(i)) { + if (indeg[i] == 0) { ans.push(i); } } diff --git a/solution/0800-0899/0802.Find Eventual Safe States/Solution.py b/solution/0800-0899/0802.Find Eventual Safe States/Solution.py index 2d8d14a6fe7ee..551aef2b6a6b4 100644 --- a/solution/0800-0899/0802.Find Eventual Safe States/Solution.py +++ b/solution/0800-0899/0802.Find Eventual Safe States/Solution.py @@ -1,15 +1,16 @@ class Solution: def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: - def dfs(i): - if color[i]: - return color[i] == 2 - color[i] = 1 - for j in graph[i]: - if not dfs(j): - return False - color[i] = 2 - return True - - n = len(graph) - color = [0] * n - return [i for i in range(n) if dfs(i)] + rg = defaultdict(list) + indeg = [0] * len(graph) + for i, vs in enumerate(graph): + for j in vs: + rg[j].append(i) + indeg[i] = len(vs) + q = deque([i for i, v in enumerate(indeg) if v == 0]) + while q: + i = q.popleft() + for j in rg[i]: + indeg[j] -= 1 + if indeg[j] == 0: + q.append(j) + return [i for i, v in enumerate(indeg) if v == 0] diff --git a/solution/0800-0899/0802.Find Eventual Safe States/Solution2.cpp b/solution/0800-0899/0802.Find Eventual Safe States/Solution2.cpp new file mode 100644 index 0000000000000..4cba32551e75e --- /dev/null +++ b/solution/0800-0899/0802.Find Eventual Safe States/Solution2.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + vector color; + + vector eventualSafeNodes(vector>& graph) { + int n = graph.size(); + color.assign(n, 0); + vector ans; + for (int i = 0; i < n; ++i) + if (dfs(i, graph)) ans.push_back(i); + return ans; + } + + bool dfs(int i, vector>& g) { + if (color[i]) return color[i] == 2; + color[i] = 1; + for (int j : g[i]) + if (!dfs(j, g)) return false; + color[i] = 2; + return true; + } +}; \ No newline at end of file diff --git a/solution/0800-0899/0802.Find Eventual Safe States/Solution2.go b/solution/0800-0899/0802.Find Eventual Safe States/Solution2.go new file mode 100644 index 0000000000000..fb44b8be6c5fa --- /dev/null +++ b/solution/0800-0899/0802.Find Eventual Safe States/Solution2.go @@ -0,0 +1,25 @@ +func eventualSafeNodes(graph [][]int) []int { + n := len(graph) + color := make([]int, n) + var dfs func(int) bool + dfs = func(i int) bool { + if color[i] > 0 { + return color[i] == 2 + } + color[i] = 1 + for _, j := range graph[i] { + if !dfs(j) { + return false + } + } + color[i] = 2 + return true + } + ans := []int{} + for i := range graph { + if dfs(i) { + ans = append(ans, i) + } + } + return ans +} \ No newline at end of file diff --git a/solution/0800-0899/0802.Find Eventual Safe States/Solution2.java b/solution/0800-0899/0802.Find Eventual Safe States/Solution2.java new file mode 100644 index 0000000000000..4c189c8deded4 --- /dev/null +++ b/solution/0800-0899/0802.Find Eventual Safe States/Solution2.java @@ -0,0 +1,31 @@ +class Solution { + private int[] color; + private int[][] g; + + public List eventualSafeNodes(int[][] graph) { + int n = graph.length; + color = new int[n]; + g = graph; + List ans = new ArrayList<>(); + for (int i = 0; i < n; ++i) { + if (dfs(i)) { + ans.add(i); + } + } + return ans; + } + + private boolean dfs(int i) { + if (color[i] > 0) { + return color[i] == 2; + } + color[i] = 1; + for (int j : g[i]) { + if (!dfs(j)) { + return false; + } + } + color[i] = 2; + return true; + } +} \ No newline at end of file diff --git a/solution/0800-0899/0802.Find Eventual Safe States/Solution2.js b/solution/0800-0899/0802.Find Eventual Safe States/Solution2.js new file mode 100644 index 0000000000000..6dbc2f3035285 --- /dev/null +++ b/solution/0800-0899/0802.Find Eventual Safe States/Solution2.js @@ -0,0 +1,28 @@ +/** + * @param {number[][]} graph + * @return {number[]} + */ +var eventualSafeNodes = function (graph) { + const n = graph.length; + const color = new Array(n).fill(0); + function dfs(i) { + if (color[i]) { + return color[i] == 2; + } + color[i] = 1; + for (const j of graph[i]) { + if (!dfs(j)) { + return false; + } + } + color[i] = 2; + return true; + } + let ans = []; + for (let i = 0; i < n; ++i) { + if (dfs(i)) { + ans.push(i); + } + } + return ans; +}; diff --git a/solution/0800-0899/0802.Find Eventual Safe States/Solution2.py b/solution/0800-0899/0802.Find Eventual Safe States/Solution2.py new file mode 100644 index 0000000000000..2d8d14a6fe7ee --- /dev/null +++ b/solution/0800-0899/0802.Find Eventual Safe States/Solution2.py @@ -0,0 +1,15 @@ +class Solution: + def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: + def dfs(i): + if color[i]: + return color[i] == 2 + color[i] = 1 + for j in graph[i]: + if not dfs(j): + return False + color[i] = 2 + return True + + n = len(graph) + color = [0] * n + return [i for i in range(n) if dfs(i)] diff --git a/solution/0800-0899/0804.Unique Morse Code Words/Solution.cpp b/solution/0800-0899/0804.Unique Morse Code Words/Solution.cpp index 93c2abc112bec..d8115a5fd857d 100644 --- a/solution/0800-0899/0804.Unique Morse Code Words/Solution.cpp +++ b/solution/0800-0899/0804.Unique Morse Code Words/Solution.cpp @@ -1,14 +1,14 @@ -class Solution { -public: - int uniqueMorseRepresentations(vector& words) { - vector codes = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", - "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; - unordered_set s; - for (auto& word : words) { - string t; - for (char& c : word) t += codes[c - 'a']; - s.insert(t); - } - return s.size(); - } +class Solution { +public: + int uniqueMorseRepresentations(vector& words) { + vector codes = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", + "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; + unordered_set s; + for (auto& word : words) { + string t; + for (char& c : word) t += codes[c - 'a']; + s.insert(t); + } + return s.size(); + } }; \ No newline at end of file diff --git a/solution/0800-0899/0804.Unique Morse Code Words/Solution.py b/solution/0800-0899/0804.Unique Morse Code Words/Solution.py index ae64b5ae87c8d..70807f4777999 100644 --- a/solution/0800-0899/0804.Unique Morse Code Words/Solution.py +++ b/solution/0800-0899/0804.Unique Morse Code Words/Solution.py @@ -1,32 +1,32 @@ -class Solution: - def uniqueMorseRepresentations(self, words: List[str]) -> int: - codes = [ - ".-", - "-...", - "-.-.", - "-..", - ".", - "..-.", - "--.", - "....", - "..", - ".---", - "-.-", - ".-..", - "--", - "-.", - "---", - ".--.", - "--.-", - ".-.", - "...", - "-", - "..-", - "...-", - ".--", - "-..-", - "-.--", - "--..", - ] - s = {''.join([codes[ord(c) - ord('a')] for c in word]) for word in words} - return len(s) +class Solution: + def uniqueMorseRepresentations(self, words: List[str]) -> int: + codes = [ + ".-", + "-...", + "-.-.", + "-..", + ".", + "..-.", + "--.", + "....", + "..", + ".---", + "-.-", + ".-..", + "--", + "-.", + "---", + ".--.", + "--.-", + ".-.", + "...", + "-", + "..-", + "...-", + ".--", + "-..-", + "-.--", + "--..", + ] + s = {''.join([codes[ord(c) - ord('a')] for c in word]) for word in words} + return len(s) diff --git a/solution/0800-0899/0806.Number of Lines To Write String/Solution.cpp b/solution/0800-0899/0806.Number of Lines To Write String/Solution.cpp index 391f5533467a6..9da7ee44856ef 100644 --- a/solution/0800-0899/0806.Number of Lines To Write String/Solution.cpp +++ b/solution/0800-0899/0806.Number of Lines To Write String/Solution.cpp @@ -1,18 +1,18 @@ -class Solution { -public: - const int MAX_WIDTH = 100; - - vector numberOfLines(vector& widths, string s) { - int last = 0, row = 1; - for (char c : s) { - int w = widths[c - 'a']; - if (last + w <= MAX_WIDTH) - last += w; - else { - ++row; - last = w; - } - } - return {row, last}; - } +class Solution { +public: + const int MAX_WIDTH = 100; + + vector numberOfLines(vector& widths, string s) { + int last = 0, row = 1; + for (char c : s) { + int w = widths[c - 'a']; + if (last + w <= MAX_WIDTH) + last += w; + else { + ++row; + last = w; + } + } + return {row, last}; + } }; \ No newline at end of file diff --git a/solution/0800-0899/0806.Number of Lines To Write String/Solution.java b/solution/0800-0899/0806.Number of Lines To Write String/Solution.java index 76720160767b3..3aedb161b71a5 100644 --- a/solution/0800-0899/0806.Number of Lines To Write String/Solution.java +++ b/solution/0800-0899/0806.Number of Lines To Write String/Solution.java @@ -1,17 +1,17 @@ -class Solution { - private static final int MAX_WIDTH = 100; - - public int[] numberOfLines(int[] widths, String s) { - int last = 0, row = 1; - for (char c : s.toCharArray()) { - int w = widths[c - 'a']; - if (last + w <= MAX_WIDTH) { - last += w; - } else { - ++row; - last = w; - } - } - return new int[] {row, last}; - } +class Solution { + private static final int MAX_WIDTH = 100; + + public int[] numberOfLines(int[] widths, String s) { + int last = 0, row = 1; + for (char c : s.toCharArray()) { + int w = widths[c - 'a']; + if (last + w <= MAX_WIDTH) { + last += w; + } else { + ++row; + last = w; + } + } + return new int[] {row, last}; + } } \ No newline at end of file diff --git a/solution/0800-0899/0806.Number of Lines To Write String/Solution.py b/solution/0800-0899/0806.Number of Lines To Write String/Solution.py index c9d0a010aafb8..e8ad29fd67980 100644 --- a/solution/0800-0899/0806.Number of Lines To Write String/Solution.py +++ b/solution/0800-0899/0806.Number of Lines To Write String/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def numberOfLines(self, widths: List[int], s: str) -> List[int]: - last, row = 0, 1 - for c in s: - w = widths[ord(c) - ord('a')] - if last + w <= 100: - last += w - else: - row += 1 - last = w - return [row, last] +class Solution: + def numberOfLines(self, widths: List[int], s: str) -> List[int]: + last, row = 0, 1 + for c in s: + w = widths[ord(c) - ord('a')] + if last + w <= 100: + last += w + else: + row += 1 + last = w + return [row, last] diff --git a/solution/0800-0899/0814.Binary Tree Pruning/Solution.java b/solution/0800-0899/0814.Binary Tree Pruning/Solution.java index b3a2bdcddc25e..5d26b15ddd550 100644 --- a/solution/0800-0899/0814.Binary Tree Pruning/Solution.java +++ b/solution/0800-0899/0814.Binary Tree Pruning/Solution.java @@ -25,4 +25,4 @@ public TreeNode pruneTree(TreeNode root) { } return root; } -} +} \ No newline at end of file diff --git a/solution/0800-0899/0815.Bus Routes/Solution.cs b/solution/0800-0899/0815.Bus Routes/Solution.cs index e853b5b589c2a..0baab5a907de9 100644 --- a/solution/0800-0899/0815.Bus Routes/Solution.cs +++ b/solution/0800-0899/0815.Bus Routes/Solution.cs @@ -3,10 +3,10 @@ public int NumBusesToDestination(int[][] routes, int source, int target) { if (source == target) { return 0; } - + Dictionary> stopToRoutes = new Dictionary>(); List> routeToStops = new List>(); - + for (int i = 0; i < routes.Length; i++) { routeToStops.Add(new HashSet()); foreach (int stop in routes[i]) { @@ -17,7 +17,7 @@ public int NumBusesToDestination(int[][] routes, int source, int target) { stopToRoutes[stop].Add(i); } } - + Queue queue = new Queue(); HashSet visited = new HashSet(); int ans = 0; diff --git a/solution/0800-0899/0815.Bus Routes/Solution.py b/solution/0800-0899/0815.Bus Routes/Solution.py index 876d283905739..3dfb07db8d911 100644 --- a/solution/0800-0899/0815.Bus Routes/Solution.py +++ b/solution/0800-0899/0815.Bus Routes/Solution.py @@ -5,7 +5,10 @@ def numBusesToDestination( if source == target: return 0 + # 一条公交线路有哪些公交站 s = [set(r) for r in routes] + + # 一个公交站在哪些公交线路有 d = defaultdict(list) for i, r in enumerate(routes): for v in r: diff --git a/solution/0800-0899/0819.Most Common Word/Solution.cpp b/solution/0800-0899/0819.Most Common Word/Solution.cpp index 05a43f17e6507..1b9a7a12608f8 100644 --- a/solution/0800-0899/0819.Most Common Word/Solution.cpp +++ b/solution/0800-0899/0819.Most Common Word/Solution.cpp @@ -1,25 +1,25 @@ -class Solution { -public: - string mostCommonWord(string paragraph, vector& banned) { - unordered_set s(banned.begin(), banned.end()); - unordered_map counter; - string ans; - for (int i = 0, mx = 0, n = paragraph.size(); i < n;) { - if (!isalpha(paragraph[i]) && (++i > 0)) continue; - int j = i; - string word; - while (j < n && isalpha(paragraph[j])) { - word.push_back(tolower(paragraph[j])); - ++j; - } - i = j + 1; - if (s.count(word)) continue; - ++counter[word]; - if (counter[word] > mx) { - ans = word; - mx = counter[word]; - } - } - return ans; - } +class Solution { +public: + string mostCommonWord(string paragraph, vector& banned) { + unordered_set s(banned.begin(), banned.end()); + unordered_map counter; + string ans; + for (int i = 0, mx = 0, n = paragraph.size(); i < n;) { + if (!isalpha(paragraph[i]) && (++i > 0)) continue; + int j = i; + string word; + while (j < n && isalpha(paragraph[j])) { + word.push_back(tolower(paragraph[j])); + ++j; + } + i = j + 1; + if (s.count(word)) continue; + ++counter[word]; + if (counter[word] > mx) { + ans = word; + mx = counter[word]; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0800-0899/0819.Most Common Word/Solution.java b/solution/0800-0899/0819.Most Common Word/Solution.java index 66567cb3d5145..a27e82cf3d7e9 100644 --- a/solution/0800-0899/0819.Most Common Word/Solution.java +++ b/solution/0800-0899/0819.Most Common Word/Solution.java @@ -1,31 +1,31 @@ -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -class Solution { - private static Pattern pattern = Pattern.compile("[a-z]+"); - - public String mostCommonWord(String paragraph, String[] banned) { - Set bannedWords = new HashSet<>(); - for (String word : banned) { - bannedWords.add(word); - } - Map counter = new HashMap<>(); - Matcher matcher = pattern.matcher(paragraph.toLowerCase()); - while (matcher.find()) { - String word = matcher.group(); - if (bannedWords.contains(word)) { - continue; - } - counter.put(word, counter.getOrDefault(word, 0) + 1); - } - int max = Integer.MIN_VALUE; - String ans = null; - for (Map.Entry entry : counter.entrySet()) { - if (entry.getValue() > max) { - max = entry.getValue(); - ans = entry.getKey(); - } - } - return ans; - } +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +class Solution { + private static Pattern pattern = Pattern.compile("[a-z]+"); + + public String mostCommonWord(String paragraph, String[] banned) { + Set bannedWords = new HashSet<>(); + for (String word : banned) { + bannedWords.add(word); + } + Map counter = new HashMap<>(); + Matcher matcher = pattern.matcher(paragraph.toLowerCase()); + while (matcher.find()) { + String word = matcher.group(); + if (bannedWords.contains(word)) { + continue; + } + counter.put(word, counter.getOrDefault(word, 0) + 1); + } + int max = Integer.MIN_VALUE; + String ans = null; + for (Map.Entry entry : counter.entrySet()) { + if (entry.getValue() > max) { + max = entry.getValue(); + ans = entry.getKey(); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0800-0899/0819.Most Common Word/Solution.py b/solution/0800-0899/0819.Most Common Word/Solution.py index 3e3a28933d4a2..c2d65b75fec4a 100644 --- a/solution/0800-0899/0819.Most Common Word/Solution.py +++ b/solution/0800-0899/0819.Most Common Word/Solution.py @@ -1,5 +1,5 @@ -class Solution: - def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: - s = set(banned) - p = Counter(re.findall('[a-z]+', paragraph.lower())) - return next(word for word, _ in p.most_common() if word not in s) +class Solution: + def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: + s = set(banned) + p = Counter(re.findall('[a-z]+', paragraph.lower())) + return next(word for word, _ in p.most_common() if word not in s) diff --git a/solution/0800-0899/0820.Short Encoding of Words/Solution.cpp b/solution/0800-0899/0820.Short Encoding of Words/Solution.cpp index e1a647698d5a9..054a535ce46bd 100644 --- a/solution/0800-0899/0820.Short Encoding of Words/Solution.cpp +++ b/solution/0800-0899/0820.Short Encoding of Words/Solution.cpp @@ -33,4 +33,4 @@ class Solution { } return ans; } -}; +}; \ No newline at end of file diff --git a/solution/0800-0899/0820.Short Encoding of Words/Solution.java b/solution/0800-0899/0820.Short Encoding of Words/Solution.java index 5a469ee7814c0..63e2da57c5916 100644 --- a/solution/0800-0899/0820.Short Encoding of Words/Solution.java +++ b/solution/0800-0899/0820.Short Encoding of Words/Solution.java @@ -32,4 +32,4 @@ private int dfs(Trie cur, int l) { } return ans; } -} +} \ No newline at end of file diff --git a/solution/0800-0899/0820.Short Encoding of Words/Solution.py b/solution/0800-0899/0820.Short Encoding of Words/Solution.py index dbdd5fa40f3dd..ab1c1da7ef2f9 100644 --- a/solution/0800-0899/0820.Short Encoding of Words/Solution.py +++ b/solution/0800-0899/0820.Short Encoding of Words/Solution.py @@ -8,8 +8,8 @@ def minimumLengthEncoding(self, words: List[str]) -> int: root = Trie() for w in words: cur = root - for i in range(len(w) - 1, -1, -1): - idx = ord(w[i]) - ord('a') + for c in w[::-1]: + idx = ord(c) - ord("a") if cur.children[idx] == None: cur.children[idx] = Trie() cur = cur.children[idx] diff --git a/solution/0800-0899/0820.Short Encoding of Words/Solution2.cpp b/solution/0800-0899/0820.Short Encoding of Words/Solution2.cpp new file mode 100644 index 0000000000000..6b815b982ff9b --- /dev/null +++ b/solution/0800-0899/0820.Short Encoding of Words/Solution2.cpp @@ -0,0 +1,34 @@ +class Trie { +public: + vector children; + Trie() + : children(26) {} + + int insert(string w) { + Trie* node = this; + bool pref = true; + for (char c : w) { + c -= 'a'; + if (!node->children[c]) { + pref = false; + node->children[c] = new Trie(); + } + node = node->children[c]; + } + return pref ? 0 : w.size() + 1; + } +}; + +class Solution { +public: + int minimumLengthEncoding(vector& words) { + sort(words.begin(), words.end(), [](string& a, string& b) { return a.size() > b.size(); }); + Trie* trie = new Trie(); + int ans = 0; + for (auto& w : words) { + reverse(w.begin(), w.end()); + ans += trie->insert(w); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0800-0899/0820.Short Encoding of Words/Solution2.go b/solution/0800-0899/0820.Short Encoding of Words/Solution2.go new file mode 100644 index 0000000000000..581a16f9de885 --- /dev/null +++ b/solution/0800-0899/0820.Short Encoding of Words/Solution2.go @@ -0,0 +1,34 @@ +type Trie struct { + children [26]*Trie +} + +func newTrie() *Trie { + return &Trie{} +} + +func (this *Trie) insert(w string) int { + node := this + pref := true + for i := len(w) - 1; i >= 0; i-- { + idx := w[i] - 'a' + if node.children[idx] == nil { + pref = false + node.children[idx] = newTrie() + } + node = node.children[idx] + } + if pref { + return 0 + } + return len(w) + 1 +} + +func minimumLengthEncoding(words []string) int { + sort.Slice(words, func(i, j int) bool { return len(words[i]) > len(words[j]) }) + trie := newTrie() + ans := 0 + for _, w := range words { + ans += trie.insert(w) + } + return ans +} \ No newline at end of file diff --git a/solution/0800-0899/0820.Short Encoding of Words/Solution2.java b/solution/0800-0899/0820.Short Encoding of Words/Solution2.java new file mode 100644 index 0000000000000..b800c33dc04db --- /dev/null +++ b/solution/0800-0899/0820.Short Encoding of Words/Solution2.java @@ -0,0 +1,29 @@ +class Trie { + Trie[] children = new Trie[26]; + + int insert(String w) { + Trie node = this; + boolean pref = true; + for (int i = w.length() - 1; i >= 0; --i) { + int idx = w.charAt(i) - 'a'; + if (node.children[idx] == null) { + pref = false; + node.children[idx] = new Trie(); + } + node = node.children[idx]; + } + return pref ? 0 : w.length() + 1; + } +} + +class Solution { + public int minimumLengthEncoding(String[] words) { + Arrays.sort(words, (a, b) -> b.length() - a.length()); + int ans = 0; + Trie trie = new Trie(); + for (String w : words) { + ans += trie.insert(w); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0800-0899/0820.Short Encoding of Words/Solution2.py b/solution/0800-0899/0820.Short Encoding of Words/Solution2.py new file mode 100644 index 0000000000000..0b31f6d6b2218 --- /dev/null +++ b/solution/0800-0899/0820.Short Encoding of Words/Solution2.py @@ -0,0 +1,21 @@ +class Trie: + def __init__(self): + self.children = [None] * 26 + + def insert(self, w): + node = self + pref = True + for c in w: + idx = ord(c) - ord("a") + if node.children[idx] is None: + node.children[idx] = Trie() + pref = False + node = node.children[idx] + return 0 if pref else len(w) + 1 + + +class Solution: + def minimumLengthEncoding(self, words: List[str]) -> int: + words.sort(key=lambda x: -len(x)) + trie = Trie() + return sum(trie.insert(w[::-1]) for w in words) diff --git a/solution/0800-0899/0821.Shortest Distance to a Character/Solution.cpp b/solution/0800-0899/0821.Shortest Distance to a Character/Solution.cpp index d41732d51f1b6..56e1cafa54efd 100644 --- a/solution/0800-0899/0821.Shortest Distance to a Character/Solution.cpp +++ b/solution/0800-0899/0821.Shortest Distance to a Character/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - vector shortestToChar(string s, char c) { - int n = s.size(); - const int inf = 1 << 30; - vector ans(n, inf); - for (int i = 0, pre = -inf; i < n; ++i) { - if (s[i] == c) { - pre = i; - } - ans[i] = min(ans[i], i - pre); - } - for (int i = n - 1, suf = inf; ~i; --i) { - if (s[i] == c) { - suf = i; - } - ans[i] = min(ans[i], suf - i); - } - return ans; - } +class Solution { +public: + vector shortestToChar(string s, char c) { + int n = s.size(); + const int inf = 1 << 30; + vector ans(n, inf); + for (int i = 0, pre = -inf; i < n; ++i) { + if (s[i] == c) { + pre = i; + } + ans[i] = min(ans[i], i - pre); + } + for (int i = n - 1, suf = inf; ~i; --i) { + if (s[i] == c) { + suf = i; + } + ans[i] = min(ans[i], suf - i); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0800-0899/0821.Shortest Distance to a Character/Solution.java b/solution/0800-0899/0821.Shortest Distance to a Character/Solution.java index 3d77c082fdb0e..6f615c3718e9e 100644 --- a/solution/0800-0899/0821.Shortest Distance to a Character/Solution.java +++ b/solution/0800-0899/0821.Shortest Distance to a Character/Solution.java @@ -1,21 +1,21 @@ -class Solution { - public int[] shortestToChar(String s, char c) { - int n = s.length(); - int[] ans = new int[n]; - final int inf = 1 << 30; - Arrays.fill(ans, inf); - for (int i = 0, pre = -inf; i < n; ++i) { - if (s.charAt(i) == c) { - pre = i; - } - ans[i] = Math.min(ans[i], i - pre); - } - for (int i = n - 1, suf = inf; i >= 0; --i) { - if (s.charAt(i) == c) { - suf = i; - } - ans[i] = Math.min(ans[i], suf - i); - } - return ans; - } +class Solution { + public int[] shortestToChar(String s, char c) { + int n = s.length(); + int[] ans = new int[n]; + final int inf = 1 << 30; + Arrays.fill(ans, inf); + for (int i = 0, pre = -inf; i < n; ++i) { + if (s.charAt(i) == c) { + pre = i; + } + ans[i] = Math.min(ans[i], i - pre); + } + for (int i = n - 1, suf = inf; i >= 0; --i) { + if (s.charAt(i) == c) { + suf = i; + } + ans[i] = Math.min(ans[i], suf - i); + } + return ans; + } } \ No newline at end of file diff --git a/solution/0800-0899/0821.Shortest Distance to a Character/Solution.py b/solution/0800-0899/0821.Shortest Distance to a Character/Solution.py index 7aa7349e1f032..d967a08a8160a 100644 --- a/solution/0800-0899/0821.Shortest Distance to a Character/Solution.py +++ b/solution/0800-0899/0821.Shortest Distance to a Character/Solution.py @@ -1,15 +1,15 @@ -class Solution: - def shortestToChar(self, s: str, c: str) -> List[int]: - n = len(s) - ans = [n] * n - pre = -inf - for i, ch in enumerate(s): - if ch == c: - pre = i - ans[i] = min(ans[i], i - pre) - suf = inf - for i in range(n - 1, -1, -1): - if s[i] == c: - suf = i - ans[i] = min(ans[i], suf - i) - return ans +class Solution: + def shortestToChar(self, s: str, c: str) -> List[int]: + n = len(s) + ans = [n] * n + pre = -inf + for i, ch in enumerate(s): + if ch == c: + pre = i + ans[i] = min(ans[i], i - pre) + suf = inf + for i in range(n - 1, -1, -1): + if s[i] == c: + suf = i + ans[i] = min(ans[i], suf - i) + return ans diff --git a/solution/0800-0899/0822.Card Flipping Game/Solution.cpp b/solution/0800-0899/0822.Card Flipping Game/Solution.cpp index 0ffa0920c2837..3390d85c9c931 100644 --- a/solution/0800-0899/0822.Card Flipping Game/Solution.cpp +++ b/solution/0800-0899/0822.Card Flipping Game/Solution.cpp @@ -1,24 +1,24 @@ -class Solution { -public: - int flipgame(vector& fronts, vector& backs) { - unordered_set s; - int n = fronts.size(); - for (int i = 0; i < n; ++i) { - if (fronts[i] == backs[i]) { - s.insert(fronts[i]); - } - } - int ans = 9999; - for (int& v : fronts) { - if (!s.count(v)) { - ans = min(ans, v); - } - } - for (int& v : backs) { - if (!s.count(v)) { - ans = min(ans, v); - } - } - return ans % 9999; - } +class Solution { +public: + int flipgame(vector& fronts, vector& backs) { + unordered_set s; + int n = fronts.size(); + for (int i = 0; i < n; ++i) { + if (fronts[i] == backs[i]) { + s.insert(fronts[i]); + } + } + int ans = 9999; + for (int& v : fronts) { + if (!s.count(v)) { + ans = min(ans, v); + } + } + for (int& v : backs) { + if (!s.count(v)) { + ans = min(ans, v); + } + } + return ans % 9999; + } }; \ No newline at end of file diff --git a/solution/0800-0899/0822.Card Flipping Game/Solution.cs b/solution/0800-0899/0822.Card Flipping Game/Solution.cs index 9217fc6febafa..161eb8766d306 100644 --- a/solution/0800-0899/0822.Card Flipping Game/Solution.cs +++ b/solution/0800-0899/0822.Card Flipping Game/Solution.cs @@ -1,21 +1,21 @@ -public class Solution { - public int Flipgame(int[] fronts, int[] backs) { - var s = new HashSet(); - int n = fronts.Length; - for (int i = 0; i < n; ++i) { - if (fronts[i] == backs[i]) { - s.Add(fronts[i]); - } - } - int ans = 9999; - for (int i = 0; i < n; ++i) { - if (!s.Contains(fronts[i])) { - ans = Math.Min(ans, fronts[i]); - } - if (!s.Contains(backs[i])) { - ans = Math.Min(ans, backs[i]); - } - } - return ans % 9999; - } -} \ No newline at end of file +public class Solution { + public int Flipgame(int[] fronts, int[] backs) { + var s = new HashSet(); + int n = fronts.Length; + for (int i = 0; i < n; ++i) { + if (fronts[i] == backs[i]) { + s.Add(fronts[i]); + } + } + int ans = 9999; + for (int i = 0; i < n; ++i) { + if (!s.Contains(fronts[i])) { + ans = Math.Min(ans, fronts[i]); + } + if (!s.Contains(backs[i])) { + ans = Math.Min(ans, backs[i]); + } + } + return ans % 9999; + } +} diff --git a/solution/0800-0899/0822.Card Flipping Game/Solution.py b/solution/0800-0899/0822.Card Flipping Game/Solution.py index fae1e8779edd1..319a54cf7828a 100644 --- a/solution/0800-0899/0822.Card Flipping Game/Solution.py +++ b/solution/0800-0899/0822.Card Flipping Game/Solution.py @@ -1,4 +1,4 @@ -class Solution: - def flipgame(self, fronts: List[int], backs: List[int]) -> int: - s = {a for a, b in zip(fronts, backs) if a == b} - return min((x for x in chain(fronts, backs) if x not in s), default=0) +class Solution: + def flipgame(self, fronts: List[int], backs: List[int]) -> int: + s = {a for a, b in zip(fronts, backs) if a == b} + return min((x for x in chain(fronts, backs) if x not in s), default=0) diff --git a/solution/0800-0899/0823.Binary Trees With Factors/Solution.cpp b/solution/0800-0899/0823.Binary Trees With Factors/Solution.cpp index b9240c497b00f..86a1df22f72f9 100644 --- a/solution/0800-0899/0823.Binary Trees With Factors/Solution.cpp +++ b/solution/0800-0899/0823.Binary Trees With Factors/Solution.cpp @@ -1,31 +1,31 @@ -class Solution { -public: - int numFactoredBinaryTrees(vector& arr) { - const int mod = 1e9 + 7; - sort(arr.begin(), arr.end()); - unordered_map idx; - int n = arr.size(); - for (int i = 0; i < n; ++i) { - idx[arr[i]] = i; - } - vector f(n, 1); - for (int i = 0; i < n; ++i) { - int a = arr[i]; - for (int j = 0; j < i; ++j) { - int b = arr[j]; - if (a % b == 0) { - int c = a / b; - if (idx.count(c)) { - int k = idx[c]; - f[i] = (f[i] + 1l * f[j] * f[k]) % mod; - } - } - } - } - long ans = 0; - for (long v : f) { - ans = (ans + v) % mod; - } - return ans; - } +class Solution { +public: + int numFactoredBinaryTrees(vector& arr) { + const int mod = 1e9 + 7; + sort(arr.begin(), arr.end()); + unordered_map idx; + int n = arr.size(); + for (int i = 0; i < n; ++i) { + idx[arr[i]] = i; + } + vector f(n, 1); + for (int i = 0; i < n; ++i) { + int a = arr[i]; + for (int j = 0; j < i; ++j) { + int b = arr[j]; + if (a % b == 0) { + int c = a / b; + if (idx.count(c)) { + int k = idx[c]; + f[i] = (f[i] + 1l * f[j] * f[k]) % mod; + } + } + } + } + long ans = 0; + for (long v : f) { + ans = (ans + v) % mod; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0800-0899/0823.Binary Trees With Factors/Solution.java b/solution/0800-0899/0823.Binary Trees With Factors/Solution.java new file mode 100644 index 0000000000000..b1b0afa94d42c --- /dev/null +++ b/solution/0800-0899/0823.Binary Trees With Factors/Solution.java @@ -0,0 +1,31 @@ +class Solution { + public int numFactoredBinaryTrees(int[] arr) { + final int mod = (int) 1e9 + 7; + Arrays.sort(arr); + int n = arr.length; + long[] f = new long[n]; + Arrays.fill(f, 1); + Map idx = new HashMap<>(n); + for (int i = 0; i < n; ++i) { + idx.put(arr[i], i); + } + for (int i = 0; i < n; ++i) { + int a = arr[i]; + for (int j = 0; j < i; ++j) { + int b = arr[j]; + if (a % b == 0) { + int c = a / b; + if (idx.containsKey(c)) { + int k = idx.get(c); + f[i] = (f[i] + f[j] * f[k]) % mod; + } + } + } + } + long ans = 0; + for (long v : f) { + ans = (ans + v) % mod; + } + return (int) ans; + } +} \ No newline at end of file diff --git a/solution/0800-0899/0827.Making A Large Island/Solution2.cpp b/solution/0800-0899/0827.Making A Large Island/Solution2.cpp new file mode 100644 index 0000000000000..f9492e3956b58 --- /dev/null +++ b/solution/0800-0899/0827.Making A Large Island/Solution2.cpp @@ -0,0 +1,55 @@ +class Solution { +public: + const static inline vector dirs = {-1, 0, 1, 0, -1}; + + int largestIsland(vector>& grid) { + int n = grid.size(); + int ans = 0; + int root = 0; + vector> p(n, vector(n)); + vector cnt(n * n + 1); + + function dfs; + dfs = [&](int i, int j) { + p[i][j] = root; + ++cnt[root]; + ans = max(ans, cnt[root]); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < n && y >= 0 && y < n && grid[x][y] && p[x][y] == 0) { + dfs(x, y); + } + } + }; + + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] && p[i][j] == 0) { + ++root; + dfs(i, j); + } + } + } + + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (!grid[i][j]) { + int t = 1; + unordered_set vis; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < n && y >= 0 && y < n) { + int root = p[x][y]; + if (!vis.count(root)) { + vis.insert(root); + t += cnt[root]; + } + } + } + ans = max(ans, t); + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0800-0899/0827.Making A Large Island/Solution2.go b/solution/0800-0899/0827.Making A Large Island/Solution2.go new file mode 100644 index 0000000000000..dba2d6edccde1 --- /dev/null +++ b/solution/0800-0899/0827.Making A Large Island/Solution2.go @@ -0,0 +1,52 @@ +func largestIsland(grid [][]int) int { + n := len(grid) + p := make([][]int, n) + for i := range p { + p[i] = make([]int, n) + } + cnt := make([]int, n*n+1) + dirs := []int{-1, 0, 1, 0, -1} + ans, root := 0, 0 + + var dfs func(i, j int) + dfs = func(i, j int) { + p[i][j] = root + cnt[root]++ + ans = max(ans, cnt[root]) + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < n && y >= 0 && y < n && grid[x][y] == 1 && p[x][y] == 0 { + dfs(x, y) + } + } + } + + for i, row := range grid { + for j, v := range row { + if v == 1 && p[i][j] == 0 { + root++ + dfs(i, j) + } + } + } + for i, row := range grid { + for j, v := range row { + if v == 0 { + t := 1 + vis := map[int]struct{}{} + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < n && y >= 0 && y < n { + root := p[x][y] + if _, ok := vis[root]; !ok { + vis[root] = struct{}{} + t += cnt[root] + } + } + } + ans = max(ans, t) + } + } + } + return ans +} \ No newline at end of file diff --git a/solution/0800-0899/0827.Making A Large Island/Solution2.java b/solution/0800-0899/0827.Making A Large Island/Solution2.java new file mode 100644 index 0000000000000..30a55eb187f2a --- /dev/null +++ b/solution/0800-0899/0827.Making A Large Island/Solution2.java @@ -0,0 +1,56 @@ +class Solution { + private int n; + private int ans; + private int root; + private int[][] p; + private int[][] grid; + private int[] cnt; + private int[] dirs = new int[] {-1, 0, 1, 0, -1}; + + public int largestIsland(int[][] grid) { + n = grid.length; + cnt = new int[n * n + 1]; + p = new int[n][n]; + this.grid = grid; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 1 && p[i][j] == 0) { + ++root; + dfs(i, j); + } + } + } + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 0) { + int t = 1; + Set vis = new HashSet<>(); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < n && y >= 0 && y < n) { + int root = p[x][y]; + if (!vis.contains(root)) { + vis.add(root); + t += cnt[root]; + } + } + } + ans = Math.max(ans, t); + } + } + } + return ans; + } + + private void dfs(int i, int j) { + p[i][j] = root; + ++cnt[root]; + ans = Math.max(ans, cnt[root]); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < n && y >= 0 && y < n && grid[x][y] == 1 && p[x][y] == 0) { + dfs(x, y); + } + } + } +} \ No newline at end of file diff --git a/solution/0800-0899/0827.Making A Large Island/Solution2.py b/solution/0800-0899/0827.Making A Large Island/Solution2.py new file mode 100644 index 0000000000000..51ee5c852a795 --- /dev/null +++ b/solution/0800-0899/0827.Making A Large Island/Solution2.py @@ -0,0 +1,35 @@ +class Solution: + def largestIsland(self, grid: List[List[int]]) -> int: + def dfs(i, j): + p[i][j] = root + cnt[root] += 1 + for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: + x, y = i + a, j + b + if 0 <= x < n and 0 <= y < n and grid[x][y] and p[x][y] == 0: + dfs(x, y) + + n = len(grid) + cnt = Counter() + p = [[0] * n for _ in range(n)] + root = 0 + for i, row in enumerate(grid): + for j, v in enumerate(row): + if v and p[i][j] == 0: + root += 1 + dfs(i, j) + + ans = max(cnt.values(), default=0) + for i, row in enumerate(grid): + for j, v in enumerate(row): + if v == 0: + t = 1 + vis = set() + for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: + x, y = i + a, j + b + if 0 <= x < n and 0 <= y < n: + root = p[x][y] + if root not in vis: + vis.add(root) + t += cnt[root] + ans = max(ans, t) + return ans diff --git a/solution/0800-0899/0829.Consecutive Numbers Sum/Solution.java b/solution/0800-0899/0829.Consecutive Numbers Sum/Solution.java index f575a7c9ba31d..57c779b5a6dce 100644 --- a/solution/0800-0899/0829.Consecutive Numbers Sum/Solution.java +++ b/solution/0800-0899/0829.Consecutive Numbers Sum/Solution.java @@ -1,4 +1,5 @@ class Solution { + public int consecutiveNumbersSum(int n) { n <<= 1; int ans = 0; diff --git a/solution/0800-0899/0833.Find And Replace in String/Solution.cpp b/solution/0800-0899/0833.Find And Replace in String/Solution.cpp index 40a35a1276820..f69cdf95b6072 100644 --- a/solution/0800-0899/0833.Find And Replace in String/Solution.cpp +++ b/solution/0800-0899/0833.Find And Replace in String/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - string findReplaceString(string s, vector& indices, vector& sources, vector& targets) { - int n = s.size(); - vector d(n, -1); - for (int k = 0; k < indices.size(); ++k) { - int i = indices[k]; - if (s.compare(i, sources[k].size(), sources[k]) == 0) { - d[i] = k; - } - } - string ans; - for (int i = 0; i < n;) { - if (~d[i]) { - ans += targets[d[i]]; - i += sources[d[i]].size(); - } else { - ans += s[i++]; - } - } - return ans; - } +class Solution { +public: + string findReplaceString(string s, vector& indices, vector& sources, vector& targets) { + int n = s.size(); + vector d(n, -1); + for (int k = 0; k < indices.size(); ++k) { + int i = indices[k]; + if (s.compare(i, sources[k].size(), sources[k]) == 0) { + d[i] = k; + } + } + string ans; + for (int i = 0; i < n;) { + if (~d[i]) { + ans += targets[d[i]]; + i += sources[d[i]].size(); + } else { + ans += s[i++]; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0800-0899/0833.Find And Replace in String/Solution.java b/solution/0800-0899/0833.Find And Replace in String/Solution.java index 44314f0d98e4c..3ba88d73a6a20 100644 --- a/solution/0800-0899/0833.Find And Replace in String/Solution.java +++ b/solution/0800-0899/0833.Find And Replace in String/Solution.java @@ -1,23 +1,23 @@ -class Solution { - public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) { - int n = s.length(); - var d = new int[n]; - Arrays.fill(d, -1); - for (int k = 0; k < indices.length; ++k) { - int i = indices[k]; - if (s.startsWith(sources[k], i)) { - d[i] = k; - } - } - var ans = new StringBuilder(); - for (int i = 0; i < n;) { - if (d[i] >= 0) { - ans.append(targets[d[i]]); - i += sources[d[i]].length(); - } else { - ans.append(s.charAt(i++)); - } - } - return ans.toString(); - } +class Solution { + public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) { + int n = s.length(); + var d = new int[n]; + Arrays.fill(d, -1); + for (int k = 0; k < indices.length; ++k) { + int i = indices[k]; + if (s.startsWith(sources[k], i)) { + d[i] = k; + } + } + var ans = new StringBuilder(); + for (int i = 0; i < n;) { + if (d[i] >= 0) { + ans.append(targets[d[i]]); + i += sources[d[i]].length(); + } else { + ans.append(s.charAt(i++)); + } + } + return ans.toString(); + } } \ No newline at end of file diff --git a/solution/0800-0899/0833.Find And Replace in String/Solution.py b/solution/0800-0899/0833.Find And Replace in String/Solution.py index 7c95c39bf65dd..de9ac39a6d9ee 100644 --- a/solution/0800-0899/0833.Find And Replace in String/Solution.py +++ b/solution/0800-0899/0833.Find And Replace in String/Solution.py @@ -1,19 +1,19 @@ -class Solution: - def findReplaceString( - self, s: str, indices: List[int], sources: List[str], targets: List[str] - ) -> str: - n = len(s) - d = [-1] * n - for k, (i, src) in enumerate(zip(indices, sources)): - if s.startswith(src, i): - d[i] = k - ans = [] - i = 0 - while i < n: - if ~d[i]: - ans.append(targets[d[i]]) - i += len(sources[d[i]]) - else: - ans.append(s[i]) - i += 1 - return "".join(ans) +class Solution: + def findReplaceString( + self, s: str, indices: List[int], sources: List[str], targets: List[str] + ) -> str: + n = len(s) + d = [-1] * n + for k, (i, src) in enumerate(zip(indices, sources)): + if s.startswith(src, i): + d[i] = k + ans = [] + i = 0 + while i < n: + if ~d[i]: + ans.append(targets[d[i]]) + i += len(sources[d[i]]) + else: + ans.append(s[i]) + i += 1 + return "".join(ans) diff --git a/solution/0800-0899/0835.Image Overlap/Solution.cpp b/solution/0800-0899/0835.Image Overlap/Solution.cpp index cf72b37614457..d230a7606e595 100644 --- a/solution/0800-0899/0835.Image Overlap/Solution.cpp +++ b/solution/0800-0899/0835.Image Overlap/Solution.cpp @@ -1,22 +1,22 @@ -class Solution { -public: - int largestOverlap(vector>& img1, vector>& img2) { - int n = img1.size(); - map, int> cnt; - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (img1[i][j]) { - for (int h = 0; h < n; ++h) { - for (int k = 0; k < n; ++k) { - if (img2[h][k]) { - ans = max(ans, ++cnt[{i - h, j - k}]); - } - } - } - } - } - } - return ans; - } +class Solution { +public: + int largestOverlap(vector>& img1, vector>& img2) { + int n = img1.size(); + map, int> cnt; + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (img1[i][j]) { + for (int h = 0; h < n; ++h) { + for (int k = 0; k < n; ++k) { + if (img2[h][k]) { + ans = max(ans, ++cnt[{i - h, j - k}]); + } + } + } + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0800-0899/0835.Image Overlap/Solution.java b/solution/0800-0899/0835.Image Overlap/Solution.java index e5e6d85ed7b47..fe5505a6eb1e2 100644 --- a/solution/0800-0899/0835.Image Overlap/Solution.java +++ b/solution/0800-0899/0835.Image Overlap/Solution.java @@ -1,22 +1,22 @@ -class Solution { - public int largestOverlap(int[][] img1, int[][] img2) { - int n = img1.length; - Map, Integer> cnt = new HashMap<>(); - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (img1[i][j] == 1) { - for (int h = 0; h < n; ++h) { - for (int k = 0; k < n; ++k) { - if (img2[h][k] == 1) { - List t = List.of(i - h, j - k); - ans = Math.max(ans, cnt.merge(t, 1, Integer::sum)); - } - } - } - } - } - } - return ans; - } +class Solution { + public int largestOverlap(int[][] img1, int[][] img2) { + int n = img1.length; + Map, Integer> cnt = new HashMap<>(); + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (img1[i][j] == 1) { + for (int h = 0; h < n; ++h) { + for (int k = 0; k < n; ++k) { + if (img2[h][k] == 1) { + List t = List.of(i - h, j - k); + ans = Math.max(ans, cnt.merge(t, 1, Integer::sum)); + } + } + } + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0800-0899/0835.Image Overlap/Solution.py b/solution/0800-0899/0835.Image Overlap/Solution.py index d47b5085204b3..2b64cd97380a2 100644 --- a/solution/0800-0899/0835.Image Overlap/Solution.py +++ b/solution/0800-0899/0835.Image Overlap/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int: - n = len(img1) - cnt = Counter() - for i in range(n): - for j in range(n): - if img1[i][j]: - for h in range(n): - for k in range(n): - if img2[h][k]: - cnt[(i - h, j - k)] += 1 - return max(cnt.values()) if cnt else 0 +class Solution: + def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int: + n = len(img1) + cnt = Counter() + for i in range(n): + for j in range(n): + if img1[i][j]: + for h in range(n): + for k in range(n): + if img2[h][k]: + cnt[(i - h, j - k)] += 1 + return max(cnt.values()) if cnt else 0 diff --git a/solution/0800-0899/0836.Rectangle Overlap/Solution.cpp b/solution/0800-0899/0836.Rectangle Overlap/Solution.cpp index 04554d400ba0e..bf193c5c7d5fb 100644 --- a/solution/0800-0899/0836.Rectangle Overlap/Solution.cpp +++ b/solution/0800-0899/0836.Rectangle Overlap/Solution.cpp @@ -1,4 +1,4 @@ -class Solution { +class Solution { public: bool isRectangleOverlap(vector& rec1, vector& rec2) { int x1 = rec1[0], y1 = rec1[1], x2 = rec1[2], y2 = rec1[3]; diff --git a/solution/0800-0899/0837.New 21 Game/Solution2.cpp b/solution/0800-0899/0837.New 21 Game/Solution2.cpp new file mode 100644 index 0000000000000..bb013714727cd --- /dev/null +++ b/solution/0800-0899/0837.New 21 Game/Solution2.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + double new21Game(int n, int k, int maxPts) { + if (k == 0) { + return 1.0; + } + double f[k + maxPts]; + memset(f, 0, sizeof(f)); + for (int i = k; i < min(n + 1, k + maxPts); ++i) { + f[i] = 1; + } + f[k - 1] = min(n - k + 1, maxPts) * 1.0 / maxPts; + for (int i = k - 2; i >= 0; --i) { + f[i] = f[i + 1] + (f[i + 1] - f[i + maxPts + 1]) / maxPts; + } + return f[0]; + } +}; \ No newline at end of file diff --git a/solution/0800-0899/0837.New 21 Game/Solution2.go b/solution/0800-0899/0837.New 21 Game/Solution2.go new file mode 100644 index 0000000000000..5b3a676345df6 --- /dev/null +++ b/solution/0800-0899/0837.New 21 Game/Solution2.go @@ -0,0 +1,14 @@ +func new21Game(n int, k int, maxPts int) float64 { + if k == 0 { + return 1 + } + f := make([]float64, k+maxPts) + for i := k; i < min(n+1, k+maxPts); i++ { + f[i] = 1 + } + f[k-1] = float64(min(n-k+1, maxPts)) / float64(maxPts) + for i := k - 2; i >= 0; i-- { + f[i] = f[i+1] + (f[i+1]-f[i+maxPts+1])/float64(maxPts) + } + return f[0] +} \ No newline at end of file diff --git a/solution/0800-0899/0837.New 21 Game/Solution2.java b/solution/0800-0899/0837.New 21 Game/Solution2.java new file mode 100644 index 0000000000000..e2349089a968d --- /dev/null +++ b/solution/0800-0899/0837.New 21 Game/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public double new21Game(int n, int k, int maxPts) { + if (k == 0) { + return 1.0; + } + double[] f = new double[k + maxPts]; + for (int i = k; i < Math.min(n + 1, k + maxPts); ++i) { + f[i] = 1; + } + f[k - 1] = Math.min(n - k + 1, maxPts) * 1.0 / maxPts; + for (int i = k - 2; i >= 0; --i) { + f[i] = f[i + 1] + (f[i + 1] - f[i + maxPts + 1]) / maxPts; + } + return f[0]; + } +} \ No newline at end of file diff --git a/solution/0800-0899/0837.New 21 Game/Solution2.py b/solution/0800-0899/0837.New 21 Game/Solution2.py new file mode 100644 index 0000000000000..ad710a36f3e95 --- /dev/null +++ b/solution/0800-0899/0837.New 21 Game/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def new21Game(self, n: int, k: int, maxPts: int) -> float: + f = [0] * (k + maxPts) + for i in range(k, min(n + 1, k + maxPts)): + f[i] = 1 + f[k - 1] = min(n - k + 1, maxPts) / maxPts + for i in range(k - 2, -1, -1): + f[i] = f[i + 1] + (f[i + 1] - f[i + maxPts + 1]) / maxPts + return f[0] diff --git a/solution/0800-0899/0837.New 21 Game/Solution2.ts b/solution/0800-0899/0837.New 21 Game/Solution2.ts new file mode 100644 index 0000000000000..fcaff0f51befd --- /dev/null +++ b/solution/0800-0899/0837.New 21 Game/Solution2.ts @@ -0,0 +1,14 @@ +function new21Game(n: number, k: number, maxPts: number): number { + if (k === 0) { + return 1; + } + const f = new Array(k + maxPts).fill(0); + for (let i = k; i < Math.min(n + 1, k + maxPts); ++i) { + f[i] = 1; + } + f[k - 1] = Math.min(n - k + 1, maxPts) / maxPts; + for (let i = k - 2; i >= 0; --i) { + f[i] = f[i + 1] + (f[i + 1] - f[i + maxPts + 1]) / maxPts; + } + return f[0]; +} diff --git a/solution/0800-0899/0838.Push Dominoes/Solution.java b/solution/0800-0899/0838.Push Dominoes/Solution.java index 0f17e4bced3aa..427e45fa359af 100644 --- a/solution/0800-0899/0838.Push Dominoes/Solution.java +++ b/solution/0800-0899/0838.Push Dominoes/Solution.java @@ -1,4 +1,4 @@ -public class Solution { +class Solution { public String pushDominoes(String dominoes) { int n = dominoes.length(); Deque q = new ArrayDeque<>(); @@ -38,5 +38,4 @@ public String pushDominoes(String dominoes) { } return new String(ans); } -} -class Solution {} +} \ No newline at end of file diff --git a/solution/0800-0899/0839.Similar String Groups/Solution.java b/solution/0800-0899/0839.Similar String Groups/Solution.java index 05d22b0040d32..b0ddcc219b9b5 100644 --- a/solution/0800-0899/0839.Similar String Groups/Solution.java +++ b/solution/0800-0899/0839.Similar String Groups/Solution.java @@ -14,29 +14,30 @@ public int numSimilarGroups(String[] strs) { } } } - int ans = 0; + int res = 0; for (int i = 0; i < n; ++i) { if (i == find(i)) { - ++ans; + ++res; } } - return ans; - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; + return res; } private boolean check(String a, String b) { int cnt = 0; - for (int i = 0; i < a.length(); ++i) { + int n = a.length(); + for (int i = 0; i < n; ++i) { if (a.charAt(i) != b.charAt(i)) { ++cnt; } } return cnt <= 2; } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } } \ No newline at end of file diff --git a/solution/0800-0899/0840.Magic Squares In Grid/Solution.cpp b/solution/0800-0899/0840.Magic Squares In Grid/Solution.cpp index e36bfe37ca06a..4f6f9fa449b7d 100644 --- a/solution/0800-0899/0840.Magic Squares In Grid/Solution.cpp +++ b/solution/0800-0899/0840.Magic Squares In Grid/Solution.cpp @@ -1,48 +1,48 @@ -class Solution { -public: - int numMagicSquaresInside(vector>& grid) { - int m = grid.size(); - int n = grid[0].size(); - int ans = 0; - auto check = [&](int i, int j) { - if (i + 3 > m || j + 3 > n) { - return 0; - } - vector cnt(16); - vector row(3); - vector col(3); - int a = 0, b = 0; - for (int x = i; x < i + 3; ++x) { - for (int y = j; y < j + 3; ++y) { - int v = grid[x][y]; - if (v < 1 || v > 9 || ++cnt[v] > 1) { - return 0; - } - row[x - i] += v; - col[y - j] += v; - if (x - i == y - j) { - a += v; - } - if (x - i + y - j == 2) { - b += v; - } - } - } - if (a != b) { - return 0; - } - for (int k = 0; k < 3; ++k) { - if (row[k] != a || col[k] != a) { - return 0; - } - } - return 1; - }; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - ans += check(i, j); - } - } - return ans; - } +class Solution { +public: + int numMagicSquaresInside(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + int ans = 0; + auto check = [&](int i, int j) { + if (i + 3 > m || j + 3 > n) { + return 0; + } + vector cnt(16); + vector row(3); + vector col(3); + int a = 0, b = 0; + for (int x = i; x < i + 3; ++x) { + for (int y = j; y < j + 3; ++y) { + int v = grid[x][y]; + if (v < 1 || v > 9 || ++cnt[v] > 1) { + return 0; + } + row[x - i] += v; + col[y - j] += v; + if (x - i == y - j) { + a += v; + } + if (x - i + y - j == 2) { + b += v; + } + } + } + if (a != b) { + return 0; + } + for (int k = 0; k < 3; ++k) { + if (row[k] != a || col[k] != a) { + return 0; + } + } + return 1; + }; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans += check(i, j); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0800-0899/0840.Magic Squares In Grid/Solution.java b/solution/0800-0899/0840.Magic Squares In Grid/Solution.java index 11854fb0aec71..3c94e59b595aa 100644 --- a/solution/0800-0899/0840.Magic Squares In Grid/Solution.java +++ b/solution/0800-0899/0840.Magic Squares In Grid/Solution.java @@ -1,53 +1,53 @@ -class Solution { - private int m; - private int n; - private int[][] grid; - - public int numMagicSquaresInside(int[][] grid) { - m = grid.length; - n = grid[0].length; - this.grid = grid; - int ans = 0; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - ans += check(i, j); - } - } - return ans; - } - - private int check(int i, int j) { - if (i + 3 > m || j + 3 > n) { - return 0; - } - int[] cnt = new int[16]; - int[] row = new int[3]; - int[] col = new int[3]; - int a = 0, b = 0; - for (int x = i; x < i + 3; ++x) { - for (int y = j; y < j + 3; ++y) { - int v = grid[x][y]; - if (v < 1 || v > 9 || ++cnt[v] > 1) { - return 0; - } - row[x - i] += v; - col[y - j] += v; - if (x - i == y - j) { - a += v; - } - if (x - i + y - j == 2) { - b += v; - } - } - } - if (a != b) { - return 0; - } - for (int k = 0; k < 3; ++k) { - if (row[k] != a || col[k] != a) { - return 0; - } - } - return 1; - } +class Solution { + private int m; + private int n; + private int[][] grid; + + public int numMagicSquaresInside(int[][] grid) { + m = grid.length; + n = grid[0].length; + this.grid = grid; + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans += check(i, j); + } + } + return ans; + } + + private int check(int i, int j) { + if (i + 3 > m || j + 3 > n) { + return 0; + } + int[] cnt = new int[16]; + int[] row = new int[3]; + int[] col = new int[3]; + int a = 0, b = 0; + for (int x = i; x < i + 3; ++x) { + for (int y = j; y < j + 3; ++y) { + int v = grid[x][y]; + if (v < 1 || v > 9 || ++cnt[v] > 1) { + return 0; + } + row[x - i] += v; + col[y - j] += v; + if (x - i == y - j) { + a += v; + } + if (x - i + y - j == 2) { + b += v; + } + } + } + if (a != b) { + return 0; + } + for (int k = 0; k < 3; ++k) { + if (row[k] != a || col[k] != a) { + return 0; + } + } + return 1; + } } \ No newline at end of file diff --git a/solution/0800-0899/0840.Magic Squares In Grid/Solution.py b/solution/0800-0899/0840.Magic Squares In Grid/Solution.py index 056374b345425..147a40381636a 100644 --- a/solution/0800-0899/0840.Magic Squares In Grid/Solution.py +++ b/solution/0800-0899/0840.Magic Squares In Grid/Solution.py @@ -1,29 +1,29 @@ -class Solution: - def numMagicSquaresInside(self, grid: List[List[int]]) -> int: - def check(i: int, j: int) -> int: - if i + 3 > m or j + 3 > n: - return 0 - s = set() - row = [0] * 3 - col = [0] * 3 - a = b = 0 - for x in range(i, i + 3): - for y in range(j, j + 3): - v = grid[x][y] - if v < 1 or v > 9: - return 0 - s.add(v) - row[x - i] += v - col[y - j] += v - if x - i == y - j: - a += v - if x - i == 2 - (y - j): - b += v - if len(s) != 9 or a != b: - return 0 - if any(x != a for x in row) or any(x != a for x in col): - return 0 - return 1 - - m, n = len(grid), len(grid[0]) - return sum(check(i, j) for i in range(m) for j in range(n)) +class Solution: + def numMagicSquaresInside(self, grid: List[List[int]]) -> int: + def check(i: int, j: int) -> int: + if i + 3 > m or j + 3 > n: + return 0 + s = set() + row = [0] * 3 + col = [0] * 3 + a = b = 0 + for x in range(i, i + 3): + for y in range(j, j + 3): + v = grid[x][y] + if v < 1 or v > 9: + return 0 + s.add(v) + row[x - i] += v + col[y - j] += v + if x - i == y - j: + a += v + if x - i == 2 - (y - j): + b += v + if len(s) != 9 or a != b: + return 0 + if any(x != a for x in row) or any(x != a for x in col): + return 0 + return 1 + + m, n = len(grid), len(grid[0]) + return sum(check(i, j) for i in range(m) for j in range(n)) diff --git a/solution/0800-0899/0841.Keys and Rooms/Solution.ts b/solution/0800-0899/0841.Keys and Rooms/Solution.ts index 613a3c81b64d4..86e8caaeae2c7 100644 --- a/solution/0800-0899/0841.Keys and Rooms/Solution.ts +++ b/solution/0800-0899/0841.Keys and Rooms/Solution.ts @@ -1,14 +1,13 @@ function canVisitAllRooms(rooms: number[][]): boolean { const n = rooms.length; const isOpen = new Array(n).fill(false); - const keys = [0]; - while (keys.length !== 0) { - const i = keys.pop(); + const dfs = (i: number) => { if (isOpen[i]) { - continue; + return; } isOpen[i] = true; - keys.push(...rooms[i]); - } + rooms[i].forEach(k => dfs(k)); + }; + dfs(0); return isOpen.every(v => v); } diff --git a/solution/0800-0899/0841.Keys and Rooms/Solution2.ts b/solution/0800-0899/0841.Keys and Rooms/Solution2.ts new file mode 100644 index 0000000000000..613a3c81b64d4 --- /dev/null +++ b/solution/0800-0899/0841.Keys and Rooms/Solution2.ts @@ -0,0 +1,14 @@ +function canVisitAllRooms(rooms: number[][]): boolean { + const n = rooms.length; + const isOpen = new Array(n).fill(false); + const keys = [0]; + while (keys.length !== 0) { + const i = keys.pop(); + if (isOpen[i]) { + continue; + } + isOpen[i] = true; + keys.push(...rooms[i]); + } + return isOpen.every(v => v); +} diff --git a/solution/0800-0899/0845.Longest Mountain in Array/Solution.cpp b/solution/0800-0899/0845.Longest Mountain in Array/Solution.cpp index bb2ab57a7d962..995d9c80bdd0a 100644 --- a/solution/0800-0899/0845.Longest Mountain in Array/Solution.cpp +++ b/solution/0800-0899/0845.Longest Mountain in Array/Solution.cpp @@ -2,20 +2,21 @@ class Solution { public: int longestMountain(vector& arr) { int n = arr.size(); + int f[n]; + int g[n]; + fill(f, f + n, 1); + fill(g, g + n, 1); + for (int i = 1; i < n; ++i) { + if (arr[i] > arr[i - 1]) { + f[i] = f[i - 1] + 1; + } + } int ans = 0; - for (int l = 0, r = 0; l + 2 < n; l = r) { - r = l + 1; - if (arr[l] < arr[r]) { - while (r + 1 < n && arr[r] < arr[r + 1]) { - ++r; - } - if (r + 1 < n && arr[r] > arr[r + 1]) { - while (r + 1 < n && arr[r] > arr[r + 1]) { - ++r; - } - ans = max(ans, r - l + 1); - } else { - ++r; + for (int i = n - 2; ~i; --i) { + if (arr[i] > arr[i + 1]) { + g[i] = g[i + 1] + 1; + if (f[i] > 1) { + ans = max(ans, f[i] + g[i] - 1); } } } diff --git a/solution/0800-0899/0845.Longest Mountain in Array/Solution.go b/solution/0800-0899/0845.Longest Mountain in Array/Solution.go index 8a72def3c1dfd..ebc9e189caf4a 100644 --- a/solution/0800-0899/0845.Longest Mountain in Array/Solution.go +++ b/solution/0800-0899/0845.Longest Mountain in Array/Solution.go @@ -1,18 +1,21 @@ func longestMountain(arr []int) (ans int) { n := len(arr) - for l, r := 0, 0; l+2 < n; l = r { - r = l + 1 - if arr[l] < arr[r] { - for r+1 < n && arr[r] < arr[r+1] { - r++ - } - if r+1 < n && arr[r] > arr[r+1] { - for r+1 < n && arr[r] > arr[r+1] { - r++ - } - ans = max(ans, r-l+1) - } else { - r++ + f := make([]int, n) + g := make([]int, n) + for i := range f { + f[i] = 1 + g[i] = 1 + } + for i := 1; i < n; i++ { + if arr[i] > arr[i-1] { + f[i] = f[i-1] + 1 + } + } + for i := n - 2; i >= 0; i-- { + if arr[i] > arr[i+1] { + g[i] = g[i+1] + 1 + if f[i] > 1 { + ans = max(ans, f[i]+g[i]-1) } } } diff --git a/solution/0800-0899/0845.Longest Mountain in Array/Solution.java b/solution/0800-0899/0845.Longest Mountain in Array/Solution.java index 491465e01fb2c..767c68363b2d6 100644 --- a/solution/0800-0899/0845.Longest Mountain in Array/Solution.java +++ b/solution/0800-0899/0845.Longest Mountain in Array/Solution.java @@ -1,20 +1,21 @@ class Solution { public int longestMountain(int[] arr) { int n = arr.length; + int[] f = new int[n]; + int[] g = new int[n]; + Arrays.fill(f, 1); + Arrays.fill(g, 1); + for (int i = 1; i < n; ++i) { + if (arr[i] > arr[i - 1]) { + f[i] = f[i - 1] + 1; + } + } int ans = 0; - for (int l = 0, r = 0; l + 2 < n; l = r) { - r = l + 1; - if (arr[l] < arr[r]) { - while (r + 1 < n && arr[r] < arr[r + 1]) { - ++r; - } - if (r + 1 < n && arr[r] > arr[r + 1]) { - while (r + 1 < n && arr[r] > arr[r + 1]) { - ++r; - } - ans = Math.max(ans, r - l + 1); - } else { - ++r; + for (int i = n - 2; i >= 0; --i) { + if (arr[i] > arr[i + 1]) { + g[i] = g[i + 1] + 1; + if (f[i] > 1) { + ans = Math.max(ans, f[i] + g[i] - 1); } } } diff --git a/solution/0800-0899/0845.Longest Mountain in Array/Solution.py b/solution/0800-0899/0845.Longest Mountain in Array/Solution.py index 8acfa6712ddae..5ecf2addb0224 100644 --- a/solution/0800-0899/0845.Longest Mountain in Array/Solution.py +++ b/solution/0800-0899/0845.Longest Mountain in Array/Solution.py @@ -1,17 +1,15 @@ class Solution: def longestMountain(self, arr: List[int]) -> int: n = len(arr) - ans = l = 0 - while l + 2 < n: - r = l + 1 - if arr[l] < arr[r]: - while r + 1 < n and arr[r] < arr[r + 1]: - r += 1 - if r < n - 1 and arr[r] > arr[r + 1]: - while r < n - 1 and arr[r] > arr[r + 1]: - r += 1 - ans = max(ans, r - l + 1) - else: - r += 1 - l = r + f = [1] * n + g = [1] * n + for i in range(1, n): + if arr[i] > arr[i - 1]: + f[i] = f[i - 1] + 1 + ans = 0 + for i in range(n - 2, -1, -1): + if arr[i] > arr[i + 1]: + g[i] = g[i + 1] + 1 + if f[i] > 1: + ans = max(ans, f[i] + g[i] - 1) return ans diff --git a/solution/0800-0899/0845.Longest Mountain in Array/Solution2.cpp b/solution/0800-0899/0845.Longest Mountain in Array/Solution2.cpp new file mode 100644 index 0000000000000..bb2ab57a7d962 --- /dev/null +++ b/solution/0800-0899/0845.Longest Mountain in Array/Solution2.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int longestMountain(vector& arr) { + int n = arr.size(); + int ans = 0; + for (int l = 0, r = 0; l + 2 < n; l = r) { + r = l + 1; + if (arr[l] < arr[r]) { + while (r + 1 < n && arr[r] < arr[r + 1]) { + ++r; + } + if (r + 1 < n && arr[r] > arr[r + 1]) { + while (r + 1 < n && arr[r] > arr[r + 1]) { + ++r; + } + ans = max(ans, r - l + 1); + } else { + ++r; + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0800-0899/0845.Longest Mountain in Array/Solution2.go b/solution/0800-0899/0845.Longest Mountain in Array/Solution2.go new file mode 100644 index 0000000000000..8a72def3c1dfd --- /dev/null +++ b/solution/0800-0899/0845.Longest Mountain in Array/Solution2.go @@ -0,0 +1,20 @@ +func longestMountain(arr []int) (ans int) { + n := len(arr) + for l, r := 0, 0; l+2 < n; l = r { + r = l + 1 + if arr[l] < arr[r] { + for r+1 < n && arr[r] < arr[r+1] { + r++ + } + if r+1 < n && arr[r] > arr[r+1] { + for r+1 < n && arr[r] > arr[r+1] { + r++ + } + ans = max(ans, r-l+1) + } else { + r++ + } + } + } + return +} \ No newline at end of file diff --git a/solution/0800-0899/0845.Longest Mountain in Array/Solution2.java b/solution/0800-0899/0845.Longest Mountain in Array/Solution2.java new file mode 100644 index 0000000000000..491465e01fb2c --- /dev/null +++ b/solution/0800-0899/0845.Longest Mountain in Array/Solution2.java @@ -0,0 +1,23 @@ +class Solution { + public int longestMountain(int[] arr) { + int n = arr.length; + int ans = 0; + for (int l = 0, r = 0; l + 2 < n; l = r) { + r = l + 1; + if (arr[l] < arr[r]) { + while (r + 1 < n && arr[r] < arr[r + 1]) { + ++r; + } + if (r + 1 < n && arr[r] > arr[r + 1]) { + while (r + 1 < n && arr[r] > arr[r + 1]) { + ++r; + } + ans = Math.max(ans, r - l + 1); + } else { + ++r; + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0800-0899/0845.Longest Mountain in Array/Solution2.py b/solution/0800-0899/0845.Longest Mountain in Array/Solution2.py new file mode 100644 index 0000000000000..8acfa6712ddae --- /dev/null +++ b/solution/0800-0899/0845.Longest Mountain in Array/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def longestMountain(self, arr: List[int]) -> int: + n = len(arr) + ans = l = 0 + while l + 2 < n: + r = l + 1 + if arr[l] < arr[r]: + while r + 1 < n and arr[r] < arr[r + 1]: + r += 1 + if r < n - 1 and arr[r] > arr[r + 1]: + while r < n - 1 and arr[r] > arr[r + 1]: + r += 1 + ans = max(ans, r - l + 1) + else: + r += 1 + l = r + return ans diff --git a/solution/0800-0899/0846.Hand of Straights/Solution2.cpp b/solution/0800-0899/0846.Hand of Straights/Solution2.cpp new file mode 100644 index 0000000000000..d36a24b98490c --- /dev/null +++ b/solution/0800-0899/0846.Hand of Straights/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + bool isNStraightHand(vector& hand, int groupSize) { + if (hand.size() % groupSize != 0) return false; + map mp; + for (int& h : hand) mp[h] += 1; + while (!mp.empty()) { + int v = mp.begin()->first; + for (int i = v; i < v + groupSize; ++i) { + if (!mp.count(i)) return false; + if (mp[i] == 1) + mp.erase(i); + else + mp[i] -= 1; + } + } + return true; + } +}; \ No newline at end of file diff --git a/solution/0800-0899/0846.Hand of Straights/Solution2.go b/solution/0800-0899/0846.Hand of Straights/Solution2.go new file mode 100644 index 0000000000000..d364408ceb4c5 --- /dev/null +++ b/solution/0800-0899/0846.Hand of Straights/Solution2.go @@ -0,0 +1,27 @@ +func isNStraightHand(hand []int, groupSize int) bool { + if len(hand)%groupSize != 0 { + return false + } + m := treemap.NewWithIntComparator() + for _, h := range hand { + if v, ok := m.Get(h); ok { + m.Put(h, v.(int)+1) + } else { + m.Put(h, 1) + } + } + for !m.Empty() { + v, _ := m.Min() + for i := v.(int); i < v.(int)+groupSize; i++ { + if _, ok := m.Get(i); !ok { + return false + } + if v, _ := m.Get(i); v.(int) == 1 { + m.Remove(i) + } else { + m.Put(i, v.(int)-1) + } + } + } + return true +} \ No newline at end of file diff --git a/solution/0800-0899/0846.Hand of Straights/Solution2.java b/solution/0800-0899/0846.Hand of Straights/Solution2.java new file mode 100644 index 0000000000000..5f8bcca97a56c --- /dev/null +++ b/solution/0800-0899/0846.Hand of Straights/Solution2.java @@ -0,0 +1,25 @@ +class Solution { + public boolean isNStraightHand(int[] hand, int groupSize) { + if (hand.length % groupSize != 0) { + return false; + } + TreeMap tm = new TreeMap<>(); + for (int h : hand) { + tm.put(h, tm.getOrDefault(h, 0) + 1); + } + while (!tm.isEmpty()) { + int v = tm.firstKey(); + for (int i = v; i < v + groupSize; ++i) { + if (!tm.containsKey(i)) { + return false; + } + if (tm.get(i) == 1) { + tm.remove(i); + } else { + tm.put(i, tm.get(i) - 1); + } + } + } + return true; + } +} \ No newline at end of file diff --git a/solution/0800-0899/0846.Hand of Straights/Solution2.py b/solution/0800-0899/0846.Hand of Straights/Solution2.py new file mode 100644 index 0000000000000..09f7e6d10e146 --- /dev/null +++ b/solution/0800-0899/0846.Hand of Straights/Solution2.py @@ -0,0 +1,23 @@ +from sortedcontainers import SortedDict + + +class Solution: + def isNStraightHand(self, hand: List[int], groupSize: int) -> bool: + if len(hand) % groupSize != 0: + return False + sd = SortedDict() + for h in hand: + if h in sd: + sd[h] += 1 + else: + sd[h] = 1 + while sd: + v = sd.peekitem(0)[0] + for i in range(v, v + groupSize): + if i not in sd: + return False + if sd[i] == 1: + sd.pop(i) + else: + sd[i] -= 1 + return True diff --git a/solution/0800-0899/0847.Shortest Path Visiting All Nodes/Solution2.cpp b/solution/0800-0899/0847.Shortest Path Visiting All Nodes/Solution2.cpp new file mode 100644 index 0000000000000..371f536ceb441 --- /dev/null +++ b/solution/0800-0899/0847.Shortest Path Visiting All Nodes/Solution2.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int n; + + int shortestPathLength(vector>& graph) { + n = graph.size(); + priority_queue, vector>, greater>> q; + vector> dist(n, vector(1 << n, INT_MAX)); + for (int i = 0; i < n; ++i) { + q.push({f(1 << i), i, 1 << i}); + dist[i][1 << i] = 0; + } + while (!q.empty()) { + auto [_, u, state] = q.top(); + q.pop(); + if (state == (1 << n) - 1) return dist[u][state]; + for (int v : graph[u]) { + int nxt = state | (1 << v); + if (dist[v][nxt] > dist[u][state] + 1) { + dist[v][nxt] = dist[u][state] + 1; + q.push({dist[v][nxt] + f(nxt), v, nxt}); + } + } + } + return 0; + } + + int f(int state) { + int ans = 0; + for (int i = 0; i < n; ++i) + if (((state >> i) & 1) == 0) + ++ans; + return ans; + } +}; \ No newline at end of file diff --git a/solution/0800-0899/0847.Shortest Path Visiting All Nodes/Solution2.java b/solution/0800-0899/0847.Shortest Path Visiting All Nodes/Solution2.java new file mode 100644 index 0000000000000..f43201ca87d5f --- /dev/null +++ b/solution/0800-0899/0847.Shortest Path Visiting All Nodes/Solution2.java @@ -0,0 +1,41 @@ +class Solution { + private int n; + + public int shortestPathLength(int[][] graph) { + n = graph.length; + int[][] dist = new int[n][1 << n]; + for (int i = 0; i < n; ++i) { + Arrays.fill(dist[i], Integer.MAX_VALUE); + } + PriorityQueue q = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); + for (int i = 0; i < n; ++i) { + q.offer(new int[] {f(1 << i), i, 1 << i}); + dist[i][1 << i] = 0; + } + while (!q.isEmpty()) { + int[] p = q.poll(); + int u = p[1], state = p[2]; + if (state == (1 << n) - 1) { + return dist[u][state]; + } + for (int v : graph[u]) { + int nxt = state | (1 << v); + if (dist[v][nxt] > dist[u][state] + 1) { + dist[v][nxt] = dist[u][state] + 1; + q.offer(new int[] {dist[v][nxt] + f(nxt), v, nxt}); + } + } + } + return 0; + } + + private int f(int state) { + int ans = 0; + for (int i = 0; i < n; ++i) { + if (((state >> i) & 1) == 0) { + ++ans; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0800-0899/0847.Shortest Path Visiting All Nodes/Solution2.py b/solution/0800-0899/0847.Shortest Path Visiting All Nodes/Solution2.py new file mode 100644 index 0000000000000..956181d46ad01 --- /dev/null +++ b/solution/0800-0899/0847.Shortest Path Visiting All Nodes/Solution2.py @@ -0,0 +1,22 @@ +class Solution: + def shortestPathLength(self, graph: List[List[int]]) -> int: + n = len(graph) + + def f(state): + return sum(((state >> i) & 1) == 0 for i in range(n)) + + q = [] + dist = [[inf] * (1 << n) for _ in range(n)] + for i in range(n): + heappush(q, (f(1 << i), i, 1 << i)) + dist[i][1 << i] = 0 + while q: + _, u, state = heappop(q) + if state == (1 << n) - 1: + return dist[u][state] + for v in graph[u]: + nxt = state | (1 << v) + if dist[v][nxt] > dist[u][state] + 1: + dist[v][nxt] = dist[u][state] + 1 + heappush(q, (dist[v][nxt] + f(nxt), v, nxt)) + return 0 diff --git a/solution/0800-0899/0848.Shifting Letters/Solution.py b/solution/0800-0899/0848.Shifting Letters/Solution.py index 24835fc8e6a8e..f0e0e8f174153 100644 --- a/solution/0800-0899/0848.Shifting Letters/Solution.py +++ b/solution/0800-0899/0848.Shifting Letters/Solution.py @@ -1,9 +1,18 @@ class Solution: def shiftingLetters(self, s: str, shifts: List[int]) -> str: - n, t = len(s), 0 - s = list(s) - for i in range(n - 1, -1, -1): - t += shifts[i] - j = (ord(s[i]) - ord('a') + t) % 26 - s[i] = ascii_lowercase[j] - return ''.join(s) + n = len(s) + d = [0] * (n + 1) + for i, c in enumerate(s): + v = ord(c) - ord('a') + d[i] += v + d[i + 1] -= v + for i, x in enumerate(shifts): + d[0] += x + d[i + 1] -= x + t = 0 + ans = [] + for i in range(n): + d[i] %= 26 + ans.append(ascii_lowercase[d[i]]) + d[i + 1] += d[i] + return ''.join(ans) diff --git a/solution/0800-0899/0848.Shifting Letters/Solution2.py b/solution/0800-0899/0848.Shifting Letters/Solution2.py new file mode 100644 index 0000000000000..24835fc8e6a8e --- /dev/null +++ b/solution/0800-0899/0848.Shifting Letters/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def shiftingLetters(self, s: str, shifts: List[int]) -> str: + n, t = len(s), 0 + s = list(s) + for i in range(n - 1, -1, -1): + t += shifts[i] + j = (ord(s[i]) - ord('a') + t) % 26 + s[i] = ascii_lowercase[j] + return ''.join(s) diff --git a/solution/0800-0899/0850.Rectangle Area II/Solution.cpp b/solution/0800-0899/0850.Rectangle Area II/Solution.cpp index 71b0f78890afb..1fb0310865e89 100644 --- a/solution/0800-0899/0850.Rectangle Area II/Solution.cpp +++ b/solution/0800-0899/0850.Rectangle Area II/Solution.cpp @@ -1,86 +1,86 @@ -class Node { -public: - int l, r, cnt, length; -}; - -class SegmentTree { -public: - vector tr; - vector nums; - - SegmentTree(vector& nums) { - this->nums = nums; - int n = nums.size() - 1; - tr.resize(n << 2); - for (int i = 0; i < tr.size(); ++i) tr[i] = new Node(); - build(1, 0, n - 1); - } - - void build(int u, int l, int r) { - tr[u]->l = l; - tr[u]->r = r; - if (l != r) { - int mid = (l + r) >> 1; - build(u << 1, l, mid); - build(u << 1 | 1, mid + 1, r); - } - } - - void modify(int u, int l, int r, int k) { - if (tr[u]->l >= l && tr[u]->r <= r) - tr[u]->cnt += k; - else { - int mid = (tr[u]->l + tr[u]->r) >> 1; - if (l <= mid) modify(u << 1, l, r, k); - if (r > mid) modify(u << 1 | 1, l, r, k); - } - pushup(u); - } - - int query() { - return tr[1]->length; - } - - void pushup(int u) { - if (tr[u]->cnt) - tr[u]->length = nums[tr[u]->r + 1] - nums[tr[u]->l]; - else if (tr[u]->l == tr[u]->r) - tr[u]->length = 0; - else - tr[u]->length = tr[u << 1]->length + tr[u << 1 | 1]->length; - } -}; - -class Solution { -public: - const int mod = 1e9 + 7; - - int rectangleArea(vector>& rectangles) { - int n = rectangles.size(); - vector> segs(n << 1); - set ts; - int i = 0; - for (auto& e : rectangles) { - int x1 = e[0], y1 = e[1], x2 = e[2], y2 = e[3]; - segs[i++] = {x1, y1, y2, 1}; - segs[i++] = {x2, y1, y2, -1}; - ts.insert(y1); - ts.insert(y2); - } - sort(segs.begin(), segs.end()); - unordered_map m; - i = 0; - for (int v : ts) m[v] = i++; - vector nums(ts.begin(), ts.end()); - SegmentTree* tree = new SegmentTree(nums); - long long ans = 0; - for (int i = 0; i < segs.size(); ++i) { - auto e = segs[i]; - int x = e[0], y1 = e[1], y2 = e[2], k = e[3]; - if (i > 0) ans += (long long) tree->query() * (x - segs[i - 1][0]); - tree->modify(1, m[y1], m[y2] - 1, k); - } - ans %= mod; - return (int) ans; - } +class Node { +public: + int l, r, cnt, length; +}; + +class SegmentTree { +public: + vector tr; + vector nums; + + SegmentTree(vector& nums) { + this->nums = nums; + int n = nums.size() - 1; + tr.resize(n << 2); + for (int i = 0; i < tr.size(); ++i) tr[i] = new Node(); + build(1, 0, n - 1); + } + + void build(int u, int l, int r) { + tr[u]->l = l; + tr[u]->r = r; + if (l != r) { + int mid = (l + r) >> 1; + build(u << 1, l, mid); + build(u << 1 | 1, mid + 1, r); + } + } + + void modify(int u, int l, int r, int k) { + if (tr[u]->l >= l && tr[u]->r <= r) + tr[u]->cnt += k; + else { + int mid = (tr[u]->l + tr[u]->r) >> 1; + if (l <= mid) modify(u << 1, l, r, k); + if (r > mid) modify(u << 1 | 1, l, r, k); + } + pushup(u); + } + + int query() { + return tr[1]->length; + } + + void pushup(int u) { + if (tr[u]->cnt) + tr[u]->length = nums[tr[u]->r + 1] - nums[tr[u]->l]; + else if (tr[u]->l == tr[u]->r) + tr[u]->length = 0; + else + tr[u]->length = tr[u << 1]->length + tr[u << 1 | 1]->length; + } +}; + +class Solution { +public: + const int mod = 1e9 + 7; + + int rectangleArea(vector>& rectangles) { + int n = rectangles.size(); + vector> segs(n << 1); + set ts; + int i = 0; + for (auto& e : rectangles) { + int x1 = e[0], y1 = e[1], x2 = e[2], y2 = e[3]; + segs[i++] = {x1, y1, y2, 1}; + segs[i++] = {x2, y1, y2, -1}; + ts.insert(y1); + ts.insert(y2); + } + sort(segs.begin(), segs.end()); + unordered_map m; + i = 0; + for (int v : ts) m[v] = i++; + vector nums(ts.begin(), ts.end()); + SegmentTree* tree = new SegmentTree(nums); + long long ans = 0; + for (int i = 0; i < segs.size(); ++i) { + auto e = segs[i]; + int x = e[0], y1 = e[1], y2 = e[2], k = e[3]; + if (i > 0) ans += (long long) tree->query() * (x - segs[i - 1][0]); + tree->modify(1, m[y1], m[y2] - 1, k); + } + ans %= mod; + return (int) ans; + } }; \ No newline at end of file diff --git a/solution/0800-0899/0850.Rectangle Area II/Solution.java b/solution/0800-0899/0850.Rectangle Area II/Solution.java index ce41032b8b5c7..8e1466819f8e3 100644 --- a/solution/0800-0899/0850.Rectangle Area II/Solution.java +++ b/solution/0800-0899/0850.Rectangle Area II/Solution.java @@ -1,96 +1,96 @@ -class Node { - int l, r, cnt, length; -} - -class SegmentTree { - private Node[] tr; - private int[] nums; - - public SegmentTree(int[] nums) { - this.nums = nums; - int n = nums.length - 1; - tr = new Node[n << 2]; - for (int i = 0; i < tr.length; ++i) { - tr[i] = new Node(); - } - build(1, 0, n - 1); - } - - private void build(int u, int l, int r) { - tr[u].l = l; - tr[u].r = r; - if (l != r) { - int mid = (l + r) >> 1; - build(u << 1, l, mid); - build(u << 1 | 1, mid + 1, r); - } - } - - public void modify(int u, int l, int r, int k) { - if (tr[u].l >= l && tr[u].r <= r) { - tr[u].cnt += k; - } else { - int mid = (tr[u].l + tr[u].r) >> 1; - if (l <= mid) { - modify(u << 1, l, r, k); - } - if (r > mid) { - modify(u << 1 | 1, l, r, k); - } - } - pushup(u); - } - - private void pushup(int u) { - if (tr[u].cnt > 0) { - tr[u].length = nums[tr[u].r + 1] - nums[tr[u].l]; - } else if (tr[u].l == tr[u].r) { - tr[u].length = 0; - } else { - tr[u].length = tr[u << 1].length + tr[u << 1 | 1].length; - } - } - - public int query() { - return tr[1].length; - } -} - -class Solution { - private static final int MOD = (int) 1e9 + 7; - - public int rectangleArea(int[][] rectangles) { - int n = rectangles.length; - int[][] segs = new int[n << 1][4]; - int i = 0; - TreeSet ts = new TreeSet<>(); - for (var e : rectangles) { - int x1 = e[0], y1 = e[1], x2 = e[2], y2 = e[3]; - segs[i++] = new int[] {x1, y1, y2, 1}; - segs[i++] = new int[] {x2, y1, y2, -1}; - ts.add(y1); - ts.add(y2); - } - Arrays.sort(segs, (a, b) -> a[0] - b[0]); - Map m = new HashMap<>(ts.size()); - i = 0; - int[] nums = new int[ts.size()]; - for (int v : ts) { - m.put(v, i); - nums[i++] = v; - } - - SegmentTree tree = new SegmentTree(nums); - long ans = 0; - for (i = 0; i < segs.length; ++i) { - var e = segs[i]; - int x = e[0], y1 = e[1], y2 = e[2], k = e[3]; - if (i > 0) { - ans += (long) tree.query() * (x - segs[i - 1][0]); - } - tree.modify(1, m.get(y1), m.get(y2) - 1, k); - } - ans %= MOD; - return (int) ans; - } +class Node { + int l, r, cnt, length; +} + +class SegmentTree { + private Node[] tr; + private int[] nums; + + public SegmentTree(int[] nums) { + this.nums = nums; + int n = nums.length - 1; + tr = new Node[n << 2]; + for (int i = 0; i < tr.length; ++i) { + tr[i] = new Node(); + } + build(1, 0, n - 1); + } + + private void build(int u, int l, int r) { + tr[u].l = l; + tr[u].r = r; + if (l != r) { + int mid = (l + r) >> 1; + build(u << 1, l, mid); + build(u << 1 | 1, mid + 1, r); + } + } + + public void modify(int u, int l, int r, int k) { + if (tr[u].l >= l && tr[u].r <= r) { + tr[u].cnt += k; + } else { + int mid = (tr[u].l + tr[u].r) >> 1; + if (l <= mid) { + modify(u << 1, l, r, k); + } + if (r > mid) { + modify(u << 1 | 1, l, r, k); + } + } + pushup(u); + } + + private void pushup(int u) { + if (tr[u].cnt > 0) { + tr[u].length = nums[tr[u].r + 1] - nums[tr[u].l]; + } else if (tr[u].l == tr[u].r) { + tr[u].length = 0; + } else { + tr[u].length = tr[u << 1].length + tr[u << 1 | 1].length; + } + } + + public int query() { + return tr[1].length; + } +} + +class Solution { + private static final int MOD = (int) 1e9 + 7; + + public int rectangleArea(int[][] rectangles) { + int n = rectangles.length; + int[][] segs = new int[n << 1][4]; + int i = 0; + TreeSet ts = new TreeSet<>(); + for (var e : rectangles) { + int x1 = e[0], y1 = e[1], x2 = e[2], y2 = e[3]; + segs[i++] = new int[] {x1, y1, y2, 1}; + segs[i++] = new int[] {x2, y1, y2, -1}; + ts.add(y1); + ts.add(y2); + } + Arrays.sort(segs, (a, b) -> a[0] - b[0]); + Map m = new HashMap<>(ts.size()); + i = 0; + int[] nums = new int[ts.size()]; + for (int v : ts) { + m.put(v, i); + nums[i++] = v; + } + + SegmentTree tree = new SegmentTree(nums); + long ans = 0; + for (i = 0; i < segs.length; ++i) { + var e = segs[i]; + int x = e[0], y1 = e[1], y2 = e[2], k = e[3]; + if (i > 0) { + ans += (long) tree.query() * (x - segs[i - 1][0]); + } + tree.modify(1, m.get(y1), m.get(y2) - 1, k); + } + ans %= MOD; + return (int) ans; + } } \ No newline at end of file diff --git a/solution/0800-0899/0850.Rectangle Area II/Solution.py b/solution/0800-0899/0850.Rectangle Area II/Solution.py index 1d133b7001e52..88b6327ee597e 100644 --- a/solution/0800-0899/0850.Rectangle Area II/Solution.py +++ b/solution/0800-0899/0850.Rectangle Area II/Solution.py @@ -1,64 +1,64 @@ -class Node: - def __init__(self): - self.l = self.r = 0 - self.cnt = self.length = 0 - - -class SegmentTree: - def __init__(self, nums): - n = len(nums) - 1 - self.nums = nums - self.tr = [Node() for _ in range(n << 2)] - self.build(1, 0, n - 1) - - def build(self, u, l, r): - self.tr[u].l, self.tr[u].r = l, r - if l != r: - mid = (l + r) >> 1 - self.build(u << 1, l, mid) - self.build(u << 1 | 1, mid + 1, r) - - def modify(self, u, l, r, k): - if self.tr[u].l >= l and self.tr[u].r <= r: - self.tr[u].cnt += k - else: - mid = (self.tr[u].l + self.tr[u].r) >> 1 - if l <= mid: - self.modify(u << 1, l, r, k) - if r > mid: - self.modify(u << 1 | 1, l, r, k) - self.pushup(u) - - def pushup(self, u): - if self.tr[u].cnt: - self.tr[u].length = self.nums[self.tr[u].r + 1] - self.nums[self.tr[u].l] - elif self.tr[u].l == self.tr[u].r: - self.tr[u].length = 0 - else: - self.tr[u].length = self.tr[u << 1].length + self.tr[u << 1 | 1].length - - @property - def length(self): - return self.tr[1].length - - -class Solution: - def rectangleArea(self, rectangles: List[List[int]]) -> int: - segs = [] - alls = set() - for x1, y1, x2, y2 in rectangles: - segs.append((x1, y1, y2, 1)) - segs.append((x2, y1, y2, -1)) - alls.update([y1, y2]) - - segs.sort() - alls = sorted(alls) - tree = SegmentTree(alls) - m = {v: i for i, v in enumerate(alls)} - ans = 0 - for i, (x, y1, y2, k) in enumerate(segs): - if i: - ans += tree.length * (x - segs[i - 1][0]) - tree.modify(1, m[y1], m[y2] - 1, k) - ans %= int(1e9 + 7) - return ans +class Node: + def __init__(self): + self.l = self.r = 0 + self.cnt = self.length = 0 + + +class SegmentTree: + def __init__(self, nums): + n = len(nums) - 1 + self.nums = nums + self.tr = [Node() for _ in range(n << 2)] + self.build(1, 0, n - 1) + + def build(self, u, l, r): + self.tr[u].l, self.tr[u].r = l, r + if l != r: + mid = (l + r) >> 1 + self.build(u << 1, l, mid) + self.build(u << 1 | 1, mid + 1, r) + + def modify(self, u, l, r, k): + if self.tr[u].l >= l and self.tr[u].r <= r: + self.tr[u].cnt += k + else: + mid = (self.tr[u].l + self.tr[u].r) >> 1 + if l <= mid: + self.modify(u << 1, l, r, k) + if r > mid: + self.modify(u << 1 | 1, l, r, k) + self.pushup(u) + + def pushup(self, u): + if self.tr[u].cnt: + self.tr[u].length = self.nums[self.tr[u].r + 1] - self.nums[self.tr[u].l] + elif self.tr[u].l == self.tr[u].r: + self.tr[u].length = 0 + else: + self.tr[u].length = self.tr[u << 1].length + self.tr[u << 1 | 1].length + + @property + def length(self): + return self.tr[1].length + + +class Solution: + def rectangleArea(self, rectangles: List[List[int]]) -> int: + segs = [] + alls = set() + for x1, y1, x2, y2 in rectangles: + segs.append((x1, y1, y2, 1)) + segs.append((x2, y1, y2, -1)) + alls.update([y1, y2]) + + segs.sort() + alls = sorted(alls) + tree = SegmentTree(alls) + m = {v: i for i, v in enumerate(alls)} + ans = 0 + for i, (x, y1, y2, k) in enumerate(segs): + if i: + ans += tree.length * (x - segs[i - 1][0]) + tree.modify(1, m[y1], m[y2] - 1, k) + ans %= int(1e9 + 7) + return ans diff --git a/solution/0800-0899/0852.Peak Index in a Mountain Array/Solution.js b/solution/0800-0899/0852.Peak Index in a Mountain Array/Solution.js index 52fafb321cdcb..50890104043c9 100644 --- a/solution/0800-0899/0852.Peak Index in a Mountain Array/Solution.js +++ b/solution/0800-0899/0852.Peak Index in a Mountain Array/Solution.js @@ -7,10 +7,10 @@ var peakIndexInMountainArray = function (arr) { let right = arr.length - 2; while (left < right) { const mid = (left + right) >> 1; - if (arr[mid] > arr[mid + 1]) { - right = mid; - } else { + if (arr[mid] < arr[mid + 1]) { left = mid + 1; + } else { + right = mid; } } return left; diff --git a/solution/0800-0899/0853.Car Fleet/Solution.cpp b/solution/0800-0899/0853.Car Fleet/Solution.cpp index 607bf3dcecfc5..ec9e1b2284fa8 100644 --- a/solution/0800-0899/0853.Car Fleet/Solution.cpp +++ b/solution/0800-0899/0853.Car Fleet/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - int carFleet(int target, vector& position, vector& speed) { - int n = position.size(); - vector idx(n); - iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) { - return position[i] > position[j]; - }); - int ans = 0; - double pre = 0; - for (int i : idx) { - double t = 1.0 * (target - position[i]) / speed[i]; - if (t > pre) { - ++ans; - pre = t; - } - } - return ans; - } +class Solution { +public: + int carFleet(int target, vector& position, vector& speed) { + int n = position.size(); + vector idx(n); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { + return position[i] > position[j]; + }); + int ans = 0; + double pre = 0; + for (int i : idx) { + double t = 1.0 * (target - position[i]) / speed[i]; + if (t > pre) { + ++ans; + pre = t; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0800-0899/0853.Car Fleet/Solution.java b/solution/0800-0899/0853.Car Fleet/Solution.java index c271f38350b6b..c346687da335c 100644 --- a/solution/0800-0899/0853.Car Fleet/Solution.java +++ b/solution/0800-0899/0853.Car Fleet/Solution.java @@ -1,20 +1,20 @@ -class Solution { - public int carFleet(int target, int[] position, int[] speed) { - int n = position.length; - Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } - Arrays.sort(idx, (i, j) -> position[j] - position[i]); - int ans = 0; - double pre = 0; - for (int i : idx) { - double t = 1.0 * (target - position[i]) / speed[i]; - if (t > pre) { - ++ans; - pre = t; - } - } - return ans; - } +class Solution { + public int carFleet(int target, int[] position, int[] speed) { + int n = position.length; + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; ++i) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> position[j] - position[i]); + int ans = 0; + double pre = 0; + for (int i : idx) { + double t = 1.0 * (target - position[i]) / speed[i]; + if (t > pre) { + ++ans; + pre = t; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0800-0899/0853.Car Fleet/Solution.py b/solution/0800-0899/0853.Car Fleet/Solution.py index fb910f530d22b..051f46fdf327f 100644 --- a/solution/0800-0899/0853.Car Fleet/Solution.py +++ b/solution/0800-0899/0853.Car Fleet/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: - idx = sorted(range(len(position)), key=lambda i: position[i]) - ans = pre = 0 - for i in idx[::-1]: - t = (target - position[i]) / speed[i] - if t > pre: - ans += 1 - pre = t - return ans +class Solution: + def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: + idx = sorted(range(len(position)), key=lambda i: position[i]) + ans = pre = 0 + for i in idx[::-1]: + t = (target - position[i]) / speed[i] + if t > pre: + ans += 1 + pre = t + return ans diff --git a/solution/0800-0899/0854.K-Similar Strings/Solution2.cpp b/solution/0800-0899/0854.K-Similar Strings/Solution2.cpp new file mode 100644 index 0000000000000..66bdf848e1d23 --- /dev/null +++ b/solution/0800-0899/0854.K-Similar Strings/Solution2.cpp @@ -0,0 +1,46 @@ +using pis = pair; + +class Solution { +public: + int kSimilarity(string s1, string s2) { + priority_queue, greater> q; + q.push({f(s1, s2), s1}); + unordered_map dist; + dist[s1] = 0; + while (1) { + auto [_, s] = q.top(); + q.pop(); + if (s == s2) { + return dist[s]; + } + for (auto& nxt : next(s, s2)) { + if (!dist.count(nxt) || dist[nxt] > dist[s] + 1) { + dist[nxt] = dist[s] + 1; + q.push({dist[nxt] + f(nxt, s2), nxt}); + } + } + } + } + + int f(string& s, string& s2) { + int cnt = 0; + for (int i = 0; i < s.size(); ++i) { + cnt += s[i] != s2[i]; + } + return (cnt + 1) >> 1; + } + + vector next(string& s, string& s2) { + int i = 0, n = s.size(); + for (; s[i] == s2[i]; ++i) {} + vector res; + for (int j = i + 1; j < n; ++j) { + if (s[j] == s2[i] && s[j] != s2[j]) { + swap(s[i], s[j]); + res.push_back(s); + swap(s[i], s[j]); + } + } + return res; + } +}; \ No newline at end of file diff --git a/solution/0800-0899/0854.K-Similar Strings/Solution2.go b/solution/0800-0899/0854.K-Similar Strings/Solution2.go new file mode 100644 index 0000000000000..cd5e5f6f9e0ff --- /dev/null +++ b/solution/0800-0899/0854.K-Similar Strings/Solution2.go @@ -0,0 +1,54 @@ +func kSimilarity(s1 string, s2 string) int { + next := func(s string) []string { + i := 0 + res := []string{} + for ; s[i] == s2[i]; i++ { + } + for j := i + 1; j < len(s1); j++ { + if s[j] == s2[i] && s[j] != s2[j] { + res = append(res, s[:i]+string(s[j])+s[i+1:j]+string(s[i])+s[j+1:]) + } + } + return res + } + + f := func(s string) int { + cnt := 0 + for i := range s { + if s[i] != s2[i] { + cnt++ + } + } + return (cnt + 1) >> 1 + } + + q := hp{pair{f(s1), s1}} + dist := map[string]int{s1: 0} + for { + s := heap.Pop(&q).(pair).s + if s == s2 { + return dist[s] + } + for _, nxt := range next(s) { + if v, ok := dist[nxt]; !ok || v > dist[s]+1 { + dist[nxt] = dist[s] + 1 + heap.Push(&q, pair{dist[nxt] + f(nxt), nxt}) + } + } + } +} + +type pair struct { + v int + s string +} +type hp []pair + +func (h hp) Len() int { return len(h) } +func (h hp) Less(i, j int) bool { + a, b := h[i], h[j] + return a.v < b.v +} +func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } +func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } \ No newline at end of file diff --git a/solution/0800-0899/0854.K-Similar Strings/Solution2.java b/solution/0800-0899/0854.K-Similar Strings/Solution2.java new file mode 100644 index 0000000000000..9f82f1c0a873c --- /dev/null +++ b/solution/0800-0899/0854.K-Similar Strings/Solution2.java @@ -0,0 +1,54 @@ +class Solution { + public int kSimilarity(String s1, String s2) { + PriorityQueue> q + = new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)); + q.offer(new Pair<>(f(s1, s2), s1)); + Map dist = new HashMap<>(); + dist.put(s1, 0); + while (true) { + String s = q.poll().getValue(); + if (s.equals(s2)) { + return dist.get(s); + } + for (String nxt : next(s, s2)) { + if (!dist.containsKey(nxt) || dist.get(nxt) > dist.get(s) + 1) { + dist.put(nxt, dist.get(s) + 1); + q.offer(new Pair<>(dist.get(nxt) + f(nxt, s2), nxt)); + } + } + } + } + + private int f(String s, String s2) { + int cnt = 0; + for (int i = 0; i < s.length(); ++i) { + if (s.charAt(i) != s2.charAt(i)) { + ++cnt; + } + } + return (cnt + 1) >> 1; + } + + private List next(String s, String s2) { + int i = 0, n = s.length(); + char[] cs = s.toCharArray(); + for (; cs[i] == s2.charAt(i); ++i) { + } + + List res = new ArrayList<>(); + for (int j = i + 1; j < n; ++j) { + if (cs[j] == s2.charAt(i) && cs[j] != s2.charAt(j)) { + swap(cs, i, j); + res.add(new String(cs)); + swap(cs, i, j); + } + } + return res; + } + + private void swap(char[] cs, int i, int j) { + char t = cs[i]; + cs[i] = cs[j]; + cs[j] = t; + } +} \ No newline at end of file diff --git a/solution/0800-0899/0854.K-Similar Strings/Solution2.py b/solution/0800-0899/0854.K-Similar Strings/Solution2.py new file mode 100644 index 0000000000000..6b6aed60941a0 --- /dev/null +++ b/solution/0800-0899/0854.K-Similar Strings/Solution2.py @@ -0,0 +1,27 @@ +class Solution: + def kSimilarity(self, s1: str, s2: str) -> int: + def f(s): + cnt = sum(c != s2[i] for i, c in enumerate(s)) + return (cnt + 1) >> 1 + + def next(s): + i = 0 + while s[i] == s2[i]: + i += 1 + res = [] + for j in range(i + 1, n): + if s[j] == s2[i] and s[j] != s2[j]: + res.append(s2[: i + 1] + s[i + 1 : j] + s[i] + s[j + 1 :]) + return res + + q = [(f(s1), s1)] + dist = {s1: 0} + n = len(s1) + while 1: + _, s = heappop(q) + if s == s2: + return dist[s] + for nxt in next(s): + if nxt not in dist or dist[nxt] > dist[s] + 1: + dist[nxt] = dist[s] + 1 + heappush(q, (dist[nxt] + f(nxt), nxt)) diff --git a/solution/0800-0899/0858.Mirror Reflection/Solution.cpp b/solution/0800-0899/0858.Mirror Reflection/Solution.cpp index 33e376643ffa4..88ca429159544 100644 --- a/solution/0800-0899/0858.Mirror Reflection/Solution.cpp +++ b/solution/0800-0899/0858.Mirror Reflection/Solution.cpp @@ -1,12 +1,12 @@ -class Solution { -public: - int mirrorReflection(int p, int q) { - int g = __gcd(p, q); - p = (p / g) % 2; - q = (q / g) % 2; - if (p == 1 && q == 1) { - return 1; - } - return p == 1 ? 0 : 2; - } +class Solution { +public: + int mirrorReflection(int p, int q) { + int g = __gcd(p, q); + p = (p / g) % 2; + q = (q / g) % 2; + if (p == 1 && q == 1) { + return 1; + } + return p == 1 ? 0 : 2; + } }; \ No newline at end of file diff --git a/solution/0800-0899/0858.Mirror Reflection/Solution.java b/solution/0800-0899/0858.Mirror Reflection/Solution.java index 1711f7ef9be67..74d457f80e72b 100644 --- a/solution/0800-0899/0858.Mirror Reflection/Solution.java +++ b/solution/0800-0899/0858.Mirror Reflection/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public int mirrorReflection(int p, int q) { - int g = gcd(p, q); - p = (p / g) % 2; - q = (q / g) % 2; - if (p == 1 && q == 1) { - return 1; - } - return p == 1 ? 0 : 2; - } - - private int gcd(int a, int b) { - return b == 0 ? a : gcd(b, a % b); - } +class Solution { + public int mirrorReflection(int p, int q) { + int g = gcd(p, q); + p = (p / g) % 2; + q = (q / g) % 2; + if (p == 1 && q == 1) { + return 1; + } + return p == 1 ? 0 : 2; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } } \ No newline at end of file diff --git a/solution/0800-0899/0858.Mirror Reflection/Solution.py b/solution/0800-0899/0858.Mirror Reflection/Solution.py index 7c5e39b6adaf3..f6081fe72b8cf 100644 --- a/solution/0800-0899/0858.Mirror Reflection/Solution.py +++ b/solution/0800-0899/0858.Mirror Reflection/Solution.py @@ -1,8 +1,8 @@ -class Solution: - def mirrorReflection(self, p: int, q: int) -> int: - g = gcd(p, q) - p = (p // g) % 2 - q = (q // g) % 2 - if p == 1 and q == 1: - return 1 - return 0 if p == 1 else 2 +class Solution: + def mirrorReflection(self, p: int, q: int) -> int: + g = gcd(p, q) + p = (p // g) % 2 + q = (q // g) % 2 + if p == 1 and q == 1: + return 1 + return 0 if p == 1 else 2 diff --git a/solution/0800-0899/0860.Lemonade Change/Solution.cpp b/solution/0800-0899/0860.Lemonade Change/Solution.cpp index 4b6102ccc53ee..ed00b1456c4c2 100644 --- a/solution/0800-0899/0860.Lemonade Change/Solution.cpp +++ b/solution/0800-0899/0860.Lemonade Change/Solution.cpp @@ -1,25 +1,25 @@ -class Solution { -public: - bool lemonadeChange(vector& bills) { - int five = 0, ten = 10; - for (int v : bills) { - if (v == 5) { - ++five; - } else if (v == 10) { - ++ten; - --five; - } else { - if (ten) { - --ten; - --five; - } else { - five -= 3; - } - } - if (five < 0) { - return false; - } - } - return true; - } +class Solution { +public: + bool lemonadeChange(vector& bills) { + int five = 0, ten = 10; + for (int v : bills) { + if (v == 5) { + ++five; + } else if (v == 10) { + ++ten; + --five; + } else { + if (ten) { + --ten; + --five; + } else { + five -= 3; + } + } + if (five < 0) { + return false; + } + } + return true; + } }; \ No newline at end of file diff --git a/solution/0800-0899/0860.Lemonade Change/Solution.java b/solution/0800-0899/0860.Lemonade Change/Solution.java index f2f3f7e7008e8..eda964c41af22 100644 --- a/solution/0800-0899/0860.Lemonade Change/Solution.java +++ b/solution/0800-0899/0860.Lemonade Change/Solution.java @@ -1,26 +1,26 @@ -class Solution { - public boolean lemonadeChange(int[] bills) { - int five = 0, ten = 0; - for (int v : bills) { - switch (v) { - case 5 -> ++five; - case 10 -> { - ++ten; - --five; - } - case 20 -> { - if (ten > 0) { - --ten; - --five; - } else { - five -= 3; - } - } - } - if (five < 0) { - return false; - } - } - return true; - } +class Solution { + public boolean lemonadeChange(int[] bills) { + int five = 0, ten = 0; + for (int v : bills) { + switch (v) { + case 5 -> ++five; + case 10 -> { + ++ten; + --five; + } + case 20 -> { + if (ten > 0) { + --ten; + --five; + } else { + five -= 3; + } + } + } + if (five < 0) { + return false; + } + } + return true; + } } \ No newline at end of file diff --git a/solution/0800-0899/0861.Score After Flipping Matrix/Solution.cs b/solution/0800-0899/0861.Score After Flipping Matrix/Solution.cs index 2c698d63d6ff2..67816cb6c633d 100644 --- a/solution/0800-0899/0861.Score After Flipping Matrix/Solution.cs +++ b/solution/0800-0899/0861.Score After Flipping Matrix/Solution.cs @@ -20,4 +20,4 @@ public int MatrixScore(int[][] grid) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/0800-0899/0863.All Nodes Distance K in Binary Tree/Solution2.py b/solution/0800-0899/0863.All Nodes Distance K in Binary Tree/Solution2.py new file mode 100644 index 0000000000000..e1d93b69d9498 --- /dev/null +++ b/solution/0800-0899/0863.All Nodes Distance K in Binary Tree/Solution2.py @@ -0,0 +1,32 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution: + def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]: + def dfs1(root, fa): + if root is None: + return + p[root] = fa + dfs1(root.left, root) + dfs1(root.right, root) + + def dfs2(root, fa, k): + if root is None: + return + if k == 0: + ans.append(root.val) + return + for nxt in (root.left, root.right, p[root]): + if nxt != fa: + dfs2(nxt, root, k - 1) + + p = {} + dfs1(root, None) + ans = [] + dfs2(target, None, k) + return ans diff --git a/solution/0800-0899/0864.Shortest Path to Get All Keys/Solution.cpp b/solution/0800-0899/0864.Shortest Path to Get All Keys/Solution.cpp index 5b1a6e15d949d..66c817ac23773 100644 --- a/solution/0800-0899/0864.Shortest Path to Get All Keys/Solution.cpp +++ b/solution/0800-0899/0864.Shortest Path to Get All Keys/Solution.cpp @@ -9,8 +9,9 @@ class Solution { for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { char c = grid[i][j]; - if (islower(c)) - ++k; + // 累加钥匙数量 + if (islower(c)) ++k; + // 起点 else if (c == '@') si = i, sj = j; } @@ -23,14 +24,20 @@ class Solution { for (int t = q.size(); t; --t) { auto [i, j, state] = q.front(); q.pop(); + // 找到所有钥匙,返回当前步数 if (state == (1 << k) - 1) return ans; + // 往四个方向搜索 for (int h = 0; h < 4; ++h) { int x = i + dirs[h], y = j + dirs[h + 1]; + // 在边界范围内 if (x >= 0 && x < m && y >= 0 && y < n) { char c = grid[x][y]; + // 是墙,或者是锁,但此时没有对应的钥匙,无法通过 if (c == '#' || (isupper(c) && (state >> (c - 'A') & 1) == 0)) continue; int nxt = state; + // 是钥匙,更新状态 if (islower(c)) nxt |= 1 << (c - 'a'); + // 此状态未访问过,入队 if (!vis[x][y][nxt]) { vis[x][y][nxt] = true; q.push({x, y, nxt}); @@ -38,6 +45,7 @@ class Solution { } } } + // 步数加一 ++ans; } return -1; diff --git a/solution/0800-0899/0864.Shortest Path to Get All Keys/Solution.go b/solution/0800-0899/0864.Shortest Path to Get All Keys/Solution.go index 87a549a4ac215..dc5f62c152785 100644 --- a/solution/0800-0899/0864.Shortest Path to Get All Keys/Solution.go +++ b/solution/0800-0899/0864.Shortest Path to Get All Keys/Solution.go @@ -4,8 +4,10 @@ func shortestPathAllKeys(grid []string) int { for i, row := range grid { for j, c := range row { if c >= 'a' && c <= 'z' { + // 累加钥匙数量 k++ } else if c == '@' { + // 起点 si, sj = i, j } } @@ -20,20 +22,26 @@ func shortestPathAllKeys(grid []string) int { p := q[0] q = q[1:] i, j, state := p.i, p.j, p.state + // 找到所有钥匙,返回当前步数 if state == 1<= 0 && x < m && y >= 0 && y < n { c := grid[x][y] + // 是墙,或者是锁,但此时没有对应的钥匙,无法通过 if c == '#' || (c >= 'A' && c <= 'Z' && (state>>(c-'A')&1 == 0)) { continue } nxt := state + // 是钥匙,更新状态 if c >= 'a' && c <= 'z' { nxt |= 1 << (c - 'a') } + // 此状态未访问过,入队 if !vis[tuple{x, y, nxt}] { vis[tuple{x, y, nxt}] = true q = append(q, tuple{x, y, nxt}) @@ -41,6 +49,7 @@ func shortestPathAllKeys(grid []string) int { } } } + // 步数加一 ans++ } return -1 diff --git a/solution/0800-0899/0864.Shortest Path to Get All Keys/Solution.java b/solution/0800-0899/0864.Shortest Path to Get All Keys/Solution.java index 5eb870726cfea..8ae6cd63b3932 100644 --- a/solution/0800-0899/0864.Shortest Path to Get All Keys/Solution.java +++ b/solution/0800-0899/0864.Shortest Path to Get All Keys/Solution.java @@ -9,8 +9,10 @@ public int shortestPathAllKeys(String[] grid) { for (int j = 0; j < n; ++j) { char c = grid[i].charAt(j); if (Character.isLowerCase(c)) { + // 累加钥匙数量 ++k; } else if (c == '@') { + // 起点 si = i; sj = j; } @@ -25,21 +27,28 @@ public int shortestPathAllKeys(String[] grid) { for (int t = q.size(); t > 0; --t) { var p = q.poll(); int i = p[0], j = p[1], state = p[2]; + // 找到所有钥匙,返回当前步数 if (state == (1 << k) - 1) { return ans; } + // 往四个方向搜索 for (int h = 0; h < 4; ++h) { int x = i + dirs[h], y = j + dirs[h + 1]; + // 在边界范围内 if (x >= 0 && x < m && y >= 0 && y < n) { char c = grid[x].charAt(y); + // 是墙,或者是锁,但此时没有对应的钥匙,无法通过 if (c == '#' || (Character.isUpperCase(c) && ((state >> (c - 'A')) & 1) == 0)) { continue; } int nxt = state; + // 是钥匙 if (Character.isLowerCase(c)) { + // 更新状态 nxt |= 1 << (c - 'a'); } + // 此状态未访问过,入队 if (!vis[x][y][nxt]) { vis[x][y][nxt] = true; q.offer(new int[] {x, y, nxt}); @@ -47,6 +56,7 @@ public int shortestPathAllKeys(String[] grid) { } } } + // 步数加一 ++ans; } return -1; diff --git a/solution/0800-0899/0864.Shortest Path to Get All Keys/Solution.py b/solution/0800-0899/0864.Shortest Path to Get All Keys/Solution.py index 60b3efbf1ded7..27c8ff0e2fad0 100644 --- a/solution/0800-0899/0864.Shortest Path to Get All Keys/Solution.py +++ b/solution/0800-0899/0864.Shortest Path to Get All Keys/Solution.py @@ -1,7 +1,9 @@ class Solution: def shortestPathAllKeys(self, grid: List[str]) -> int: m, n = len(grid), len(grid[0]) + # 找起点 (si, sj) si, sj = next((i, j) for i in range(m) for j in range(n) if grid[i][j] == '@') + # 统计钥匙数量 k = sum(v.islower() for row in grid for v in row) dirs = (-1, 0, 1, 0, -1) q = deque([(si, sj, 0)]) @@ -10,23 +12,32 @@ def shortestPathAllKeys(self, grid: List[str]) -> int: while q: for _ in range(len(q)): i, j, state = q.popleft() + # 找到所有钥匙,返回当前步数 if state == (1 << k) - 1: return ans + + # 往四个方向搜索 for a, b in pairwise(dirs): x, y = i + a, j + b nxt = state + # 在边界范围内 if 0 <= x < m and 0 <= y < n: c = grid[x][y] + # 是墙,或者是锁,但此时没有对应的钥匙,无法通过 if ( c == '#' or c.isupper() and (state & (1 << (ord(c) - ord('A')))) == 0 ): continue + # 是钥匙 if c.islower(): + # 更新状态 nxt |= 1 << (ord(c) - ord('a')) + # 此状态未访问过,入队 if (x, y, nxt) not in vis: vis.add((x, y, nxt)) q.append((x, y, nxt)) + # 步数加一 ans += 1 return -1 diff --git a/solution/0800-0899/0868.Binary Gap/Solution.cpp b/solution/0800-0899/0868.Binary Gap/Solution.cpp index a360fde6cdeae..5e1e8885e5f5d 100644 --- a/solution/0800-0899/0868.Binary Gap/Solution.cpp +++ b/solution/0800-0899/0868.Binary Gap/Solution.cpp @@ -1,13 +1,13 @@ -class Solution { -public: - int binaryGap(int n) { - int ans = 0; - for (int i = 0, j = -1; n; ++i, n >>= 1) { - if (n & 1) { - if (j != -1) ans = max(ans, i - j); - j = i; - } - } - return ans; - } +class Solution { +public: + int binaryGap(int n) { + int ans = 0; + for (int i = 0, j = -1; n; ++i, n >>= 1) { + if (n & 1) { + if (j != -1) ans = max(ans, i - j); + j = i; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0800-0899/0868.Binary Gap/Solution.java b/solution/0800-0899/0868.Binary Gap/Solution.java index 0a92afd8fea93..923489a6b986d 100644 --- a/solution/0800-0899/0868.Binary Gap/Solution.java +++ b/solution/0800-0899/0868.Binary Gap/Solution.java @@ -1,14 +1,14 @@ -class Solution { - public int binaryGap(int n) { - int ans = 0; - for (int i = 0, j = -1; n != 0; ++i, n >>= 1) { - if ((n & 1) == 1) { - if (j != -1) { - ans = Math.max(ans, i - j); - } - j = i; - } - } - return ans; - } +class Solution { + public int binaryGap(int n) { + int ans = 0; + for (int i = 0, j = -1; n != 0; ++i, n >>= 1) { + if ((n & 1) == 1) { + if (j != -1) { + ans = Math.max(ans, i - j); + } + j = i; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0800-0899/0868.Binary Gap/Solution.py b/solution/0800-0899/0868.Binary Gap/Solution.py index 8e7f4d1f02f8d..bd3050a9b6260 100644 --- a/solution/0800-0899/0868.Binary Gap/Solution.py +++ b/solution/0800-0899/0868.Binary Gap/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def binaryGap(self, n: int) -> int: - ans, j = 0, -1 - for i in range(32): - if n & 1: - if j != -1: - ans = max(ans, i - j) - j = i - n >>= 1 - return ans +class Solution: + def binaryGap(self, n: int) -> int: + ans, j = 0, -1 + for i in range(32): + if n & 1: + if j != -1: + ans = max(ans, i - j) + j = i + n >>= 1 + return ans diff --git a/solution/0800-0899/0874.Walking Robot Simulation/Solution.cpp b/solution/0800-0899/0874.Walking Robot Simulation/Solution.cpp index 69ddd9394189e..8dff1cfcf1c98 100644 --- a/solution/0800-0899/0874.Walking Robot Simulation/Solution.cpp +++ b/solution/0800-0899/0874.Walking Robot Simulation/Solution.cpp @@ -1,33 +1,33 @@ -class Solution { -public: - int robotSim(vector& commands, vector>& obstacles) { - int dirs[5] = {0, 1, 0, -1, 0}; - auto f = [](int x, int y) { - return x * 60010 + y; - }; - unordered_set s; - for (auto& e : obstacles) { - s.insert(f(e[0], e[1])); - } - int ans = 0, k = 0; - int x = 0, y = 0; - for (int c : commands) { - if (c == -2) { - k = (k + 3) % 4; - } else if (c == -1) { - k = (k + 1) % 4; - } else { - while (c--) { - int nx = x + dirs[k], ny = y + dirs[k + 1]; - if (s.count(f(nx, ny))) { - break; - } - x = nx; - y = ny; - ans = max(ans, x * x + y * y); - } - } - } - return ans; - } +class Solution { +public: + int robotSim(vector& commands, vector>& obstacles) { + int dirs[5] = {0, 1, 0, -1, 0}; + auto f = [](int x, int y) { + return x * 60010 + y; + }; + unordered_set s; + for (auto& e : obstacles) { + s.insert(f(e[0], e[1])); + } + int ans = 0, k = 0; + int x = 0, y = 0; + for (int c : commands) { + if (c == -2) { + k = (k + 3) % 4; + } else if (c == -1) { + k = (k + 1) % 4; + } else { + while (c--) { + int nx = x + dirs[k], ny = y + dirs[k + 1]; + if (s.count(f(nx, ny))) { + break; + } + x = nx; + y = ny; + ans = max(ans, x * x + y * y); + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0800-0899/0874.Walking Robot Simulation/Solution.java b/solution/0800-0899/0874.Walking Robot Simulation/Solution.java index 15379ccd15d85..9a64af28cc414 100644 --- a/solution/0800-0899/0874.Walking Robot Simulation/Solution.java +++ b/solution/0800-0899/0874.Walking Robot Simulation/Solution.java @@ -1,33 +1,33 @@ -class Solution { - public int robotSim(int[] commands, int[][] obstacles) { - int[] dirs = {0, 1, 0, -1, 0}; - Set s = new HashSet<>(obstacles.length); - for (var e : obstacles) { - s.add(f(e[0], e[1])); - } - int ans = 0, k = 0; - int x = 0, y = 0; - for (int c : commands) { - if (c == -2) { - k = (k + 3) % 4; - } else if (c == -1) { - k = (k + 1) % 4; - } else { - while (c-- > 0) { - int nx = x + dirs[k], ny = y + dirs[k + 1]; - if (s.contains(f(nx, ny))) { - break; - } - x = nx; - y = ny; - ans = Math.max(ans, x * x + y * y); - } - } - } - return ans; - } - - private int f(int x, int y) { - return x * 60010 + y; - } +class Solution { + public int robotSim(int[] commands, int[][] obstacles) { + int[] dirs = {0, 1, 0, -1, 0}; + Set s = new HashSet<>(obstacles.length); + for (var e : obstacles) { + s.add(f(e[0], e[1])); + } + int ans = 0, k = 0; + int x = 0, y = 0; + for (int c : commands) { + if (c == -2) { + k = (k + 3) % 4; + } else if (c == -1) { + k = (k + 1) % 4; + } else { + while (c-- > 0) { + int nx = x + dirs[k], ny = y + dirs[k + 1]; + if (s.contains(f(nx, ny))) { + break; + } + x = nx; + y = ny; + ans = Math.max(ans, x * x + y * y); + } + } + } + return ans; + } + + private int f(int x, int y) { + return x * 60010 + y; + } } \ No newline at end of file diff --git a/solution/0800-0899/0874.Walking Robot Simulation/Solution.py b/solution/0800-0899/0874.Walking Robot Simulation/Solution.py index e8e091ec93291..bbe2c2e5a7360 100644 --- a/solution/0800-0899/0874.Walking Robot Simulation/Solution.py +++ b/solution/0800-0899/0874.Walking Robot Simulation/Solution.py @@ -1,19 +1,19 @@ -class Solution: - def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: - dirs = (0, 1, 0, -1, 0) - s = {(x, y) for x, y in obstacles} - ans = k = 0 - x = y = 0 - for c in commands: - if c == -2: - k = (k + 3) % 4 - elif c == -1: - k = (k + 1) % 4 - else: - for _ in range(c): - nx, ny = x + dirs[k], y + dirs[k + 1] - if (nx, ny) in s: - break - x, y = nx, ny - ans = max(ans, x * x + y * y) - return ans +class Solution: + def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: + dirs = (0, 1, 0, -1, 0) + s = {(x, y) for x, y in obstacles} + ans = k = 0 + x = y = 0 + for c in commands: + if c == -2: + k = (k + 3) % 4 + elif c == -1: + k = (k + 1) % 4 + else: + for _ in range(c): + nx, ny = x + dirs[k], y + dirs[k + 1] + if (nx, ny) in s: + break + x, y = nx, ny + ans = max(ans, x * x + y * y) + return ans diff --git a/solution/0800-0899/0875.Koko Eating Bananas/Solution.cpp b/solution/0800-0899/0875.Koko Eating Bananas/Solution.cpp index 6de7eb00ee07c..77b796c064dbd 100644 --- a/solution/0800-0899/0875.Koko Eating Bananas/Solution.cpp +++ b/solution/0800-0899/0875.Koko Eating Bananas/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - int minEatingSpeed(vector& piles, int h) { - int left = 1, right = 1e9; - while (left < right) { - int mid = (left + right) >> 1; - int s = 0; - for (int& x : piles) s += (x + mid - 1) / mid; - if (s <= h) - right = mid; - else - left = mid + 1; - } - return left; - } +class Solution { +public: + int minEatingSpeed(vector& piles, int h) { + int left = 1, right = 1e9; + while (left < right) { + int mid = (left + right) >> 1; + int s = 0; + for (int& x : piles) s += (x + mid - 1) / mid; + if (s <= h) + right = mid; + else + left = mid + 1; + } + return left; + } }; \ No newline at end of file diff --git a/solution/0800-0899/0875.Koko Eating Bananas/Solution.cs b/solution/0800-0899/0875.Koko Eating Bananas/Solution.cs index fb1be7d77049d..c7a8f8c1322da 100644 --- a/solution/0800-0899/0875.Koko Eating Bananas/Solution.cs +++ b/solution/0800-0899/0875.Koko Eating Bananas/Solution.cs @@ -20,4 +20,4 @@ public int MinEatingSpeed(int[] piles, int h) { } return left; } -} \ No newline at end of file +} diff --git a/solution/0800-0899/0875.Koko Eating Bananas/Solution.java b/solution/0800-0899/0875.Koko Eating Bananas/Solution.java index 17097f2b4f322..e6af7095c127e 100644 --- a/solution/0800-0899/0875.Koko Eating Bananas/Solution.java +++ b/solution/0800-0899/0875.Koko Eating Bananas/Solution.java @@ -1,18 +1,18 @@ -class Solution { - public int minEatingSpeed(int[] piles, int h) { - int left = 1, right = (int) 1e9; - while (left < right) { - int mid = (left + right) >>> 1; - int s = 0; - for (int x : piles) { - s += (x + mid - 1) / mid; - } - if (s <= h) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - } +class Solution { + public int minEatingSpeed(int[] piles, int h) { + int left = 1, right = (int) 1e9; + while (left < right) { + int mid = (left + right) >>> 1; + int s = 0; + for (int x : piles) { + s += (x + mid - 1) / mid; + } + if (s <= h) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } } \ No newline at end of file diff --git a/solution/0800-0899/0875.Koko Eating Bananas/Solution.py b/solution/0800-0899/0875.Koko Eating Bananas/Solution.py index 6b5bc42fd1b51..65b698996967e 100644 --- a/solution/0800-0899/0875.Koko Eating Bananas/Solution.py +++ b/solution/0800-0899/0875.Koko Eating Bananas/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def minEatingSpeed(self, piles: List[int], h: int) -> int: - left, right = 1, int(1e9) - while left < right: - mid = (left + right) >> 1 - s = sum((x + mid - 1) // mid for x in piles) - if s <= h: - right = mid - else: - left = mid + 1 - return left +class Solution: + def minEatingSpeed(self, piles: List[int], h: int) -> int: + left, right = 1, int(1e9) + while left < right: + mid = (left + right) >> 1 + s = sum((x + mid - 1) // mid for x in piles) + if s <= h: + right = mid + else: + left = mid + 1 + return left diff --git a/solution/0800-0899/0876.Middle of the Linked List/Solution.c b/solution/0800-0899/0876.Middle of the Linked List/Solution.c index 587685cc40f5f..066e879b7ea72 100644 --- a/solution/0800-0899/0876.Middle of the Linked List/Solution.c +++ b/solution/0800-0899/0876.Middle of the Linked List/Solution.c @@ -14,4 +14,4 @@ struct ListNode* middleNode(struct ListNode* head) { slow = slow->next; } return slow; -} +} \ No newline at end of file diff --git a/solution/0800-0899/0876.Middle of the Linked List/Solution.php b/solution/0800-0899/0876.Middle of the Linked List/Solution.php index 2d3632813b0df..815c4c29bbf0a 100644 --- a/solution/0800-0899/0876.Middle of the Linked List/Solution.php +++ b/solution/0800-0899/0876.Middle of the Linked List/Solution.php @@ -28,4 +28,4 @@ function middleNode($head) { } return $head; } -} \ No newline at end of file +} diff --git a/solution/0800-0899/0877.Stone Game/Solution.cpp b/solution/0800-0899/0877.Stone Game/Solution.cpp index 0a33a67952949..a9ee327b9d700 100644 --- a/solution/0800-0899/0877.Stone Game/Solution.cpp +++ b/solution/0800-0899/0877.Stone Game/Solution.cpp @@ -4,14 +4,15 @@ class Solution { int n = piles.size(); int f[n][n]; memset(f, 0, sizeof(f)); - for (int i = 0; i < n; ++i) { - f[i][i] = piles[i]; - } - for (int i = n - 2; ~i; --i) { - for (int j = i + 1; j < n; ++j) { - f[i][j] = max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]); + function dfs = [&](int i, int j) -> int { + if (i > j) { + return 0; } - } - return f[0][n - 1] > 0; + if (f[i][j]) { + return f[i][j]; + } + return f[i][j] = max(piles[i] - dfs(i + 1, j), piles[j] - dfs(i, j - 1)); + }; + return dfs(0, n - 1) > 0; } }; \ No newline at end of file diff --git a/solution/0800-0899/0877.Stone Game/Solution.go b/solution/0800-0899/0877.Stone Game/Solution.go index 9dd2b1d4657c0..b1ebb41e9e368 100644 --- a/solution/0800-0899/0877.Stone Game/Solution.go +++ b/solution/0800-0899/0877.Stone Game/Solution.go @@ -1,14 +1,18 @@ func stoneGame(piles []int) bool { n := len(piles) f := make([][]int, n) - for i, x := range piles { + for i := range f { f[i] = make([]int, n) - f[i][i] = x } - for i := n - 2; i >= 0; i-- { - for j := i + 1; j < n; j++ { - f[i][j] = max(piles[i]-f[i+1][j], piles[j]-f[i][j-1]) + var dfs func(i, j int) int + dfs = func(i, j int) int { + if i > j { + return 0 } + if f[i][j] == 0 { + f[i][j] = max(piles[i]-dfs(i+1, j), piles[j]-dfs(i, j-1)) + } + return f[i][j] } - return f[0][n-1] > 0 + return dfs(0, n-1) > 0 } \ No newline at end of file diff --git a/solution/0800-0899/0877.Stone Game/Solution.java b/solution/0800-0899/0877.Stone Game/Solution.java index 102656d72da90..ab6379cfb3e8d 100644 --- a/solution/0800-0899/0877.Stone Game/Solution.java +++ b/solution/0800-0899/0877.Stone Game/Solution.java @@ -1,15 +1,21 @@ class Solution { + private int[] piles; + private int[][] f; + public boolean stoneGame(int[] piles) { + this.piles = piles; int n = piles.length; - int[][] f = new int[n][n]; - for (int i = 0; i < n; ++i) { - f[i][i] = piles[i]; + f = new int[n][n]; + return dfs(0, n - 1) > 0; + } + + private int dfs(int i, int j) { + if (i > j) { + return 0; } - for (int i = n - 2; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - f[i][j] = Math.max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]); - } + if (f[i][j] != 0) { + return f[i][j]; } - return f[0][n - 1] > 0; + return f[i][j] = Math.max(piles[i] - dfs(i + 1, j), piles[j] - dfs(i, j - 1)); } } \ No newline at end of file diff --git a/solution/0800-0899/0877.Stone Game/Solution.py b/solution/0800-0899/0877.Stone Game/Solution.py index d4b6bd7870ffc..6dbcab81e23ed 100644 --- a/solution/0800-0899/0877.Stone Game/Solution.py +++ b/solution/0800-0899/0877.Stone Game/Solution.py @@ -1,10 +1,9 @@ class Solution: def stoneGame(self, piles: List[int]) -> bool: - n = len(piles) - f = [[0] * n for _ in range(n)] - for i, x in enumerate(piles): - f[i][i] = x - for i in range(n - 2, -1, -1): - for j in range(i + 1, n): - f[i][j] = max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]) - return f[0][n - 1] > 0 + @cache + def dfs(i: int, j: int) -> int: + if i > j: + return 0 + return max(piles[i] - dfs(i + 1, j), piles[j] - dfs(i, j - 1)) + + return dfs(0, len(piles) - 1) > 0 diff --git a/solution/0800-0899/0877.Stone Game/Solution.ts b/solution/0800-0899/0877.Stone Game/Solution.ts index b186a0a9c39c3..d4f84afc9c476 100644 --- a/solution/0800-0899/0877.Stone Game/Solution.ts +++ b/solution/0800-0899/0877.Stone Game/Solution.ts @@ -1,13 +1,14 @@ function stoneGame(piles: number[]): boolean { const n = piles.length; const f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(0)); - for (let i = 0; i < n; ++i) { - f[i][i] = piles[i]; - } - for (let i = n - 2; i >= 0; --i) { - for (let j = i + 1; j < n; ++j) { - f[i][j] = Math.max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]); + const dfs = (i: number, j: number): number => { + if (i > j) { + return 0; } - } - return f[0][n - 1] > 0; + if (f[i][j] === 0) { + f[i][j] = Math.max(piles[i] - dfs(i + 1, j), piles[j] - dfs(i, j - 1)); + } + return f[i][j]; + }; + return dfs(0, n - 1) > 0; } diff --git a/solution/0800-0899/0877.Stone Game/Solution2.cpp b/solution/0800-0899/0877.Stone Game/Solution2.cpp new file mode 100644 index 0000000000000..0a33a67952949 --- /dev/null +++ b/solution/0800-0899/0877.Stone Game/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool stoneGame(vector& piles) { + int n = piles.size(); + int f[n][n]; + memset(f, 0, sizeof(f)); + for (int i = 0; i < n; ++i) { + f[i][i] = piles[i]; + } + for (int i = n - 2; ~i; --i) { + for (int j = i + 1; j < n; ++j) { + f[i][j] = max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]); + } + } + return f[0][n - 1] > 0; + } +}; \ No newline at end of file diff --git a/solution/0800-0899/0877.Stone Game/Solution2.go b/solution/0800-0899/0877.Stone Game/Solution2.go new file mode 100644 index 0000000000000..9dd2b1d4657c0 --- /dev/null +++ b/solution/0800-0899/0877.Stone Game/Solution2.go @@ -0,0 +1,14 @@ +func stoneGame(piles []int) bool { + n := len(piles) + f := make([][]int, n) + for i, x := range piles { + f[i] = make([]int, n) + f[i][i] = x + } + for i := n - 2; i >= 0; i-- { + for j := i + 1; j < n; j++ { + f[i][j] = max(piles[i]-f[i+1][j], piles[j]-f[i][j-1]) + } + } + return f[0][n-1] > 0 +} \ No newline at end of file diff --git a/solution/0800-0899/0877.Stone Game/Solution2.java b/solution/0800-0899/0877.Stone Game/Solution2.java new file mode 100644 index 0000000000000..102656d72da90 --- /dev/null +++ b/solution/0800-0899/0877.Stone Game/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public boolean stoneGame(int[] piles) { + int n = piles.length; + int[][] f = new int[n][n]; + for (int i = 0; i < n; ++i) { + f[i][i] = piles[i]; + } + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + f[i][j] = Math.max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]); + } + } + return f[0][n - 1] > 0; + } +} \ No newline at end of file diff --git a/solution/0800-0899/0877.Stone Game/Solution2.py b/solution/0800-0899/0877.Stone Game/Solution2.py new file mode 100644 index 0000000000000..d4b6bd7870ffc --- /dev/null +++ b/solution/0800-0899/0877.Stone Game/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def stoneGame(self, piles: List[int]) -> bool: + n = len(piles) + f = [[0] * n for _ in range(n)] + for i, x in enumerate(piles): + f[i][i] = x + for i in range(n - 2, -1, -1): + for j in range(i + 1, n): + f[i][j] = max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]) + return f[0][n - 1] > 0 diff --git a/solution/0800-0899/0877.Stone Game/Solution2.ts b/solution/0800-0899/0877.Stone Game/Solution2.ts new file mode 100644 index 0000000000000..b186a0a9c39c3 --- /dev/null +++ b/solution/0800-0899/0877.Stone Game/Solution2.ts @@ -0,0 +1,13 @@ +function stoneGame(piles: number[]): boolean { + const n = piles.length; + const f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(0)); + for (let i = 0; i < n; ++i) { + f[i][i] = piles[i]; + } + for (let i = n - 2; i >= 0; --i) { + for (let j = i + 1; j < n; ++j) { + f[i][j] = Math.max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]); + } + } + return f[0][n - 1] > 0; +} diff --git a/solution/0800-0899/0879.Profitable Schemes/Solution.cpp b/solution/0800-0899/0879.Profitable Schemes/Solution.cpp index b181c0fd3ecc6..4496d6d2bb196 100644 --- a/solution/0800-0899/0879.Profitable Schemes/Solution.cpp +++ b/solution/0800-0899/0879.Profitable Schemes/Solution.cpp @@ -2,22 +2,23 @@ class Solution { public: int profitableSchemes(int n, int minProfit, vector& group, vector& profit) { int m = group.size(); - int f[m + 1][n + 1][minProfit + 1]; - memset(f, 0, sizeof(f)); - for (int j = 0; j <= n; ++j) { - f[0][j][0] = 1; - } + int f[m][n + 1][minProfit + 1]; + memset(f, -1, sizeof(f)); const int mod = 1e9 + 7; - for (int i = 1; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - for (int k = 0; k <= minProfit; ++k) { - f[i][j][k] = f[i - 1][j][k]; - if (j >= group[i - 1]) { - f[i][j][k] = (f[i][j][k] + f[i - 1][j - group[i - 1]][max(0, k - profit[i - 1])]) % mod; - } - } + function dfs = [&](int i, int j, int k) -> int { + if (i >= m) { + return k == minProfit ? 1 : 0; } - } - return f[m][n][minProfit]; + if (f[i][j][k] != -1) { + return f[i][j][k]; + } + int ans = dfs(i + 1, j, k); + if (j + group[i] <= n) { + ans += dfs(i + 1, j + group[i], min(k + profit[i], minProfit)); + } + ans %= mod; + return f[i][j][k] = ans; + }; + return dfs(0, 0, 0); } }; \ No newline at end of file diff --git a/solution/0800-0899/0879.Profitable Schemes/Solution.go b/solution/0800-0899/0879.Profitable Schemes/Solution.go index 3da77b321365c..a7763175caf6a 100644 --- a/solution/0800-0899/0879.Profitable Schemes/Solution.go +++ b/solution/0800-0899/0879.Profitable Schemes/Solution.go @@ -1,26 +1,34 @@ func profitableSchemes(n int, minProfit int, group []int, profit []int) int { m := len(group) - f := make([][][]int, m+1) + f := make([][][]int, m) for i := range f { f[i] = make([][]int, n+1) for j := range f[i] { f[i][j] = make([]int, minProfit+1) + for k := range f[i][j] { + f[i][j][k] = -1 + } } } - for j := 0; j <= n; j++ { - f[0][j][0] = 1 - } const mod = 1e9 + 7 - for i := 1; i <= m; i++ { - for j := 0; j <= n; j++ { - for k := 0; k <= minProfit; k++ { - f[i][j][k] = f[i-1][j][k] - if j >= group[i-1] { - f[i][j][k] += f[i-1][j-group[i-1]][max(0, k-profit[i-1])] - f[i][j][k] %= mod - } + var dfs func(i, j, k int) int + dfs = func(i, j, k int) int { + if i >= m { + if k >= minProfit { + return 1 } + return 0 + } + if f[i][j][k] != -1 { + return f[i][j][k] + } + ans := dfs(i+1, j, k) + if j+group[i] <= n { + ans += dfs(i+1, j+group[i], min(k+profit[i], minProfit)) } + ans %= mod + f[i][j][k] = ans + return ans } - return f[m][n][minProfit] + return dfs(0, 0, 0) } \ No newline at end of file diff --git a/solution/0800-0899/0879.Profitable Schemes/Solution.java b/solution/0800-0899/0879.Profitable Schemes/Solution.java index f95d3af71bda6..61cf332757afd 100644 --- a/solution/0800-0899/0879.Profitable Schemes/Solution.java +++ b/solution/0800-0899/0879.Profitable Schemes/Solution.java @@ -1,24 +1,34 @@ class Solution { + private Integer[][][] f; + private int m; + private int n; + private int minProfit; + private int[] group; + private int[] profit; + private final int mod = (int) 1e9 + 7; + public int profitableSchemes(int n, int minProfit, int[] group, int[] profit) { - final int mod = (int) 1e9 + 7; - int m = group.length; - int[][][] f = new int[m + 1][n + 1][minProfit + 1]; - for (int j = 0; j <= n; ++j) { - f[0][j][0] = 1; + m = group.length; + this.n = n; + f = new Integer[m][n + 1][minProfit + 1]; + this.minProfit = minProfit; + this.group = group; + this.profit = profit; + return dfs(0, 0, 0); + } + + private int dfs(int i, int j, int k) { + if (i >= m) { + return k == minProfit ? 1 : 0; + } + if (f[i][j][k] != null) { + return f[i][j][k]; } - for (int i = 1; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - for (int k = 0; k <= minProfit; ++k) { - f[i][j][k] = f[i - 1][j][k]; - if (j >= group[i - 1]) { - f[i][j][k] - = (f[i][j][k] - + f[i - 1][j - group[i - 1]][Math.max(0, k - profit[i - 1])]) - % mod; - } - } - } + int ans = dfs(i + 1, j, k); + if (j + group[i] <= n) { + ans += dfs(i + 1, j + group[i], Math.min(k + profit[i], minProfit)); } - return f[m][n][minProfit]; + ans %= mod; + return f[i][j][k] = ans; } } \ No newline at end of file diff --git a/solution/0800-0899/0879.Profitable Schemes/Solution.py b/solution/0800-0899/0879.Profitable Schemes/Solution.py index ec548940a47e2..bb73fa55e42b1 100644 --- a/solution/0800-0899/0879.Profitable Schemes/Solution.py +++ b/solution/0800-0899/0879.Profitable Schemes/Solution.py @@ -2,15 +2,13 @@ class Solution: def profitableSchemes( self, n: int, minProfit: int, group: List[int], profit: List[int] ) -> int: - mod = 10**9 + 7 - m = len(group) - f = [[[0] * (minProfit + 1) for _ in range(n + 1)] for _ in range(m + 1)] - for j in range(n + 1): - f[0][j][0] = 1 - for i, (x, p) in enumerate(zip(group, profit), 1): - for j in range(n + 1): - for k in range(minProfit + 1): - f[i][j][k] = f[i - 1][j][k] - if j >= x: - f[i][j][k] = (f[i][j][k] + f[i - 1][j - x][max(0, k - p)]) % mod - return f[m][n][minProfit] + @cache + def dfs(i: int, j: int, k: int) -> int: + if i >= len(group): + return 1 if k == minProfit else 0 + ans = dfs(i + 1, j, k) + if j + group[i] <= n: + ans += dfs(i + 1, j + group[i], min(k + profit[i], minProfit)) + return ans % (10**9 + 7) + + return dfs(0, 0, 0) diff --git a/solution/0800-0899/0879.Profitable Schemes/Solution2.cpp b/solution/0800-0899/0879.Profitable Schemes/Solution2.cpp new file mode 100644 index 0000000000000..b181c0fd3ecc6 --- /dev/null +++ b/solution/0800-0899/0879.Profitable Schemes/Solution2.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int profitableSchemes(int n, int minProfit, vector& group, vector& profit) { + int m = group.size(); + int f[m + 1][n + 1][minProfit + 1]; + memset(f, 0, sizeof(f)); + for (int j = 0; j <= n; ++j) { + f[0][j][0] = 1; + } + const int mod = 1e9 + 7; + for (int i = 1; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + for (int k = 0; k <= minProfit; ++k) { + f[i][j][k] = f[i - 1][j][k]; + if (j >= group[i - 1]) { + f[i][j][k] = (f[i][j][k] + f[i - 1][j - group[i - 1]][max(0, k - profit[i - 1])]) % mod; + } + } + } + } + return f[m][n][minProfit]; + } +}; \ No newline at end of file diff --git a/solution/0800-0899/0879.Profitable Schemes/Solution2.go b/solution/0800-0899/0879.Profitable Schemes/Solution2.go new file mode 100644 index 0000000000000..3da77b321365c --- /dev/null +++ b/solution/0800-0899/0879.Profitable Schemes/Solution2.go @@ -0,0 +1,26 @@ +func profitableSchemes(n int, minProfit int, group []int, profit []int) int { + m := len(group) + f := make([][][]int, m+1) + for i := range f { + f[i] = make([][]int, n+1) + for j := range f[i] { + f[i][j] = make([]int, minProfit+1) + } + } + for j := 0; j <= n; j++ { + f[0][j][0] = 1 + } + const mod = 1e9 + 7 + for i := 1; i <= m; i++ { + for j := 0; j <= n; j++ { + for k := 0; k <= minProfit; k++ { + f[i][j][k] = f[i-1][j][k] + if j >= group[i-1] { + f[i][j][k] += f[i-1][j-group[i-1]][max(0, k-profit[i-1])] + f[i][j][k] %= mod + } + } + } + } + return f[m][n][minProfit] +} \ No newline at end of file diff --git a/solution/0800-0899/0879.Profitable Schemes/Solution2.java b/solution/0800-0899/0879.Profitable Schemes/Solution2.java new file mode 100644 index 0000000000000..f95d3af71bda6 --- /dev/null +++ b/solution/0800-0899/0879.Profitable Schemes/Solution2.java @@ -0,0 +1,24 @@ +class Solution { + public int profitableSchemes(int n, int minProfit, int[] group, int[] profit) { + final int mod = (int) 1e9 + 7; + int m = group.length; + int[][][] f = new int[m + 1][n + 1][minProfit + 1]; + for (int j = 0; j <= n; ++j) { + f[0][j][0] = 1; + } + for (int i = 1; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + for (int k = 0; k <= minProfit; ++k) { + f[i][j][k] = f[i - 1][j][k]; + if (j >= group[i - 1]) { + f[i][j][k] + = (f[i][j][k] + + f[i - 1][j - group[i - 1]][Math.max(0, k - profit[i - 1])]) + % mod; + } + } + } + } + return f[m][n][minProfit]; + } +} \ No newline at end of file diff --git a/solution/0800-0899/0879.Profitable Schemes/Solution2.py b/solution/0800-0899/0879.Profitable Schemes/Solution2.py new file mode 100644 index 0000000000000..ec548940a47e2 --- /dev/null +++ b/solution/0800-0899/0879.Profitable Schemes/Solution2.py @@ -0,0 +1,16 @@ +class Solution: + def profitableSchemes( + self, n: int, minProfit: int, group: List[int], profit: List[int] + ) -> int: + mod = 10**9 + 7 + m = len(group) + f = [[[0] * (minProfit + 1) for _ in range(n + 1)] for _ in range(m + 1)] + for j in range(n + 1): + f[0][j][0] = 1 + for i, (x, p) in enumerate(zip(group, profit), 1): + for j in range(n + 1): + for k in range(minProfit + 1): + f[i][j][k] = f[i - 1][j][k] + if j >= x: + f[i][j][k] = (f[i][j][k] + f[i - 1][j - x][max(0, k - p)]) % mod + return f[m][n][minProfit] diff --git a/solution/0800-0899/0886.Possible Bipartition/Solution.cpp b/solution/0800-0899/0886.Possible Bipartition/Solution.cpp index b00e283a7f51d..85906d1b31298 100644 --- a/solution/0800-0899/0886.Possible Bipartition/Solution.cpp +++ b/solution/0800-0899/0886.Possible Bipartition/Solution.cpp @@ -1,23 +1,23 @@ class Solution { public: bool possibleBipartition(int n, vector>& dislikes) { - vector p(n); - iota(p.begin(), p.end(), 0); unordered_map> g; for (auto& e : dislikes) { int a = e[0] - 1, b = e[1] - 1; g[a].push_back(b); g[b].push_back(a); } - function find = [&](int x) -> int { - if (p[x] != x) p[x] = find(p[x]); - return p[x]; - }; - for (int i = 0; i < n; ++i) { + vector color(n); + function dfs = [&](int i, int c) -> bool { + color[i] = c; for (int j : g[i]) { - if (find(i) == find(j)) return false; - p[find(j)] = find(g[i][0]); + if (!color[j] && !dfs(j, 3 - c)) return false; + if (color[j] == c) return false; } + return true; + }; + for (int i = 0; i < n; ++i) { + if (!color[i] && !dfs(i, 1)) return false; } return true; } diff --git a/solution/0800-0899/0886.Possible Bipartition/Solution.go b/solution/0800-0899/0886.Possible Bipartition/Solution.go index ae087144afecf..1983adfbf11b2 100644 --- a/solution/0800-0899/0886.Possible Bipartition/Solution.go +++ b/solution/0800-0899/0886.Possible Bipartition/Solution.go @@ -1,27 +1,27 @@ func possibleBipartition(n int, dislikes [][]int) bool { - p := make([]int, n) g := make([][]int, n) - for i := range p { - p[i] = i - } for _, e := range dislikes { a, b := e[0]-1, e[1]-1 g[a] = append(g[a], b) g[b] = append(g[b], a) } - var find func(int) int - find = func(x int) int { - if p[x] != x { - p[x] = find(p[x]) - } - return p[x] - } - for i := 0; i < n; i++ { + color := make([]int, n) + var dfs func(int, int) bool + dfs = func(i, c int) bool { + color[i] = c for _, j := range g[i] { - if find(i) == find(j) { + if color[j] == c { return false } - p[find(j)] = find(g[i][0]) + if color[j] == 0 && !dfs(j, 3-c) { + return false + } + } + return true + } + for i, c := range color { + if c == 0 && !dfs(i, 1) { + return false } } return true diff --git a/solution/0800-0899/0886.Possible Bipartition/Solution.java b/solution/0800-0899/0886.Possible Bipartition/Solution.java index 389abc544ea4e..f2d792d245387 100644 --- a/solution/0800-0899/0886.Possible Bipartition/Solution.java +++ b/solution/0800-0899/0886.Possible Bipartition/Solution.java @@ -1,33 +1,36 @@ class Solution { - private int[] p; + private List[] g; + private int[] color; public boolean possibleBipartition(int n, int[][] dislikes) { - p = new int[n]; - List[] g = new List[n]; + g = new List[n]; + color = new int[n]; Arrays.setAll(g, k -> new ArrayList<>()); - for (int i = 0; i < n; ++i) { - p[i] = i; - } for (var e : dislikes) { int a = e[0] - 1, b = e[1] - 1; g[a].add(b); g[b].add(a); } for (int i = 0; i < n; ++i) { - for (int j : g[i]) { - if (find(i) == find(j)) { + if (color[i] == 0) { + if (!dfs(i, 1)) { return false; } - p[find(j)] = find(g[i].get(0)); } } return true; } - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); + private boolean dfs(int i, int c) { + color[i] = c; + for (int j : g[i]) { + if (color[j] == c) { + return false; + } + if (color[j] == 0 && !dfs(j, 3 - c)) { + return false; + } } - return p[x]; + return true; } } \ No newline at end of file diff --git a/solution/0800-0899/0886.Possible Bipartition/Solution.py b/solution/0800-0899/0886.Possible Bipartition/Solution.py index 74d8270abb53c..856ae66419fb9 100644 --- a/solution/0800-0899/0886.Possible Bipartition/Solution.py +++ b/solution/0800-0899/0886.Possible Bipartition/Solution.py @@ -1,19 +1,18 @@ class Solution: def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool: - def find(x): - if p[x] != x: - p[x] = find(p[x]) - return p[x] + def dfs(i, c): + color[i] = c + for j in g[i]: + if color[j] == c: + return False + if color[j] == 0 and not dfs(j, 3 - c): + return False + return True g = defaultdict(list) + color = [0] * n for a, b in dislikes: a, b = a - 1, b - 1 g[a].append(b) g[b].append(a) - p = list(range(n)) - for i in range(n): - for j in g[i]: - if find(i) == find(j): - return False - p[find(j)] = find(g[i][0]) - return True + return all(c or dfs(i, 1) for i, c in enumerate(color)) diff --git a/solution/0800-0899/0886.Possible Bipartition/Solution2.cpp b/solution/0800-0899/0886.Possible Bipartition/Solution2.cpp new file mode 100644 index 0000000000000..b00e283a7f51d --- /dev/null +++ b/solution/0800-0899/0886.Possible Bipartition/Solution2.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + bool possibleBipartition(int n, vector>& dislikes) { + vector p(n); + iota(p.begin(), p.end(), 0); + unordered_map> g; + for (auto& e : dislikes) { + int a = e[0] - 1, b = e[1] - 1; + g[a].push_back(b); + g[b].push_back(a); + } + function find = [&](int x) -> int { + if (p[x] != x) p[x] = find(p[x]); + return p[x]; + }; + for (int i = 0; i < n; ++i) { + for (int j : g[i]) { + if (find(i) == find(j)) return false; + p[find(j)] = find(g[i][0]); + } + } + return true; + } +}; \ No newline at end of file diff --git a/solution/0800-0899/0886.Possible Bipartition/Solution2.go b/solution/0800-0899/0886.Possible Bipartition/Solution2.go new file mode 100644 index 0000000000000..ae087144afecf --- /dev/null +++ b/solution/0800-0899/0886.Possible Bipartition/Solution2.go @@ -0,0 +1,28 @@ +func possibleBipartition(n int, dislikes [][]int) bool { + p := make([]int, n) + g := make([][]int, n) + for i := range p { + p[i] = i + } + for _, e := range dislikes { + a, b := e[0]-1, e[1]-1 + g[a] = append(g[a], b) + g[b] = append(g[b], a) + } + var find func(int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + for i := 0; i < n; i++ { + for _, j := range g[i] { + if find(i) == find(j) { + return false + } + p[find(j)] = find(g[i][0]) + } + } + return true +} \ No newline at end of file diff --git a/solution/0800-0899/0886.Possible Bipartition/Solution2.java b/solution/0800-0899/0886.Possible Bipartition/Solution2.java new file mode 100644 index 0000000000000..389abc544ea4e --- /dev/null +++ b/solution/0800-0899/0886.Possible Bipartition/Solution2.java @@ -0,0 +1,33 @@ +class Solution { + private int[] p; + + public boolean possibleBipartition(int n, int[][] dislikes) { + p = new int[n]; + List[] g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (int i = 0; i < n; ++i) { + p[i] = i; + } + for (var e : dislikes) { + int a = e[0] - 1, b = e[1] - 1; + g[a].add(b); + g[b].add(a); + } + for (int i = 0; i < n; ++i) { + for (int j : g[i]) { + if (find(i) == find(j)) { + return false; + } + p[find(j)] = find(g[i].get(0)); + } + } + return true; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} \ No newline at end of file diff --git a/solution/0800-0899/0886.Possible Bipartition/Solution2.py b/solution/0800-0899/0886.Possible Bipartition/Solution2.py new file mode 100644 index 0000000000000..74d8270abb53c --- /dev/null +++ b/solution/0800-0899/0886.Possible Bipartition/Solution2.py @@ -0,0 +1,19 @@ +class Solution: + def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool: + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + g = defaultdict(list) + for a, b in dislikes: + a, b = a - 1, b - 1 + g[a].append(b) + g[b].append(a) + p = list(range(n)) + for i in range(n): + for j in g[i]: + if find(i) == find(j): + return False + p[find(j)] = find(g[i][0]) + return True diff --git a/solution/0800-0899/0887.Super Egg Drop/Solution2.cpp b/solution/0800-0899/0887.Super Egg Drop/Solution2.cpp new file mode 100644 index 0000000000000..72b9e4d28ca3a --- /dev/null +++ b/solution/0800-0899/0887.Super Egg Drop/Solution2.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int superEggDrop(int k, int n) { + int f[n + 1][k + 1]; + memset(f, 0, sizeof(f)); + for (int i = 1; i <= n; ++i) { + f[i][1] = i; + } + for (int i = 1; i <= n; ++i) { + for (int j = 2; j <= k; ++j) { + int l = 1, r = i; + while (l < r) { + int mid = (l + r + 1) >> 1; + int a = f[mid - 1][j - 1]; + int b = f[i - mid][j]; + if (a <= b) { + l = mid; + } else { + r = mid - 1; + } + } + f[i][j] = max(f[l - 1][j - 1], f[i - l][j]) + 1; + } + } + return f[n][k]; + } +}; \ No newline at end of file diff --git a/solution/0800-0899/0887.Super Egg Drop/Solution2.go b/solution/0800-0899/0887.Super Egg Drop/Solution2.go new file mode 100644 index 0000000000000..fd9bc3ca3e38d --- /dev/null +++ b/solution/0800-0899/0887.Super Egg Drop/Solution2.go @@ -0,0 +1,25 @@ +func superEggDrop(k int, n int) int { + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, k+1) + } + for i := 1; i <= n; i++ { + f[i][1] = i + } + for i := 1; i <= n; i++ { + for j := 2; j <= k; j++ { + l, r := 1, i + for l < r { + mid := (l + r + 1) >> 1 + a, b := f[mid-1][j-1], f[i-mid][j] + if a <= b { + l = mid + } else { + r = mid - 1 + } + } + f[i][j] = max(f[l-1][j-1], f[i-l][j]) + 1 + } + } + return f[n][k] +} \ No newline at end of file diff --git a/solution/0800-0899/0887.Super Egg Drop/Solution2.java b/solution/0800-0899/0887.Super Egg Drop/Solution2.java new file mode 100644 index 0000000000000..e36965499f644 --- /dev/null +++ b/solution/0800-0899/0887.Super Egg Drop/Solution2.java @@ -0,0 +1,25 @@ +class Solution { + public int superEggDrop(int k, int n) { + int[][] f = new int[n + 1][k + 1]; + for (int i = 1; i <= n; ++i) { + f[i][1] = i; + } + for (int i = 1; i <= n; ++i) { + for (int j = 2; j <= k; ++j) { + int l = 1, r = i; + while (l < r) { + int mid = (l + r + 1) >> 1; + int a = f[mid - 1][j - 1]; + int b = f[i - mid][j]; + if (a <= b) { + l = mid; + } else { + r = mid - 1; + } + } + f[i][j] = Math.max(f[l - 1][j - 1], f[i - l][j]) + 1; + } + } + return f[n][k]; + } +} \ No newline at end of file diff --git a/solution/0800-0899/0887.Super Egg Drop/Solution2.py b/solution/0800-0899/0887.Super Egg Drop/Solution2.py new file mode 100644 index 0000000000000..6fbb350c1fc07 --- /dev/null +++ b/solution/0800-0899/0887.Super Egg Drop/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def superEggDrop(self, k: int, n: int) -> int: + f = [[0] * (k + 1) for _ in range(n + 1)] + for i in range(1, n + 1): + f[i][1] = i + for i in range(1, n + 1): + for j in range(2, k + 1): + l, r = 1, i + while l < r: + mid = (l + r + 1) >> 1 + a, b = f[mid - 1][j - 1], f[i - mid][j] + if a <= b: + l = mid + else: + r = mid - 1 + f[i][j] = max(f[l - 1][j - 1], f[i - l][j]) + 1 + return f[n][k] diff --git a/solution/0800-0899/0887.Super Egg Drop/Solution2.ts b/solution/0800-0899/0887.Super Egg Drop/Solution2.ts new file mode 100644 index 0000000000000..493c8986e9e24 --- /dev/null +++ b/solution/0800-0899/0887.Super Egg Drop/Solution2.ts @@ -0,0 +1,24 @@ +function superEggDrop(k: number, n: number): number { + const f: number[][] = new Array(n + 1).fill(0).map(() => new Array(k + 1).fill(0)); + for (let i = 1; i <= n; ++i) { + f[i][1] = i; + } + for (let i = 1; i <= n; ++i) { + for (let j = 2; j <= k; ++j) { + let l = 1; + let r = i; + while (l < r) { + const mid = (l + r + 1) >> 1; + const a = f[mid - 1][j - 1]; + const b = f[i - mid][j]; + if (a <= b) { + l = mid; + } else { + r = mid - 1; + } + } + f[i][j] = Math.max(f[l - 1][j - 1], f[i - l][j]) + 1; + } + } + return f[n][k]; +} diff --git a/solution/0800-0899/0889.Construct Binary Tree from Preorder and Postorder Traversal/Solution.cpp b/solution/0800-0899/0889.Construct Binary Tree from Preorder and Postorder Traversal/Solution.cpp index bd4ddeded4c78..b472be3a36a2c 100644 --- a/solution/0800-0899/0889.Construct Binary Tree from Preorder and Postorder Traversal/Solution.cpp +++ b/solution/0800-0899/0889.Construct Binary Tree from Preorder and Postorder Traversal/Solution.cpp @@ -29,4 +29,4 @@ class Solution { root->right = build(preorder, prel + leftLength + 1, prer, postorder, leftRootIndex + 1, postr - 1); return root; } -}; +}; \ No newline at end of file diff --git a/solution/0800-0899/0895.Maximum Frequency Stack/Solution.cpp b/solution/0800-0899/0895.Maximum Frequency Stack/Solution.cpp index 46a19955d44de..3e0381148260d 100644 --- a/solution/0800-0899/0895.Maximum Frequency Stack/Solution.cpp +++ b/solution/0800-0899/0895.Maximum Frequency Stack/Solution.cpp @@ -5,22 +5,20 @@ class FreqStack { void push(int val) { ++cnt[val]; - d[cnt[val]].push(val); - mx = max(mx, cnt[val]); + q.emplace(cnt[val], ++ts, val); } int pop() { - int val = d[mx].top(); + auto [a, b, val] = q.top(); + q.pop(); --cnt[val]; - d[mx].pop(); - if (d[mx].empty()) --mx; return val; } private: unordered_map cnt; - unordered_map> d; - int mx = 0; + priority_queue> q; + int ts = 0; }; /** diff --git a/solution/0800-0899/0895.Maximum Frequency Stack/Solution.go b/solution/0800-0899/0895.Maximum Frequency Stack/Solution.go index cbe4bf8236407..f6649c041d3fc 100644 --- a/solution/0800-0899/0895.Maximum Frequency Stack/Solution.go +++ b/solution/0800-0899/0895.Maximum Frequency Stack/Solution.go @@ -1,29 +1,36 @@ type FreqStack struct { cnt map[int]int - d map[int][]int - mx int + q hp + ts int } func Constructor() FreqStack { - return FreqStack{map[int]int{}, map[int][]int{}, 0} + return FreqStack{map[int]int{}, hp{}, 0} } func (this *FreqStack) Push(val int) { this.cnt[val]++ - this.d[this.cnt[val]] = append(this.d[this.cnt[val]], val) - this.mx = max(this.mx, this.cnt[val]) + this.ts++ + heap.Push(&this.q, tuple{this.cnt[val], this.ts, val}) } func (this *FreqStack) Pop() int { - val := this.d[this.mx][len(this.d[this.mx])-1] - this.d[this.mx] = this.d[this.mx][:len(this.d[this.mx])-1] + val := heap.Pop(&this.q).(tuple).val this.cnt[val]-- - if len(this.d[this.mx]) == 0 { - this.mx-- - } return val } +type tuple struct{ cnt, ts, val int } +type hp []tuple + +func (h hp) Len() int { return len(h) } +func (h hp) Less(i, j int) bool { + return h[i].cnt > h[j].cnt || h[i].cnt == h[j].cnt && h[i].ts > h[j].ts +} +func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } +func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } + /** * Your FreqStack object will be instantiated and called as such: * obj := Constructor(); diff --git a/solution/0800-0899/0895.Maximum Frequency Stack/Solution.java b/solution/0800-0899/0895.Maximum Frequency Stack/Solution.java index 7bd5d3cb77219..49bd6b23ffbd4 100644 --- a/solution/0800-0899/0895.Maximum Frequency Stack/Solution.java +++ b/solution/0800-0899/0895.Maximum Frequency Stack/Solution.java @@ -1,24 +1,20 @@ class FreqStack { private Map cnt = new HashMap<>(); - private Map> d = new HashMap<>(); - private int mx; + private PriorityQueue q + = new PriorityQueue<>((a, b) -> a[0] == b[0] ? b[1] - a[1] : b[0] - a[0]); + private int ts; public FreqStack() { } public void push(int val) { cnt.put(val, cnt.getOrDefault(val, 0) + 1); - int t = cnt.get(val); - d.computeIfAbsent(t, k -> new ArrayDeque<>()).push(val); - mx = Math.max(mx, t); + q.offer(new int[] {cnt.get(val), ++ts, val}); } public int pop() { - int val = d.get(mx).pop(); + int val = q.poll()[2]; cnt.put(val, cnt.get(val) - 1); - if (d.get(mx).isEmpty()) { - --mx; - } return val; } } diff --git a/solution/0800-0899/0895.Maximum Frequency Stack/Solution.py b/solution/0800-0899/0895.Maximum Frequency Stack/Solution.py index bf61f07f0c5c0..9aaa7fdada9ee 100644 --- a/solution/0800-0899/0895.Maximum Frequency Stack/Solution.py +++ b/solution/0800-0899/0895.Maximum Frequency Stack/Solution.py @@ -1,19 +1,17 @@ class FreqStack: def __init__(self): self.cnt = defaultdict(int) - self.d = defaultdict(list) - self.mx = 0 + self.q = [] + self.ts = 0 def push(self, val: int) -> None: + self.ts += 1 self.cnt[val] += 1 - self.d[self.cnt[val]].append(val) - self.mx = max(self.mx, self.cnt[val]) + heappush(self.q, (-self.cnt[val], -self.ts, val)) def pop(self) -> int: - val = self.d[self.mx].pop() + val = heappop(self.q)[2] self.cnt[val] -= 1 - if not self.d[self.mx]: - self.mx -= 1 return val diff --git a/solution/0800-0899/0895.Maximum Frequency Stack/Solution2.cpp b/solution/0800-0899/0895.Maximum Frequency Stack/Solution2.cpp new file mode 100644 index 0000000000000..46a19955d44de --- /dev/null +++ b/solution/0800-0899/0895.Maximum Frequency Stack/Solution2.cpp @@ -0,0 +1,31 @@ +class FreqStack { +public: + FreqStack() { + } + + void push(int val) { + ++cnt[val]; + d[cnt[val]].push(val); + mx = max(mx, cnt[val]); + } + + int pop() { + int val = d[mx].top(); + --cnt[val]; + d[mx].pop(); + if (d[mx].empty()) --mx; + return val; + } + +private: + unordered_map cnt; + unordered_map> d; + int mx = 0; +}; + +/** + * Your FreqStack object will be instantiated and called as such: + * FreqStack* obj = new FreqStack(); + * obj->push(val); + * int param_2 = obj->pop(); + */ \ No newline at end of file diff --git a/solution/0800-0899/0895.Maximum Frequency Stack/Solution2.go b/solution/0800-0899/0895.Maximum Frequency Stack/Solution2.go new file mode 100644 index 0000000000000..cbe4bf8236407 --- /dev/null +++ b/solution/0800-0899/0895.Maximum Frequency Stack/Solution2.go @@ -0,0 +1,32 @@ +type FreqStack struct { + cnt map[int]int + d map[int][]int + mx int +} + +func Constructor() FreqStack { + return FreqStack{map[int]int{}, map[int][]int{}, 0} +} + +func (this *FreqStack) Push(val int) { + this.cnt[val]++ + this.d[this.cnt[val]] = append(this.d[this.cnt[val]], val) + this.mx = max(this.mx, this.cnt[val]) +} + +func (this *FreqStack) Pop() int { + val := this.d[this.mx][len(this.d[this.mx])-1] + this.d[this.mx] = this.d[this.mx][:len(this.d[this.mx])-1] + this.cnt[val]-- + if len(this.d[this.mx]) == 0 { + this.mx-- + } + return val +} + +/** + * Your FreqStack object will be instantiated and called as such: + * obj := Constructor(); + * obj.Push(val); + * param_2 := obj.Pop(); + */ \ No newline at end of file diff --git a/solution/0800-0899/0895.Maximum Frequency Stack/Solution2.java b/solution/0800-0899/0895.Maximum Frequency Stack/Solution2.java new file mode 100644 index 0000000000000..7bd5d3cb77219 --- /dev/null +++ b/solution/0800-0899/0895.Maximum Frequency Stack/Solution2.java @@ -0,0 +1,31 @@ +class FreqStack { + private Map cnt = new HashMap<>(); + private Map> d = new HashMap<>(); + private int mx; + + public FreqStack() { + } + + public void push(int val) { + cnt.put(val, cnt.getOrDefault(val, 0) + 1); + int t = cnt.get(val); + d.computeIfAbsent(t, k -> new ArrayDeque<>()).push(val); + mx = Math.max(mx, t); + } + + public int pop() { + int val = d.get(mx).pop(); + cnt.put(val, cnt.get(val) - 1); + if (d.get(mx).isEmpty()) { + --mx; + } + return val; + } +} + +/** + * Your FreqStack object will be instantiated and called as such: + * FreqStack obj = new FreqStack(); + * obj.push(val); + * int param_2 = obj.pop(); + */ \ No newline at end of file diff --git a/solution/0800-0899/0895.Maximum Frequency Stack/Solution2.py b/solution/0800-0899/0895.Maximum Frequency Stack/Solution2.py new file mode 100644 index 0000000000000..bf61f07f0c5c0 --- /dev/null +++ b/solution/0800-0899/0895.Maximum Frequency Stack/Solution2.py @@ -0,0 +1,23 @@ +class FreqStack: + def __init__(self): + self.cnt = defaultdict(int) + self.d = defaultdict(list) + self.mx = 0 + + def push(self, val: int) -> None: + self.cnt[val] += 1 + self.d[self.cnt[val]].append(val) + self.mx = max(self.mx, self.cnt[val]) + + def pop(self) -> int: + val = self.d[self.mx].pop() + self.cnt[val] -= 1 + if not self.d[self.mx]: + self.mx -= 1 + return val + + +# Your FreqStack object will be instantiated and called as such: +# obj = FreqStack() +# obj.push(val) +# param_2 = obj.pop() diff --git a/solution/0800-0899/0896.Monotonic Array/Solution.cpp b/solution/0800-0899/0896.Monotonic Array/Solution.cpp index 6145b84e605e5..eee55f64b0e09 100644 --- a/solution/0800-0899/0896.Monotonic Array/Solution.cpp +++ b/solution/0800-0899/0896.Monotonic Array/Solution.cpp @@ -1,17 +1,17 @@ -class Solution { -public: - bool isMonotonic(vector& nums) { - bool asc = false, desc = false; - for (int i = 1; i < nums.size(); ++i) { - if (nums[i - 1] < nums[i]) { - asc = true; - } else if (nums[i - 1] > nums[i]) { - desc = true; - } - if (asc && desc) { - return false; - } - } - return true; - } +class Solution { +public: + bool isMonotonic(vector& nums) { + bool asc = false, desc = false; + for (int i = 1; i < nums.size(); ++i) { + if (nums[i - 1] < nums[i]) { + asc = true; + } else if (nums[i - 1] > nums[i]) { + desc = true; + } + if (asc && desc) { + return false; + } + } + return true; + } }; \ No newline at end of file diff --git a/solution/0800-0899/0896.Monotonic Array/Solution.java b/solution/0800-0899/0896.Monotonic Array/Solution.java index 95c351ec0fa8a..239c39faef3a5 100644 --- a/solution/0800-0899/0896.Monotonic Array/Solution.java +++ b/solution/0800-0899/0896.Monotonic Array/Solution.java @@ -1,16 +1,16 @@ -class Solution { - public boolean isMonotonic(int[] nums) { - boolean asc = false, desc = false; - for (int i = 1; i < nums.length; ++i) { - if (nums[i - 1] < nums[i]) { - asc = true; - } else if (nums[i - 1] > nums[i]) { - desc = true; - } - if (asc && desc) { - return false; - } - } - return true; - } +class Solution { + public boolean isMonotonic(int[] nums) { + boolean asc = false, desc = false; + for (int i = 1; i < nums.length; ++i) { + if (nums[i - 1] < nums[i]) { + asc = true; + } else if (nums[i - 1] > nums[i]) { + desc = true; + } + if (asc && desc) { + return false; + } + } + return true; + } } \ No newline at end of file diff --git a/solution/0800-0899/0896.Monotonic Array/Solution.py b/solution/0800-0899/0896.Monotonic Array/Solution.py index a4b7d0f176786..7dc6906d94ffc 100644 --- a/solution/0800-0899/0896.Monotonic Array/Solution.py +++ b/solution/0800-0899/0896.Monotonic Array/Solution.py @@ -1,5 +1,5 @@ -class Solution: - def isMonotonic(self, nums: List[int]) -> bool: - asc = all(a <= b for a, b in pairwise(nums)) - desc = all(a >= b for a, b in pairwise(nums)) - return asc or desc +class Solution: + def isMonotonic(self, nums: List[int]) -> bool: + asc = all(a <= b for a, b in pairwise(nums)) + desc = all(a >= b for a, b in pairwise(nums)) + return asc or desc diff --git a/solution/0800-0899/0897.Increasing Order Search Tree/Solution.cpp b/solution/0800-0899/0897.Increasing Order Search Tree/Solution.cpp index 25a34d670957c..aaaaa3a19602f 100644 --- a/solution/0800-0899/0897.Increasing Order Search Tree/Solution.cpp +++ b/solution/0800-0899/0897.Increasing Order Search Tree/Solution.cpp @@ -1,30 +1,30 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* increasingBST(TreeNode* root) { - TreeNode* dummy = new TreeNode(0, nullptr, root); - TreeNode* prev = dummy; - function dfs = [&](TreeNode* root) { - if (!root) { - return; - } - dfs(root->left); - prev->right = root; - root->left = nullptr; - prev = root; - dfs(root->right); - }; - dfs(root); - return dummy->right; - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* increasingBST(TreeNode* root) { + TreeNode* dummy = new TreeNode(0, nullptr, root); + TreeNode* prev = dummy; + function dfs = [&](TreeNode* root) { + if (!root) { + return; + } + dfs(root->left); + prev->right = root; + root->left = nullptr; + prev = root; + dfs(root->right); + }; + dfs(root); + return dummy->right; + } }; \ No newline at end of file diff --git a/solution/0800-0899/0897.Increasing Order Search Tree/Solution.java b/solution/0800-0899/0897.Increasing Order Search Tree/Solution.java index 58ea6241f76a6..8fe4a327b6640 100644 --- a/solution/0800-0899/0897.Increasing Order Search Tree/Solution.java +++ b/solution/0800-0899/0897.Increasing Order Search Tree/Solution.java @@ -1,35 +1,35 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private TreeNode prev; - public TreeNode increasingBST(TreeNode root) { - TreeNode dummy = new TreeNode(0, null, root); - prev = dummy; - dfs(root); - return dummy.right; - } - - private void dfs(TreeNode root) { - if (root == null) { - return; - } - dfs(root.left); - prev.right = root; - root.left = null; - prev = root; - dfs(root.right); - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private TreeNode prev; + public TreeNode increasingBST(TreeNode root) { + TreeNode dummy = new TreeNode(0, null, root); + prev = dummy; + dfs(root); + return dummy.right; + } + + private void dfs(TreeNode root) { + if (root == null) { + return; + } + dfs(root.left); + prev.right = root; + root.left = null; + prev = root; + dfs(root.right); + } } \ No newline at end of file diff --git a/solution/0800-0899/0897.Increasing Order Search Tree/Solution.py b/solution/0800-0899/0897.Increasing Order Search Tree/Solution.py index 2ef6d7690b328..4fda648655b75 100644 --- a/solution/0800-0899/0897.Increasing Order Search Tree/Solution.py +++ b/solution/0800-0899/0897.Increasing Order Search Tree/Solution.py @@ -1,21 +1,21 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def increasingBST(self, root: TreeNode) -> TreeNode: - def dfs(root): - if root is None: - return - nonlocal prev - dfs(root.left) - prev.right = root - root.left = None - prev = root - dfs(root.right) - - dummy = prev = TreeNode(right=root) - dfs(root) - return dummy.right +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def increasingBST(self, root: TreeNode) -> TreeNode: + def dfs(root): + if root is None: + return + nonlocal prev + dfs(root.left) + prev.right = root + root.left = None + prev = root + dfs(root.right) + + dummy = prev = TreeNode(right=root) + dfs(root) + return dummy.right diff --git a/solution/0800-0899/0898.Bitwise ORs of Subarrays/Solution.cpp b/solution/0800-0899/0898.Bitwise ORs of Subarrays/Solution.cpp index fcff01a405c7e..c4417a1fcf5c0 100644 --- a/solution/0800-0899/0898.Bitwise ORs of Subarrays/Solution.cpp +++ b/solution/0800-0899/0898.Bitwise ORs of Subarrays/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - int subarrayBitwiseORs(vector& arr) { - unordered_set s{{0}}; - unordered_set ans; - for (int& x : arr) { - unordered_set t{{x}}; - for (int y : s) { - t.insert(x | y); - } - s = move(t); - ans.insert(s.begin(), s.end()); - } - return ans.size(); - } +class Solution { +public: + int subarrayBitwiseORs(vector& arr) { + unordered_set s{{0}}; + unordered_set ans; + for (int& x : arr) { + unordered_set t{{x}}; + for (int y : s) { + t.insert(x | y); + } + s = move(t); + ans.insert(s.begin(), s.end()); + } + return ans.size(); + } }; \ No newline at end of file diff --git a/solution/0800-0899/0898.Bitwise ORs of Subarrays/Solution.java b/solution/0800-0899/0898.Bitwise ORs of Subarrays/Solution.java index 8749f8515d355..5ff6c49e19595 100644 --- a/solution/0800-0899/0898.Bitwise ORs of Subarrays/Solution.java +++ b/solution/0800-0899/0898.Bitwise ORs of Subarrays/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public int subarrayBitwiseORs(int[] arr) { - Set s = new HashSet<>(); - s.add(0); - Set ans = new HashSet<>(); - for (int x : arr) { - Set t = new HashSet<>(); - for (int y : s) { - t.add(x | y); - } - t.add(x); - s = t; - ans.addAll(s); - } - return ans.size(); - } +class Solution { + public int subarrayBitwiseORs(int[] arr) { + Set s = new HashSet<>(); + s.add(0); + Set ans = new HashSet<>(); + for (int x : arr) { + Set t = new HashSet<>(); + for (int y : s) { + t.add(x | y); + } + t.add(x); + s = t; + ans.addAll(s); + } + return ans.size(); + } } \ No newline at end of file diff --git a/solution/0800-0899/0898.Bitwise ORs of Subarrays/Solution.py b/solution/0800-0899/0898.Bitwise ORs of Subarrays/Solution.py index 4400928eb8e5a..eeb068dd19f1c 100644 --- a/solution/0800-0899/0898.Bitwise ORs of Subarrays/Solution.py +++ b/solution/0800-0899/0898.Bitwise ORs of Subarrays/Solution.py @@ -1,8 +1,8 @@ -class Solution: - def subarrayBitwiseORs(self, arr: List[int]) -> int: - s = {0} - ans = set() - for x in arr: - s = {x | y for y in s} | {x} - ans |= s - return len(ans) +class Solution: + def subarrayBitwiseORs(self, arr: List[int]) -> int: + s = {0} + ans = set() + for x in arr: + s = {x | y for y in s} | {x} + ans |= s + return len(ans) diff --git a/solution/0800-0899/0899.Orderly Queue/Solution.java b/solution/0800-0899/0899.Orderly Queue/Solution.java new file mode 100644 index 0000000000000..76c495fa5eedc --- /dev/null +++ b/solution/0800-0899/0899.Orderly Queue/Solution.java @@ -0,0 +1,18 @@ +class Solution { + public String orderlyQueue(String s, int k) { + if (k == 1) { + String ans = s; + StringBuilder sb = new StringBuilder(s); + for (int i = 0; i < s.length() - 1; ++i) { + sb.append(sb.charAt(0)).deleteCharAt(0); + if (sb.toString().compareTo(ans) < 0) { + ans = sb.toString(); + } + } + return ans; + } + char[] cs = s.toCharArray(); + Arrays.sort(cs); + return String.valueOf(cs); + } +} \ No newline at end of file diff --git a/solution/0900-0999/0900.RLE Iterator/Solution.cpp b/solution/0900-0999/0900.RLE Iterator/Solution.cpp index 55f97fd09bde5..df7a4fc9c0064 100644 --- a/solution/0900-0999/0900.RLE Iterator/Solution.cpp +++ b/solution/0900-0999/0900.RLE Iterator/Solution.cpp @@ -1,31 +1,31 @@ -class RLEIterator { -public: - RLEIterator(vector& encoding) { - this->encoding = encoding; - } - - int next(int n) { - while (i < encoding.size()) { - if (encoding[i] - j < n) { - n -= (encoding[i] - j); - i += 2; - j = 0; - } else { - j += n; - return encoding[i + 1]; - } - } - return -1; - } - -private: - vector encoding; - int i = 0; - int j = 0; -}; - -/** - * Your RLEIterator object will be instantiated and called as such: - * RLEIterator* obj = new RLEIterator(encoding); - * int param_1 = obj->next(n); +class RLEIterator { +public: + RLEIterator(vector& encoding) { + this->encoding = encoding; + } + + int next(int n) { + while (i < encoding.size()) { + if (encoding[i] - j < n) { + n -= (encoding[i] - j); + i += 2; + j = 0; + } else { + j += n; + return encoding[i + 1]; + } + } + return -1; + } + +private: + vector encoding; + int i = 0; + int j = 0; +}; + +/** + * Your RLEIterator object will be instantiated and called as such: + * RLEIterator* obj = new RLEIterator(encoding); + * int param_1 = obj->next(n); */ \ No newline at end of file diff --git a/solution/0900-0999/0900.RLE Iterator/Solution.java b/solution/0900-0999/0900.RLE Iterator/Solution.java index 94f0ad4d82376..735c3fac873cf 100644 --- a/solution/0900-0999/0900.RLE Iterator/Solution.java +++ b/solution/0900-0999/0900.RLE Iterator/Solution.java @@ -1,29 +1,29 @@ -class RLEIterator { - private int[] encoding; - private int i; - private int j; - - public RLEIterator(int[] encoding) { - this.encoding = encoding; - } - - public int next(int n) { - while (i < encoding.length) { - if (encoding[i] - j < n) { - n -= (encoding[i] - j); - i += 2; - j = 0; - } else { - j += n; - return encoding[i + 1]; - } - } - return -1; - } -} - -/** - * Your RLEIterator object will be instantiated and called as such: - * RLEIterator obj = new RLEIterator(encoding); - * int param_1 = obj.next(n); +class RLEIterator { + private int[] encoding; + private int i; + private int j; + + public RLEIterator(int[] encoding) { + this.encoding = encoding; + } + + public int next(int n) { + while (i < encoding.length) { + if (encoding[i] - j < n) { + n -= (encoding[i] - j); + i += 2; + j = 0; + } else { + j += n; + return encoding[i + 1]; + } + } + return -1; + } +} + +/** + * Your RLEIterator object will be instantiated and called as such: + * RLEIterator obj = new RLEIterator(encoding); + * int param_1 = obj.next(n); */ \ No newline at end of file diff --git a/solution/0900-0999/0900.RLE Iterator/Solution.py b/solution/0900-0999/0900.RLE Iterator/Solution.py index 0344fbf233712..496f351d51eee 100644 --- a/solution/0900-0999/0900.RLE Iterator/Solution.py +++ b/solution/0900-0999/0900.RLE Iterator/Solution.py @@ -1,21 +1,21 @@ -class RLEIterator: - def __init__(self, encoding: List[int]): - self.encoding = encoding - self.i = 0 - self.j = 0 - - def next(self, n: int) -> int: - while self.i < len(self.encoding): - if self.encoding[self.i] - self.j < n: - n -= self.encoding[self.i] - self.j - self.i += 2 - self.j = 0 - else: - self.j += n - return self.encoding[self.i + 1] - return -1 - - -# Your RLEIterator object will be instantiated and called as such: -# obj = RLEIterator(encoding) -# param_1 = obj.next(n) +class RLEIterator: + def __init__(self, encoding: List[int]): + self.encoding = encoding + self.i = 0 + self.j = 0 + + def next(self, n: int) -> int: + while self.i < len(self.encoding): + if self.encoding[self.i] - self.j < n: + n -= self.encoding[self.i] - self.j + self.i += 2 + self.j = 0 + else: + self.j += n + return self.encoding[self.i + 1] + return -1 + + +# Your RLEIterator object will be instantiated and called as such: +# obj = RLEIterator(encoding) +# param_1 = obj.next(n) diff --git a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.cpp b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.cpp index c3845da5f6bd8..9c32a3fe26a80 100644 --- a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.cpp +++ b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.cpp @@ -1,30 +1,30 @@ -class Solution { -public: - int numPermsDISequence(string s) { - const int mod = 1e9 + 7; - int n = s.size(); - vector f(n + 1); - f[0] = 1; - for (int i = 1; i <= n; ++i) { - int pre = 0; - vector g(n + 1); - if (s[i - 1] == 'D') { - for (int j = i; j >= 0; --j) { - pre = (pre + f[j]) % mod; - g[j] = pre; - } - } else { - for (int j = 0; j <= i; ++j) { - g[j] = pre; - pre = (pre + f[j]) % mod; - } - } - f = move(g); - } - int ans = 0; - for (int j = 0; j <= n; ++j) { - ans = (ans + f[j]) % mod; - } - return ans; - } +class Solution { +public: + int numPermsDISequence(string s) { + const int mod = 1e9 + 7; + int n = s.size(); + int f[n + 1][n + 1]; + memset(f, 0, sizeof(f)); + f[0][0] = 1; + for (int i = 1; i <= n; ++i) { + if (s[i - 1] == 'D') { + for (int j = 0; j <= i; ++j) { + for (int k = j; k < i; ++k) { + f[i][j] = (f[i][j] + f[i - 1][k]) % mod; + } + } + } else { + for (int j = 0; j <= i; ++j) { + for (int k = 0; k < j; ++k) { + f[i][j] = (f[i][j] + f[i - 1][k]) % mod; + } + } + } + } + int ans = 0; + for (int j = 0; j <= n; ++j) { + ans = (ans + f[n][j]) % mod; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.go b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.go index 391b2e74a02dd..5dd5ff91fa696 100644 --- a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.go +++ b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.go @@ -1,26 +1,28 @@ func numPermsDISequence(s string) (ans int) { const mod = 1e9 + 7 n := len(s) - f := make([]int, n+1) - f[0] = 1 + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, n+1) + } + f[0][0] = 1 for i := 1; i <= n; i++ { - pre := 0 - g := make([]int, n+1) if s[i-1] == 'D' { - for j := i; j >= 0; j-- { - pre = (pre + f[j]) % mod - g[j] = pre + for j := 0; j <= i; j++ { + for k := j; k < i; k++ { + f[i][j] = (f[i][j] + f[i-1][k]) % mod + } } } else { for j := 0; j <= i; j++ { - g[j] = pre - pre = (pre + f[j]) % mod + for k := 0; k < j; k++ { + f[i][j] = (f[i][j] + f[i-1][k]) % mod + } } } - f = g } for j := 0; j <= n; j++ { - ans = (ans + f[j]) % mod + ans = (ans + f[n][j]) % mod } return } \ No newline at end of file diff --git a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.java b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.java index 9d11a43771f96..73a84bfe8c084 100644 --- a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.java +++ b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.java @@ -1,29 +1,28 @@ -class Solution { - public int numPermsDISequence(String s) { - final int mod = (int) 1e9 + 7; - int n = s.length(); - int[] f = new int[n + 1]; - f[0] = 1; - for (int i = 1; i <= n; ++i) { - int pre = 0; - int[] g = new int[n + 1]; - if (s.charAt(i - 1) == 'D') { - for (int j = i; j >= 0; --j) { - pre = (pre + f[j]) % mod; - g[j] = pre; - } - } else { - for (int j = 0; j <= i; ++j) { - g[j] = pre; - pre = (pre + f[j]) % mod; - } - } - f = g; - } - int ans = 0; - for (int j = 0; j <= n; ++j) { - ans = (ans + f[j]) % mod; - } - return ans; - } +class Solution { + public int numPermsDISequence(String s) { + final int mod = (int) 1e9 + 7; + int n = s.length(); + int[][] f = new int[n + 1][n + 1]; + f[0][0] = 1; + for (int i = 1; i <= n; ++i) { + if (s.charAt(i - 1) == 'D') { + for (int j = 0; j <= i; ++j) { + for (int k = j; k < i; ++k) { + f[i][j] = (f[i][j] + f[i - 1][k]) % mod; + } + } + } else { + for (int j = 0; j <= i; ++j) { + for (int k = 0; k < j; ++k) { + f[i][j] = (f[i][j] + f[i - 1][k]) % mod; + } + } + } + } + int ans = 0; + for (int j = 0; j <= n; ++j) { + ans = (ans + f[n][j]) % mod; + } + return ans; + } } \ No newline at end of file diff --git a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.py b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.py index bb5771382502e..a5e166cf456dd 100644 --- a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.py +++ b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.py @@ -1,18 +1,16 @@ -class Solution: - def numPermsDISequence(self, s: str) -> int: - mod = 10**9 + 7 - n = len(s) - f = [1] + [0] * n - for i, c in enumerate(s, 1): - pre = 0 - g = [0] * (n + 1) - if c == "D": - for j in range(i, -1, -1): - pre = (pre + f[j]) % mod - g[j] = pre - else: - for j in range(i + 1): - g[j] = pre - pre = (pre + f[j]) % mod - f = g - return sum(f) % mod +class Solution: + def numPermsDISequence(self, s: str) -> int: + mod = 10**9 + 7 + n = len(s) + f = [[0] * (n + 1) for _ in range(n + 1)] + f[0][0] = 1 + for i, c in enumerate(s, 1): + if c == "D": + for j in range(i + 1): + for k in range(j, i): + f[i][j] = (f[i][j] + f[i - 1][k]) % mod + else: + for j in range(i + 1): + for k in range(j): + f[i][j] = (f[i][j] + f[i - 1][k]) % mod + return sum(f[n][j] for j in range(n + 1)) % mod diff --git a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.ts b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.ts index 509517a1473df..476600401ead1 100644 --- a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.ts +++ b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution.ts @@ -1,27 +1,28 @@ function numPermsDISequence(s: string): number { const n = s.length; - let f: number[] = Array(n + 1).fill(0); - f[0] = 1; + const f: number[][] = Array(n + 1) + .fill(0) + .map(() => Array(n + 1).fill(0)); + f[0][0] = 1; const mod = 10 ** 9 + 7; for (let i = 1; i <= n; ++i) { - let pre = 0; - const g: number[] = Array(n + 1).fill(0); if (s[i - 1] === 'D') { - for (let j = i; j >= 0; --j) { - pre = (pre + f[j]) % mod; - g[j] = pre; + for (let j = 0; j <= i; ++j) { + for (let k = j; k < i; ++k) { + f[i][j] = (f[i][j] + f[i - 1][k]) % mod; + } } } else { for (let j = 0; j <= i; ++j) { - g[j] = pre; - pre = (pre + f[j]) % mod; + for (let k = 0; k < j; ++k) { + f[i][j] = (f[i][j] + f[i - 1][k]) % mod; + } } } - f = g; } let ans = 0; for (let j = 0; j <= n; ++j) { - ans = (ans + f[j]) % mod; + ans = (ans + f[n][j]) % mod; } return ans; } diff --git a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution2.cpp b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution2.cpp new file mode 100644 index 0000000000000..dd1333325ce17 --- /dev/null +++ b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution2.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int numPermsDISequence(string s) { + const int mod = 1e9 + 7; + int n = s.size(); + int f[n + 1][n + 1]; + memset(f, 0, sizeof(f)); + f[0][0] = 1; + for (int i = 1; i <= n; ++i) { + int pre = 0; + if (s[i - 1] == 'D') { + for (int j = i; j >= 0; --j) { + pre = (pre + f[i - 1][j]) % mod; + f[i][j] = pre; + } + } else { + for (int j = 0; j <= i; ++j) { + f[i][j] = pre; + pre = (pre + f[i - 1][j]) % mod; + } + } + } + int ans = 0; + for (int j = 0; j <= n; ++j) { + ans = (ans + f[n][j]) % mod; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution2.go b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution2.go new file mode 100644 index 0000000000000..95e1b18d67c86 --- /dev/null +++ b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution2.go @@ -0,0 +1,27 @@ +func numPermsDISequence(s string) (ans int) { + const mod = 1e9 + 7 + n := len(s) + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, n+1) + } + f[0][0] = 1 + for i := 1; i <= n; i++ { + pre := 0 + if s[i-1] == 'D' { + for j := i; j >= 0; j-- { + pre = (pre + f[i-1][j]) % mod + f[i][j] = pre + } + } else { + for j := 0; j <= i; j++ { + f[i][j] = pre + pre = (pre + f[i-1][j]) % mod + } + } + } + for j := 0; j <= n; j++ { + ans = (ans + f[n][j]) % mod + } + return +} \ No newline at end of file diff --git a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution2.java b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution2.java new file mode 100644 index 0000000000000..eafa5cc8a305e --- /dev/null +++ b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution2.java @@ -0,0 +1,27 @@ +class Solution { + public int numPermsDISequence(String s) { + final int mod = (int) 1e9 + 7; + int n = s.length(); + int[][] f = new int[n + 1][n + 1]; + f[0][0] = 1; + for (int i = 1; i <= n; ++i) { + int pre = 0; + if (s.charAt(i - 1) == 'D') { + for (int j = i; j >= 0; --j) { + pre = (pre + f[i - 1][j]) % mod; + f[i][j] = pre; + } + } else { + for (int j = 0; j <= i; ++j) { + f[i][j] = pre; + pre = (pre + f[i - 1][j]) % mod; + } + } + } + int ans = 0; + for (int j = 0; j <= n; ++j) { + ans = (ans + f[n][j]) % mod; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution2.py b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution2.py new file mode 100644 index 0000000000000..0279d18062738 --- /dev/null +++ b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def numPermsDISequence(self, s: str) -> int: + mod = 10**9 + 7 + n = len(s) + f = [[0] * (n + 1) for _ in range(n + 1)] + f[0][0] = 1 + for i, c in enumerate(s, 1): + pre = 0 + if c == "D": + for j in range(i, -1, -1): + pre = (pre + f[i - 1][j]) % mod + f[i][j] = pre + else: + for j in range(i + 1): + f[i][j] = pre + pre = (pre + f[i - 1][j]) % mod + return sum(f[n][j] for j in range(n + 1)) % mod diff --git a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution2.ts b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution2.ts new file mode 100644 index 0000000000000..4039350ea8cac --- /dev/null +++ b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution2.ts @@ -0,0 +1,27 @@ +function numPermsDISequence(s: string): number { + const n = s.length; + const f: number[][] = Array(n + 1) + .fill(0) + .map(() => Array(n + 1).fill(0)); + f[0][0] = 1; + const mod = 10 ** 9 + 7; + for (let i = 1; i <= n; ++i) { + let pre = 0; + if (s[i - 1] === 'D') { + for (let j = i; j >= 0; --j) { + pre = (pre + f[i - 1][j]) % mod; + f[i][j] = pre; + } + } else { + for (let j = 0; j <= i; ++j) { + f[i][j] = pre; + pre = (pre + f[i - 1][j]) % mod; + } + } + } + let ans = 0; + for (let j = 0; j <= n; ++j) { + ans = (ans + f[n][j]) % mod; + } + return ans; +} diff --git a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution3.cpp b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution3.cpp new file mode 100644 index 0000000000000..d577f07b0801e --- /dev/null +++ b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution3.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int numPermsDISequence(string s) { + const int mod = 1e9 + 7; + int n = s.size(); + vector f(n + 1); + f[0] = 1; + for (int i = 1; i <= n; ++i) { + int pre = 0; + vector g(n + 1); + if (s[i - 1] == 'D') { + for (int j = i; j >= 0; --j) { + pre = (pre + f[j]) % mod; + g[j] = pre; + } + } else { + for (int j = 0; j <= i; ++j) { + g[j] = pre; + pre = (pre + f[j]) % mod; + } + } + f = move(g); + } + int ans = 0; + for (int j = 0; j <= n; ++j) { + ans = (ans + f[j]) % mod; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution3.go b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution3.go new file mode 100644 index 0000000000000..391b2e74a02dd --- /dev/null +++ b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution3.go @@ -0,0 +1,26 @@ +func numPermsDISequence(s string) (ans int) { + const mod = 1e9 + 7 + n := len(s) + f := make([]int, n+1) + f[0] = 1 + for i := 1; i <= n; i++ { + pre := 0 + g := make([]int, n+1) + if s[i-1] == 'D' { + for j := i; j >= 0; j-- { + pre = (pre + f[j]) % mod + g[j] = pre + } + } else { + for j := 0; j <= i; j++ { + g[j] = pre + pre = (pre + f[j]) % mod + } + } + f = g + } + for j := 0; j <= n; j++ { + ans = (ans + f[j]) % mod + } + return +} \ No newline at end of file diff --git a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution3.java b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution3.java new file mode 100644 index 0000000000000..378da89a9186d --- /dev/null +++ b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution3.java @@ -0,0 +1,29 @@ +class Solution { + public int numPermsDISequence(String s) { + final int mod = (int) 1e9 + 7; + int n = s.length(); + int[] f = new int[n + 1]; + f[0] = 1; + for (int i = 1; i <= n; ++i) { + int pre = 0; + int[] g = new int[n + 1]; + if (s.charAt(i - 1) == 'D') { + for (int j = i; j >= 0; --j) { + pre = (pre + f[j]) % mod; + g[j] = pre; + } + } else { + for (int j = 0; j <= i; ++j) { + g[j] = pre; + pre = (pre + f[j]) % mod; + } + } + f = g; + } + int ans = 0; + for (int j = 0; j <= n; ++j) { + ans = (ans + f[j]) % mod; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution3.py b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution3.py new file mode 100644 index 0000000000000..6b06595bdeb4b --- /dev/null +++ b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution3.py @@ -0,0 +1,18 @@ +class Solution: + def numPermsDISequence(self, s: str) -> int: + mod = 10**9 + 7 + n = len(s) + f = [1] + [0] * n + for i, c in enumerate(s, 1): + pre = 0 + g = [0] * (n + 1) + if c == "D": + for j in range(i, -1, -1): + pre = (pre + f[j]) % mod + g[j] = pre + else: + for j in range(i + 1): + g[j] = pre + pre = (pre + f[j]) % mod + f = g + return sum(f) % mod diff --git a/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution3.ts b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution3.ts new file mode 100644 index 0000000000000..509517a1473df --- /dev/null +++ b/solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution3.ts @@ -0,0 +1,27 @@ +function numPermsDISequence(s: string): number { + const n = s.length; + let f: number[] = Array(n + 1).fill(0); + f[0] = 1; + const mod = 10 ** 9 + 7; + for (let i = 1; i <= n; ++i) { + let pre = 0; + const g: number[] = Array(n + 1).fill(0); + if (s[i - 1] === 'D') { + for (let j = i; j >= 0; --j) { + pre = (pre + f[j]) % mod; + g[j] = pre; + } + } else { + for (let j = 0; j <= i; ++j) { + g[j] = pre; + pre = (pre + f[j]) % mod; + } + } + f = g; + } + let ans = 0; + for (let j = 0; j <= n; ++j) { + ans = (ans + f[j]) % mod; + } + return ans; +} diff --git a/solution/0900-0999/0904.Fruit Into Baskets/Solution.cpp b/solution/0900-0999/0904.Fruit Into Baskets/Solution.cpp index 51edbc4eb67fc..764fdf4dfda21 100644 --- a/solution/0900-0999/0904.Fruit Into Baskets/Solution.cpp +++ b/solution/0900-0999/0904.Fruit Into Baskets/Solution.cpp @@ -2,14 +2,16 @@ class Solution { public: int totalFruit(vector& fruits) { unordered_map cnt; - int j = 0, n = fruits.size(); - for (int& x : fruits) { + int ans = 0; + for (int i = 0, j = 0; i < fruits.size(); ++i) { + int x = fruits[i]; ++cnt[x]; - if (cnt.size() > 2) { + while (cnt.size() > 2) { int y = fruits[j++]; if (--cnt[y] == 0) cnt.erase(y); } + ans = max(ans, i - j + 1); } - return n - j; + return ans; } }; \ No newline at end of file diff --git a/solution/0900-0999/0904.Fruit Into Baskets/Solution.go b/solution/0900-0999/0904.Fruit Into Baskets/Solution.go index f63749063f22e..b7749a4cce734 100644 --- a/solution/0900-0999/0904.Fruit Into Baskets/Solution.go +++ b/solution/0900-0999/0904.Fruit Into Baskets/Solution.go @@ -1,16 +1,16 @@ func totalFruit(fruits []int) int { cnt := map[int]int{} - j := 0 - for _, x := range fruits { + ans, j := 0, 0 + for i, x := range fruits { cnt[x]++ - if len(cnt) > 2 { + for ; len(cnt) > 2; j++ { y := fruits[j] cnt[y]-- if cnt[y] == 0 { delete(cnt, y) } - j++ } + ans = max(ans, i-j+1) } - return len(fruits) - j + return ans } \ No newline at end of file diff --git a/solution/0900-0999/0904.Fruit Into Baskets/Solution.java b/solution/0900-0999/0904.Fruit Into Baskets/Solution.java index 6f4820f5cddbb..73671ba5606e1 100644 --- a/solution/0900-0999/0904.Fruit Into Baskets/Solution.java +++ b/solution/0900-0999/0904.Fruit Into Baskets/Solution.java @@ -1,17 +1,19 @@ class Solution { public int totalFruit(int[] fruits) { Map cnt = new HashMap<>(); - int j = 0, n = fruits.length; - for (int x : fruits) { + int ans = 0; + for (int i = 0, j = 0; i < fruits.length; ++i) { + int x = fruits[i]; cnt.put(x, cnt.getOrDefault(x, 0) + 1); - if (cnt.size() > 2) { + while (cnt.size() > 2) { int y = fruits[j++]; cnt.put(y, cnt.get(y) - 1); if (cnt.get(y) == 0) { cnt.remove(y); } } + ans = Math.max(ans, i - j + 1); } - return n - j; + return ans; } } \ No newline at end of file diff --git a/solution/0900-0999/0904.Fruit Into Baskets/Solution.py b/solution/0900-0999/0904.Fruit Into Baskets/Solution.py index ec2aaaf507346..d0b093a123414 100644 --- a/solution/0900-0999/0904.Fruit Into Baskets/Solution.py +++ b/solution/0900-0999/0904.Fruit Into Baskets/Solution.py @@ -1,13 +1,14 @@ class Solution: def totalFruit(self, fruits: List[int]) -> int: cnt = Counter() - j = 0 - for x in fruits: + ans = j = 0 + for i, x in enumerate(fruits): cnt[x] += 1 - if len(cnt) > 2: + while len(cnt) > 2: y = fruits[j] cnt[y] -= 1 if cnt[y] == 0: cnt.pop(y) j += 1 - return len(fruits) - j + ans = max(ans, i - j + 1) + return ans diff --git a/solution/0900-0999/0904.Fruit Into Baskets/Solution.rs b/solution/0900-0999/0904.Fruit Into Baskets/Solution.rs index 03cb62530415d..a2eb0967bf173 100644 --- a/solution/0900-0999/0904.Fruit Into Baskets/Solution.rs +++ b/solution/0900-0999/0904.Fruit Into Baskets/Solution.rs @@ -3,18 +3,22 @@ impl Solution { pub fn total_fruit(fruits: Vec) -> i32 { let n = fruits.len(); let mut map = HashMap::new(); - let mut i = 0; - for &fruit in fruits.iter() { - *map.entry(fruit).or_insert(0) += 1; - if map.len() > 2 { - let k = fruits[i]; + let mut res = 0; + let mut left = 0; + let mut right = 0; + while right < n { + *map.entry(fruits[right]).or_insert(0) += 1; + right += 1; + while map.len() > 2 { + let k = fruits[left]; map.insert(k, map[&k] - 1); if map[&k] == 0 { map.remove(&k); } - i += 1; + left += 1; } + res = res.max(right - left); } - (n - i) as i32 + res as i32 } } diff --git a/solution/0900-0999/0904.Fruit Into Baskets/Solution.ts b/solution/0900-0999/0904.Fruit Into Baskets/Solution.ts index d543a926299cb..bd22134fecb25 100644 --- a/solution/0900-0999/0904.Fruit Into Baskets/Solution.ts +++ b/solution/0900-0999/0904.Fruit Into Baskets/Solution.ts @@ -1,16 +1,20 @@ function totalFruit(fruits: number[]): number { const n = fruits.length; const map = new Map(); - let i = 0; - for (const fruit of fruits) { - map.set(fruit, (map.get(fruit) ?? 0) + 1); - if (map.size > 2) { - const k = fruits[i++]; + let res = 0; + let left = 0; + let right = 0; + while (right < n) { + map.set(fruits[right], (map.get(fruits[right]) ?? 0) + 1); + right++; + while (map.size > 2) { + const k = fruits[left++]; map.set(k, map.get(k) - 1); - if (map.get(k) == 0) { + if (map.get(k) === 0) { map.delete(k); } } + res = Math.max(res, right - left); } - return n - i; + return res; } diff --git a/solution/0900-0999/0904.Fruit Into Baskets/Solution2.cpp b/solution/0900-0999/0904.Fruit Into Baskets/Solution2.cpp new file mode 100644 index 0000000000000..51edbc4eb67fc --- /dev/null +++ b/solution/0900-0999/0904.Fruit Into Baskets/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int totalFruit(vector& fruits) { + unordered_map cnt; + int j = 0, n = fruits.size(); + for (int& x : fruits) { + ++cnt[x]; + if (cnt.size() > 2) { + int y = fruits[j++]; + if (--cnt[y] == 0) cnt.erase(y); + } + } + return n - j; + } +}; \ No newline at end of file diff --git a/solution/0900-0999/0904.Fruit Into Baskets/Solution2.go b/solution/0900-0999/0904.Fruit Into Baskets/Solution2.go new file mode 100644 index 0000000000000..f63749063f22e --- /dev/null +++ b/solution/0900-0999/0904.Fruit Into Baskets/Solution2.go @@ -0,0 +1,16 @@ +func totalFruit(fruits []int) int { + cnt := map[int]int{} + j := 0 + for _, x := range fruits { + cnt[x]++ + if len(cnt) > 2 { + y := fruits[j] + cnt[y]-- + if cnt[y] == 0 { + delete(cnt, y) + } + j++ + } + } + return len(fruits) - j +} \ No newline at end of file diff --git a/solution/0900-0999/0904.Fruit Into Baskets/Solution2.java b/solution/0900-0999/0904.Fruit Into Baskets/Solution2.java new file mode 100644 index 0000000000000..6f4820f5cddbb --- /dev/null +++ b/solution/0900-0999/0904.Fruit Into Baskets/Solution2.java @@ -0,0 +1,17 @@ +class Solution { + public int totalFruit(int[] fruits) { + Map cnt = new HashMap<>(); + int j = 0, n = fruits.length; + for (int x : fruits) { + cnt.put(x, cnt.getOrDefault(x, 0) + 1); + if (cnt.size() > 2) { + int y = fruits[j++]; + cnt.put(y, cnt.get(y) - 1); + if (cnt.get(y) == 0) { + cnt.remove(y); + } + } + } + return n - j; + } +} \ No newline at end of file diff --git a/solution/0900-0999/0904.Fruit Into Baskets/Solution2.py b/solution/0900-0999/0904.Fruit Into Baskets/Solution2.py new file mode 100644 index 0000000000000..ec2aaaf507346 --- /dev/null +++ b/solution/0900-0999/0904.Fruit Into Baskets/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def totalFruit(self, fruits: List[int]) -> int: + cnt = Counter() + j = 0 + for x in fruits: + cnt[x] += 1 + if len(cnt) > 2: + y = fruits[j] + cnt[y] -= 1 + if cnt[y] == 0: + cnt.pop(y) + j += 1 + return len(fruits) - j diff --git a/solution/0900-0999/0904.Fruit Into Baskets/Solution2.rs b/solution/0900-0999/0904.Fruit Into Baskets/Solution2.rs new file mode 100644 index 0000000000000..03cb62530415d --- /dev/null +++ b/solution/0900-0999/0904.Fruit Into Baskets/Solution2.rs @@ -0,0 +1,20 @@ +use std::collections::HashMap; +impl Solution { + pub fn total_fruit(fruits: Vec) -> i32 { + let n = fruits.len(); + let mut map = HashMap::new(); + let mut i = 0; + for &fruit in fruits.iter() { + *map.entry(fruit).or_insert(0) += 1; + if map.len() > 2 { + let k = fruits[i]; + map.insert(k, map[&k] - 1); + if map[&k] == 0 { + map.remove(&k); + } + i += 1; + } + } + (n - i) as i32 + } +} diff --git a/solution/0900-0999/0904.Fruit Into Baskets/Solution2.ts b/solution/0900-0999/0904.Fruit Into Baskets/Solution2.ts new file mode 100644 index 0000000000000..d543a926299cb --- /dev/null +++ b/solution/0900-0999/0904.Fruit Into Baskets/Solution2.ts @@ -0,0 +1,16 @@ +function totalFruit(fruits: number[]): number { + const n = fruits.length; + const map = new Map(); + let i = 0; + for (const fruit of fruits) { + map.set(fruit, (map.get(fruit) ?? 0) + 1); + if (map.size > 2) { + const k = fruits[i++]; + map.set(k, map.get(k) - 1); + if (map.get(k) == 0) { + map.delete(k); + } + } + } + return n - i; +} diff --git a/solution/0900-0999/0905.Sort Array By Parity/Solution.cpp b/solution/0900-0999/0905.Sort Array By Parity/Solution.cpp index 5ad1948aa54e1..278c70a8ad8f3 100644 --- a/solution/0900-0999/0905.Sort Array By Parity/Solution.cpp +++ b/solution/0900-0999/0905.Sort Array By Parity/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - vector sortArrayByParity(vector& nums) { - int i = 0, j = nums.size() - 1; - while (i < j) { - if (nums[i] % 2 == 0) { - ++i; - } else if (nums[j] % 2 == 1) { - --j; - } else { - swap(nums[i++], nums[j--]); - } - } - return nums; - } +class Solution { +public: + vector sortArrayByParity(vector& nums) { + int i = 0, j = nums.size() - 1; + while (i < j) { + if (nums[i] % 2 == 0) { + ++i; + } else if (nums[j] % 2 == 1) { + --j; + } else { + swap(nums[i++], nums[j--]); + } + } + return nums; + } }; \ No newline at end of file diff --git a/solution/0900-0999/0905.Sort Array By Parity/Solution.java b/solution/0900-0999/0905.Sort Array By Parity/Solution.java index 9b49ca6dcfec0..05f32140f85d8 100644 --- a/solution/0900-0999/0905.Sort Array By Parity/Solution.java +++ b/solution/0900-0999/0905.Sort Array By Parity/Solution.java @@ -1,19 +1,19 @@ -class Solution { - public int[] sortArrayByParity(int[] nums) { - int i = 0, j = nums.length - 1; - while (i < j) { - if (nums[i] % 2 == 0) { - ++i; - } else if (nums[j] % 2 == 1) { - --j; - } else { - int t = nums[i]; - nums[i] = nums[j]; - nums[j] = t; - ++i; - --j; - } - } - return nums; - } +class Solution { + public int[] sortArrayByParity(int[] nums) { + int i = 0, j = nums.length - 1; + while (i < j) { + if (nums[i] % 2 == 0) { + ++i; + } else if (nums[j] % 2 == 1) { + --j; + } else { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + ++i; + --j; + } + } + return nums; + } } \ No newline at end of file diff --git a/solution/0900-0999/0905.Sort Array By Parity/Solution.py b/solution/0900-0999/0905.Sort Array By Parity/Solution.py index 5d425faa7e838..00c830f30e6ca 100644 --- a/solution/0900-0999/0905.Sort Array By Parity/Solution.py +++ b/solution/0900-0999/0905.Sort Array By Parity/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def sortArrayByParity(self, nums: List[int]) -> List[int]: - i, j = 0, len(nums) - 1 - while i < j: - if nums[i] % 2 == 0: - i += 1 - elif nums[j] % 2 == 1: - j -= 1 - else: - nums[i], nums[j] = nums[j], nums[i] - i, j = i + 1, j - 1 - return nums +class Solution: + def sortArrayByParity(self, nums: List[int]) -> List[int]: + i, j = 0, len(nums) - 1 + while i < j: + if nums[i] % 2 == 0: + i += 1 + elif nums[j] % 2 == 1: + j -= 1 + else: + nums[i], nums[j] = nums[j], nums[i] + i, j = i + 1, j - 1 + return nums diff --git a/solution/0900-0999/0907.Sum of Subarray Minimums/Solution.cpp b/solution/0900-0999/0907.Sum of Subarray Minimums/Solution.cpp index 674fb59ea90d5..4efa2268471b1 100644 --- a/solution/0900-0999/0907.Sum of Subarray Minimums/Solution.cpp +++ b/solution/0900-0999/0907.Sum of Subarray Minimums/Solution.cpp @@ -1,35 +1,35 @@ -class Solution { -public: - int sumSubarrayMins(vector& arr) { - int n = arr.size(); - vector left(n, -1); - vector right(n, n); - stack stk; - for (int i = 0; i < n; ++i) { - while (!stk.empty() && arr[stk.top()] >= arr[i]) { - stk.pop(); - } - if (!stk.empty()) { - left[i] = stk.top(); - } - stk.push(i); - } - stk = stack(); - for (int i = n - 1; i >= 0; --i) { - while (!stk.empty() && arr[stk.top()] > arr[i]) { - stk.pop(); - } - if (!stk.empty()) { - right[i] = stk.top(); - } - stk.push(i); - } - long long ans = 0; - const int mod = 1e9 + 7; - for (int i = 0; i < n; ++i) { - ans += 1LL * (i - left[i]) * (right[i] - i) * arr[i] % mod; - ans %= mod; - } - return ans; - } +class Solution { +public: + int sumSubarrayMins(vector& arr) { + int n = arr.size(); + vector left(n, -1); + vector right(n, n); + stack stk; + for (int i = 0; i < n; ++i) { + while (!stk.empty() && arr[stk.top()] >= arr[i]) { + stk.pop(); + } + if (!stk.empty()) { + left[i] = stk.top(); + } + stk.push(i); + } + stk = stack(); + for (int i = n - 1; i >= 0; --i) { + while (!stk.empty() && arr[stk.top()] > arr[i]) { + stk.pop(); + } + if (!stk.empty()) { + right[i] = stk.top(); + } + stk.push(i); + } + long long ans = 0; + const int mod = 1e9 + 7; + for (int i = 0; i < n; ++i) { + ans += 1LL * (i - left[i]) * (right[i] - i) * arr[i] % mod; + ans %= mod; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0900-0999/0907.Sum of Subarray Minimums/Solution.java b/solution/0900-0999/0907.Sum of Subarray Minimums/Solution.java index 853a5f116185c..4b4b052420f26 100644 --- a/solution/0900-0999/0907.Sum of Subarray Minimums/Solution.java +++ b/solution/0900-0999/0907.Sum of Subarray Minimums/Solution.java @@ -1,36 +1,36 @@ -class Solution { - public int sumSubarrayMins(int[] arr) { - int n = arr.length; - int[] left = new int[n]; - int[] right = new int[n]; - Arrays.fill(left, -1); - Arrays.fill(right, n); - Deque stk = new ArrayDeque<>(); - for (int i = 0; i < n; ++i) { - while (!stk.isEmpty() && arr[stk.peek()] >= arr[i]) { - stk.pop(); - } - if (!stk.isEmpty()) { - left[i] = stk.peek(); - } - stk.push(i); - } - stk.clear(); - for (int i = n - 1; i >= 0; --i) { - while (!stk.isEmpty() && arr[stk.peek()] > arr[i]) { - stk.pop(); - } - if (!stk.isEmpty()) { - right[i] = stk.peek(); - } - stk.push(i); - } - final int mod = (int) 1e9 + 7; - long ans = 0; - for (int i = 0; i < n; ++i) { - ans += (long) (i - left[i]) * (right[i] - i) % mod * arr[i] % mod; - ans %= mod; - } - return (int) ans; - } +class Solution { + public int sumSubarrayMins(int[] arr) { + int n = arr.length; + int[] left = new int[n]; + int[] right = new int[n]; + Arrays.fill(left, -1); + Arrays.fill(right, n); + Deque stk = new ArrayDeque<>(); + for (int i = 0; i < n; ++i) { + while (!stk.isEmpty() && arr[stk.peek()] >= arr[i]) { + stk.pop(); + } + if (!stk.isEmpty()) { + left[i] = stk.peek(); + } + stk.push(i); + } + stk.clear(); + for (int i = n - 1; i >= 0; --i) { + while (!stk.isEmpty() && arr[stk.peek()] > arr[i]) { + stk.pop(); + } + if (!stk.isEmpty()) { + right[i] = stk.peek(); + } + stk.push(i); + } + final int mod = (int) 1e9 + 7; + long ans = 0; + for (int i = 0; i < n; ++i) { + ans += (long) (i - left[i]) * (right[i] - i) % mod * arr[i] % mod; + ans %= mod; + } + return (int) ans; + } } \ No newline at end of file diff --git a/solution/0900-0999/0907.Sum of Subarray Minimums/Solution2.rs b/solution/0900-0999/0907.Sum of Subarray Minimums/Solution2.rs new file mode 100644 index 0000000000000..88a984f333273 --- /dev/null +++ b/solution/0900-0999/0907.Sum of Subarray Minimums/Solution2.rs @@ -0,0 +1,48 @@ +const MOD: i64 = (1e9 as i64) + 7; + +impl Solution { + pub fn sum_subarray_mins(arr: Vec) -> i32 { + let n: usize = arr.len(); + let mut ret: i64 = 0; + let mut left: Vec = vec![-1; n]; + let mut right: Vec = vec![n as i32; n]; + // Index stack, store the index of the value in the given array + let mut stack: Vec = Vec::new(); + + // Find the first element that's less than the current value for the left side + // The default value of which is -1 + for i in 0..n { + while !stack.is_empty() && arr[*stack.last().unwrap() as usize] >= arr[i] { + stack.pop(); + } + if !stack.is_empty() { + left[i] = *stack.last().unwrap(); + } + stack.push(i as i32); + } + + stack.clear(); + + // Find the first element that's less or equal than the current value for the right side + // The default value of which is n + for i in (0..n).rev() { + while !stack.is_empty() && arr[*stack.last().unwrap() as usize] > arr[i] { + stack.pop(); + } + if !stack.is_empty() { + right[i] = *stack.last().unwrap(); + } + stack.push(i as i32); + } + + // Traverse the array, to find the sum + for i in 0..n { + ret += + ((((right[i] - (i as i32)) * ((i as i32) - left[i])) as i64) * (arr[i] as i64)) % + MOD; + ret %= MOD; + } + + (ret % (MOD as i64)) as i32 + } +} diff --git a/solution/0900-0999/0908.Smallest Range I/Solution.cpp b/solution/0900-0999/0908.Smallest Range I/Solution.cpp index 7be5ca1f19eec..0ab7249be0638 100644 --- a/solution/0900-0999/0908.Smallest Range I/Solution.cpp +++ b/solution/0900-0999/0908.Smallest Range I/Solution.cpp @@ -1,7 +1,7 @@ -class Solution { -public: - int smallestRangeI(vector& nums, int k) { - auto [mi, mx] = minmax_element(nums.begin(), nums.end()); - return max(0, *mx - *mi - k * 2); - } +class Solution { +public: + int smallestRangeI(vector& nums, int k) { + auto [mi, mx] = minmax_element(nums.begin(), nums.end()); + return max(0, *mx - *mi - k * 2); + } }; \ No newline at end of file diff --git a/solution/0900-0999/0911.Online Election/Solution.java b/solution/0900-0999/0911.Online Election/Solution.java index 1c3834c7927cf..537faacd96b05 100644 --- a/solution/0900-0999/0911.Online Election/Solution.java +++ b/solution/0900-0999/0911.Online Election/Solution.java @@ -1,34 +1,33 @@ class TopVotedCandidate { private int[] times; - private int[] wins; + private int[] winPersons; public TopVotedCandidate(int[] persons, int[] times) { - int n = persons.length; - int mx = 0, cur = 0; this.times = times; - wins = new int[n]; - int[] counter = new int[n]; + int mx = -1, curWin = -1; + int n = persons.length; + int[] counter = new int[n + 1]; + winPersons = new int[n]; for (int i = 0; i < n; ++i) { - int p = persons[i]; - if (++counter[p] >= mx) { - mx = counter[p]; - cur = p; + if (++counter[persons[i]] >= mx) { + mx = counter[persons[i]]; + curWin = persons[i]; } - wins[i] = cur; + winPersons[i] = curWin; } } public int q(int t) { - int left = 0, right = wins.length - 1; + int left = 0, right = winPersons.length - 1; while (left < right) { - int mid = (left + right + 1) >>> 1; + int mid = (left + right + 1) >> 1; if (times[mid] <= t) { left = mid; } else { right = mid - 1; } } - return wins[left]; + return winPersons[left]; } } diff --git a/solution/0900-0999/0912.Sort an Array/Solution2.cpp b/solution/0900-0999/0912.Sort an Array/Solution2.cpp new file mode 100644 index 0000000000000..124328cd2dd22 --- /dev/null +++ b/solution/0900-0999/0912.Sort an Array/Solution2.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + vector sortArray(vector& nums) { + function merge_sort = [&](int l, int r) { + if (l >= r) { + return; + } + int mid = (l + r) >> 1; + merge_sort(l, mid); + merge_sort(mid + 1, r); + int i = l, j = mid + 1, k = 0; + int tmp[r - l + 1]; + while (i <= mid && j <= r) { + if (nums[i] <= nums[j]) { + tmp[k++] = nums[i++]; + } else { + tmp[k++] = nums[j++]; + } + } + while (i <= mid) { + tmp[k++] = nums[i++]; + } + while (j <= r) { + tmp[k++] = nums[j++]; + } + for (i = l; i <= r; ++i) { + nums[i] = tmp[i - l]; + } + }; + merge_sort(0, nums.size() - 1); + return nums; + } +}; \ No newline at end of file diff --git a/solution/0900-0999/0912.Sort an Array/Solution2.go b/solution/0900-0999/0912.Sort an Array/Solution2.go new file mode 100644 index 0000000000000..a54fa17fc3f85 --- /dev/null +++ b/solution/0900-0999/0912.Sort an Array/Solution2.go @@ -0,0 +1,36 @@ +func sortArray(nums []int) []int { + mergeSort(nums, 0, len(nums)-1) + return nums +} + +func mergeSort(nums []int, l, r int) { + if l >= r { + return + } + mid := (l + r) >> 1 + mergeSort(nums, l, mid) + mergeSort(nums, mid+1, r) + i, j, k := l, mid+1, 0 + tmp := make([]int, r-l+1) + for i <= mid && j <= r { + if nums[i] <= nums[j] { + tmp[k] = nums[i] + i++ + } else { + tmp[k] = nums[j] + j++ + } + k++ + } + for ; i <= mid; i++ { + tmp[k] = nums[i] + k++ + } + for ; j <= r; j++ { + tmp[k] = nums[j] + k++ + } + for i = l; i <= r; i++ { + nums[i] = tmp[i-l] + } +} \ No newline at end of file diff --git a/solution/0900-0999/0912.Sort an Array/Solution2.java b/solution/0900-0999/0912.Sort an Array/Solution2.java new file mode 100644 index 0000000000000..60e337375a9e6 --- /dev/null +++ b/solution/0900-0999/0912.Sort an Array/Solution2.java @@ -0,0 +1,34 @@ +class Solution { + private int[] nums; + + public int[] sortArray(int[] nums) { + this.nums = nums; + quickSort(0, nums.length - 1); + return nums; + } + + private void quickSort(int l, int r) { + if (l >= r) { + return; + } + int i = l - 1, j = r + 1, k = l; + int x = nums[(l + r) >> 1]; + while (k < j) { + if (nums[k] < x) { + swap(++i, k++); + } else if (nums[k] > x) { + swap(--j, k); + } else { + ++k; + } + } + quickSort(l, i); + quickSort(j, r); + } + + private void swap(int i, int j) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } +} \ No newline at end of file diff --git a/solution/0900-0999/0912.Sort an Array/Solution2.js b/solution/0900-0999/0912.Sort an Array/Solution2.js new file mode 100644 index 0000000000000..3cbb9b5a3017f --- /dev/null +++ b/solution/0900-0999/0912.Sort an Array/Solution2.js @@ -0,0 +1,35 @@ +/** + * @param {number[]} nums + * @return {number[]} + */ +var sortArray = function (nums) { + function mergetSort(l, r) { + if (l >= r) { + return; + } + const mid = (l + r) >> 1; + mergetSort(l, mid); + mergetSort(mid + 1, r); + let [i, j, k] = [l, mid + 1, 0]; + while (i <= mid && j <= r) { + if (nums[i] <= nums[j]) { + tmp[k++] = nums[i++]; + } else { + tmp[k++] = nums[j++]; + } + } + while (i <= mid) { + tmp[k++] = nums[i++]; + } + while (j <= r) { + tmp[k++] = nums[j++]; + } + for (i = l, j = 0; i <= r; ++i, ++j) { + nums[i] = tmp[j]; + } + } + const n = nums.length; + let tmp = new Array(n).fill(0); + mergetSort(0, n - 1); + return nums; +}; diff --git a/solution/0900-0999/0912.Sort an Array/Solution2.py b/solution/0900-0999/0912.Sort an Array/Solution2.py new file mode 100644 index 0000000000000..58abe8b460494 --- /dev/null +++ b/solution/0900-0999/0912.Sort an Array/Solution2.py @@ -0,0 +1,26 @@ +class Solution: + def sortArray(self, nums: List[int]) -> List[int]: + def merge_sort(l, r): + if l >= r: + return + mid = (l + r) >> 1 + merge_sort(l, mid) + merge_sort(mid + 1, r) + i, j = l, mid + 1 + tmp = [] + while i <= mid and j <= r: + if nums[i] <= nums[j]: + tmp.append(nums[i]) + i += 1 + else: + tmp.append(nums[j]) + j += 1 + if i <= mid: + tmp.extend(nums[i : mid + 1]) + if j <= r: + tmp.extend(nums[j : r + 1]) + for i in range(l, r + 1): + nums[i] = tmp[i - l] + + merge_sort(0, len(nums) - 1) + return nums diff --git a/solution/0900-0999/0912.Sort an Array/Solution2.ts b/solution/0900-0999/0912.Sort an Array/Solution2.ts new file mode 100644 index 0000000000000..cff137e826493 --- /dev/null +++ b/solution/0900-0999/0912.Sort an Array/Solution2.ts @@ -0,0 +1,31 @@ +function sortArray(nums: number[]): number[] { + function mergetSort(l: number, r: number) { + if (l >= r) { + return; + } + const mid = (l + r) >> 1; + mergetSort(l, mid); + mergetSort(mid + 1, r); + let [i, j, k] = [l, mid + 1, 0]; + while (i <= mid && j <= r) { + if (nums[i] <= nums[j]) { + tmp[k++] = nums[i++]; + } else { + tmp[k++] = nums[j++]; + } + } + while (i <= mid) { + tmp[k++] = nums[i++]; + } + while (j <= r) { + tmp[k++] = nums[j++]; + } + for (i = l, j = 0; i <= r; ++i, ++j) { + nums[i] = tmp[j]; + } + } + const n = nums.length; + let tmp = new Array(n).fill(0); + mergetSort(0, n - 1); + return nums; +} diff --git a/solution/0900-0999/0912.Sort an Array/Solution3.java b/solution/0900-0999/0912.Sort an Array/Solution3.java new file mode 100644 index 0000000000000..a6f73d89123c8 --- /dev/null +++ b/solution/0900-0999/0912.Sort an Array/Solution3.java @@ -0,0 +1,36 @@ +class Solution { + private int[] nums; + + public int[] sortArray(int[] nums) { + this.nums = nums; + mergeSort(0, nums.length - 1); + return nums; + } + + private void mergeSort(int l, int r) { + if (l >= r) { + return; + } + int mid = (l + r) >> 1; + mergeSort(l, mid); + mergeSort(mid + 1, r); + int i = l, j = mid + 1, k = 0; + int[] tmp = new int[r - l + 1]; + while (i <= mid && j <= r) { + if (nums[i] <= nums[j]) { + tmp[k++] = nums[i++]; + } else { + tmp[k++] = nums[j++]; + } + } + while (i <= mid) { + tmp[k++] = nums[i++]; + } + while (j <= r) { + tmp[k++] = nums[j++]; + } + for (i = l; i <= r; ++i) { + nums[i] = tmp[i - l]; + } + } +} \ No newline at end of file diff --git a/solution/0900-0999/0913.Cat and Mouse/Solution.py b/solution/0900-0999/0913.Cat and Mouse/Solution.py new file mode 100644 index 0000000000000..5bb3156bc233c --- /dev/null +++ b/solution/0900-0999/0913.Cat and Mouse/Solution.py @@ -0,0 +1,56 @@ +HOLE, MOUSE_START, CAT_START = 0, 1, 2 +MOUSE_TURN, CAT_TURN = 0, 1 +MOUSE_WIN, CAT_WIN, TIE = 1, 2, 0 + + +class Solution: + def catMouseGame(self, graph: List[List[int]]) -> int: + def get_prev_states(state): + m, c, t = state + pt = t ^ 1 + pre = [] + if pt == CAT_TURN: + for pc in graph[c]: + if pc != HOLE: + pre.append((m, pc, pt)) + else: + for pm in graph[m]: + pre.append((pm, c, pt)) + return pre + + n = len(graph) + res = [[[0, 0] for _ in range(n)] for _ in range(n)] + degree = [[[0, 0] for _ in range(n)] for _ in range(n)] + for i in range(n): + for j in range(1, n): + degree[i][j][MOUSE_TURN] = len(graph[i]) + degree[i][j][CAT_TURN] = len(graph[j]) + for j in graph[HOLE]: + degree[i][j][CAT_TURN] -= 1 + q = deque() + for j in range(1, n): + res[0][j][MOUSE_TURN] = res[0][j][CAT_TURN] = MOUSE_WIN + q.append((0, j, MOUSE_TURN)) + q.append((0, j, CAT_TURN)) + for i in range(1, n): + res[i][i][MOUSE_TURN] = res[i][i][CAT_TURN] = CAT_WIN + q.append((i, i, MOUSE_TURN)) + q.append((i, i, CAT_TURN)) + while q: + state = q.popleft() + t = res[state[0]][state[1]][state[2]] + for prev_state in get_prev_states(state): + pm, pc, pt = prev_state + if res[pm][pc][pt] == TIE: + win = (t == MOUSE_WIN and pt == MOUSE_TURN) or ( + t == CAT_WIN and pt == CAT_TURN + ) + if win: + res[pm][pc][pt] = t + q.append(prev_state) + else: + degree[pm][pc][pt] -= 1 + if degree[pm][pc][pt] == 0: + res[pm][pc][pt] = t + q.append(prev_state) + return res[MOUSE_START][CAT_START][MOUSE_TURN] diff --git a/solution/0900-0999/0918.Maximum Sum Circular Subarray/Solution2.cpp b/solution/0900-0999/0918.Maximum Sum Circular Subarray/Solution2.cpp new file mode 100644 index 0000000000000..36ad73af9cace --- /dev/null +++ b/solution/0900-0999/0918.Maximum Sum Circular Subarray/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int maxSubarraySumCircular(vector& nums) { + const int inf = 1 << 30; + int pmi = 0, pmx = -inf; + int ans = -inf, s = 0, smi = inf; + for (int x : nums) { + s += x; + ans = max(ans, s - pmi); + smi = min(smi, s - pmx); + pmi = min(pmi, s); + pmx = max(pmx, s); + } + return max(ans, s - smi); + } +}; \ No newline at end of file diff --git a/solution/0900-0999/0918.Maximum Sum Circular Subarray/Solution2.go b/solution/0900-0999/0918.Maximum Sum Circular Subarray/Solution2.go new file mode 100644 index 0000000000000..2d9b9748db0cb --- /dev/null +++ b/solution/0900-0999/0918.Maximum Sum Circular Subarray/Solution2.go @@ -0,0 +1,13 @@ +func maxSubarraySumCircular(nums []int) int { + const inf = 1 << 30 + pmi, pmx := 0, -inf + ans, s, smi := -inf, 0, inf + for _, x := range nums { + s += x + ans = max(ans, s-pmi) + smi = min(smi, s-pmx) + pmi = min(pmi, s) + pmx = max(pmx, s) + } + return max(ans, s-smi) +} \ No newline at end of file diff --git a/solution/0900-0999/0918.Maximum Sum Circular Subarray/Solution2.java b/solution/0900-0999/0918.Maximum Sum Circular Subarray/Solution2.java new file mode 100644 index 0000000000000..c3b4c1c9d4ca0 --- /dev/null +++ b/solution/0900-0999/0918.Maximum Sum Circular Subarray/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public int maxSubarraySumCircular(int[] nums) { + final int inf = 1 << 30; + int pmi = 0, pmx = -inf; + int ans = -inf, s = 0, smi = inf; + for (int x : nums) { + s += x; + ans = Math.max(ans, s - pmi); + smi = Math.min(smi, s - pmx); + pmi = Math.min(pmi, s); + pmx = Math.max(pmx, s); + } + return Math.max(ans, s - smi); + } +} \ No newline at end of file diff --git a/solution/0900-0999/0918.Maximum Sum Circular Subarray/Solution2.py b/solution/0900-0999/0918.Maximum Sum Circular Subarray/Solution2.py new file mode 100644 index 0000000000000..59161e8c69e64 --- /dev/null +++ b/solution/0900-0999/0918.Maximum Sum Circular Subarray/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def maxSubarraySumCircular(self, nums: List[int]) -> int: + pmi, pmx = 0, -inf + ans, s, smi = -inf, 0, inf + for x in nums: + s += x + ans = max(ans, s - pmi) + smi = min(smi, s - pmx) + pmi = min(pmi, s) + pmx = max(pmx, s) + return max(ans, s - smi) diff --git a/solution/0900-0999/0918.Maximum Sum Circular Subarray/Solution2.ts b/solution/0900-0999/0918.Maximum Sum Circular Subarray/Solution2.ts new file mode 100644 index 0000000000000..632003cacf568 --- /dev/null +++ b/solution/0900-0999/0918.Maximum Sum Circular Subarray/Solution2.ts @@ -0,0 +1,13 @@ +function maxSubarraySumCircular(nums: number[]): number { + const inf = 1 << 30; + let [pmi, pmx] = [0, -inf]; + let [ans, s, smi] = [-inf, 0, inf]; + for (const x of nums) { + s += x; + ans = Math.max(ans, s - pmi); + smi = Math.min(smi, s - pmx); + pmi = Math.min(pmi, s); + pmx = Math.max(pmx, s); + } + return Math.max(ans, s - smi); +} diff --git a/solution/0900-0999/0920.Number of Music Playlists/Solution2.cpp b/solution/0900-0999/0920.Number of Music Playlists/Solution2.cpp new file mode 100644 index 0000000000000..e10d13068e8b8 --- /dev/null +++ b/solution/0900-0999/0920.Number of Music Playlists/Solution2.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int numMusicPlaylists(int n, int goal, int k) { + const int mod = 1e9 + 7; + vector f(n + 1); + f[0] = 1; + for (int i = 1; i <= goal; ++i) { + vector g(n + 1); + for (int j = 1; j <= n; ++j) { + g[j] = f[j - 1] * (n - j + 1); + if (j > k) { + g[j] += f[j] * (j - k); + } + g[j] %= mod; + } + f = move(g); + } + return f[n]; + } +}; \ No newline at end of file diff --git a/solution/0900-0999/0920.Number of Music Playlists/Solution2.go b/solution/0900-0999/0920.Number of Music Playlists/Solution2.go new file mode 100644 index 0000000000000..110bf0b5c0b7b --- /dev/null +++ b/solution/0900-0999/0920.Number of Music Playlists/Solution2.go @@ -0,0 +1,17 @@ +func numMusicPlaylists(n int, goal int, k int) int { + const mod = 1e9 + 7 + f := make([]int, goal+1) + f[0] = 1 + for i := 1; i <= goal; i++ { + g := make([]int, goal+1) + for j := 1; j <= n; j++ { + g[j] = f[j-1] * (n - j + 1) + if j > k { + g[j] += f[j] * (j - k) + } + g[j] %= mod + } + f = g + } + return f[n] +} \ No newline at end of file diff --git a/solution/0900-0999/0920.Number of Music Playlists/Solution2.java b/solution/0900-0999/0920.Number of Music Playlists/Solution2.java new file mode 100644 index 0000000000000..1f3cb91e3eb10 --- /dev/null +++ b/solution/0900-0999/0920.Number of Music Playlists/Solution2.java @@ -0,0 +1,19 @@ +class Solution { + public int numMusicPlaylists(int n, int goal, int k) { + final int mod = (int) 1e9 + 7; + long[] f = new long[n + 1]; + f[0] = 1; + for (int i = 1; i <= goal; ++i) { + long[] g = new long[n + 1]; + for (int j = 1; j <= n; ++j) { + g[j] = f[j - 1] * (n - j + 1); + if (j > k) { + g[j] += f[j] * (j - k); + } + g[j] %= mod; + } + f = g; + } + return (int) f[n]; + } +} \ No newline at end of file diff --git a/solution/0900-0999/0920.Number of Music Playlists/Solution2.py b/solution/0900-0999/0920.Number of Music Playlists/Solution2.py new file mode 100644 index 0000000000000..c02fbc029d971 --- /dev/null +++ b/solution/0900-0999/0920.Number of Music Playlists/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def numMusicPlaylists(self, n: int, goal: int, k: int) -> int: + mod = 10**9 + 7 + f = [0] * (goal + 1) + f[0] = 1 + for i in range(1, goal + 1): + g = [0] * (goal + 1) + for j in range(1, n + 1): + g[j] = f[j - 1] * (n - j + 1) + if j > k: + g[j] += f[j] * (j - k) + g[j] %= mod + f = g + return f[n] diff --git a/solution/0900-0999/0920.Number of Music Playlists/Solution2.ts b/solution/0900-0999/0920.Number of Music Playlists/Solution2.ts new file mode 100644 index 0000000000000..4d463fbe95bfc --- /dev/null +++ b/solution/0900-0999/0920.Number of Music Playlists/Solution2.ts @@ -0,0 +1,17 @@ +function numMusicPlaylists(n: number, goal: number, k: number): number { + const mod = 1e9 + 7; + let f = new Array(goal + 1).fill(0); + f[0] = 1; + for (let i = 1; i <= goal; ++i) { + const g = new Array(goal + 1).fill(0); + for (let j = 1; j <= n; ++j) { + g[j] = f[j - 1] * (n - j + 1); + if (j > k) { + g[j] += f[j] * (j - k); + } + g[j] %= mod; + } + f = g; + } + return f[n]; +} diff --git a/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution.cpp b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution.cpp index d744ad56804b5..8ea027bd82506 100644 --- a/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution.cpp +++ b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution.cpp @@ -1,16 +1,13 @@ class Solution { public: int minAddToMakeValid(string s) { - int ans = 0, cnt = 0; + string stk; for (char c : s) { - if (c == '(') - ++cnt; - else if (cnt) - --cnt; + if (c == ')' && stk.size() && stk.back() == '(') + stk.pop_back(); else - ++ans; + stk.push_back(c); } - ans += cnt; - return ans; + return stk.size(); } }; \ No newline at end of file diff --git a/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution.go b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution.go index 62d92fbc5b399..ebb8bf91b8a34 100644 --- a/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution.go +++ b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution.go @@ -1,14 +1,11 @@ func minAddToMakeValid(s string) int { - ans, cnt := 0, 0 + stk := []rune{} for _, c := range s { - if c == '(' { - cnt++ - } else if cnt > 0 { - cnt-- + if c == ')' && len(stk) > 0 && stk[len(stk)-1] == '(' { + stk = stk[:len(stk)-1] } else { - ans++ + stk = append(stk, c) } } - ans += cnt - return ans + return len(stk) } \ No newline at end of file diff --git a/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution.java b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution.java index 8a489c89de5ed..845e8bd25998a 100644 --- a/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution.java +++ b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution.java @@ -1,16 +1,13 @@ class Solution { public int minAddToMakeValid(String s) { - int ans = 0, cnt = 0; + Deque stk = new ArrayDeque<>(); for (char c : s.toCharArray()) { - if (c == '(') { - ++cnt; - } else if (cnt > 0) { - --cnt; + if (c == ')' && !stk.isEmpty() && stk.peek() == '(') { + stk.pop(); } else { - ++ans; + stk.push(c); } } - ans += cnt; - return ans; + return stk.size(); } } \ No newline at end of file diff --git a/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution.py b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution.py index f38cd8fe520b8..858a1d8a9223d 100644 --- a/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution.py +++ b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution.py @@ -1,12 +1,9 @@ class Solution: def minAddToMakeValid(self, s: str) -> int: - ans = cnt = 0 + stk = [] for c in s: - if c == '(': - cnt += 1 - elif cnt: - cnt -= 1 + if c == ')' and stk and stk[-1] == '(': + stk.pop() else: - ans += 1 - ans += cnt - return ans + stk.append(c) + return len(stk) diff --git a/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution2.cpp b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution2.cpp new file mode 100644 index 0000000000000..d744ad56804b5 --- /dev/null +++ b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int minAddToMakeValid(string s) { + int ans = 0, cnt = 0; + for (char c : s) { + if (c == '(') + ++cnt; + else if (cnt) + --cnt; + else + ++ans; + } + ans += cnt; + return ans; + } +}; \ No newline at end of file diff --git a/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution2.go b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution2.go new file mode 100644 index 0000000000000..62d92fbc5b399 --- /dev/null +++ b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution2.go @@ -0,0 +1,14 @@ +func minAddToMakeValid(s string) int { + ans, cnt := 0, 0 + for _, c := range s { + if c == '(' { + cnt++ + } else if cnt > 0 { + cnt-- + } else { + ans++ + } + } + ans += cnt + return ans +} \ No newline at end of file diff --git a/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution2.java b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution2.java new file mode 100644 index 0000000000000..8a489c89de5ed --- /dev/null +++ b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public int minAddToMakeValid(String s) { + int ans = 0, cnt = 0; + for (char c : s.toCharArray()) { + if (c == '(') { + ++cnt; + } else if (cnt > 0) { + --cnt; + } else { + ++ans; + } + } + ans += cnt; + return ans; + } +} \ No newline at end of file diff --git a/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution2.py b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution2.py new file mode 100644 index 0000000000000..f38cd8fe520b8 --- /dev/null +++ b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def minAddToMakeValid(self, s: str) -> int: + ans = cnt = 0 + for c in s: + if c == '(': + cnt += 1 + elif cnt: + cnt -= 1 + else: + ans += 1 + ans += cnt + return ans diff --git a/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution.cpp b/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution.cpp index 8d4ac3bc59f9c..192551d610915 100644 --- a/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution.cpp +++ b/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution.cpp @@ -15,4 +15,4 @@ class Solution { } return ans; } -}; +}; \ No newline at end of file diff --git a/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution.java b/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution.java index 726f299874014..a4a575e1f993a 100644 --- a/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution.java +++ b/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution.java @@ -15,4 +15,4 @@ public int minFlipsMonoIncr(String s) { } return ans; } -} +} \ No newline at end of file diff --git a/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution2.cpp b/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution2.cpp new file mode 100644 index 0000000000000..f029c9602d4bd --- /dev/null +++ b/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution2.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int minFlipsMonoIncr(string s) { + int n = s.size(); + vector presum(n + 1); + for (int i = 0; i < n; ++i) presum[i + 1] = presum[i] + (s[i] == '1'); + int ans = presum[n]; + for (int i = 0; i < n; ++i) ans = min(ans, presum[i] + n - i - (presum[n] - presum[i])); + return ans; + } +}; \ No newline at end of file diff --git a/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution2.go b/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution2.go new file mode 100644 index 0000000000000..04ac5e67c27f6 --- /dev/null +++ b/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution2.go @@ -0,0 +1,12 @@ +func minFlipsMonoIncr(s string) int { + n := len(s) + presum := make([]int, n+1) + for i, c := range s { + presum[i+1] = presum[i] + int(c-'0') + } + ans := presum[n] + for i := range s { + ans = min(ans, presum[i]+n-i-(presum[n]-presum[i])) + } + return ans +} \ No newline at end of file diff --git a/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution2.java b/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution2.java new file mode 100644 index 0000000000000..d248df525e2ea --- /dev/null +++ b/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public int minFlipsMonoIncr(String s) { + int n = s.length(); + int[] presum = new int[n + 1]; + for (int i = 0; i < n; ++i) { + presum[i + 1] = presum[i] + (s.charAt(i) - '0'); + } + int ans = presum[n]; + for (int i = 0; i < n; ++i) { + ans = Math.min(ans, presum[i] + n - i - (presum[n] - presum[i])); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution2.py b/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution2.py new file mode 100644 index 0000000000000..9477e296881b9 --- /dev/null +++ b/solution/0900-0999/0926.Flip String to Monotone Increasing/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def minFlipsMonoIncr(self, s: str) -> int: + n = len(s) + presum = [0] * (n + 1) + for i, c in enumerate(s): + presum[i + 1] = presum[i] + int(c) + ans = presum[-1] + for i in range(n): + ans = min(ans, presum[i] + n - i - (presum[-1] - presum[i])) + return ans diff --git a/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.cpp b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.cpp index 35a24bdc5561c..ecc22b8990dd3 100644 --- a/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.cpp +++ b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.cpp @@ -1,15 +1,16 @@ class Solution { public: int numSubarraysWithSum(vector& nums, int goal) { - int i1 = 0, i2 = 0, s1 = 0, s2 = 0, j = 0, ans = 0; - int n = nums.size(); - while (j < n) { - s1 += nums[j]; - s2 += nums[j]; - while (i1 <= j && s1 > goal) s1 -= nums[i1++]; - while (i2 <= j && s2 >= goal) s2 -= nums[i2++]; - ans += i2 - i1; - ++j; + int cnt[nums.size() + 1]; + memset(cnt, 0, sizeof cnt); + cnt[0] = 1; + int ans = 0, s = 0; + for (int& v : nums) { + s += v; + if (s - goal >= 0) { + ans += cnt[s - goal]; + } + ++cnt[s]; } return ans; } diff --git a/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.go b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.go index 85224d38b6ab3..c56dfc930a8e4 100644 --- a/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.go +++ b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.go @@ -1,18 +1,10 @@ -func numSubarraysWithSum(nums []int, goal int) int { - i1, i2, s1, s2, j, ans, n := 0, 0, 0, 0, 0, 0, len(nums) - for j < n { - s1 += nums[j] - s2 += nums[j] - for i1 <= j && s1 > goal { - s1 -= nums[i1] - i1++ - } - for i2 <= j && s2 >= goal { - s2 -= nums[i2] - i2++ - } - ans += i2 - i1 - j++ +func numSubarraysWithSum(nums []int, goal int) (ans int) { + cnt := map[int]int{0: 1} + s := 0 + for _, v := range nums { + s += v + ans += cnt[s-goal] + cnt[s]++ } - return ans + return } \ No newline at end of file diff --git a/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.java b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.java index 1a04ce09ddb10..893b440075ce6 100644 --- a/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.java +++ b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.java @@ -1,18 +1,14 @@ class Solution { public int numSubarraysWithSum(int[] nums, int goal) { - int i1 = 0, i2 = 0, s1 = 0, s2 = 0, j = 0, ans = 0; - int n = nums.length; - while (j < n) { - s1 += nums[j]; - s2 += nums[j]; - while (i1 <= j && s1 > goal) { - s1 -= nums[i1++]; + int[] cnt = new int[nums.length + 1]; + cnt[0] = 1; + int ans = 0, s = 0; + for (int v : nums) { + s += v; + if (s - goal >= 0) { + ans += cnt[s - goal]; } - while (i2 <= j && s2 >= goal) { - s2 -= nums[i2++]; - } - ans += i2 - i1; - ++j; + ++cnt[s]; } return ans; } diff --git a/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.js b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.js index 5ccd2c62b069a..7ad82e0bfab0e 100644 --- a/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.js +++ b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.js @@ -4,20 +4,16 @@ * @return {number} */ var numSubarraysWithSum = function (nums, goal) { - let i1 = 0, - i2 = 0, - s1 = 0, - s2 = 0, - j = 0, - ans = 0; - const n = nums.length; - while (j < n) { - s1 += nums[j]; - s2 += nums[j]; - while (i1 <= j && s1 > goal) s1 -= nums[i1++]; - while (i2 <= j && s2 >= goal) s2 -= nums[i2++]; - ans += i2 - i1; - ++j; + const cnt = new Array(nums.length + 1).fill(0); + cnt[0] = 1; + let ans = 0; + let s = 0; + for (const v of nums) { + s += v; + if (s >= goal) { + ans += cnt[s - goal]; + } + ++cnt[s]; } return ans; }; diff --git a/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.py b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.py index a51b12c711ed6..36ce30b016073 100644 --- a/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.py +++ b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution.py @@ -1,16 +1,9 @@ class Solution: def numSubarraysWithSum(self, nums: List[int], goal: int) -> int: - i1 = i2 = s1 = s2 = j = ans = 0 - n = len(nums) - while j < n: - s1 += nums[j] - s2 += nums[j] - while i1 <= j and s1 > goal: - s1 -= nums[i1] - i1 += 1 - while i2 <= j and s2 >= goal: - s2 -= nums[i2] - i2 += 1 - ans += i2 - i1 - j += 1 + cnt = Counter({0: 1}) + ans = s = 0 + for v in nums: + s += v + ans += cnt[s - goal] + cnt[s] += 1 return ans diff --git a/solution/0900-0999/0930.Binary Subarrays With Sum/Solution2.cpp b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution2.cpp new file mode 100644 index 0000000000000..35a24bdc5561c --- /dev/null +++ b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int numSubarraysWithSum(vector& nums, int goal) { + int i1 = 0, i2 = 0, s1 = 0, s2 = 0, j = 0, ans = 0; + int n = nums.size(); + while (j < n) { + s1 += nums[j]; + s2 += nums[j]; + while (i1 <= j && s1 > goal) s1 -= nums[i1++]; + while (i2 <= j && s2 >= goal) s2 -= nums[i2++]; + ans += i2 - i1; + ++j; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0900-0999/0930.Binary Subarrays With Sum/Solution2.go b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution2.go new file mode 100644 index 0000000000000..85224d38b6ab3 --- /dev/null +++ b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution2.go @@ -0,0 +1,18 @@ +func numSubarraysWithSum(nums []int, goal int) int { + i1, i2, s1, s2, j, ans, n := 0, 0, 0, 0, 0, 0, len(nums) + for j < n { + s1 += nums[j] + s2 += nums[j] + for i1 <= j && s1 > goal { + s1 -= nums[i1] + i1++ + } + for i2 <= j && s2 >= goal { + s2 -= nums[i2] + i2++ + } + ans += i2 - i1 + j++ + } + return ans +} \ No newline at end of file diff --git a/solution/0900-0999/0930.Binary Subarrays With Sum/Solution2.java b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution2.java new file mode 100644 index 0000000000000..1a04ce09ddb10 --- /dev/null +++ b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution2.java @@ -0,0 +1,19 @@ +class Solution { + public int numSubarraysWithSum(int[] nums, int goal) { + int i1 = 0, i2 = 0, s1 = 0, s2 = 0, j = 0, ans = 0; + int n = nums.length; + while (j < n) { + s1 += nums[j]; + s2 += nums[j]; + while (i1 <= j && s1 > goal) { + s1 -= nums[i1++]; + } + while (i2 <= j && s2 >= goal) { + s2 -= nums[i2++]; + } + ans += i2 - i1; + ++j; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0900-0999/0930.Binary Subarrays With Sum/Solution2.js b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution2.js new file mode 100644 index 0000000000000..5ccd2c62b069a --- /dev/null +++ b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution2.js @@ -0,0 +1,23 @@ +/** + * @param {number[]} nums + * @param {number} goal + * @return {number} + */ +var numSubarraysWithSum = function (nums, goal) { + let i1 = 0, + i2 = 0, + s1 = 0, + s2 = 0, + j = 0, + ans = 0; + const n = nums.length; + while (j < n) { + s1 += nums[j]; + s2 += nums[j]; + while (i1 <= j && s1 > goal) s1 -= nums[i1++]; + while (i2 <= j && s2 >= goal) s2 -= nums[i2++]; + ans += i2 - i1; + ++j; + } + return ans; +}; diff --git a/solution/0900-0999/0930.Binary Subarrays With Sum/Solution2.py b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution2.py new file mode 100644 index 0000000000000..a51b12c711ed6 --- /dev/null +++ b/solution/0900-0999/0930.Binary Subarrays With Sum/Solution2.py @@ -0,0 +1,16 @@ +class Solution: + def numSubarraysWithSum(self, nums: List[int], goal: int) -> int: + i1 = i2 = s1 = s2 = j = ans = 0 + n = len(nums) + while j < n: + s1 += nums[j] + s2 += nums[j] + while i1 <= j and s1 > goal: + s1 -= nums[i1] + i1 += 1 + while i2 <= j and s2 >= goal: + s2 -= nums[i2] + i2 += 1 + ans += i2 - i1 + j += 1 + return ans diff --git a/solution/0900-0999/0931.Minimum Falling Path Sum/Solution.cpp b/solution/0900-0999/0931.Minimum Falling Path Sum/Solution.cpp index 668f5c6bc5ced..b66811c7b8b15 100644 --- a/solution/0900-0999/0931.Minimum Falling Path Sum/Solution.cpp +++ b/solution/0900-0999/0931.Minimum Falling Path Sum/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - int minFallingPathSum(vector>& matrix) { - int n = matrix.size(); - vector f(n); - for (auto& row : matrix) { - auto g = f; - for (int j = 0; j < n; ++j) { - if (j) { - g[j] = min(g[j], f[j - 1]); - } - if (j + 1 < n) { - g[j] = min(g[j], f[j + 1]); - } - g[j] += row[j]; - } - f = move(g); - } - return *min_element(f.begin(), f.end()); - } +class Solution { +public: + int minFallingPathSum(vector>& matrix) { + int n = matrix.size(); + vector f(n); + for (auto& row : matrix) { + auto g = f; + for (int j = 0; j < n; ++j) { + if (j) { + g[j] = min(g[j], f[j - 1]); + } + if (j + 1 < n) { + g[j] = min(g[j], f[j + 1]); + } + g[j] += row[j]; + } + f = move(g); + } + return *min_element(f.begin(), f.end()); + } }; \ No newline at end of file diff --git a/solution/0900-0999/0931.Minimum Falling Path Sum/Solution.java b/solution/0900-0999/0931.Minimum Falling Path Sum/Solution.java index a8cd5a48de874..590787efaf76b 100644 --- a/solution/0900-0999/0931.Minimum Falling Path Sum/Solution.java +++ b/solution/0900-0999/0931.Minimum Falling Path Sum/Solution.java @@ -1,25 +1,25 @@ -class Solution { - public int minFallingPathSum(int[][] matrix) { - int n = matrix.length; - var f = new int[n]; - for (var row : matrix) { - var g = f.clone(); - for (int j = 0; j < n; ++j) { - if (j > 0) { - g[j] = Math.min(g[j], f[j - 1]); - } - if (j + 1 < n) { - g[j] = Math.min(g[j], f[j + 1]); - } - g[j] += row[j]; - } - f = g; - } - // return Arrays.stream(f).min().getAsInt(); - int ans = 1 << 30; - for (int x : f) { - ans = Math.min(ans, x); - } - return ans; - } +class Solution { + public int minFallingPathSum(int[][] matrix) { + int n = matrix.length; + var f = new int[n]; + for (var row : matrix) { + var g = f.clone(); + for (int j = 0; j < n; ++j) { + if (j > 0) { + g[j] = Math.min(g[j], f[j - 1]); + } + if (j + 1 < n) { + g[j] = Math.min(g[j], f[j + 1]); + } + g[j] += row[j]; + } + f = g; + } + // return Arrays.stream(f).min().getAsInt(); + int ans = 1 << 30; + for (int x : f) { + ans = Math.min(ans, x); + } + return ans; + } } \ No newline at end of file diff --git a/solution/0900-0999/0931.Minimum Falling Path Sum/Solution.py b/solution/0900-0999/0931.Minimum Falling Path Sum/Solution.py index 908a4ab112d55..38545fcd874bc 100644 --- a/solution/0900-0999/0931.Minimum Falling Path Sum/Solution.py +++ b/solution/0900-0999/0931.Minimum Falling Path Sum/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def minFallingPathSum(self, matrix: List[List[int]]) -> int: - n = len(matrix) - f = [0] * n - for row in matrix: - g = [0] * n - for j, x in enumerate(row): - l, r = max(0, j - 1), min(n, j + 2) - g[j] = min(f[l:r]) + x - f = g - return min(f) +class Solution: + def minFallingPathSum(self, matrix: List[List[int]]) -> int: + n = len(matrix) + f = [0] * n + for row in matrix: + g = [0] * n + for j, x in enumerate(row): + l, r = max(0, j - 1), min(n, j + 2) + g[j] = min(f[l:r]) + x + f = g + return min(f) diff --git a/solution/0900-0999/0933.Number of Recent Calls/Solution.cpp b/solution/0900-0999/0933.Number of Recent Calls/Solution.cpp index 3b28b2c570b3c..dea5886cf34ad 100644 --- a/solution/0900-0999/0933.Number of Recent Calls/Solution.cpp +++ b/solution/0900-0999/0933.Number of Recent Calls/Solution.cpp @@ -1,15 +1,13 @@ class RecentCounter { public: - deque q; + queue q; RecentCounter() { } int ping(int t) { - q.push_back(t); - while (q.front() < t - 3000) { - q.pop_front(); - } + q.push(t); + while (q.front() < t - 3000) q.pop(); return q.size(); } }; diff --git a/solution/0900-0999/0933.Number of Recent Calls/Solution.cs b/solution/0900-0999/0933.Number of Recent Calls/Solution.cs index 9497320e98a6f..a372799d48e93 100644 --- a/solution/0900-0999/0933.Number of Recent Calls/Solution.cs +++ b/solution/0900-0999/0933.Number of Recent Calls/Solution.cs @@ -4,7 +4,7 @@ public class RecentCounter { public RecentCounter() { } - + public int Ping(int t) { q.Enqueue(t); while (q.Peek() < t - 3000) @@ -19,4 +19,4 @@ public int Ping(int t) { * Your RecentCounter object will be instantiated and called as such: * RecentCounter obj = new RecentCounter(); * int param_1 = obj.Ping(t); - */ \ No newline at end of file + */ diff --git a/solution/0900-0999/0933.Number of Recent Calls/Solution.java b/solution/0900-0999/0933.Number of Recent Calls/Solution.java index d4f4ede952132..d7f51201cb8d5 100644 --- a/solution/0900-0999/0933.Number of Recent Calls/Solution.java +++ b/solution/0900-0999/0933.Number of Recent Calls/Solution.java @@ -1,15 +1,26 @@ class RecentCounter { - private Deque q = new ArrayDeque<>(); + private int[] s = new int[10010]; + private int idx; public RecentCounter() { } public int ping(int t) { - q.offer(t); - while (q.peekFirst() < t - 3000) { - q.pollFirst(); + s[idx++] = t; + return idx - search(t - 3000); + } + + private int search(int x) { + int left = 0, right = idx; + while (left < right) { + int mid = (left + right) >> 1; + if (s[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } } - return q.size(); + return left; } } diff --git a/solution/0900-0999/0933.Number of Recent Calls/Solution2.cpp b/solution/0900-0999/0933.Number of Recent Calls/Solution2.cpp new file mode 100644 index 0000000000000..ffd0b4c5571e6 --- /dev/null +++ b/solution/0900-0999/0933.Number of Recent Calls/Solution2.cpp @@ -0,0 +1,18 @@ +class RecentCounter { +public: + vector s; + + RecentCounter() { + } + + int ping(int t) { + s.push_back(t); + return s.size() - (lower_bound(s.begin(), s.end(), t - 3000) - s.begin()); + } +}; + +/** + * Your RecentCounter object will be instantiated and called as such: + * RecentCounter* obj = new RecentCounter(); + * int param_1 = obj->ping(t); + */ \ No newline at end of file diff --git a/solution/0900-0999/0933.Number of Recent Calls/Solution2.go b/solution/0900-0999/0933.Number of Recent Calls/Solution2.go new file mode 100644 index 0000000000000..77d6a9a3b4323 --- /dev/null +++ b/solution/0900-0999/0933.Number of Recent Calls/Solution2.go @@ -0,0 +1,30 @@ +type RecentCounter struct { + s []int +} + +func Constructor() RecentCounter { + return RecentCounter{[]int{}} +} + +func (this *RecentCounter) Ping(t int) int { + this.s = append(this.s, t) + search := func(x int) int { + left, right := 0, len(this.s) + for left < right { + mid := (left + right) >> 1 + if this.s[mid] >= x { + right = mid + } else { + left = mid + 1 + } + } + return left + } + return len(this.s) - search(t-3000) +} + +/** + * Your RecentCounter object will be instantiated and called as such: + * obj := Constructor(); + * param_1 := obj.Ping(t); + */ \ No newline at end of file diff --git a/solution/0900-0999/0933.Number of Recent Calls/Solution2.py b/solution/0900-0999/0933.Number of Recent Calls/Solution2.py new file mode 100644 index 0000000000000..10e36ce7ae266 --- /dev/null +++ b/solution/0900-0999/0933.Number of Recent Calls/Solution2.py @@ -0,0 +1,12 @@ +class RecentCounter: + def __init__(self): + self.s = [] + + def ping(self, t: int) -> int: + self.s.append(t) + return len(self.s) - bisect_left(self.s, t - 3000) + + +# Your RecentCounter object will be instantiated and called as such: +# obj = RecentCounter() +# param_1 = obj.ping(t) diff --git a/solution/0900-0999/0934.Shortest Bridge/Solution.py b/solution/0900-0999/0934.Shortest Bridge/Solution.py index 9a62bdd1b6f83..c526fcd925b8f 100644 --- a/solution/0900-0999/0934.Shortest Bridge/Solution.py +++ b/solution/0900-0999/0934.Shortest Bridge/Solution.py @@ -1,28 +1,28 @@ -class Solution: - def shortestBridge(self, grid: List[List[int]]) -> int: - def dfs(i, j): - q.append((i, j)) - grid[i][j] = 2 - for a, b in pairwise(dirs): - x, y = i + a, j + b - if 0 <= x < n and 0 <= y < n and grid[x][y] == 1: - dfs(x, y) - - n = len(grid) - dirs = (-1, 0, 1, 0, -1) - q = deque() - i, j = next((i, j) for i in range(n) for j in range(n) if grid[i][j]) - dfs(i, j) - ans = 0 - while 1: - for _ in range(len(q)): - i, j = q.popleft() - for a, b in pairwise(dirs): - x, y = i + a, j + b - if 0 <= x < n and 0 <= y < n: - if grid[x][y] == 1: - return ans - if grid[x][y] == 0: - grid[x][y] = 2 - q.append((x, y)) - ans += 1 +class Solution: + def shortestBridge(self, grid: List[List[int]]) -> int: + def dfs(i, j): + q.append((i, j)) + grid[i][j] = 2 + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < n and 0 <= y < n and grid[x][y] == 1: + dfs(x, y) + + n = len(grid) + dirs = (-1, 0, 1, 0, -1) + q = deque() + i, j = next((i, j) for i in range(n) for j in range(n) if grid[i][j]) + dfs(i, j) + ans = 0 + while 1: + for _ in range(len(q)): + i, j = q.popleft() + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < n and 0 <= y < n: + if grid[x][y] == 1: + return ans + if grid[x][y] == 0: + grid[x][y] = 2 + q.append((x, y)) + ans += 1 diff --git a/solution/0900-0999/0935.Knight Dialer/Solution.cs b/solution/0900-0999/0935.Knight Dialer/Solution.cs index 729a2f2ae4442..4c11a2da4ea9a 100644 --- a/solution/0900-0999/0935.Knight Dialer/Solution.cs +++ b/solution/0900-0999/0935.Knight Dialer/Solution.cs @@ -16,7 +16,7 @@ public int KnightDialer(int n) { C = (tempA + (2 * tempD) % MOD) % MOD; D = tempC; } - + int ans = (A + B) % MOD; ans = (ans + C) % MOD; return (ans + D) % MOD; diff --git a/solution/0900-0999/0935.Knight Dialer/Solution.ts b/solution/0900-0999/0935.Knight Dialer/Solution.ts new file mode 100644 index 0000000000000..e262e04661c56 --- /dev/null +++ b/solution/0900-0999/0935.Knight Dialer/Solution.ts @@ -0,0 +1,34 @@ +function knightDialer(n: number): number { + const MOD: number = 1e9 + 7; + + if (n === 1) { + return 10; + } + + const f: number[] = new Array(10).fill(1); + + while (--n > 0) { + const t: number[] = new Array(10).fill(0); + + t[0] = f[4] + f[6]; + t[1] = f[6] + f[8]; + t[2] = f[7] + f[9]; + t[3] = f[4] + f[8]; + t[4] = f[0] + f[3] + f[9]; + t[6] = f[0] + f[1] + f[7]; + t[7] = f[2] + f[6]; + t[8] = f[1] + f[3]; + t[9] = f[2] + f[4]; + + for (let i = 0; i < 10; ++i) { + f[i] = t[i] % MOD; + } + } + + let ans: number = 0; + for (const v of f) { + ans = (ans + v) % MOD; + } + + return ans; +} diff --git a/solution/0900-0999/0936.Stamping The Sequence/Solution.cpp b/solution/0900-0999/0936.Stamping The Sequence/Solution.cpp index b7610957a37a0..b08781c09ce08 100644 --- a/solution/0900-0999/0936.Stamping The Sequence/Solution.cpp +++ b/solution/0900-0999/0936.Stamping The Sequence/Solution.cpp @@ -1,44 +1,44 @@ -class Solution { -public: - vector movesToStamp(string stamp, string target) { - int m = stamp.size(), n = target.size(); - vector indeg(n - m + 1, m); - vector g[n]; - queue q; - for (int i = 0; i < n - m + 1; ++i) { - for (int j = 0; j < m; ++j) { - if (target[i + j] == stamp[j]) { - if (--indeg[i] == 0) { - q.push(i); - } - } else { - g[i + j].push_back(i); - } - } - } - vector ans; - vector vis(n); - while (q.size()) { - int i = q.front(); - q.pop(); - ans.push_back(i); - for (int j = 0; j < m; ++j) { - if (!vis[i + j]) { - vis[i + j] = true; - for (int k : g[i + j]) { - if (--indeg[k] == 0) { - q.push(k); - } - } - } - } - } - for (int i = 0; i < n; ++i) { - if (!vis[i]) { - return {}; - } - } - reverse(ans.begin(), ans.end()); - return ans; - } +class Solution { +public: + vector movesToStamp(string stamp, string target) { + int m = stamp.size(), n = target.size(); + vector indeg(n - m + 1, m); + vector g[n]; + queue q; + for (int i = 0; i < n - m + 1; ++i) { + for (int j = 0; j < m; ++j) { + if (target[i + j] == stamp[j]) { + if (--indeg[i] == 0) { + q.push(i); + } + } else { + g[i + j].push_back(i); + } + } + } + vector ans; + vector vis(n); + while (q.size()) { + int i = q.front(); + q.pop(); + ans.push_back(i); + for (int j = 0; j < m; ++j) { + if (!vis[i + j]) { + vis[i + j] = true; + for (int k : g[i + j]) { + if (--indeg[k] == 0) { + q.push(k); + } + } + } + } + } + for (int i = 0; i < n; ++i) { + if (!vis[i]) { + return {}; + } + } + reverse(ans.begin(), ans.end()); + return ans; + } }; \ No newline at end of file diff --git a/solution/0900-0999/0936.Stamping The Sequence/Solution.java b/solution/0900-0999/0936.Stamping The Sequence/Solution.java index ac552f6482285..a4901b5849b19 100644 --- a/solution/0900-0999/0936.Stamping The Sequence/Solution.java +++ b/solution/0900-0999/0936.Stamping The Sequence/Solution.java @@ -1,44 +1,44 @@ -class Solution { - public int[] movesToStamp(String stamp, String target) { - int m = stamp.length(), n = target.length(); - int[] indeg = new int[n - m + 1]; - Arrays.fill(indeg, m); - List[] g = new List[n]; - Arrays.setAll(g, i -> new ArrayList<>()); - Deque q = new ArrayDeque<>(); - for (int i = 0; i < n - m + 1; ++i) { - for (int j = 0; j < m; ++j) { - if (target.charAt(i + j) == stamp.charAt(j)) { - if (--indeg[i] == 0) { - q.offer(i); - } - } else { - g[i + j].add(i); - } - } - } - List ans = new ArrayList<>(); - boolean[] vis = new boolean[n]; - while (!q.isEmpty()) { - int i = q.poll(); - ans.add(i); - for (int j = 0; j < m; ++j) { - if (!vis[i + j]) { - vis[i + j] = true; - for (int k : g[i + j]) { - if (--indeg[k] == 0) { - q.offer(k); - } - } - } - } - } - for (int i = 0; i < n; ++i) { - if (!vis[i]) { - return new int[0]; - } - } - Collections.reverse(ans); - return ans.stream().mapToInt(Integer::intValue).toArray(); - } +class Solution { + public int[] movesToStamp(String stamp, String target) { + int m = stamp.length(), n = target.length(); + int[] indeg = new int[n - m + 1]; + Arrays.fill(indeg, m); + List[] g = new List[n]; + Arrays.setAll(g, i -> new ArrayList<>()); + Deque q = new ArrayDeque<>(); + for (int i = 0; i < n - m + 1; ++i) { + for (int j = 0; j < m; ++j) { + if (target.charAt(i + j) == stamp.charAt(j)) { + if (--indeg[i] == 0) { + q.offer(i); + } + } else { + g[i + j].add(i); + } + } + } + List ans = new ArrayList<>(); + boolean[] vis = new boolean[n]; + while (!q.isEmpty()) { + int i = q.poll(); + ans.add(i); + for (int j = 0; j < m; ++j) { + if (!vis[i + j]) { + vis[i + j] = true; + for (int k : g[i + j]) { + if (--indeg[k] == 0) { + q.offer(k); + } + } + } + } + } + for (int i = 0; i < n; ++i) { + if (!vis[i]) { + return new int[0]; + } + } + Collections.reverse(ans); + return ans.stream().mapToInt(Integer::intValue).toArray(); + } } \ No newline at end of file diff --git a/solution/0900-0999/0936.Stamping The Sequence/Solution.py b/solution/0900-0999/0936.Stamping The Sequence/Solution.py index a72cfacb13298..b29a11dc188af 100644 --- a/solution/0900-0999/0936.Stamping The Sequence/Solution.py +++ b/solution/0900-0999/0936.Stamping The Sequence/Solution.py @@ -1,27 +1,27 @@ -class Solution: - def movesToStamp(self, stamp: str, target: str) -> List[int]: - m, n = len(stamp), len(target) - indeg = [m] * (n - m + 1) - q = deque() - g = [[] for _ in range(n)] - for i in range(n - m + 1): - for j, c in enumerate(stamp): - if target[i + j] == c: - indeg[i] -= 1 - if indeg[i] == 0: - q.append(i) - else: - g[i + j].append(i) - ans = [] - vis = [False] * n - while q: - i = q.popleft() - ans.append(i) - for j in range(m): - if not vis[i + j]: - vis[i + j] = True - for k in g[i + j]: - indeg[k] -= 1 - if indeg[k] == 0: - q.append(k) - return ans[::-1] if all(vis) else [] +class Solution: + def movesToStamp(self, stamp: str, target: str) -> List[int]: + m, n = len(stamp), len(target) + indeg = [m] * (n - m + 1) + q = deque() + g = [[] for _ in range(n)] + for i in range(n - m + 1): + for j, c in enumerate(stamp): + if target[i + j] == c: + indeg[i] -= 1 + if indeg[i] == 0: + q.append(i) + else: + g[i + j].append(i) + ans = [] + vis = [False] * n + while q: + i = q.popleft() + ans.append(i) + for j in range(m): + if not vis[i + j]: + vis[i + j] = True + for k in g[i + j]: + indeg[k] -= 1 + if indeg[k] == 0: + q.append(k) + return ans[::-1] if all(vis) else [] diff --git a/solution/0900-0999/0940.Distinct Subsequences II/Solution.c b/solution/0900-0999/0940.Distinct Subsequences II/Solution.c index b43208b9dff60..3f050fc50ce2c 100644 --- a/solution/0900-0999/0940.Distinct Subsequences II/Solution.c +++ b/solution/0900-0999/0940.Distinct Subsequences II/Solution.c @@ -14,4 +14,4 @@ int distinctSubseqII(char* s) { res = (res + dp[i]) % mod; } return res; -} +} \ No newline at end of file diff --git a/solution/0900-0999/0940.Distinct Subsequences II/Solution.cpp b/solution/0900-0999/0940.Distinct Subsequences II/Solution.cpp index 688080d81a912..faf5ec9367092 100644 --- a/solution/0900-0999/0940.Distinct Subsequences II/Solution.cpp +++ b/solution/0900-0999/0940.Distinct Subsequences II/Solution.cpp @@ -4,13 +4,10 @@ class Solution { int distinctSubseqII(string s) { vector dp(26); - long ans = 0; for (char& c : s) { int i = c - 'a'; - long add = ans - dp[i] + 1; - ans = (ans + add + mod) % mod; - dp[i] = (dp[i] + add) % mod; + dp[i] = accumulate(dp.begin(), dp.end(), 1l) % mod; } - return ans; + return accumulate(dp.begin(), dp.end(), 0l) % mod; } }; \ No newline at end of file diff --git a/solution/0900-0999/0940.Distinct Subsequences II/Solution.go b/solution/0900-0999/0940.Distinct Subsequences II/Solution.go index 1260b71bc4de1..084f05c9e3177 100644 --- a/solution/0900-0999/0940.Distinct Subsequences II/Solution.go +++ b/solution/0900-0999/0940.Distinct Subsequences II/Solution.go @@ -1,12 +1,17 @@ func distinctSubseqII(s string) int { const mod int = 1e9 + 7 + sum := func(arr []int) int { + x := 0 + for _, v := range arr { + x = (x + v) % mod + } + return x + } + dp := make([]int, 26) - ans := 0 for _, c := range s { c -= 'a' - add := ans - dp[c] + 1 - ans = (ans + add) % mod - dp[c] = (dp[c] + add) % mod + dp[c] = sum(dp) + 1 } - return (ans + mod) % mod + return sum(dp) } \ No newline at end of file diff --git a/solution/0900-0999/0940.Distinct Subsequences II/Solution.java b/solution/0900-0999/0940.Distinct Subsequences II/Solution.java index ab8e7359e0546..377b30300779e 100644 --- a/solution/0900-0999/0940.Distinct Subsequences II/Solution.java +++ b/solution/0900-0999/0940.Distinct Subsequences II/Solution.java @@ -3,13 +3,18 @@ class Solution { public int distinctSubseqII(String s) { int[] dp = new int[26]; - int ans = 0; for (int i = 0; i < s.length(); ++i) { int j = s.charAt(i) - 'a'; - int add = (ans - dp[j] + 1) % MOD; - ans = (ans + add) % MOD; - dp[j] = (dp[j] + add) % MOD; + dp[j] = sum(dp) + 1; } - return (ans + MOD) % MOD; + return sum(dp); + } + + private int sum(int[] arr) { + int x = 0; + for (int v : arr) { + x = (x + v) % MOD; + } + return x; } } \ No newline at end of file diff --git a/solution/0900-0999/0940.Distinct Subsequences II/Solution.py b/solution/0900-0999/0940.Distinct Subsequences II/Solution.py index 8206bbc3b1d2a..b61f8b3b44925 100644 --- a/solution/0900-0999/0940.Distinct Subsequences II/Solution.py +++ b/solution/0900-0999/0940.Distinct Subsequences II/Solution.py @@ -1,11 +1,13 @@ class Solution: def distinctSubseqII(self, s: str) -> int: mod = 10**9 + 7 - dp = [0] * 26 - ans = 0 - for c in s: - i = ord(c) - ord('a') - add = ans - dp[i] + 1 - ans = (ans + add) % mod - dp[i] += add - return ans + n = len(s) + dp = [[0] * 26 for _ in range(n + 1)] + for i, c in enumerate(s, 1): + k = ord(c) - ord('a') + for j in range(26): + if j == k: + dp[i][j] = sum(dp[i - 1]) % mod + 1 + else: + dp[i][j] = dp[i - 1][j] + return sum(dp[-1]) % mod diff --git a/solution/0900-0999/0940.Distinct Subsequences II/Solution2.cpp b/solution/0900-0999/0940.Distinct Subsequences II/Solution2.cpp new file mode 100644 index 0000000000000..688080d81a912 --- /dev/null +++ b/solution/0900-0999/0940.Distinct Subsequences II/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + const int mod = 1e9 + 7; + + int distinctSubseqII(string s) { + vector dp(26); + long ans = 0; + for (char& c : s) { + int i = c - 'a'; + long add = ans - dp[i] + 1; + ans = (ans + add + mod) % mod; + dp[i] = (dp[i] + add) % mod; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/0900-0999/0940.Distinct Subsequences II/Solution2.go b/solution/0900-0999/0940.Distinct Subsequences II/Solution2.go new file mode 100644 index 0000000000000..1260b71bc4de1 --- /dev/null +++ b/solution/0900-0999/0940.Distinct Subsequences II/Solution2.go @@ -0,0 +1,12 @@ +func distinctSubseqII(s string) int { + const mod int = 1e9 + 7 + dp := make([]int, 26) + ans := 0 + for _, c := range s { + c -= 'a' + add := ans - dp[c] + 1 + ans = (ans + add) % mod + dp[c] = (dp[c] + add) % mod + } + return (ans + mod) % mod +} \ No newline at end of file diff --git a/solution/0900-0999/0940.Distinct Subsequences II/Solution2.java b/solution/0900-0999/0940.Distinct Subsequences II/Solution2.java new file mode 100644 index 0000000000000..ab8e7359e0546 --- /dev/null +++ b/solution/0900-0999/0940.Distinct Subsequences II/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + private static final int MOD = (int) 1e9 + 7; + + public int distinctSubseqII(String s) { + int[] dp = new int[26]; + int ans = 0; + for (int i = 0; i < s.length(); ++i) { + int j = s.charAt(i) - 'a'; + int add = (ans - dp[j] + 1) % MOD; + ans = (ans + add) % MOD; + dp[j] = (dp[j] + add) % MOD; + } + return (ans + MOD) % MOD; + } +} \ No newline at end of file diff --git a/solution/0900-0999/0940.Distinct Subsequences II/Solution2.py b/solution/0900-0999/0940.Distinct Subsequences II/Solution2.py new file mode 100644 index 0000000000000..c882e7cd71745 --- /dev/null +++ b/solution/0900-0999/0940.Distinct Subsequences II/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def distinctSubseqII(self, s: str) -> int: + mod = 10**9 + 7 + dp = [0] * 26 + for c in s: + i = ord(c) - ord('a') + dp[i] = sum(dp) % mod + 1 + return sum(dp) % mod diff --git a/solution/0900-0999/0940.Distinct Subsequences II/Solution3.py b/solution/0900-0999/0940.Distinct Subsequences II/Solution3.py new file mode 100644 index 0000000000000..8206bbc3b1d2a --- /dev/null +++ b/solution/0900-0999/0940.Distinct Subsequences II/Solution3.py @@ -0,0 +1,11 @@ +class Solution: + def distinctSubseqII(self, s: str) -> int: + mod = 10**9 + 7 + dp = [0] * 26 + ans = 0 + for c in s: + i = ord(c) - ord('a') + add = ans - dp[i] + 1 + ans = (ans + add) % mod + dp[i] += add + return ans diff --git a/solution/0900-0999/0941.Valid Mountain Array/Solution.java b/solution/0900-0999/0941.Valid Mountain Array/Solution.java index 3d3c0eb081c60..f16714064ceb5 100644 --- a/solution/0900-0999/0941.Valid Mountain Array/Solution.java +++ b/solution/0900-0999/0941.Valid Mountain Array/Solution.java @@ -1,4 +1,5 @@ class Solution { + public boolean validMountainArray(int[] arr) { int n = arr.length; if (n < 3) { diff --git a/solution/0900-0999/0942.DI String Match/Solution.cpp b/solution/0900-0999/0942.DI String Match/Solution.cpp index e9fc17c00532a..efee75a7be8c4 100644 --- a/solution/0900-0999/0942.DI String Match/Solution.cpp +++ b/solution/0900-0999/0942.DI String Match/Solution.cpp @@ -14,4 +14,4 @@ class Solution { ans[n] = low; return ans; } -}; +}; \ No newline at end of file diff --git a/solution/0900-0999/0942.DI String Match/Solution.java b/solution/0900-0999/0942.DI String Match/Solution.java index 51121975d8ddf..5157f05f9a71f 100644 --- a/solution/0900-0999/0942.DI String Match/Solution.java +++ b/solution/0900-0999/0942.DI String Match/Solution.java @@ -13,4 +13,4 @@ public int[] diStringMatch(String s) { ans[n] = low; return ans; } -} +} \ No newline at end of file diff --git a/solution/0900-0999/0944.Delete Columns to Make Sorted/Solution.cpp b/solution/0900-0999/0944.Delete Columns to Make Sorted/Solution.cpp index de7d571212e2c..f54f5f6cac1ba 100644 --- a/solution/0900-0999/0944.Delete Columns to Make Sorted/Solution.cpp +++ b/solution/0900-0999/0944.Delete Columns to Make Sorted/Solution.cpp @@ -14,4 +14,4 @@ class Solution { } return res; } -}; +}; \ No newline at end of file diff --git a/solution/0900-0999/0946.Validate Stack Sequences/Solution.cs b/solution/0900-0999/0946.Validate Stack Sequences/Solution.cs index 128092b209972..eb939e6252c72 100644 --- a/solution/0900-0999/0946.Validate Stack Sequences/Solution.cs +++ b/solution/0900-0999/0946.Validate Stack Sequences/Solution.cs @@ -12,4 +12,4 @@ public bool ValidateStackSequences(int[] pushed, int[] popped) { } return stk.Count == 0; } -} \ No newline at end of file +} diff --git a/solution/0900-0999/0949.Largest Time for Given Digits/Solution.py b/solution/0900-0999/0949.Largest Time for Given Digits/Solution.py index 9f20cd60d61b9..183c5eb1f07a5 100644 --- a/solution/0900-0999/0949.Largest Time for Given Digits/Solution.py +++ b/solution/0900-0999/0949.Largest Time for Given Digits/Solution.py @@ -1,12 +1,15 @@ class Solution: def largestTimeFromDigits(self, arr: List[int]) -> str: - ans = -1 - for i in range(4): - for j in range(4): - for k in range(4): - if i != j and i != k and j != k: - h = arr[i] * 10 + arr[j] - m = arr[k] * 10 + arr[6 - i - j - k] - if h < 24 and m < 60: - ans = max(ans, h * 60 + m) - return '' if ans < 0 else f'{ans // 60:02}:{ans % 60:02}' + cnt = [0] * 10 + for v in arr: + cnt[v] += 1 + for h in range(23, -1, -1): + for m in range(59, -1, -1): + t = [0] * 10 + t[h // 10] += 1 + t[h % 10] += 1 + t[m // 10] += 1 + t[m % 10] += 1 + if cnt == t: + return f'{h:02}:{m:02}' + return '' diff --git a/solution/0900-0999/0949.Largest Time for Given Digits/Solution2.py b/solution/0900-0999/0949.Largest Time for Given Digits/Solution2.py new file mode 100644 index 0000000000000..9f20cd60d61b9 --- /dev/null +++ b/solution/0900-0999/0949.Largest Time for Given Digits/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def largestTimeFromDigits(self, arr: List[int]) -> str: + ans = -1 + for i in range(4): + for j in range(4): + for k in range(4): + if i != j and i != k and j != k: + h = arr[i] * 10 + arr[j] + m = arr[k] * 10 + arr[6 - i - j - k] + if h < 24 and m < 60: + ans = max(ans, h * 60 + m) + return '' if ans < 0 else f'{ans // 60:02}:{ans % 60:02}' diff --git a/solution/0900-0999/0950.Reveal Cards In Increasing Order/Solution.cpp b/solution/0900-0999/0950.Reveal Cards In Increasing Order/Solution.cpp index 49464ef0859b1..99c0bd3083167 100644 --- a/solution/0900-0999/0950.Reveal Cards In Increasing Order/Solution.cpp +++ b/solution/0900-0999/0950.Reveal Cards In Increasing Order/Solution.cpp @@ -1,4 +1,4 @@ -class Solution { +class Solution { public: vector deckRevealedIncreasing(vector& deck) { sort(deck.rbegin(), deck.rend()); diff --git a/solution/0900-0999/0953.Verifying an Alien Dictionary/Solution.c b/solution/0900-0999/0953.Verifying an Alien Dictionary/Solution.c index 3f44347e15691..ab915c4d0dd14 100644 --- a/solution/0900-0999/0953.Verifying an Alien Dictionary/Solution.c +++ b/solution/0900-0999/0953.Verifying an Alien Dictionary/Solution.c @@ -26,4 +26,4 @@ bool isAlienSorted(char** words, int wordsSize, char* order) { } } return 1; -} +} \ No newline at end of file diff --git a/solution/0900-0999/0953.Verifying an Alien Dictionary/Solution.cpp b/solution/0900-0999/0953.Verifying an Alien Dictionary/Solution.cpp index cdbf1db888f66..512387ec7ae32 100644 --- a/solution/0900-0999/0953.Verifying an Alien Dictionary/Solution.cpp +++ b/solution/0900-0999/0953.Verifying an Alien Dictionary/Solution.cpp @@ -1,4 +1,4 @@ -class Solution { +class Solution { public: bool isAlienSorted(vector& words, string order) { vector m(26); diff --git a/solution/0900-0999/0956.Tallest Billboard/Solution.cpp b/solution/0900-0999/0956.Tallest Billboard/Solution.cpp index 4e9d570297ddd..04a6ede01326d 100644 --- a/solution/0900-0999/0956.Tallest Billboard/Solution.cpp +++ b/solution/0900-0999/0956.Tallest Billboard/Solution.cpp @@ -1,27 +1,21 @@ class Solution { public: int tallestBillboard(vector& rods) { - int n = rods.size(); int s = accumulate(rods.begin(), rods.end(), 0); - int f[n + 1][s + 1]; - memset(f, -0x3f, sizeof(f)); - f[0][0] = 0; - for (int i = 1, t = 0; i <= n; ++i) { - int x = rods[i - 1]; - t += x; - for (int j = 0; j <= t; ++j) { - f[i][j] = f[i - 1][j]; - if (j >= x) { - f[i][j] = max(f[i][j], f[i - 1][j - x]); - } - if (j + x <= t) { - f[i][j] = max(f[i][j], f[i - 1][j + x] + x); - } - if (j < x) { - f[i][j] = max(f[i][j], f[i - 1][x - j] + x - j); - } + int n = rods.size(); + int f[n][s + 1]; + memset(f, -1, sizeof(f)); + function dfs = [&](int i, int j) -> int { + if (i >= n) { + return j == 0 ? 0 : -(1 << 30); + } + if (f[i][j] != -1) { + return f[i][j]; } - } - return f[n][0]; + int ans = max(dfs(i + 1, j), dfs(i + 1, j + rods[i])); + ans = max(ans, dfs(i + 1, abs(j - rods[i])) + min(j, rods[i])); + return f[i][j] = ans; + }; + return dfs(0, 0); } }; \ No newline at end of file diff --git a/solution/0900-0999/0956.Tallest Billboard/Solution.go b/solution/0900-0999/0956.Tallest Billboard/Solution.go index 74b5a6ed974a0..7ee9a150bf236 100644 --- a/solution/0900-0999/0956.Tallest Billboard/Solution.go +++ b/solution/0900-0999/0956.Tallest Billboard/Solution.go @@ -1,32 +1,38 @@ func tallestBillboard(rods []int) int { - n := len(rods) s := 0 for _, x := range rods { s += x } - f := make([][]int, n+1) + n := len(rods) + f := make([][]int, n) for i := range f { f[i] = make([]int, s+1) for j := range f[i] { - f[i][j] = -(1 << 30) + f[i][j] = -1 } } - f[0][0] = 0 - for i, t := 1, 0; i <= n; i++ { - x := rods[i-1] - t += x - for j := 0; j <= t; j++ { - f[i][j] = f[i-1][j] - if j >= x { - f[i][j] = max(f[i][j], f[i-1][j-x]) - } - if j+x <= t { - f[i][j] = max(f[i][j], f[i-1][j+x]+x) - } - if j < x { - f[i][j] = max(f[i][j], f[i-1][x-j]+x-j) + var dfs func(i, j int) int + dfs = func(i, j int) int { + if i >= n { + if j == 0 { + return 0 } + return -(1 << 30) + } + if f[i][j] != -1 { + return f[i][j] } + ans := max(dfs(i+1, j), dfs(i+1, j+rods[i])) + ans = max(ans, dfs(i+1, abs(j-rods[i]))+min(j, rods[i])) + f[i][j] = ans + return ans + } + return dfs(0, 0) +} + +func abs(x int) int { + if x < 0 { + return -x } - return f[n][0] + return x } \ No newline at end of file diff --git a/solution/0900-0999/0956.Tallest Billboard/Solution.java b/solution/0900-0999/0956.Tallest Billboard/Solution.java index 7573c8e9fd314..01b6f2de09b3e 100644 --- a/solution/0900-0999/0956.Tallest Billboard/Solution.java +++ b/solution/0900-0999/0956.Tallest Billboard/Solution.java @@ -1,31 +1,28 @@ class Solution { + private Integer[][] f; + private int[] rods; + private int n; + public int tallestBillboard(int[] rods) { - int n = rods.length; int s = 0; for (int x : rods) { s += x; } - int[][] f = new int[n + 1][s + 1]; - for (var e : f) { - Arrays.fill(e, -(1 << 30)); + n = rods.length; + this.rods = rods; + f = new Integer[n][s + 1]; + return dfs(0, 0); + } + + private int dfs(int i, int j) { + if (i >= n) { + return j == 0 ? 0 : -(1 << 30); } - f[0][0] = 0; - for (int i = 1, t = 0; i <= n; ++i) { - int x = rods[i - 1]; - t += x; - for (int j = 0; j <= t; ++j) { - f[i][j] = f[i - 1][j]; - if (j >= x) { - f[i][j] = Math.max(f[i][j], f[i - 1][j - x]); - } - if (j + x <= t) { - f[i][j] = Math.max(f[i][j], f[i - 1][j + x] + x); - } - if (j < x) { - f[i][j] = Math.max(f[i][j], f[i - 1][x - j] + x - j); - } - } + if (f[i][j] != null) { + return f[i][j]; } - return f[n][0]; + int ans = Math.max(dfs(i + 1, j), dfs(i + 1, j + rods[i])); + ans = Math.max(ans, dfs(i + 1, Math.abs(rods[i] - j)) + Math.min(j, rods[i])); + return f[i][j] = ans; } } \ No newline at end of file diff --git a/solution/0900-0999/0956.Tallest Billboard/Solution.py b/solution/0900-0999/0956.Tallest Billboard/Solution.py index a53385996333a..0e80436536d7b 100644 --- a/solution/0900-0999/0956.Tallest Billboard/Solution.py +++ b/solution/0900-0999/0956.Tallest Billboard/Solution.py @@ -1,18 +1,11 @@ class Solution: def tallestBillboard(self, rods: List[int]) -> int: - n = len(rods) - s = sum(rods) - f = [[-inf] * (s + 1) for _ in range(n + 1)] - f[0][0] = 0 - t = 0 - for i, x in enumerate(rods, 1): - t += x - for j in range(t + 1): - f[i][j] = f[i - 1][j] - if j >= x: - f[i][j] = max(f[i][j], f[i - 1][j - x]) - if j + x <= t: - f[i][j] = max(f[i][j], f[i - 1][j + x] + x) - if j < x: - f[i][j] = max(f[i][j], f[i - 1][x - j] + x - j) - return f[n][0] + @cache + def dfs(i: int, j: int) -> int: + if i >= len(rods): + return 0 if j == 0 else -inf + ans = max(dfs(i + 1, j), dfs(i + 1, j + rods[i])) + ans = max(ans, dfs(i + 1, abs(rods[i] - j)) + min(j, rods[i])) + return ans + + return dfs(0, 0) diff --git a/solution/0900-0999/0956.Tallest Billboard/Solution2.cpp b/solution/0900-0999/0956.Tallest Billboard/Solution2.cpp new file mode 100644 index 0000000000000..4e9d570297ddd --- /dev/null +++ b/solution/0900-0999/0956.Tallest Billboard/Solution2.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int tallestBillboard(vector& rods) { + int n = rods.size(); + int s = accumulate(rods.begin(), rods.end(), 0); + int f[n + 1][s + 1]; + memset(f, -0x3f, sizeof(f)); + f[0][0] = 0; + for (int i = 1, t = 0; i <= n; ++i) { + int x = rods[i - 1]; + t += x; + for (int j = 0; j <= t; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= x) { + f[i][j] = max(f[i][j], f[i - 1][j - x]); + } + if (j + x <= t) { + f[i][j] = max(f[i][j], f[i - 1][j + x] + x); + } + if (j < x) { + f[i][j] = max(f[i][j], f[i - 1][x - j] + x - j); + } + } + } + return f[n][0]; + } +}; \ No newline at end of file diff --git a/solution/0900-0999/0956.Tallest Billboard/Solution2.go b/solution/0900-0999/0956.Tallest Billboard/Solution2.go new file mode 100644 index 0000000000000..74b5a6ed974a0 --- /dev/null +++ b/solution/0900-0999/0956.Tallest Billboard/Solution2.go @@ -0,0 +1,32 @@ +func tallestBillboard(rods []int) int { + n := len(rods) + s := 0 + for _, x := range rods { + s += x + } + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, s+1) + for j := range f[i] { + f[i][j] = -(1 << 30) + } + } + f[0][0] = 0 + for i, t := 1, 0; i <= n; i++ { + x := rods[i-1] + t += x + for j := 0; j <= t; j++ { + f[i][j] = f[i-1][j] + if j >= x { + f[i][j] = max(f[i][j], f[i-1][j-x]) + } + if j+x <= t { + f[i][j] = max(f[i][j], f[i-1][j+x]+x) + } + if j < x { + f[i][j] = max(f[i][j], f[i-1][x-j]+x-j) + } + } + } + return f[n][0] +} \ No newline at end of file diff --git a/solution/0900-0999/0956.Tallest Billboard/Solution2.java b/solution/0900-0999/0956.Tallest Billboard/Solution2.java new file mode 100644 index 0000000000000..7573c8e9fd314 --- /dev/null +++ b/solution/0900-0999/0956.Tallest Billboard/Solution2.java @@ -0,0 +1,31 @@ +class Solution { + public int tallestBillboard(int[] rods) { + int n = rods.length; + int s = 0; + for (int x : rods) { + s += x; + } + int[][] f = new int[n + 1][s + 1]; + for (var e : f) { + Arrays.fill(e, -(1 << 30)); + } + f[0][0] = 0; + for (int i = 1, t = 0; i <= n; ++i) { + int x = rods[i - 1]; + t += x; + for (int j = 0; j <= t; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= x) { + f[i][j] = Math.max(f[i][j], f[i - 1][j - x]); + } + if (j + x <= t) { + f[i][j] = Math.max(f[i][j], f[i - 1][j + x] + x); + } + if (j < x) { + f[i][j] = Math.max(f[i][j], f[i - 1][x - j] + x - j); + } + } + } + return f[n][0]; + } +} \ No newline at end of file diff --git a/solution/0900-0999/0956.Tallest Billboard/Solution2.py b/solution/0900-0999/0956.Tallest Billboard/Solution2.py new file mode 100644 index 0000000000000..a53385996333a --- /dev/null +++ b/solution/0900-0999/0956.Tallest Billboard/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def tallestBillboard(self, rods: List[int]) -> int: + n = len(rods) + s = sum(rods) + f = [[-inf] * (s + 1) for _ in range(n + 1)] + f[0][0] = 0 + t = 0 + for i, x in enumerate(rods, 1): + t += x + for j in range(t + 1): + f[i][j] = f[i - 1][j] + if j >= x: + f[i][j] = max(f[i][j], f[i - 1][j - x]) + if j + x <= t: + f[i][j] = max(f[i][j], f[i - 1][j + x] + x) + if j < x: + f[i][j] = max(f[i][j], f[i - 1][x - j] + x - j) + return f[n][0] diff --git a/solution/0900-0999/0958.Check Completeness of a Binary Tree/Solution.cpp b/solution/0900-0999/0958.Check Completeness of a Binary Tree/Solution.cpp index 68c6b084e0268..f00df8bc85b36 100644 --- a/solution/0900-0999/0958.Check Completeness of a Binary Tree/Solution.cpp +++ b/solution/0900-0999/0958.Check Completeness of a Binary Tree/Solution.cpp @@ -1,25 +1,25 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - bool isCompleteTree(TreeNode* root) { - queue q{{root}}; - while (q.front()) { - root = q.front(); - q.pop(); - q.push(root->left); - q.push(root->right); - } - while (!q.empty() && !q.front()) q.pop(); - return q.empty(); - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isCompleteTree(TreeNode* root) { + queue q{{root}}; + while (q.front()) { + root = q.front(); + q.pop(); + q.push(root->left); + q.push(root->right); + } + while (!q.empty() && !q.front()) q.pop(); + return q.empty(); + } }; \ No newline at end of file diff --git a/solution/0900-0999/0958.Check Completeness of a Binary Tree/Solution.java b/solution/0900-0999/0958.Check Completeness of a Binary Tree/Solution.java index 3b63ad060aa5a..98c36e853d8d6 100644 --- a/solution/0900-0999/0958.Check Completeness of a Binary Tree/Solution.java +++ b/solution/0900-0999/0958.Check Completeness of a Binary Tree/Solution.java @@ -1,30 +1,30 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public boolean isCompleteTree(TreeNode root) { - Deque q = new LinkedList<>(); - q.offer(root); - while (q.peek() != null) { - TreeNode node = q.poll(); - q.offer(node.left); - q.offer(node.right); - } - while (!q.isEmpty() && q.peek() == null) { - q.poll(); - } - return q.isEmpty(); - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean isCompleteTree(TreeNode root) { + Deque q = new LinkedList<>(); + q.offer(root); + while (q.peek() != null) { + TreeNode node = q.poll(); + q.offer(node.left); + q.offer(node.right); + } + while (!q.isEmpty() && q.peek() == null) { + q.poll(); + } + return q.isEmpty(); + } } \ No newline at end of file diff --git a/solution/0900-0999/0958.Check Completeness of a Binary Tree/Solution.py b/solution/0900-0999/0958.Check Completeness of a Binary Tree/Solution.py index 6add43d844e53..e4204bf06b4c9 100644 --- a/solution/0900-0999/0958.Check Completeness of a Binary Tree/Solution.py +++ b/solution/0900-0999/0958.Check Completeness of a Binary Tree/Solution.py @@ -1,16 +1,16 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def isCompleteTree(self, root: TreeNode) -> bool: - q = deque([root]) - while q: - node = q.popleft() - if node is None: - break - q.append(node.left) - q.append(node.right) - return all(node is None for node in q) +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isCompleteTree(self, root: TreeNode) -> bool: + q = deque([root]) + while q: + node = q.popleft() + if node is None: + break + q.append(node.left) + q.append(node.right) + return all(node is None for node in q) diff --git a/solution/0900-0999/0960.Delete Columns to Make Sorted III/Solution.cpp b/solution/0900-0999/0960.Delete Columns to Make Sorted III/Solution.cpp index 26082b92f978e..ec0ec1f91a386 100644 --- a/solution/0900-0999/0960.Delete Columns to Make Sorted III/Solution.cpp +++ b/solution/0900-0999/0960.Delete Columns to Make Sorted III/Solution.cpp @@ -1,24 +1,24 @@ -class Solution { -public: - int minDeletionSize(vector& strs) { - int n = strs[0].size(); - vector dp(n, 1); - int mx = 1; - for (int i = 1; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (check(i, j, strs)) { - dp[i] = max(dp[i], dp[j] + 1); - } - } - mx = max(mx, dp[i]); - } - return n - mx; - } - - bool check(int i, int j, vector& strs) { - for (string& s : strs) - if (s[i] < s[j]) - return false; - return true; - } +class Solution { +public: + int minDeletionSize(vector& strs) { + int n = strs[0].size(); + vector dp(n, 1); + int mx = 1; + for (int i = 1; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (check(i, j, strs)) { + dp[i] = max(dp[i], dp[j] + 1); + } + } + mx = max(mx, dp[i]); + } + return n - mx; + } + + bool check(int i, int j, vector& strs) { + for (string& s : strs) + if (s[i] < s[j]) + return false; + return true; + } }; \ No newline at end of file diff --git a/solution/0900-0999/0960.Delete Columns to Make Sorted III/Solution.java b/solution/0900-0999/0960.Delete Columns to Make Sorted III/Solution.java index 169b08de0c85f..2de0dfcc649eb 100644 --- a/solution/0900-0999/0960.Delete Columns to Make Sorted III/Solution.java +++ b/solution/0900-0999/0960.Delete Columns to Make Sorted III/Solution.java @@ -1,26 +1,26 @@ -class Solution { - public int minDeletionSize(String[] strs) { - int n = strs[0].length(); - int[] dp = new int[n]; - Arrays.fill(dp, 1); - int mx = 1; - for (int i = 1; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (check(i, j, strs)) { - dp[i] = Math.max(dp[i], dp[j] + 1); - } - } - mx = Math.max(mx, dp[i]); - } - return n - mx; - } - - private boolean check(int i, int j, String[] strs) { - for (String s : strs) { - if (s.charAt(i) < s.charAt(j)) { - return false; - } - } - return true; - } +class Solution { + public int minDeletionSize(String[] strs) { + int n = strs[0].length(); + int[] dp = new int[n]; + Arrays.fill(dp, 1); + int mx = 1; + for (int i = 1; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (check(i, j, strs)) { + dp[i] = Math.max(dp[i], dp[j] + 1); + } + } + mx = Math.max(mx, dp[i]); + } + return n - mx; + } + + private boolean check(int i, int j, String[] strs) { + for (String s : strs) { + if (s.charAt(i) < s.charAt(j)) { + return false; + } + } + return true; + } } \ No newline at end of file diff --git a/solution/0900-0999/0960.Delete Columns to Make Sorted III/Solution.py b/solution/0900-0999/0960.Delete Columns to Make Sorted III/Solution.py index 7c413b5c76916..c9bc149baa62e 100644 --- a/solution/0900-0999/0960.Delete Columns to Make Sorted III/Solution.py +++ b/solution/0900-0999/0960.Delete Columns to Make Sorted III/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def minDeletionSize(self, strs: List[str]) -> int: - n = len(strs[0]) - dp = [1] * n - for i in range(1, n): - for j in range(i): - if all(s[j] <= s[i] for s in strs): - dp[i] = max(dp[i], dp[j] + 1) - return n - max(dp) +class Solution: + def minDeletionSize(self, strs: List[str]) -> int: + n = len(strs[0]) + dp = [1] * n + for i in range(1, n): + for j in range(i): + if all(s[j] <= s[i] for s in strs): + dp[i] = max(dp[i], dp[j] + 1) + return n - max(dp) diff --git a/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/Solution.cpp b/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/Solution.cpp index 4562412205ade..6d49dbcfbf326 100644 --- a/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/Solution.cpp +++ b/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/Solution.cpp @@ -1,12 +1,12 @@ -class Solution { -public: - int repeatedNTimes(vector& nums) { - unordered_set s; - for (int i = 0;; ++i) { - if (s.count(nums[i])) { - return nums[i]; - } - s.insert(nums[i]); - } - } +class Solution { +public: + int repeatedNTimes(vector& nums) { + unordered_set s; + for (int i = 0;; ++i) { + if (s.count(nums[i])) { + return nums[i]; + } + s.insert(nums[i]); + } + } }; \ No newline at end of file diff --git a/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/Solution.java b/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/Solution.java index 52d2da5f22a7d..72119e0f092b1 100644 --- a/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/Solution.java +++ b/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/Solution.java @@ -1,10 +1,10 @@ -class Solution { - public int repeatedNTimes(int[] nums) { - Set s = new HashSet<>(nums.length / 2 + 1); - for (int i = 0;; ++i) { - if (!s.add(nums[i])) { - return nums[i]; - } - } - } +class Solution { + public int repeatedNTimes(int[] nums) { + Set s = new HashSet<>(nums.length / 2 + 1); + for (int i = 0;; ++i) { + if (!s.add(nums[i])) { + return nums[i]; + } + } + } } \ No newline at end of file diff --git a/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/Solution.py b/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/Solution.py index 52cbf1b484c0d..67a6514e417d9 100644 --- a/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/Solution.py +++ b/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def repeatedNTimes(self, nums: List[int]) -> int: - s = set() - for x in nums: - if x in s: - return x - s.add(x) +class Solution: + def repeatedNTimes(self, nums: List[int]) -> int: + s = set() + for x in nums: + if x in s: + return x + s.add(x) diff --git a/solution/0900-0999/0963.Minimum Area Rectangle II/Solution.cpp b/solution/0900-0999/0963.Minimum Area Rectangle II/Solution.cpp index 013b00983807c..5ac10571c1ffd 100644 --- a/solution/0900-0999/0963.Minimum Area Rectangle II/Solution.cpp +++ b/solution/0900-0999/0963.Minimum Area Rectangle II/Solution.cpp @@ -1,36 +1,36 @@ -class Solution { -public: - double minAreaFreeRect(vector>& points) { - auto f = [](int x, int y) { - return x * 40001 + y; - }; - int n = points.size(); - unordered_set s; - for (auto& p : points) { - s.insert(f(p[0], p[1])); - } - double ans = 1e20; - for (int i = 0; i < n; ++i) { - int x1 = points[i][0], y1 = points[i][1]; - for (int j = 0; j < n; ++j) { - if (j != i) { - int x2 = points[j][0], y2 = points[j][1]; - for (int k = j + 1; k < n; ++k) { - if (k != i) { - int x3 = points[k][0], y3 = points[k][1]; - int x4 = x2 - x1 + x3, y4 = y2 - y1 + y3; - if (x4 >= 0 && x4 < 40000 && y4 >= 0 && y4 <= 40000 && s.count(f(x4, y4))) { - if ((x2 - x1) * (x3 - x1) + (y2 - y1) * (y3 - y1) == 0) { - int ww = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); - int hh = (x3 - x1) * (x3 - x1) + (y3 - y1) * (y3 - y1); - ans = min(ans, sqrt(1LL * ww * hh)); - } - } - } - } - } - } - } - return ans == 1e20 ? 0 : ans; - } +class Solution { +public: + double minAreaFreeRect(vector>& points) { + auto f = [](int x, int y) { + return x * 40001 + y; + }; + int n = points.size(); + unordered_set s; + for (auto& p : points) { + s.insert(f(p[0], p[1])); + } + double ans = 1e20; + for (int i = 0; i < n; ++i) { + int x1 = points[i][0], y1 = points[i][1]; + for (int j = 0; j < n; ++j) { + if (j != i) { + int x2 = points[j][0], y2 = points[j][1]; + for (int k = j + 1; k < n; ++k) { + if (k != i) { + int x3 = points[k][0], y3 = points[k][1]; + int x4 = x2 - x1 + x3, y4 = y2 - y1 + y3; + if (x4 >= 0 && x4 < 40000 && y4 >= 0 && y4 <= 40000 && s.count(f(x4, y4))) { + if ((x2 - x1) * (x3 - x1) + (y2 - y1) * (y3 - y1) == 0) { + int ww = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); + int hh = (x3 - x1) * (x3 - x1) + (y3 - y1) * (y3 - y1); + ans = min(ans, sqrt(1LL * ww * hh)); + } + } + } + } + } + } + } + return ans == 1e20 ? 0 : ans; + } }; \ No newline at end of file diff --git a/solution/0900-0999/0963.Minimum Area Rectangle II/Solution.java b/solution/0900-0999/0963.Minimum Area Rectangle II/Solution.java index 60baafd29e1b6..ab7ae0e0fcf27 100644 --- a/solution/0900-0999/0963.Minimum Area Rectangle II/Solution.java +++ b/solution/0900-0999/0963.Minimum Area Rectangle II/Solution.java @@ -1,36 +1,36 @@ -class Solution { - public double minAreaFreeRect(int[][] points) { - int n = points.length; - Set s = new HashSet<>(n); - for (int[] p : points) { - s.add(f(p[0], p[1])); - } - double ans = Double.MAX_VALUE; - for (int i = 0; i < n; ++i) { - int x1 = points[i][0], y1 = points[i][1]; - for (int j = 0; j < n; ++j) { - if (j != i) { - int x2 = points[j][0], y2 = points[j][1]; - for (int k = j + 1; k < n; ++k) { - if (k != i) { - int x3 = points[k][0], y3 = points[k][1]; - int x4 = x2 - x1 + x3, y4 = y2 - y1 + y3; - if (s.contains(f(x4, y4))) { - if ((x2 - x1) * (x3 - x1) + (y2 - y1) * (y3 - y1) == 0) { - int ww = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); - int hh = (x3 - x1) * (x3 - x1) + (y3 - y1) * (y3 - y1); - ans = Math.min(ans, Math.sqrt(1L * ww * hh)); - } - } - } - } - } - } - } - return ans == Double.MAX_VALUE ? 0 : ans; - } - - private int f(int x, int y) { - return x * 40001 + y; - } +class Solution { + public double minAreaFreeRect(int[][] points) { + int n = points.length; + Set s = new HashSet<>(n); + for (int[] p : points) { + s.add(f(p[0], p[1])); + } + double ans = Double.MAX_VALUE; + for (int i = 0; i < n; ++i) { + int x1 = points[i][0], y1 = points[i][1]; + for (int j = 0; j < n; ++j) { + if (j != i) { + int x2 = points[j][0], y2 = points[j][1]; + for (int k = j + 1; k < n; ++k) { + if (k != i) { + int x3 = points[k][0], y3 = points[k][1]; + int x4 = x2 - x1 + x3, y4 = y2 - y1 + y3; + if (s.contains(f(x4, y4))) { + if ((x2 - x1) * (x3 - x1) + (y2 - y1) * (y3 - y1) == 0) { + int ww = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); + int hh = (x3 - x1) * (x3 - x1) + (y3 - y1) * (y3 - y1); + ans = Math.min(ans, Math.sqrt(1L * ww * hh)); + } + } + } + } + } + } + } + return ans == Double.MAX_VALUE ? 0 : ans; + } + + private int f(int x, int y) { + return x * 40001 + y; + } } \ No newline at end of file diff --git a/solution/0900-0999/0963.Minimum Area Rectangle II/Solution.py b/solution/0900-0999/0963.Minimum Area Rectangle II/Solution.py index 37ec8cbea9add..736f6bcd4ce55 100644 --- a/solution/0900-0999/0963.Minimum Area Rectangle II/Solution.py +++ b/solution/0900-0999/0963.Minimum Area Rectangle II/Solution.py @@ -1,23 +1,23 @@ -class Solution: - def minAreaFreeRect(self, points: List[List[int]]) -> float: - s = {(x, y) for x, y in points} - n = len(points) - ans = inf - for i in range(n): - x1, y1 = points[i] - for j in range(n): - if j != i: - x2, y2 = points[j] - for k in range(j + 1, n): - if k != i: - x3, y3 = points[k] - x4 = x2 - x1 + x3 - y4 = y2 - y1 + y3 - if (x4, y4) in s: - v21 = (x2 - x1, y2 - y1) - v31 = (x3 - x1, y3 - y1) - if v21[0] * v31[0] + v21[1] * v31[1] == 0: - w = sqrt(v21[0] ** 2 + v21[1] ** 2) - h = sqrt(v31[0] ** 2 + v31[1] ** 2) - ans = min(ans, w * h) - return 0 if ans == inf else ans +class Solution: + def minAreaFreeRect(self, points: List[List[int]]) -> float: + s = {(x, y) for x, y in points} + n = len(points) + ans = inf + for i in range(n): + x1, y1 = points[i] + for j in range(n): + if j != i: + x2, y2 = points[j] + for k in range(j + 1, n): + if k != i: + x3, y3 = points[k] + x4 = x2 - x1 + x3 + y4 = y2 - y1 + y3 + if (x4, y4) in s: + v21 = (x2 - x1, y2 - y1) + v31 = (x3 - x1, y3 - y1) + if v21[0] * v31[0] + v21[1] * v31[1] == 0: + w = sqrt(v21[0] ** 2 + v21[1] ** 2) + h = sqrt(v31[0] ** 2 + v31[1] ** 2) + ans = min(ans, w * h) + return 0 if ans == inf else ans diff --git a/solution/0900-0999/0964.Least Operators to Express Number/Solution.cpp b/solution/0900-0999/0964.Least Operators to Express Number/Solution.cpp index 7659d5f29ae8b..222a74f6632e5 100644 --- a/solution/0900-0999/0964.Least Operators to Express Number/Solution.cpp +++ b/solution/0900-0999/0964.Least Operators to Express Number/Solution.cpp @@ -1,27 +1,27 @@ -class Solution { -public: - int leastOpsExpressTarget(int x, int target) { - unordered_map f; - function dfs = [&](int v) -> int { - if (x >= v) { - return min(v * 2 - 1, 2 * (x - v)); - } - if (f.count(v)) { - return f[v]; - } - int k = 2; - long long y = x * x; - while (y < v) { - y *= x; - ++k; - } - int ans = k - 1 + dfs(v - y / x); - if (y - v < v) { - ans = min(ans, k + dfs(y - v)); - } - f[v] = ans; - return ans; - }; - return dfs(target); - } +class Solution { +public: + int leastOpsExpressTarget(int x, int target) { + unordered_map f; + function dfs = [&](int v) -> int { + if (x >= v) { + return min(v * 2 - 1, 2 * (x - v)); + } + if (f.count(v)) { + return f[v]; + } + int k = 2; + long long y = x * x; + while (y < v) { + y *= x; + ++k; + } + int ans = k - 1 + dfs(v - y / x); + if (y - v < v) { + ans = min(ans, k + dfs(y - v)); + } + f[v] = ans; + return ans; + }; + return dfs(target); + } }; \ No newline at end of file diff --git a/solution/0900-0999/0964.Least Operators to Express Number/Solution.java b/solution/0900-0999/0964.Least Operators to Express Number/Solution.java index a427eef6933b2..e3017f784280f 100644 --- a/solution/0900-0999/0964.Least Operators to Express Number/Solution.java +++ b/solution/0900-0999/0964.Least Operators to Express Number/Solution.java @@ -1,30 +1,30 @@ -class Solution { - private int x; - private Map f = new HashMap<>(); - - public int leastOpsExpressTarget(int x, int target) { - this.x = x; - return dfs(target); - } - - private int dfs(int v) { - if (x >= v) { - return Math.min(v * 2 - 1, 2 * (x - v)); - } - if (f.containsKey(v)) { - return f.get(v); - } - int k = 2; - long y = (long) x * x; - while (y < v) { - y *= x; - ++k; - } - int ans = k - 1 + dfs(v - (int) (y / x)); - if (y - v < v) { - ans = Math.min(ans, k + dfs((int) y - v)); - } - f.put(v, ans); - return ans; - } +class Solution { + private int x; + private Map f = new HashMap<>(); + + public int leastOpsExpressTarget(int x, int target) { + this.x = x; + return dfs(target); + } + + private int dfs(int v) { + if (x >= v) { + return Math.min(v * 2 - 1, 2 * (x - v)); + } + if (f.containsKey(v)) { + return f.get(v); + } + int k = 2; + long y = (long) x * x; + while (y < v) { + y *= x; + ++k; + } + int ans = k - 1 + dfs(v - (int) (y / x)); + if (y - v < v) { + ans = Math.min(ans, k + dfs((int) y - v)); + } + f.put(v, ans); + return ans; + } } \ No newline at end of file diff --git a/solution/0900-0999/0964.Least Operators to Express Number/Solution.py b/solution/0900-0999/0964.Least Operators to Express Number/Solution.py index 9fde3d4861333..cb8b72597917a 100644 --- a/solution/0900-0999/0964.Least Operators to Express Number/Solution.py +++ b/solution/0900-0999/0964.Least Operators to Express Number/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def leastOpsExpressTarget(self, x: int, target: int) -> int: - @cache - def dfs(v: int) -> int: - if x >= v: - return min(v * 2 - 1, 2 * (x - v)) - k = 2 - while x**k < v: - k += 1 - if x**k - v < v: - return min(k + dfs(x**k - v), k - 1 + dfs(v - x ** (k - 1))) - return k - 1 + dfs(v - x ** (k - 1)) - - return dfs(target) +class Solution: + def leastOpsExpressTarget(self, x: int, target: int) -> int: + @cache + def dfs(v: int) -> int: + if x >= v: + return min(v * 2 - 1, 2 * (x - v)) + k = 2 + while x**k < v: + k += 1 + if x**k - v < v: + return min(k + dfs(x**k - v), k - 1 + dfs(v - x ** (k - 1))) + return k - 1 + dfs(v - x ** (k - 1)) + + return dfs(target) diff --git a/solution/0900-0999/0965.Univalued Binary Tree/Solution.cpp b/solution/0900-0999/0965.Univalued Binary Tree/Solution.cpp index 29fe3d1fc533e..472b182e6a984 100644 --- a/solution/0900-0999/0965.Univalued Binary Tree/Solution.cpp +++ b/solution/0900-0999/0965.Univalued Binary Tree/Solution.cpp @@ -1,4 +1,4 @@ -/** +/** * Definition for a binary tree node. * struct TreeNode { * int val; diff --git a/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/Solution.cpp b/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/Solution.cpp index 57e97189326c3..4af1e0189df2d 100644 --- a/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/Solution.cpp +++ b/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/Solution.cpp @@ -1,39 +1,39 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - vector flipMatchVoyage(TreeNode* root, vector& voyage) { - bool ok = true; - int i = 0; - vector ans; - function dfs = [&](TreeNode* root) { - if (!root || !ok) { - return; - } - if (root->val != voyage[i]) { - ok = false; - return; - } - ++i; - if (!root->left || root->left->val == voyage[i]) { - dfs(root->left); - dfs(root->right); - } else { - ans.push_back(root->val); - dfs(root->right); - dfs(root->left); - } - }; - dfs(root); - return ok ? ans : vector{-1}; - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector flipMatchVoyage(TreeNode* root, vector& voyage) { + bool ok = true; + int i = 0; + vector ans; + function dfs = [&](TreeNode* root) { + if (!root || !ok) { + return; + } + if (root->val != voyage[i]) { + ok = false; + return; + } + ++i; + if (!root->left || root->left->val == voyage[i]) { + dfs(root->left); + dfs(root->right); + } else { + ans.push_back(root->val); + dfs(root->right); + dfs(root->left); + } + }; + dfs(root); + return ok ? ans : vector{-1}; + } }; \ No newline at end of file diff --git a/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/Solution.java b/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/Solution.java index 198571905e65f..18933d416b3e0 100644 --- a/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/Solution.java +++ b/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/Solution.java @@ -1,47 +1,47 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private int i; - private boolean ok; - private int[] voyage; - private List ans = new ArrayList<>(); - - public List flipMatchVoyage(TreeNode root, int[] voyage) { - this.voyage = voyage; - ok = true; - dfs(root); - return ok ? ans : List.of(-1); - } - - private void dfs(TreeNode root) { - if (root == null || !ok) { - return; - } - if (root.val != voyage[i]) { - ok = false; - return; - } - ++i; - if (root.left == null || root.left.val == voyage[i]) { - dfs(root.left); - dfs(root.right); - } else { - ans.add(root.val); - dfs(root.right); - dfs(root.left); - } - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int i; + private boolean ok; + private int[] voyage; + private List ans = new ArrayList<>(); + + public List flipMatchVoyage(TreeNode root, int[] voyage) { + this.voyage = voyage; + ok = true; + dfs(root); + return ok ? ans : List.of(-1); + } + + private void dfs(TreeNode root) { + if (root == null || !ok) { + return; + } + if (root.val != voyage[i]) { + ok = false; + return; + } + ++i; + if (root.left == null || root.left.val == voyage[i]) { + dfs(root.left); + dfs(root.right); + } else { + ans.add(root.val); + dfs(root.right); + dfs(root.left); + } + } } \ No newline at end of file diff --git a/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/Solution.py b/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/Solution.py index 299fe74984dc3..644b045481f2b 100644 --- a/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/Solution.py +++ b/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/Solution.py @@ -1,29 +1,29 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def flipMatchVoyage(self, root: Optional[TreeNode], voyage: List[int]) -> List[int]: - def dfs(root): - nonlocal i, ok - if root is None or not ok: - return - if root.val != voyage[i]: - ok = False - return - i += 1 - if root.left is None or root.left.val == voyage[i]: - dfs(root.left) - dfs(root.right) - else: - ans.append(root.val) - dfs(root.right) - dfs(root.left) - - ans = [] - i = 0 - ok = True - dfs(root) - return ans if ok else [-1] +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def flipMatchVoyage(self, root: Optional[TreeNode], voyage: List[int]) -> List[int]: + def dfs(root): + nonlocal i, ok + if root is None or not ok: + return + if root.val != voyage[i]: + ok = False + return + i += 1 + if root.left is None or root.left.val == voyage[i]: + dfs(root.left) + dfs(root.right) + else: + ans.append(root.val) + dfs(root.right) + dfs(root.left) + + ans = [] + i = 0 + ok = True + dfs(root) + return ans if ok else [-1] diff --git a/solution/0900-0999/0976.Largest Perimeter Triangle/Solution.c b/solution/0900-0999/0976.Largest Perimeter Triangle/Solution.c index fde2cc793eed7..61c7bfaa56e51 100644 --- a/solution/0900-0999/0976.Largest Perimeter Triangle/Solution.c +++ b/solution/0900-0999/0976.Largest Perimeter Triangle/Solution.c @@ -10,4 +10,4 @@ int largestPerimeter(int* nums, int numsSize) { } } return 0; -} +} \ No newline at end of file diff --git a/solution/0900-0999/0977.Squares of a Sorted Array/Solution.php b/solution/0900-0999/0977.Squares of a Sorted Array/Solution.php index 7bda360d327a5..61e4f515d3df7 100644 --- a/solution/0900-0999/0977.Squares of a Sorted Array/Solution.php +++ b/solution/0900-0999/0977.Squares of a Sorted Array/Solution.php @@ -21,4 +21,4 @@ function sortedSquares($nums) { } return $rs; } -} \ No newline at end of file +} diff --git a/solution/0900-0999/0980.Unique Paths III/Solution.py b/solution/0900-0999/0980.Unique Paths III/Solution.py index feb68ba8fc21b..994ecba3329e5 100644 --- a/solution/0900-0999/0980.Unique Paths III/Solution.py +++ b/solution/0900-0999/0980.Unique Paths III/Solution.py @@ -1,20 +1,20 @@ -class Solution: - def uniquePathsIII(self, grid: List[List[int]]) -> int: - def dfs(i: int, j: int, k: int) -> int: - if grid[i][j] == 2: - return int(k == cnt + 1) - ans = 0 - for a, b in pairwise(dirs): - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n and (x, y) not in vis and grid[x][y] != -1: - vis.add((x, y)) - ans += dfs(x, y, k + 1) - vis.remove((x, y)) - return ans - - m, n = len(grid), len(grid[0]) - start = next((i, j) for i in range(m) for j in range(n) if grid[i][j] == 1) - dirs = (-1, 0, 1, 0, -1) - cnt = sum(row.count(0) for row in grid) - vis = {start} - return dfs(*start, 0) +class Solution: + def uniquePathsIII(self, grid: List[List[int]]) -> int: + def dfs(i: int, j: int, k: int) -> int: + if grid[i][j] == 2: + return int(k == cnt + 1) + ans = 0 + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n and (x, y) not in vis and grid[x][y] != -1: + vis.add((x, y)) + ans += dfs(x, y, k + 1) + vis.remove((x, y)) + return ans + + m, n = len(grid), len(grid[0]) + start = next((i, j) for i in range(m) for j in range(n) if grid[i][j] == 1) + dirs = (-1, 0, 1, 0, -1) + cnt = sum(row.count(0) for row in grid) + vis = {start} + return dfs(*start, 0) diff --git a/solution/0900-0999/0981.Time Based Key-Value Store/Solution.py b/solution/0900-0999/0981.Time Based Key-Value Store/Solution.py index c2fc692df7233..e089b0752df08 100644 --- a/solution/0900-0999/0981.Time Based Key-Value Store/Solution.py +++ b/solution/0900-0999/0981.Time Based Key-Value Store/Solution.py @@ -1,19 +1,19 @@ -class TimeMap: - def __init__(self): - self.ktv = defaultdict(list) - - def set(self, key: str, value: str, timestamp: int) -> None: - self.ktv[key].append((timestamp, value)) - - def get(self, key: str, timestamp: int) -> str: - if key not in self.ktv: - return '' - tv = self.ktv[key] - i = bisect_right(tv, (timestamp, chr(127))) - return tv[i - 1][1] if i else '' - - -# Your TimeMap object will be instantiated and called as such: -# obj = TimeMap() -# obj.set(key,value,timestamp) -# param_2 = obj.get(key,timestamp) +class TimeMap: + def __init__(self): + self.ktv = defaultdict(list) + + def set(self, key: str, value: str, timestamp: int) -> None: + self.ktv[key].append((timestamp, value)) + + def get(self, key: str, timestamp: int) -> str: + if key not in self.ktv: + return '' + tv = self.ktv[key] + i = bisect_right(tv, (timestamp, chr(127))) + return tv[i - 1][1] if i else '' + + +# Your TimeMap object will be instantiated and called as such: +# obj = TimeMap() +# obj.set(key,value,timestamp) +# param_2 = obj.get(key,timestamp) diff --git a/solution/0900-0999/0987.Vertical Order Traversal of a Binary Tree/Solution.java b/solution/0900-0999/0987.Vertical Order Traversal of a Binary Tree/Solution.java index 2f28071e9c3a5..1fb8a87edb789 100644 --- a/solution/0900-0999/0987.Vertical Order Traversal of a Binary Tree/Solution.java +++ b/solution/0900-0999/0987.Vertical Order Traversal of a Binary Tree/Solution.java @@ -30,4 +30,4 @@ private void dfs(TreeNode root, int x, int y, List list) { dfs(root.left, x - 1, y - 1, list); dfs(root.right, x + 1, y - 1, list); } -} +} \ No newline at end of file diff --git a/solution/0900-0999/0987.Vertical Order Traversal of a Binary Tree/Solution.ts b/solution/0900-0999/0987.Vertical Order Traversal of a Binary Tree/Solution.ts index f968b85f4d4de..5228090ba5ede 100644 --- a/solution/0900-0999/0987.Vertical Order Traversal of a Binary Tree/Solution.ts +++ b/solution/0900-0999/0987.Vertical Order Traversal of a Binary Tree/Solution.ts @@ -15,6 +15,7 @@ function verticalTraversal(root: TreeNode | null): number[][] { let solution = []; dfs(root, 0, 0, solution); + // 优先依据i=2排序, 然后依据i=1排序 solution.sort(compare); let ans = []; let pre = Number.MIN_SAFE_INTEGER; diff --git a/solution/0900-0999/0989.Add to Array-Form of Integer/Solution2.ts b/solution/0900-0999/0989.Add to Array-Form of Integer/Solution2.ts new file mode 100644 index 0000000000000..b30c3171765fc --- /dev/null +++ b/solution/0900-0999/0989.Add to Array-Form of Integer/Solution2.ts @@ -0,0 +1,13 @@ +function addToArrayForm(num: number[], k: number): number[] { + const n = num.length; + const res = []; + let sum = 0; + for (let i = 0; i < n || sum !== 0 || k !== 0; i++) { + sum += num[n - i - 1] ?? 0; + sum += k % 10; + res.push(sum % 10); + k = Math.floor(k / 10); + sum = Math.floor(sum / 10); + } + return res.reverse(); +} diff --git a/solution/0900-0999/0993.Cousins in Binary Tree/Solution.cpp b/solution/0900-0999/0993.Cousins in Binary Tree/Solution.cpp index 7fe390f57cb15..ec80a4f74591e 100644 --- a/solution/0900-0999/0993.Cousins in Binary Tree/Solution.cpp +++ b/solution/0900-0999/0993.Cousins in Binary Tree/Solution.cpp @@ -12,24 +12,33 @@ class Solution { public: bool isCousins(TreeNode* root, int x, int y) { - TreeNode *p1, *p2; - int d1, d2; - function dfs = [&](TreeNode* root, TreeNode* fa, int d) { - if (!root) { - return; + TreeNode* p1 = nullptr; + TreeNode* p2 = nullptr; + int d1 = 0, d2 = 0; + queue> q; + q.emplace(root, nullptr); + int d = 0; + while (!q.empty()) { + for (int n = q.size(); n; --n) { + auto [node, fa] = q.front(); + q.pop(); + if (node->val == x) { + p1 = fa; + d1 = d; + } + if (node->val == y) { + p2 = fa; + d2 = d; + } + if (node->left) { + q.emplace(node->left, node); + } + if (node->right) { + q.emplace(node->right, node); + } } - if (root->val == x) { - p1 = fa; - d1 = d; - } - if (root->val == y) { - p2 = fa; - d2 = d; - } - dfs(root->left, root, d + 1); - dfs(root->right, root, d + 1); - }; - dfs(root, nullptr, 0); + ++d; + } return p1 != p2 && d1 == d2; } }; \ No newline at end of file diff --git a/solution/0900-0999/0993.Cousins in Binary Tree/Solution.go b/solution/0900-0999/0993.Cousins in Binary Tree/Solution.go index 12f092ff1f0e5..2de89e76477ec 100644 --- a/solution/0900-0999/0993.Cousins in Binary Tree/Solution.go +++ b/solution/0900-0999/0993.Cousins in Binary Tree/Solution.go @@ -7,22 +7,29 @@ * } */ func isCousins(root *TreeNode, x int, y int) bool { + type pair struct{ node, fa *TreeNode } + q := []pair{pair{root, nil}} var p1, p2 *TreeNode - var d1, d2 int - var dfs func(*TreeNode, *TreeNode, int) - dfs = func(root *TreeNode, fa *TreeNode, d int) { - if root == nil { - return + var d, d1, d2 int + for len(q) > 0 { + for n := len(q); n > 0; n-- { + p := q[0] + q = q[1:] + node, fa := p.node, p.fa + if node.Val == x { + p1, d1 = fa, d + } + if node.Val == y { + p2, d2 = fa, d + } + if node.Left != nil { + q = append(q, pair{node.Left, node}) + } + if node.Right != nil { + q = append(q, pair{node.Right, node}) + } } - if root.Val == x { - p1, d1 = fa, d - } - if root.Val == y { - p2, d2 = fa, d - } - dfs(root.Left, root, d+1) - dfs(root.Right, root, d+1) + d++ } - dfs(root, nil, 0) return p1 != p2 && d1 == d2 } \ No newline at end of file diff --git a/solution/0900-0999/0993.Cousins in Binary Tree/Solution.java b/solution/0900-0999/0993.Cousins in Binary Tree/Solution.java index ff70cfd8bd2f3..527b0c1ff194d 100644 --- a/solution/0900-0999/0993.Cousins in Binary Tree/Solution.java +++ b/solution/0900-0999/0993.Cousins in Binary Tree/Solution.java @@ -14,30 +14,33 @@ * } */ class Solution { - private int x, y; - private TreeNode p1, p2; - private int d1, d2; - public boolean isCousins(TreeNode root, int x, int y) { - this.x = x; - this.y = y; - dfs(root, null, 0); - return p1 != p2 && d1 == d2; - } - - private void dfs(TreeNode root, TreeNode p, int d) { - if (root == null) { - return; - } - if (root.val == x) { - p1 = p; - d1 = d; + TreeNode p1 = null, p2 = null; + int d1 = 0, d2 = 0; + Deque q = new ArrayDeque<>(); + q.offer(new TreeNode[] {root, null}); + int d = 0; + while (!q.isEmpty()) { + for (int n = q.size(); n > 0; --n) { + var p = q.poll(); + TreeNode node = p[0], fa = p[1]; + if (node.val == x) { + p1 = fa; + d1 = d; + } + if (node.val == y) { + p2 = fa; + d2 = d; + } + if (node.left != null) { + q.offer(new TreeNode[] {node.left, node}); + } + if (node.right != null) { + q.offer(new TreeNode[] {node.right, node}); + } + } + ++d; } - if (root.val == y) { - p2 = p; - d2 = d; - } - dfs(root.left, root, d + 1); - dfs(root.right, root, d + 1); + return p1 != p2 && d1 == d2; } } \ No newline at end of file diff --git a/solution/0900-0999/0993.Cousins in Binary Tree/Solution.py b/solution/0900-0999/0993.Cousins in Binary Tree/Solution.py index ffd5ca0f0b3a4..ec3455c189510 100644 --- a/solution/0900-0999/0993.Cousins in Binary Tree/Solution.py +++ b/solution/0900-0999/0993.Cousins in Binary Tree/Solution.py @@ -6,16 +6,20 @@ # self.right = right class Solution: def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool: - def dfs(root, fa, d): - if root is None: - return - if root.val == x: - t[0] = (fa, d) - if root.val == y: - t[1] = (fa, d) - dfs(root.left, root, d + 1) - dfs(root.right, root, d + 1) - - t = [None, None] - dfs(root, None, 0) - return t[0][0] != t[1][0] and t[0][1] == t[1][1] + q = deque([(root, None)]) + d = 0 + p1 = p2 = None + d1 = d2 = 0 + while q: + for _ in range(len(q)): + node, fa = q.popleft() + if node.val == x: + p1, d1 = fa, d + if node.val == y: + p2, d2 = fa, d + if node.left: + q.append((node.left, node)) + if node.right: + q.append((node.right, node)) + d += 1 + return p1 != p2 and d1 == d2 diff --git a/solution/0900-0999/0993.Cousins in Binary Tree/Solution2.cpp b/solution/0900-0999/0993.Cousins in Binary Tree/Solution2.cpp new file mode 100644 index 0000000000000..7fe390f57cb15 --- /dev/null +++ b/solution/0900-0999/0993.Cousins in Binary Tree/Solution2.cpp @@ -0,0 +1,35 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isCousins(TreeNode* root, int x, int y) { + TreeNode *p1, *p2; + int d1, d2; + function dfs = [&](TreeNode* root, TreeNode* fa, int d) { + if (!root) { + return; + } + if (root->val == x) { + p1 = fa; + d1 = d; + } + if (root->val == y) { + p2 = fa; + d2 = d; + } + dfs(root->left, root, d + 1); + dfs(root->right, root, d + 1); + }; + dfs(root, nullptr, 0); + return p1 != p2 && d1 == d2; + } +}; \ No newline at end of file diff --git a/solution/0900-0999/0993.Cousins in Binary Tree/Solution2.go b/solution/0900-0999/0993.Cousins in Binary Tree/Solution2.go new file mode 100644 index 0000000000000..12f092ff1f0e5 --- /dev/null +++ b/solution/0900-0999/0993.Cousins in Binary Tree/Solution2.go @@ -0,0 +1,28 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func isCousins(root *TreeNode, x int, y int) bool { + var p1, p2 *TreeNode + var d1, d2 int + var dfs func(*TreeNode, *TreeNode, int) + dfs = func(root *TreeNode, fa *TreeNode, d int) { + if root == nil { + return + } + if root.Val == x { + p1, d1 = fa, d + } + if root.Val == y { + p2, d2 = fa, d + } + dfs(root.Left, root, d+1) + dfs(root.Right, root, d+1) + } + dfs(root, nil, 0) + return p1 != p2 && d1 == d2 +} \ No newline at end of file diff --git a/solution/0900-0999/0993.Cousins in Binary Tree/Solution2.java b/solution/0900-0999/0993.Cousins in Binary Tree/Solution2.java new file mode 100644 index 0000000000000..ff70cfd8bd2f3 --- /dev/null +++ b/solution/0900-0999/0993.Cousins in Binary Tree/Solution2.java @@ -0,0 +1,43 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int x, y; + private TreeNode p1, p2; + private int d1, d2; + + public boolean isCousins(TreeNode root, int x, int y) { + this.x = x; + this.y = y; + dfs(root, null, 0); + return p1 != p2 && d1 == d2; + } + + private void dfs(TreeNode root, TreeNode p, int d) { + if (root == null) { + return; + } + if (root.val == x) { + p1 = p; + d1 = d; + } + if (root.val == y) { + p2 = p; + d2 = d; + } + dfs(root.left, root, d + 1); + dfs(root.right, root, d + 1); + } +} \ No newline at end of file diff --git a/solution/0900-0999/0993.Cousins in Binary Tree/Solution2.py b/solution/0900-0999/0993.Cousins in Binary Tree/Solution2.py new file mode 100644 index 0000000000000..ffd5ca0f0b3a4 --- /dev/null +++ b/solution/0900-0999/0993.Cousins in Binary Tree/Solution2.py @@ -0,0 +1,21 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool: + def dfs(root, fa, d): + if root is None: + return + if root.val == x: + t[0] = (fa, d) + if root.val == y: + t[1] = (fa, d) + dfs(root.left, root, d + 1) + dfs(root.right, root, d + 1) + + t = [None, None] + dfs(root, None, 0) + return t[0][0] != t[1][0] and t[0][1] == t[1][1] diff --git a/solution/0900-0999/0994.Rotting Oranges/Solution.cpp b/solution/0900-0999/0994.Rotting Oranges/Solution.cpp index ed59f741edce5..5c22df84639a2 100644 --- a/solution/0900-0999/0994.Rotting Oranges/Solution.cpp +++ b/solution/0900-0999/0994.Rotting Oranges/Solution.cpp @@ -1,36 +1,36 @@ -class Solution { -public: - int orangesRotting(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - int cnt = 0; - typedef pair pii; - queue q; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == 2) - q.emplace(i, j); - else if (grid[i][j] == 1) - ++cnt; - } - } - int ans = 0; - vector dirs = {-1, 0, 1, 0, -1}; - while (!q.empty() && cnt > 0) { - ++ans; - for (int i = q.size(); i > 0; --i) { - auto p = q.front(); - q.pop(); - for (int j = 0; j < 4; ++j) { - int x = p.first + dirs[j]; - int y = p.second + dirs[j + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) { - --cnt; - grid[x][y] = 2; - q.emplace(x, y); - } - } - } - } - return cnt > 0 ? -1 : ans; - } +class Solution { +public: + int orangesRotting(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int cnt = 0; + typedef pair pii; + queue q; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 2) + q.emplace(i, j); + else if (grid[i][j] == 1) + ++cnt; + } + } + int ans = 0; + vector dirs = {-1, 0, 1, 0, -1}; + while (!q.empty() && cnt > 0) { + ++ans; + for (int i = q.size(); i > 0; --i) { + auto p = q.front(); + q.pop(); + for (int j = 0; j < 4; ++j) { + int x = p.first + dirs[j]; + int y = p.second + dirs[j + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) { + --cnt; + grid[x][y] = 2; + q.emplace(x, y); + } + } + } + } + return cnt > 0 ? -1 : ans; + } }; \ No newline at end of file diff --git a/solution/0900-0999/0994.Rotting Oranges/Solution.java b/solution/0900-0999/0994.Rotting Oranges/Solution.java index a98a94e6cafd8..84d1624900eb7 100644 --- a/solution/0900-0999/0994.Rotting Oranges/Solution.java +++ b/solution/0900-0999/0994.Rotting Oranges/Solution.java @@ -1,34 +1,34 @@ -class Solution { - public int orangesRotting(int[][] grid) { - int m = grid.length, n = grid[0].length; - int cnt = 0; - Deque q = new LinkedList<>(); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == 2) { - q.offer(new int[] {i, j}); - } else if (grid[i][j] == 1) { - ++cnt; - } - } - } - int ans = 0; - int[] dirs = {1, 0, -1, 0, 1}; - while (!q.isEmpty() && cnt > 0) { - ++ans; - for (int i = q.size(); i > 0; --i) { - int[] p = q.poll(); - for (int j = 0; j < 4; ++j) { - int x = p[0] + dirs[j]; - int y = p[1] + dirs[j + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) { - grid[x][y] = 2; - --cnt; - q.offer(new int[] {x, y}); - } - } - } - } - return cnt > 0 ? -1 : ans; - } +class Solution { + public int orangesRotting(int[][] grid) { + int m = grid.length, n = grid[0].length; + int cnt = 0; + Deque q = new LinkedList<>(); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 2) { + q.offer(new int[] {i, j}); + } else if (grid[i][j] == 1) { + ++cnt; + } + } + } + int ans = 0; + int[] dirs = {1, 0, -1, 0, 1}; + while (!q.isEmpty() && cnt > 0) { + ++ans; + for (int i = q.size(); i > 0; --i) { + int[] p = q.poll(); + for (int j = 0; j < 4; ++j) { + int x = p[0] + dirs[j]; + int y = p[1] + dirs[j + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) { + grid[x][y] = 2; + --cnt; + q.offer(new int[] {x, y}); + } + } + } + } + return cnt > 0 ? -1 : ans; + } } \ No newline at end of file diff --git a/solution/0900-0999/0994.Rotting Oranges/Solution.py b/solution/0900-0999/0994.Rotting Oranges/Solution.py index de69cf3740d72..66ec796bf2919 100644 --- a/solution/0900-0999/0994.Rotting Oranges/Solution.py +++ b/solution/0900-0999/0994.Rotting Oranges/Solution.py @@ -1,23 +1,23 @@ -class Solution: - def orangesRotting(self, grid: List[List[int]]) -> int: - m, n = len(grid), len(grid[0]) - q = deque() - cnt = 0 - for i in range(m): - for j in range(n): - if grid[i][j] == 2: - q.append((i, j)) - elif grid[i][j] == 1: - cnt += 1 - ans = 0 - while q and cnt: - ans += 1 - for _ in range(len(q)): - i, j = q.popleft() - for a, b in [[0, 1], [0, -1], [1, 0], [-1, 0]]: - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n and grid[x][y] == 1: - cnt -= 1 - grid[x][y] = 2 - q.append((x, y)) - return ans if cnt == 0 else -1 +class Solution: + def orangesRotting(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + q = deque() + cnt = 0 + for i in range(m): + for j in range(n): + if grid[i][j] == 2: + q.append((i, j)) + elif grid[i][j] == 1: + cnt += 1 + ans = 0 + while q and cnt: + ans += 1 + for _ in range(len(q)): + i, j = q.popleft() + for a, b in [[0, 1], [0, -1], [1, 0], [-1, 0]]: + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n and grid[x][y] == 1: + cnt -= 1 + grid[x][y] = 2 + q.append((x, y)) + return ans if cnt == 0 else -1 diff --git a/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/Solution.cpp b/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/Solution.cpp index 0a72c1559640a..b06a9f69137ce 100644 --- a/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/Solution.cpp +++ b/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/Solution.cpp @@ -1,22 +1,22 @@ -class Solution { -public: - int minKBitFlips(vector& nums, int k) { - int n = nums.size(); - int d[n + 1]; - memset(d, 0, sizeof(d)); - int ans = 0, s = 0; - for (int i = 0; i < n; ++i) { - s += d[i]; - if (s % 2 == nums[i] % 2) { - if (i + k > n) { - return -1; - } - ++d[i]; - --d[i + k]; - ++s; - ++ans; - } - } - return ans; - } +class Solution { +public: + int minKBitFlips(vector& nums, int k) { + int n = nums.size(); + int d[n + 1]; + memset(d, 0, sizeof(d)); + int ans = 0, s = 0; + for (int i = 0; i < n; ++i) { + s += d[i]; + if (s % 2 == nums[i] % 2) { + if (i + k > n) { + return -1; + } + ++d[i]; + --d[i + k]; + ++s; + ++ans; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/Solution.java b/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/Solution.java index 60ec234f569cd..ba8d9e3a63703 100644 --- a/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/Solution.java +++ b/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/Solution.java @@ -1,20 +1,20 @@ -class Solution { - public int minKBitFlips(int[] nums, int k) { - int n = nums.length; - int[] d = new int[n + 1]; - int ans = 0, s = 0; - for (int i = 0; i < n; ++i) { - s += d[i]; - if (nums[i] % 2 == s % 2) { - if (i + k > n) { - return -1; - } - ++d[i]; - --d[i + k]; - ++s; - ++ans; - } - } - return ans; - } +class Solution { + public int minKBitFlips(int[] nums, int k) { + int n = nums.length; + int[] d = new int[n + 1]; + int ans = 0, s = 0; + for (int i = 0; i < n; ++i) { + s += d[i]; + if (nums[i] % 2 == s % 2) { + if (i + k > n) { + return -1; + } + ++d[i]; + --d[i + k]; + ++s; + ++ans; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/Solution.py b/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/Solution.py index 598ff8125da9b..6a01248c8b2a9 100644 --- a/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/Solution.py +++ b/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/Solution.py @@ -1,15 +1,15 @@ -class Solution: - def minKBitFlips(self, nums: List[int], k: int) -> int: - n = len(nums) - d = [0] * (n + 1) - ans = s = 0 - for i, x in enumerate(nums): - s += d[i] - if x % 2 == s % 2: - if i + k > n: - return -1 - d[i] += 1 - d[i + k] -= 1 - s += 1 - ans += 1 - return ans +class Solution: + def minKBitFlips(self, nums: List[int], k: int) -> int: + n = len(nums) + d = [0] * (n + 1) + ans = s = 0 + for i, x in enumerate(nums): + s += d[i] + if x % 2 == s % 2: + if i + k > n: + return -1 + d[i] += 1 + d[i + k] -= 1 + s += 1 + ans += 1 + return ans diff --git a/solution/0900-0999/0998.Maximum Binary Tree II/Solution.c b/solution/0900-0999/0998.Maximum Binary Tree II/Solution.c index ac2bbf5e69634..ba6b160543151 100644 --- a/solution/0900-0999/0998.Maximum Binary Tree II/Solution.c +++ b/solution/0900-0999/0998.Maximum Binary Tree II/Solution.c @@ -17,4 +17,4 @@ struct TreeNode* insertIntoMaxTree(struct TreeNode* root, int val) { } root->right = insertIntoMaxTree(root->right, val); return root; -} +} \ No newline at end of file diff --git a/solution/0900-0999/0998.Maximum Binary Tree II/Solution2.cpp b/solution/0900-0999/0998.Maximum Binary Tree II/Solution2.cpp new file mode 100644 index 0000000000000..baf2d5765e4fb --- /dev/null +++ b/solution/0900-0999/0998.Maximum Binary Tree II/Solution2.cpp @@ -0,0 +1,23 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* insertIntoMaxTree(TreeNode* root, int val) { + if (root->val < val) return new TreeNode(val, root, nullptr); + TreeNode* curr = root; + TreeNode* node = new TreeNode(val); + while (curr->right && curr->right->val > val) curr = curr->right; + node->left = curr->right; + curr->right = node; + return root; + } +}; \ No newline at end of file diff --git a/solution/0900-0999/0998.Maximum Binary Tree II/Solution2.go b/solution/0900-0999/0998.Maximum Binary Tree II/Solution2.go new file mode 100644 index 0000000000000..c9d3671d16a49 --- /dev/null +++ b/solution/0900-0999/0998.Maximum Binary Tree II/Solution2.go @@ -0,0 +1,21 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func insertIntoMaxTree(root *TreeNode, val int) *TreeNode { + if root.Val < val { + return &TreeNode{val, root, nil} + } + node := &TreeNode{Val: val} + curr := root + for curr.Right != nil && curr.Right.Val > val { + curr = curr.Right + } + node.Left = curr.Right + curr.Right = node + return root +} \ No newline at end of file diff --git a/solution/0900-0999/0998.Maximum Binary Tree II/Solution2.java b/solution/0900-0999/0998.Maximum Binary Tree II/Solution2.java new file mode 100644 index 0000000000000..8dc0b2dcf576d --- /dev/null +++ b/solution/0900-0999/0998.Maximum Binary Tree II/Solution2.java @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode insertIntoMaxTree(TreeNode root, int val) { + if (root.val < val) { + return new TreeNode(val, root, null); + } + TreeNode curr = root; + TreeNode node = new TreeNode(val); + while (curr.right != null && curr.right.val > val) { + curr = curr.right; + } + node.left = curr.right; + curr.right = node; + return root; + } +} \ No newline at end of file diff --git a/solution/0900-0999/0998.Maximum Binary Tree II/Solution2.py b/solution/0900-0999/0998.Maximum Binary Tree II/Solution2.py new file mode 100644 index 0000000000000..eacd8ff35556a --- /dev/null +++ b/solution/0900-0999/0998.Maximum Binary Tree II/Solution2.py @@ -0,0 +1,19 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def insertIntoMaxTree( + self, root: Optional[TreeNode], val: int + ) -> Optional[TreeNode]: + if root.val < val: + return TreeNode(val, root) + curr = root + node = TreeNode(val) + while curr.right and curr.right.val > val: + curr = curr.right + node.left = curr.right + curr.right = node + return root diff --git a/solution/0900-0999/0998.Maximum Binary Tree II/Solution2.ts b/solution/0900-0999/0998.Maximum Binary Tree II/Solution2.ts new file mode 100644 index 0000000000000..cd83c39908334 --- /dev/null +++ b/solution/0900-0999/0998.Maximum Binary Tree II/Solution2.ts @@ -0,0 +1,27 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function insertIntoMaxTree(root: TreeNode | null, val: number): TreeNode | null { + if (root.val < val) { + return new TreeNode(val, root); + } + const node = new TreeNode(val); + let curr = root; + while (curr.right && curr.right.val > val) { + curr = curr.right; + } + node.left = curr.right; + curr.right = node; + return root; +} diff --git a/solution/1000-1099/1004.Max Consecutive Ones III/Solution.cpp b/solution/1000-1099/1004.Max Consecutive Ones III/Solution.cpp index cdf78071b9df8..923c677683956 100644 --- a/solution/1000-1099/1004.Max Consecutive Ones III/Solution.cpp +++ b/solution/1000-1099/1004.Max Consecutive Ones III/Solution.cpp @@ -1,11 +1,19 @@ class Solution { public: int longestOnes(vector& nums, int k) { - int l = 0, r = 0; - while (r < nums.size()) { - if (nums[r++] == 0) --k; - if (k < 0 && nums[l++] == 0) ++k; + int ans = 0; + int cnt = 0, j = 0; + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] == 0) { + ++cnt; + } + while (cnt > k) { + if (nums[j++] == 0) { + --cnt; + } + } + ans = max(ans, i - j + 1); } - return r - l; + return ans; } }; \ No newline at end of file diff --git a/solution/1000-1099/1004.Max Consecutive Ones III/Solution.go b/solution/1000-1099/1004.Max Consecutive Ones III/Solution.go index 64dc822dd8900..3419554a0d09a 100644 --- a/solution/1000-1099/1004.Max Consecutive Ones III/Solution.go +++ b/solution/1000-1099/1004.Max Consecutive Ones III/Solution.go @@ -1,16 +1,17 @@ func longestOnes(nums []int, k int) int { - l, r := -1, -1 - for r < len(nums)-1 { - r++ - if nums[r] == 0 { - k-- + ans := 0 + j, cnt := 0, 0 + for i, v := range nums { + if v == 0 { + cnt++ } - if k < 0 { - l++ - if nums[l] == 0 { - k++ + for cnt > k { + if nums[j] == 0 { + cnt-- } + j++ } + ans = max(ans, i-j+1) } - return r - l + return ans } \ No newline at end of file diff --git a/solution/1000-1099/1004.Max Consecutive Ones III/Solution.java b/solution/1000-1099/1004.Max Consecutive Ones III/Solution.java index 5771abd5d3330..e3285860f7b76 100644 --- a/solution/1000-1099/1004.Max Consecutive Ones III/Solution.java +++ b/solution/1000-1099/1004.Max Consecutive Ones III/Solution.java @@ -1,14 +1,18 @@ class Solution { public int longestOnes(int[] nums, int k) { - int l = 0, r = 0; - while (r < nums.length) { - if (nums[r++] == 0) { - --k; + int j = 0, cnt = 0; + int ans = 0; + for (int i = 0; i < nums.length; ++i) { + if (nums[i] == 0) { + ++cnt; } - if (k < 0 && nums[l++] == 0) { - ++k; + while (cnt > k) { + if (nums[j++] == 0) { + --cnt; + } } + ans = Math.max(ans, i - j + 1); } - return r - l; + return ans; } } \ No newline at end of file diff --git a/solution/1000-1099/1004.Max Consecutive Ones III/Solution.py b/solution/1000-1099/1004.Max Consecutive Ones III/Solution.py index 77ec15b9cd4ba..868a067e7a2ca 100644 --- a/solution/1000-1099/1004.Max Consecutive Ones III/Solution.py +++ b/solution/1000-1099/1004.Max Consecutive Ones III/Solution.py @@ -1,12 +1,13 @@ class Solution: def longestOnes(self, nums: List[int], k: int) -> int: - l = r = -1 - while r < len(nums) - 1: - r += 1 - if nums[r] == 0: - k -= 1 - if k < 0: - l += 1 - if nums[l] == 0: - k += 1 - return r - l + ans = 0 + cnt = j = 0 + for i, v in enumerate(nums): + if v == 0: + cnt += 1 + while cnt > k: + if nums[j] == 0: + cnt -= 1 + j += 1 + ans = max(ans, i - j + 1) + return ans diff --git a/solution/1000-1099/1004.Max Consecutive Ones III/Solution2.cpp b/solution/1000-1099/1004.Max Consecutive Ones III/Solution2.cpp new file mode 100644 index 0000000000000..cdf78071b9df8 --- /dev/null +++ b/solution/1000-1099/1004.Max Consecutive Ones III/Solution2.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int longestOnes(vector& nums, int k) { + int l = 0, r = 0; + while (r < nums.size()) { + if (nums[r++] == 0) --k; + if (k < 0 && nums[l++] == 0) ++k; + } + return r - l; + } +}; \ No newline at end of file diff --git a/solution/1000-1099/1004.Max Consecutive Ones III/Solution2.go b/solution/1000-1099/1004.Max Consecutive Ones III/Solution2.go new file mode 100644 index 0000000000000..64dc822dd8900 --- /dev/null +++ b/solution/1000-1099/1004.Max Consecutive Ones III/Solution2.go @@ -0,0 +1,16 @@ +func longestOnes(nums []int, k int) int { + l, r := -1, -1 + for r < len(nums)-1 { + r++ + if nums[r] == 0 { + k-- + } + if k < 0 { + l++ + if nums[l] == 0 { + k++ + } + } + } + return r - l +} \ No newline at end of file diff --git a/solution/1000-1099/1004.Max Consecutive Ones III/Solution2.java b/solution/1000-1099/1004.Max Consecutive Ones III/Solution2.java new file mode 100644 index 0000000000000..5771abd5d3330 --- /dev/null +++ b/solution/1000-1099/1004.Max Consecutive Ones III/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public int longestOnes(int[] nums, int k) { + int l = 0, r = 0; + while (r < nums.length) { + if (nums[r++] == 0) { + --k; + } + if (k < 0 && nums[l++] == 0) { + ++k; + } + } + return r - l; + } +} \ No newline at end of file diff --git a/solution/1000-1099/1004.Max Consecutive Ones III/Solution2.py b/solution/1000-1099/1004.Max Consecutive Ones III/Solution2.py new file mode 100644 index 0000000000000..77ec15b9cd4ba --- /dev/null +++ b/solution/1000-1099/1004.Max Consecutive Ones III/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def longestOnes(self, nums: List[int], k: int) -> int: + l = r = -1 + while r < len(nums) - 1: + r += 1 + if nums[r] == 0: + k -= 1 + if k < 0: + l += 1 + if nums[l] == 0: + k += 1 + return r - l diff --git a/solution/1000-1099/1004.Max Consecutive Ones III/Solution2.ts b/solution/1000-1099/1004.Max Consecutive Ones III/Solution2.ts new file mode 100644 index 0000000000000..e00437d73d108 --- /dev/null +++ b/solution/1000-1099/1004.Max Consecutive Ones III/Solution2.ts @@ -0,0 +1,15 @@ +function longestOnes(nums: number[], k: number): number { + const n = nums.length; + let l = 0; + let res = k; + const count = [0, 0]; + for (let r = 0; r < n; r++) { + count[nums[r]]++; + res = Math.max(res, r - l); + while (count[0] > k) { + count[nums[l]]--; + l++; + } + } + return Math.max(res, n - l); +} diff --git a/solution/1000-1099/1008.Construct Binary Search Tree from Preorder Traversal/Solution.java b/solution/1000-1099/1008.Construct Binary Search Tree from Preorder Traversal/Solution.java index 9eb38e64079c5..05ca64f7aa651 100644 --- a/solution/1000-1099/1008.Construct Binary Search Tree from Preorder Traversal/Solution.java +++ b/solution/1000-1099/1008.Construct Binary Search Tree from Preorder Traversal/Solution.java @@ -14,6 +14,7 @@ * } */ class Solution { + public TreeNode bstFromPreorder(int[] preorder) { return dfs(preorder, 0, preorder.length - 1); } diff --git a/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/Solution2.cpp b/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/Solution2.cpp new file mode 100644 index 0000000000000..812ef109055c4 --- /dev/null +++ b/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int numPairsDivisibleBy60(vector& time) { + int cnt[60]{}; + int ans = 0; + for (int x : time) { + x %= 60; + int y = (60 - x) % 60; + ans += cnt[y]; + ++cnt[x]; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/Solution2.go b/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/Solution2.go new file mode 100644 index 0000000000000..a3bc988287e22 --- /dev/null +++ b/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/Solution2.go @@ -0,0 +1,10 @@ +func numPairsDivisibleBy60(time []int) (ans int) { + cnt := [60]int{} + for _, x := range time { + x %= 60 + y := (60 - x) % 60 + ans += cnt[y] + cnt[x]++ + } + return +} \ No newline at end of file diff --git a/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/Solution2.java b/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/Solution2.java new file mode 100644 index 0000000000000..ab354e9032f75 --- /dev/null +++ b/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/Solution2.java @@ -0,0 +1,13 @@ +class Solution { + public int numPairsDivisibleBy60(int[] time) { + int[] cnt = new int[60]; + int ans = 0; + for (int x : time) { + x %= 60; + int y = (60 - x) % 60; + ans += cnt[y]; + ++cnt[x]; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/Solution2.py b/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/Solution2.py new file mode 100644 index 0000000000000..f5005b5a70294 --- /dev/null +++ b/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def numPairsDivisibleBy60(self, time: List[int]) -> int: + cnt = Counter() + ans = 0 + for x in time: + x %= 60 + y = (60 - x) % 60 + ans += cnt[y] + cnt[x] += 1 + return ans diff --git a/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/Solution2.ts b/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/Solution2.ts new file mode 100644 index 0000000000000..63744c80fd742 --- /dev/null +++ b/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/Solution2.ts @@ -0,0 +1,11 @@ +function numPairsDivisibleBy60(time: number[]): number { + const cnt: number[] = new Array(60).fill(0); + let ans: number = 0; + for (let x of time) { + x %= 60; + const y = (60 - x) % 60; + ans += cnt[y]; + ++cnt[x]; + } + return ans; +} diff --git a/solution/1000-1099/1012.Numbers With Repeated Digits/Solution.cpp b/solution/1000-1099/1012.Numbers With Repeated Digits/Solution.cpp index 6c97091af703b..c312610d52eb2 100644 --- a/solution/1000-1099/1012.Numbers With Repeated Digits/Solution.cpp +++ b/solution/1000-1099/1012.Numbers With Repeated Digits/Solution.cpp @@ -4,41 +4,37 @@ class Solution { return n - f(n); } -private: - int nums[11]; - int dp[11][1 << 11]; - int f(int n) { - memset(dp, -1, sizeof(dp)); - int i = -1; - for (; n; n /= 10) { - nums[++i] = n % 10; - } - return dfs(i, 0, true, true); - } - - int dfs(int pos, int mask, bool lead, bool limit) { - if (pos < 0) { - return lead ? 0 : 1; + int ans = 0; + vector digits; + while (n) { + digits.push_back(n % 10); + n /= 10; } - if (!lead && !limit && dp[pos][mask] != -1) { - return dp[pos][mask]; + int m = digits.size(); + vector vis(10); + for (int i = 1; i < m; ++i) { + ans += 9 * A(9, i - 1); } - int up = limit ? nums[pos] : 9; - int ans = 0; - for (int i = 0; i <= up; ++i) { - if (mask >> i & 1) { - continue; + for (int i = m - 1; ~i; --i) { + int v = digits[i]; + for (int j = i == m - 1 ? 1 : 0; j < v; ++j) { + if (!vis[j]) { + ans += A(10 - (m - i), i); + } } - if (i == 0 && lead) { - ans += dfs(pos - 1, mask, lead, limit && i == up); - } else { - ans += dfs(pos - 1, mask | 1 << i, false, limit && i == up); + if (vis[v]) { + break; + } + vis[v] = true; + if (i == 0) { + ++ans; } - } - if (!lead && !limit) { - dp[pos][mask] = ans; } return ans; } + + int A(int m, int n) { + return n == 0 ? 1 : A(m, n - 1) * (m - n + 1); + } }; \ No newline at end of file diff --git a/solution/1000-1099/1012.Numbers With Repeated Digits/Solution.go b/solution/1000-1099/1012.Numbers With Repeated Digits/Solution.go index 31704f2ebb67d..a33eb792bc460 100644 --- a/solution/1000-1099/1012.Numbers With Repeated Digits/Solution.go +++ b/solution/1000-1099/1012.Numbers With Repeated Digits/Solution.go @@ -3,46 +3,42 @@ func numDupDigitsAtMostN(n int) int { } func f(n int) int { - nums := []int{} - for ; n > 0; n /= 10 { - nums = append(nums, n%10) + digits := []int{} + for n != 0 { + digits = append(digits, n%10) + n /= 10 } - dp := [11][1 << 11]int{} - for i := range dp { - for j := range dp[i] { - dp[i][j] = -1 - } + m := len(digits) + vis := make([]bool, 10) + ans := 0 + for i := 1; i < m; i++ { + ans += 9 * A(9, i-1) } - var dfs func(int, int, bool, bool) int - dfs = func(pos int, mask int, lead bool, limit bool) int { - if pos < 0 { - if lead { - return 0 - } - return 1 - } - if !lead && !limit && dp[pos][mask] != -1 { - return dp[pos][mask] + for i := m - 1; i >= 0; i-- { + v := digits[i] + j := 0 + if i == m-1 { + j = 1 } - up := 9 - if limit { - up = nums[pos] - } - ans := 0 - for i := 0; i <= up; i++ { - if mask>>i&1 == 1 { - continue - } - if i == 0 && lead { - ans += dfs(pos-1, mask, lead, limit && i == up) - } else { - ans += dfs(pos-1, mask|1< 0; n /= 10) { - nums[++i] = n % 10; - } - return dfs(i, 0, true, true); - } - - private int dfs(int pos, int mask, boolean lead, boolean limit) { - if (pos < 0) { - return lead ? 0 : 1; - } - if (!lead && !limit && dp[pos][mask] != null) { - return dp[pos][mask]; + public int f(int n) { + List digits = new ArrayList<>(); + while (n != 0) { + digits.add(n % 10); + n /= 10; } + int m = digits.size(); int ans = 0; - int up = limit ? nums[pos] : 9; - for (int i = 0; i <= up; ++i) { - if ((mask >> i & 1) == 1) { - continue; + for (int i = 1; i < m; ++i) { + ans += 9 * A(9, i - 1); + } + boolean[] vis = new boolean[10]; + for (int i = m - 1; i >= 0; --i) { + int v = digits.get(i); + for (int j = i == m - 1 ? 1 : 0; j < v; ++j) { + if (vis[j]) { + continue; + } + ans += A(10 - (m - i), i); } - if (i == 0 && lead) { - ans += dfs(pos - 1, mask, lead, limit && i == up); - } else { - ans += dfs(pos - 1, mask | 1 << i, false, limit && i == up); + if (vis[v]) { + break; + } + vis[v] = true; + if (i == 0) { + ++ans; } - } - if (!lead && !limit) { - dp[pos][mask] = ans; } return ans; } + + private int A(int m, int n) { + return n == 0 ? 1 : A(m, n - 1) * (m - n + 1); + } } \ No newline at end of file diff --git a/solution/1000-1099/1012.Numbers With Repeated Digits/Solution.py b/solution/1000-1099/1012.Numbers With Repeated Digits/Solution.py index 2f9732635eb58..76dc654b17e41 100644 --- a/solution/1000-1099/1012.Numbers With Repeated Digits/Solution.py +++ b/solution/1000-1099/1012.Numbers With Repeated Digits/Solution.py @@ -2,24 +2,26 @@ class Solution: def numDupDigitsAtMostN(self, n: int) -> int: return n - self.f(n) - def f(self, n: int) -> int: - @cache - def dfs(pos: int, mask: int, lead: bool, limit: bool) -> int: - if pos < 0: - return int(lead) ^ 1 - up = nums[pos] if limit else 9 - ans = 0 - for i in range(up + 1): - if mask >> i & 1: - continue - if i == 0 and lead: - ans += dfs(pos - 1, mask, lead, limit and i == up) - else: - ans += dfs(pos - 1, mask | 1 << i, False, limit and i == up) - return ans + def f(self, n): + def A(m, n): + return 1 if n == 0 else A(m, n - 1) * (m - n + 1) - nums = [] - while n: - nums.append(n % 10) - n //= 10 - return dfs(len(nums) - 1, 0, True, True) + vis = [False] * 10 + ans = 0 + digits = [int(c) for c in str(n)[::-1]] + m = len(digits) + for i in range(1, m): + ans += 9 * A(9, i - 1) + for i in range(m - 1, -1, -1): + v = digits[i] + j = 1 if i == m - 1 else 0 + while j < v: + if not vis[j]: + ans += A(10 - (m - i), i) + j += 1 + if vis[v]: + break + vis[v] = True + if i == 0: + ans += 1 + return ans diff --git a/solution/1000-1099/1012.Numbers With Repeated Digits/Solution2.cpp b/solution/1000-1099/1012.Numbers With Repeated Digits/Solution2.cpp new file mode 100644 index 0000000000000..6c97091af703b --- /dev/null +++ b/solution/1000-1099/1012.Numbers With Repeated Digits/Solution2.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + int numDupDigitsAtMostN(int n) { + return n - f(n); + } + +private: + int nums[11]; + int dp[11][1 << 11]; + + int f(int n) { + memset(dp, -1, sizeof(dp)); + int i = -1; + for (; n; n /= 10) { + nums[++i] = n % 10; + } + return dfs(i, 0, true, true); + } + + int dfs(int pos, int mask, bool lead, bool limit) { + if (pos < 0) { + return lead ? 0 : 1; + } + if (!lead && !limit && dp[pos][mask] != -1) { + return dp[pos][mask]; + } + int up = limit ? nums[pos] : 9; + int ans = 0; + for (int i = 0; i <= up; ++i) { + if (mask >> i & 1) { + continue; + } + if (i == 0 && lead) { + ans += dfs(pos - 1, mask, lead, limit && i == up); + } else { + ans += dfs(pos - 1, mask | 1 << i, false, limit && i == up); + } + } + if (!lead && !limit) { + dp[pos][mask] = ans; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1000-1099/1012.Numbers With Repeated Digits/Solution2.go b/solution/1000-1099/1012.Numbers With Repeated Digits/Solution2.go new file mode 100644 index 0000000000000..31704f2ebb67d --- /dev/null +++ b/solution/1000-1099/1012.Numbers With Repeated Digits/Solution2.go @@ -0,0 +1,48 @@ +func numDupDigitsAtMostN(n int) int { + return n - f(n) +} + +func f(n int) int { + nums := []int{} + for ; n > 0; n /= 10 { + nums = append(nums, n%10) + } + dp := [11][1 << 11]int{} + for i := range dp { + for j := range dp[i] { + dp[i][j] = -1 + } + } + var dfs func(int, int, bool, bool) int + dfs = func(pos int, mask int, lead bool, limit bool) int { + if pos < 0 { + if lead { + return 0 + } + return 1 + } + if !lead && !limit && dp[pos][mask] != -1 { + return dp[pos][mask] + } + up := 9 + if limit { + up = nums[pos] + } + ans := 0 + for i := 0; i <= up; i++ { + if mask>>i&1 == 1 { + continue + } + if i == 0 && lead { + ans += dfs(pos-1, mask, lead, limit && i == up) + } else { + ans += dfs(pos-1, mask|1< 0; n /= 10) { + nums[++i] = n % 10; + } + return dfs(i, 0, true, true); + } + + private int dfs(int pos, int mask, boolean lead, boolean limit) { + if (pos < 0) { + return lead ? 0 : 1; + } + if (!lead && !limit && dp[pos][mask] != null) { + return dp[pos][mask]; + } + int ans = 0; + int up = limit ? nums[pos] : 9; + for (int i = 0; i <= up; ++i) { + if ((mask >> i & 1) == 1) { + continue; + } + if (i == 0 && lead) { + ans += dfs(pos - 1, mask, lead, limit && i == up); + } else { + ans += dfs(pos - 1, mask | 1 << i, false, limit && i == up); + } + } + if (!lead && !limit) { + dp[pos][mask] = ans; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1000-1099/1012.Numbers With Repeated Digits/Solution2.py b/solution/1000-1099/1012.Numbers With Repeated Digits/Solution2.py new file mode 100644 index 0000000000000..2f9732635eb58 --- /dev/null +++ b/solution/1000-1099/1012.Numbers With Repeated Digits/Solution2.py @@ -0,0 +1,25 @@ +class Solution: + def numDupDigitsAtMostN(self, n: int) -> int: + return n - self.f(n) + + def f(self, n: int) -> int: + @cache + def dfs(pos: int, mask: int, lead: bool, limit: bool) -> int: + if pos < 0: + return int(lead) ^ 1 + up = nums[pos] if limit else 9 + ans = 0 + for i in range(up + 1): + if mask >> i & 1: + continue + if i == 0 and lead: + ans += dfs(pos - 1, mask, lead, limit and i == up) + else: + ans += dfs(pos - 1, mask | 1 << i, False, limit and i == up) + return ans + + nums = [] + while n: + nums.append(n % 10) + n //= 10 + return dfs(len(nums) - 1, 0, True, True) diff --git a/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.cpp b/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.cpp index 997f1c2008889..33d57850a288e 100644 --- a/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.cpp +++ b/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.cpp @@ -1,7 +1,7 @@ class Solution { public: bool queryString(string s, int n) { - if (n > 1023) { + if (n > 1000) { return false; } for (int i = n; i > n / 2; --i) { diff --git a/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.go b/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.go index 106d2076fd5f9..42af716ee3572 100644 --- a/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.go +++ b/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.go @@ -1,5 +1,5 @@ func queryString(s string, n int) bool { - if n > 1023 { + if n > 1000 { return false } for i := n; i > n/2; i-- { diff --git a/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.java b/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.java index b42d51e3495f1..254d45880fd98 100644 --- a/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.java +++ b/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.java @@ -1,6 +1,6 @@ class Solution { public boolean queryString(String s, int n) { - if (n > 1023) { + if (n > 1000) { return false; } for (int i = n; i > n / 2; i--) { diff --git a/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.ts b/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.ts index d5c5628966853..d8927601c2c4c 100644 --- a/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.ts +++ b/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.ts @@ -1,5 +1,5 @@ function queryString(s: string, n: number): boolean { - if (n > 1023) { + if (n > 1000) { return false; } for (let i = n; i > n / 2; --i) { diff --git a/solution/1000-1099/1019.Next Greater Node In Linked List/Solution2.ts b/solution/1000-1099/1019.Next Greater Node In Linked List/Solution2.ts new file mode 100644 index 0000000000000..0cb92b03aa9f7 --- /dev/null +++ b/solution/1000-1099/1019.Next Greater Node In Linked List/Solution2.ts @@ -0,0 +1,35 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +interface Item { + index: number; + val: number; +} + +function nextLargerNodes(head: ListNode | null): number[] { + const res: number[] = []; + const stack: Item[] = []; + let cur = head; + for (let i = 0; cur != null; i++) { + res.push(0); + const { val, next } = cur; + while (stack.length !== 0 && stack[stack.length - 1].val < val) { + res[stack.pop().index] = val; + } + stack.push({ + val, + index: i, + }); + cur = next; + } + return res; +} diff --git a/solution/1000-1099/1020.Number of Enclaves/Solution2.cpp b/solution/1000-1099/1020.Number of Enclaves/Solution2.cpp new file mode 100644 index 0000000000000..8fc106ef8c934 --- /dev/null +++ b/solution/1000-1099/1020.Number of Enclaves/Solution2.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int numEnclaves(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int dirs[5] = {-1, 0, 1, 0, -1}; + queue> q; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] && (i == 0 || i == m - 1 || j == 0 || j == n - 1)) { + q.emplace(i, j); + grid[i][j] = 0; + } + } + } + while (!q.empty()) { + auto [i, j] = q.front(); + q.pop(); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y]) { + q.emplace(x, y); + grid[x][y] = 0; + } + } + } + int ans = 0; + for (auto& row : grid) { + for (auto& v : row) { + ans += v; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1000-1099/1020.Number of Enclaves/Solution2.go b/solution/1000-1099/1020.Number of Enclaves/Solution2.go new file mode 100644 index 0000000000000..d34a1d5fe1625 --- /dev/null +++ b/solution/1000-1099/1020.Number of Enclaves/Solution2.go @@ -0,0 +1,30 @@ +func numEnclaves(grid [][]int) (ans int) { + m, n := len(grid), len(grid[0]) + dirs := [5]int{-1, 0, 1, 0, -1} + q := [][2]int{} + for i, row := range grid { + for j, v := range row { + if v == 1 && (i == 0 || i == m-1 || j == 0 || j == n-1) { + q = append(q, [2]int{i, j}) + grid[i][j] = 0 + } + } + } + for len(q) > 0 { + p := q[0] + q = q[1:] + for k := 0; k < 4; k++ { + x, y := p[0]+dirs[k], p[1]+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1 { + q = append(q, [2]int{x, y}) + grid[x][y] = 0 + } + } + } + for _, row := range grid { + for _, v := range row { + ans += v + } + } + return +} \ No newline at end of file diff --git a/solution/1000-1099/1020.Number of Enclaves/Solution2.java b/solution/1000-1099/1020.Number of Enclaves/Solution2.java new file mode 100644 index 0000000000000..fece462c3199c --- /dev/null +++ b/solution/1000-1099/1020.Number of Enclaves/Solution2.java @@ -0,0 +1,33 @@ +class Solution { + public int numEnclaves(int[][] grid) { + int m = grid.length; + int n = grid[0].length; + Deque q = new ArrayDeque<>(); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 1 && (i == 0 || i == m - 1 || j == 0 || j == n - 1)) { + q.offer(new int[] {i, j}); + grid[i][j] = 0; + } + } + } + int[] dirs = {-1, 0, 1, 0, -1}; + while (!q.isEmpty()) { + var p = q.poll(); + for (int k = 0; k < 4; ++k) { + int x = p[0] + dirs[k], y = p[1] + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) { + q.offer(new int[] {x, y}); + grid[x][y] = 0; + } + } + } + int ans = 0; + for (var row : grid) { + for (var v : row) { + ans += v; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1000-1099/1020.Number of Enclaves/Solution2.py b/solution/1000-1099/1020.Number of Enclaves/Solution2.py new file mode 100644 index 0000000000000..3e32875a3fc95 --- /dev/null +++ b/solution/1000-1099/1020.Number of Enclaves/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def numEnclaves(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + q = deque() + for i in range(m): + for j in range(n): + if grid[i][j] and (i == 0 or i == m - 1 or j == 0 or j == n - 1): + q.append((i, j)) + grid[i][j] = 0 + dirs = (-1, 0, 1, 0, -1) + while q: + i, j = q.popleft() + for a, b in pairwise(dirs): + x, y = i + a, j + b + if x >= 0 and x < m and y >= 0 and y < n and grid[x][y]: + q.append((x, y)) + grid[x][y] = 0 + return sum(v for row in grid for v in row) diff --git a/solution/1000-1099/1020.Number of Enclaves/Solution2.ts b/solution/1000-1099/1020.Number of Enclaves/Solution2.ts new file mode 100644 index 0000000000000..45da5776346aa --- /dev/null +++ b/solution/1000-1099/1020.Number of Enclaves/Solution2.ts @@ -0,0 +1,32 @@ +function numEnclaves(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const dirs = [-1, 0, 1, 0, -1]; + const q: number[][] = []; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (grid[i][j] === 1 && (i === 0 || i === m - 1 || j === 0 || j === n - 1)) { + q.push([i, j]); + grid[i][j] = 0; + } + } + } + while (q.length) { + const [i, j] = q.shift()!; + for (let k = 0; k < 4; ++k) { + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y <= n && grid[x][y] === 1) { + q.push([x, y]); + grid[x][y] = 0; + } + } + } + let ans = 0; + for (const row of grid) { + for (const v of row) { + ans += v; + } + } + return ans; +} diff --git a/solution/1000-1099/1020.Number of Enclaves/Solution3.cpp b/solution/1000-1099/1020.Number of Enclaves/Solution3.cpp new file mode 100644 index 0000000000000..b4305dffb92d9 --- /dev/null +++ b/solution/1000-1099/1020.Number of Enclaves/Solution3.cpp @@ -0,0 +1,63 @@ +class UnionFind { +public: + UnionFind(int n) { + p = vector(n); + size = vector(n, 1); + iota(p.begin(), p.end(), 0); + } + + void unite(int a, int b) { + int pa = find(a), pb = find(b); + if (pa != pb) { + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + } + } + + int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + +private: + vector p, size; +}; + +class Solution { +public: + int numEnclaves(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + UnionFind uf(m * n + 1); + int dirs[5] = {-1, 0, 1, 0, -1}; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 1) { + if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { + uf.unite(i * n + j, m * n); + } else { + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) { + uf.unite(i * n + j, x * n + y); + } + } + } + } + } + } + int ans = 0; + for (int i = 1; i < m - 1; ++i) { + for (int j = 1; j < n - 1; ++j) { + ans += grid[i][j] == 1 && uf.find(i * n + j) != uf.find(m * n); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1000-1099/1020.Number of Enclaves/Solution3.go b/solution/1000-1099/1020.Number of Enclaves/Solution3.go new file mode 100644 index 0000000000000..d07b95e242691 --- /dev/null +++ b/solution/1000-1099/1020.Number of Enclaves/Solution3.go @@ -0,0 +1,63 @@ +type unionFind struct { + p, size []int +} + +func newUnionFind(n int) *unionFind { + p := make([]int, n) + size := make([]int, n) + for i := range p { + p[i] = i + size[i] = 1 + } + return &unionFind{p, size} +} + +func (uf *unionFind) find(x int) int { + if uf.p[x] != x { + uf.p[x] = uf.find(uf.p[x]) + } + return uf.p[x] +} + +func (uf *unionFind) union(a, b int) { + pa, pb := uf.find(a), uf.find(b) + if pa != pb { + if uf.size[pa] > uf.size[pb] { + uf.p[pb] = pa + uf.size[pa] += uf.size[pb] + } else { + uf.p[pa] = pb + uf.size[pb] += uf.size[pa] + } + } +} + +func numEnclaves(grid [][]int) (ans int) { + m, n := len(grid), len(grid[0]) + uf := newUnionFind(m*n + 1) + dirs := [5]int{-1, 0, 1, 0, -1} + for i, row := range grid { + for j, v := range row { + if v == 1 { + if i == 0 || i == m-1 || j == 0 || j == n-1 { + uf.union(i*n+j, m*n) + } else { + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1 { + uf.union(i*n+j, x*n+y) + } + } + } + } + } + } + for i, row := range grid { + for j, v := range row { + if v == 1 && uf.find(i*n+j) != uf.find(m*n) { + ans++ + } + } + } + return +} \ No newline at end of file diff --git a/solution/1000-1099/1020.Number of Enclaves/Solution3.java b/solution/1000-1099/1020.Number of Enclaves/Solution3.java new file mode 100644 index 0000000000000..7ab85352f33ee --- /dev/null +++ b/solution/1000-1099/1020.Number of Enclaves/Solution3.java @@ -0,0 +1,67 @@ +class UnionFind { + private int[] p; + private int[] size; + + public UnionFind(int n) { + p = new int[n]; + size = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + size[i] = 1; + } + } + + public int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + + public void union(int a, int b) { + int pa = find(a), pb = find(b); + if (pa != pb) { + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + } + } +} + +class Solution { + public int numEnclaves(int[][] grid) { + int m = grid.length; + int n = grid[0].length; + UnionFind uf = new UnionFind(m * n + 1); + int[] dirs = {-1, 0, 1, 0, -1}; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 1) { + if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { + uf.union(i * n + j, m * n); + } else { + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) { + uf.union(i * n + j, x * n + y); + } + } + } + } + } + } + int ans = 0; + for (int i = 1; i < m - 1; ++i) { + for (int j = 1; j < n - 1; ++j) { + if (grid[i][j] == 1 && uf.find(i * n + j) != uf.find(m * n)) { + ++ans; + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1000-1099/1020.Number of Enclaves/Solution3.py b/solution/1000-1099/1020.Number of Enclaves/Solution3.py new file mode 100644 index 0000000000000..e6ed61276431e --- /dev/null +++ b/solution/1000-1099/1020.Number of Enclaves/Solution3.py @@ -0,0 +1,41 @@ +class UnionFind: + def __init__(self, n): + self.p = list(range(n)) + self.size = [1] * n + + def find(self, x): + if self.p[x] != x: + self.p[x] = self.find(self.p[x]) + return self.p[x] + + def union(self, a, b): + pa, pb = self.find(a), self.find(b) + if pa != pb: + if self.size[pa] > self.size[pb]: + self.p[pb] = pa + self.size[pa] += self.size[pb] + else: + self.p[pa] = pb + self.size[pb] += self.size[pa] + + +class Solution: + def numEnclaves(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + uf = UnionFind(m * n + 1) + dirs = (-1, 0, 1, 0, -1) + for i, row in enumerate(grid): + for j, v in enumerate(row): + if v: + if i == 0 or i == m - 1 or j == 0 or j == n - 1: + uf.union(i * n + j, m * n) + else: + for a, b in pairwise(dirs): + x, y = i + a, j + b + if x >= 0 and x < m and y >= 0 and y < n and grid[x][y]: + uf.union(i * n + j, x * n + y) + return sum( + grid[i][j] == 1 and uf.find(i * n + j) != uf.find(m * n) + for i in range(m) + for j in range(n) + ) diff --git a/solution/1000-1099/1021.Remove Outermost Parentheses/Solution2.cpp b/solution/1000-1099/1021.Remove Outermost Parentheses/Solution2.cpp new file mode 100644 index 0000000000000..1724e2a9428e6 --- /dev/null +++ b/solution/1000-1099/1021.Remove Outermost Parentheses/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + string removeOuterParentheses(string s) { + string ans; + int cnt = 0; + for (char& c : s) { + if (c == '(') { + ++cnt; + } + if (cnt > 1) { + ans.push_back(c); + } + if (c == ')') { + --cnt; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1000-1099/1021.Remove Outermost Parentheses/Solution2.go b/solution/1000-1099/1021.Remove Outermost Parentheses/Solution2.go new file mode 100644 index 0000000000000..5f9a8f63828ce --- /dev/null +++ b/solution/1000-1099/1021.Remove Outermost Parentheses/Solution2.go @@ -0,0 +1,16 @@ +func removeOuterParentheses(s string) string { + ans := []rune{} + cnt := 0 + for _, c := range s { + if c == '(' { + cnt++ + } + if cnt > 1 { + ans = append(ans, c) + } + if c == ')' { + cnt-- + } + } + return string(ans) +} \ No newline at end of file diff --git a/solution/1000-1099/1021.Remove Outermost Parentheses/Solution2.java b/solution/1000-1099/1021.Remove Outermost Parentheses/Solution2.java new file mode 100644 index 0000000000000..5081d49ebba60 --- /dev/null +++ b/solution/1000-1099/1021.Remove Outermost Parentheses/Solution2.java @@ -0,0 +1,19 @@ +class Solution { + public String removeOuterParentheses(String s) { + StringBuilder ans = new StringBuilder(); + int cnt = 0; + for (int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if (c == '(') { + ++cnt; + } + if (cnt > 1) { + ans.append(c); + } + if (c == ')') { + --cnt; + } + } + return ans.toString(); + } +} \ No newline at end of file diff --git a/solution/1000-1099/1021.Remove Outermost Parentheses/Solution2.py b/solution/1000-1099/1021.Remove Outermost Parentheses/Solution2.py new file mode 100644 index 0000000000000..bf9648e46e953 --- /dev/null +++ b/solution/1000-1099/1021.Remove Outermost Parentheses/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def removeOuterParentheses(self, s: str) -> str: + ans = [] + cnt = 0 + for c in s: + if c == '(': + cnt += 1 + if cnt > 1: + ans.append(c) + if c == ')': + cnt -= 1 + return ''.join(ans) diff --git a/solution/1000-1099/1029.Two City Scheduling/Solution.cpp b/solution/1000-1099/1029.Two City Scheduling/Solution.cpp index 09df95d63a92a..71344e35ef385 100644 --- a/solution/1000-1099/1029.Two City Scheduling/Solution.cpp +++ b/solution/1000-1099/1029.Two City Scheduling/Solution.cpp @@ -11,4 +11,4 @@ class Solution { } return ans; } -}; +}; \ No newline at end of file diff --git a/solution/1000-1099/1029.Two City Scheduling/Solution.java b/solution/1000-1099/1029.Two City Scheduling/Solution.java index 6cbc1ba2c5007..adfcecbecedb7 100644 --- a/solution/1000-1099/1029.Two City Scheduling/Solution.java +++ b/solution/1000-1099/1029.Two City Scheduling/Solution.java @@ -1,11 +1,11 @@ -class Solution { - public int twoCitySchedCost(int[][] costs) { - Arrays.sort(costs, (a, b) -> { return a[0] - a[1] - (b[0] - b[1]); }); - int ans = 0; - int n = costs.length >> 1; - for (int i = 0; i < n; ++i) { - ans += costs[i][0] + costs[i + n][1]; - } - return ans; - } +class Solution { + public int twoCitySchedCost(int[][] costs) { + Arrays.sort(costs, (a, b) -> { return a[0] - a[1] - (b[0] - b[1]); }); + int ans = 0; + int n = costs.length >> 1; + for (int i = 0; i < n; ++i) { + ans += costs[i][0] + costs[i + n][1]; + } + return ans; + } } \ No newline at end of file diff --git a/solution/1000-1099/1029.Two City Scheduling/Solution.py b/solution/1000-1099/1029.Two City Scheduling/Solution.py index 2196d1645b82f..7c5efb5b0a0d4 100644 --- a/solution/1000-1099/1029.Two City Scheduling/Solution.py +++ b/solution/1000-1099/1029.Two City Scheduling/Solution.py @@ -1,5 +1,5 @@ -class Solution: - def twoCitySchedCost(self, costs: List[List[int]]) -> int: - costs.sort(key=lambda x: x[0] - x[1]) - n = len(costs) >> 1 - return sum(costs[i][0] + costs[i + n][1] for i in range(n)) +class Solution: + def twoCitySchedCost(self, costs: List[List[int]]) -> int: + costs.sort(key=lambda x: x[0] - x[1]) + n = len(costs) >> 1 + return sum(costs[i][0] + costs[i + n][1] for i in range(n)) diff --git a/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.cpp b/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.cpp index 4046ec9a397d8..a7c1b5da8bb95 100644 --- a/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.cpp +++ b/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.cpp @@ -1,28 +1,28 @@ -class Solution { -public: - vector> allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) { - queue> q; - q.emplace(rCenter, cCenter); - vector> ans; - bool vis[rows][cols]; - memset(vis, false, sizeof(vis)); - vis[rCenter][cCenter] = true; - int dirs[5] = {-1, 0, 1, 0, -1}; - while (!q.empty()) { - for (int n = q.size(); n; --n) { - auto [i, j] = q.front(); - q.pop(); - ans.push_back({i, j}); - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k]; - int y = j + dirs[k + 1]; - if (x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y]) { - vis[x][y] = true; - q.emplace(x, y); - } - } - } - } - return ans; - } +class Solution { +public: + vector> allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) { + queue> q; + q.emplace(rCenter, cCenter); + vector> ans; + bool vis[rows][cols]; + memset(vis, false, sizeof(vis)); + vis[rCenter][cCenter] = true; + int dirs[5] = {-1, 0, 1, 0, -1}; + while (!q.empty()) { + for (int n = q.size(); n; --n) { + auto [i, j] = q.front(); + q.pop(); + ans.push_back({i, j}); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k]; + int y = j + dirs[k + 1]; + if (x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y]) { + vis[x][y] = true; + q.emplace(x, y); + } + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.java b/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.java index d74244896f041..012b93f09ea2b 100644 --- a/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.java +++ b/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.java @@ -1,27 +1,27 @@ -import java.util.Deque; - -class Solution { - public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) { - Deque q = new ArrayDeque<>(); - q.offer(new int[] {rCenter, cCenter}); - boolean[][] vis = new boolean[rows][cols]; - vis[rCenter][cCenter] = true; - int[][] ans = new int[rows * cols][2]; - int[] dirs = {-1, 0, 1, 0, -1}; - int idx = 0; - while (!q.isEmpty()) { - for (int n = q.size(); n > 0; --n) { - var p = q.poll(); - ans[idx++] = p; - for (int k = 0; k < 4; ++k) { - int x = p[0] + dirs[k], y = p[1] + dirs[k + 1]; - if (x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y]) { - vis[x][y] = true; - q.offer(new int[] {x, y}); - } - } - } - } - return ans; - } +import java.util.Deque; + +class Solution { + public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) { + Deque q = new ArrayDeque<>(); + q.offer(new int[] {rCenter, cCenter}); + boolean[][] vis = new boolean[rows][cols]; + vis[rCenter][cCenter] = true; + int[][] ans = new int[rows * cols][2]; + int[] dirs = {-1, 0, 1, 0, -1}; + int idx = 0; + while (!q.isEmpty()) { + for (int n = q.size(); n > 0; --n) { + var p = q.poll(); + ans[idx++] = p; + for (int k = 0; k < 4; ++k) { + int x = p[0] + dirs[k], y = p[1] + dirs[k + 1]; + if (x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y]) { + vis[x][y] = true; + q.offer(new int[] {x, y}); + } + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.py b/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.py index db138df35efaa..0fea2669d4b2f 100644 --- a/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.py +++ b/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.py @@ -1,18 +1,18 @@ -class Solution: - def allCellsDistOrder( - self, rows: int, cols: int, rCenter: int, cCenter: int - ) -> List[List[int]]: - q = deque([[rCenter, cCenter]]) - vis = [[False] * cols for _ in range(rows)] - vis[rCenter][cCenter] = True - ans = [] - while q: - for _ in range(len(q)): - p = q.popleft() - ans.append(p) - for a, b in pairwise((-1, 0, 1, 0, -1)): - x, y = p[0] + a, p[1] + b - if 0 <= x < rows and 0 <= y < cols and not vis[x][y]: - vis[x][y] = True - q.append([x, y]) - return ans +class Solution: + def allCellsDistOrder( + self, rows: int, cols: int, rCenter: int, cCenter: int + ) -> List[List[int]]: + q = deque([[rCenter, cCenter]]) + vis = [[False] * cols for _ in range(rows)] + vis[rCenter][cCenter] = True + ans = [] + while q: + for _ in range(len(q)): + p = q.popleft() + ans.append(p) + for a, b in pairwise((-1, 0, 1, 0, -1)): + x, y = p[0] + a, p[1] + b + if 0 <= x < rows and 0 <= y < cols and not vis[x][y]: + vis[x][y] = True + q.append([x, y]) + return ans diff --git a/solution/1000-1099/1035.Uncrossed Lines/Solution.cpp b/solution/1000-1099/1035.Uncrossed Lines/Solution.cpp index 703f5011759b8..9d5e571698609 100644 --- a/solution/1000-1099/1035.Uncrossed Lines/Solution.cpp +++ b/solution/1000-1099/1035.Uncrossed Lines/Solution.cpp @@ -14,4 +14,4 @@ class Solution { } return dp[m][n]; } -}; +}; \ No newline at end of file diff --git a/solution/1000-1099/1035.Uncrossed Lines/Solution.java b/solution/1000-1099/1035.Uncrossed Lines/Solution.java index 205ef140471c8..292f14a655f96 100644 --- a/solution/1000-1099/1035.Uncrossed Lines/Solution.java +++ b/solution/1000-1099/1035.Uncrossed Lines/Solution.java @@ -14,4 +14,4 @@ public int maxUncrossedLines(int[] nums1, int[] nums2) { } return dp[m][n]; } -} +} \ No newline at end of file diff --git a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.c b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.c index 63cfab0b20a49..bb42454b9cbae 100644 --- a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.c +++ b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.c @@ -7,29 +7,16 @@ * }; */ -struct TreeNode* bstToGst(struct TreeNode* root) { - struct TreeNode* cur = root; - int sum = 0; - while (cur) { - if (!cur->right) { - sum += cur->val; - cur->val = sum; - cur = cur->left; - } else { - struct TreeNode* next = cur->right; - while (next->left && next->left != cur) { - next = next->left; - } - if (!next->left) { - next->left = cur; - cur = cur->right; - } else { - next->left = NULL; - sum += cur->val; - cur->val = sum; - cur = cur->left; - } - } +int dfs(struct TreeNode* root, int sum) { + if (root) { + sum = dfs(root->right, sum) + root->val; + root->val = sum; + sum = dfs(root->left, sum); } - return root; + return sum; } + +struct TreeNode* bstToGst(struct TreeNode* root) { + dfs(root, 0); + return root; +} \ No newline at end of file diff --git a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.cpp b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.cpp index 26862bb00fbf1..e3f8ad1c493cf 100644 --- a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.cpp +++ b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.cpp @@ -11,30 +11,18 @@ */ class Solution { public: + int s = 0; + TreeNode* bstToGst(TreeNode* root) { - int s = 0; - TreeNode* node = root; - while (root) { - if (root->right == nullptr) { - s += root->val; - root->val = s; - root = root->left; - } else { - TreeNode* next = root->right; - while (next->left && next->left != root) { - next = next->left; - } - if (next->left == nullptr) { - next->left = root; - root = root->right; - } else { - s += root->val; - root->val = s; - next->left = nullptr; - root = root->left; - } - } - } - return node; + dfs(root); + return root; + } + + void dfs(TreeNode* root) { + if (!root) return; + dfs(root->right); + s += root->val; + root->val = s; + dfs(root->left); } }; \ No newline at end of file diff --git a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.go b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.go index 15c83ee394341..61b8b244344fd 100644 --- a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.go +++ b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.go @@ -8,27 +8,16 @@ */ func bstToGst(root *TreeNode) *TreeNode { s := 0 - node := root - for root != nil { - if root.Right == nil { - s += root.Val - root.Val = s - root = root.Left - } else { - next := root.Right - for next.Left != nil && next.Left != root { - next = next.Left - } - if next.Left == nil { - next.Left = root - root = root.Right - } else { - s += root.Val - root.Val = s - next.Left = nil - root = root.Left - } + var dfs func(*TreeNode) + dfs = func(root *TreeNode) { + if root == nil { + return } + dfs(root.Right) + s += root.Val + root.Val = s + dfs(root.Left) } - return node + dfs(root) + return root } \ No newline at end of file diff --git a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.java b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.java index 7c525b306caab..db05bd3836915 100644 --- a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.java +++ b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.java @@ -14,30 +14,20 @@ * } */ class Solution { + private int s; + public TreeNode bstToGst(TreeNode root) { - int s = 0; - TreeNode node = root; - while (root != null) { - if (root.right == null) { - s += root.val; - root.val = s; - root = root.left; - } else { - TreeNode next = root.right; - while (next.left != null && next.left != root) { - next = next.left; - } - if (next.left == null) { - next.left = root; - root = root.right; - } else { - s += root.val; - root.val = s; - next.left = null; - root = root.left; - } - } + dfs(root); + return root; + } + + private void dfs(TreeNode root) { + if (root == null) { + return; } - return node; + dfs(root.right); + s += root.val; + root.val = s; + dfs(root.left); } } \ No newline at end of file diff --git a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.py b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.py index 67f6e49202f0f..db01d320edb78 100644 --- a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.py +++ b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.py @@ -6,23 +6,15 @@ # self.right = right class Solution: def bstToGst(self, root: TreeNode) -> TreeNode: + def dfs(root): + nonlocal s + if root is None: + return + dfs(root.right) + s += root.val + root.val = s + dfs(root.left) + s = 0 - node = root - while root: - if root.right is None: - s += root.val - root.val = s - root = root.left - else: - next = root.right - while next.left and next.left != root: - next = next.left - if next.left is None: - next.left = root - root = root.right - else: - s += root.val - root.val = s - next.left = None - root = root.left - return node + dfs(root) + return root diff --git a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.ts b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.ts index 1c04d55140525..2f90397898b6c 100644 --- a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.ts +++ b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution.ts @@ -13,29 +13,16 @@ */ function bstToGst(root: TreeNode | null): TreeNode | null { - let cur = root; - let sum = 0; - while (cur != null) { - const { val, left, right } = cur; - if (right == null) { - sum += val; - cur.val = sum; - cur = left; - } else { - let next = right; - while (next.left != null && next.left != cur) { - next = next.left; - } - if (next.left == null) { - next.left = cur; - cur = right; - } else { - next.left = null; - sum += val; - cur.val = sum; - cur = left; - } + const dfs = (root: TreeNode | null, sum: number) => { + if (root == null) { + return sum; } - } + const { val, left, right } = root; + sum = dfs(right, sum) + val; + root.val = sum; + sum = dfs(left, sum); + return sum; + }; + dfs(root, 0); return root; } diff --git a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution2.c b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution2.c new file mode 100644 index 0000000000000..af9bfe6864aa6 --- /dev/null +++ b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution2.c @@ -0,0 +1,35 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +struct TreeNode* bstToGst(struct TreeNode* root) { + struct TreeNode* cur = root; + int sum = 0; + while (cur) { + if (!cur->right) { + sum += cur->val; + cur->val = sum; + cur = cur->left; + } else { + struct TreeNode* next = cur->right; + while (next->left && next->left != cur) { + next = next->left; + } + if (!next->left) { + next->left = cur; + cur = cur->right; + } else { + next->left = NULL; + sum += cur->val; + cur->val = sum; + cur = cur->left; + } + } + } + return root; +} \ No newline at end of file diff --git a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution2.cpp b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution2.cpp new file mode 100644 index 0000000000000..26862bb00fbf1 --- /dev/null +++ b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution2.cpp @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* bstToGst(TreeNode* root) { + int s = 0; + TreeNode* node = root; + while (root) { + if (root->right == nullptr) { + s += root->val; + root->val = s; + root = root->left; + } else { + TreeNode* next = root->right; + while (next->left && next->left != root) { + next = next->left; + } + if (next->left == nullptr) { + next->left = root; + root = root->right; + } else { + s += root->val; + root->val = s; + next->left = nullptr; + root = root->left; + } + } + } + return node; + } +}; \ No newline at end of file diff --git a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution2.go b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution2.go new file mode 100644 index 0000000000000..15c83ee394341 --- /dev/null +++ b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution2.go @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func bstToGst(root *TreeNode) *TreeNode { + s := 0 + node := root + for root != nil { + if root.Right == nil { + s += root.Val + root.Val = s + root = root.Left + } else { + next := root.Right + for next.Left != nil && next.Left != root { + next = next.Left + } + if next.Left == nil { + next.Left = root + root = root.Right + } else { + s += root.Val + root.Val = s + next.Left = nil + root = root.Left + } + } + } + return node +} \ No newline at end of file diff --git a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution2.java b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution2.java new file mode 100644 index 0000000000000..7c525b306caab --- /dev/null +++ b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution2.java @@ -0,0 +1,43 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode bstToGst(TreeNode root) { + int s = 0; + TreeNode node = root; + while (root != null) { + if (root.right == null) { + s += root.val; + root.val = s; + root = root.left; + } else { + TreeNode next = root.right; + while (next.left != null && next.left != root) { + next = next.left; + } + if (next.left == null) { + next.left = root; + root = root.right; + } else { + s += root.val; + root.val = s; + next.left = null; + root = root.left; + } + } + } + return node; + } +} \ No newline at end of file diff --git a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution2.py b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution2.py new file mode 100644 index 0000000000000..67f6e49202f0f --- /dev/null +++ b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution2.py @@ -0,0 +1,28 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def bstToGst(self, root: TreeNode) -> TreeNode: + s = 0 + node = root + while root: + if root.right is None: + s += root.val + root.val = s + root = root.left + else: + next = root.right + while next.left and next.left != root: + next = next.left + if next.left is None: + next.left = root + root = root.right + else: + s += root.val + root.val = s + next.left = None + root = root.left + return node diff --git a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution2.ts b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution2.ts new file mode 100644 index 0000000000000..1c04d55140525 --- /dev/null +++ b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/Solution2.ts @@ -0,0 +1,41 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function bstToGst(root: TreeNode | null): TreeNode | null { + let cur = root; + let sum = 0; + while (cur != null) { + const { val, left, right } = cur; + if (right == null) { + sum += val; + cur.val = sum; + cur = left; + } else { + let next = right; + while (next.left != null && next.left != cur) { + next = next.left; + } + if (next.left == null) { + next.left = cur; + cur = right; + } else { + next.left = null; + sum += val; + cur.val = sum; + cur = left; + } + } + } + return root; +} diff --git a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution.ts b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution.ts index 2ead0a9a14d3a..a6555c542d7b3 100644 --- a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution.ts +++ b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution.ts @@ -1,14 +1,19 @@ function minScoreTriangulation(values: number[]): number { const n = values.length; const f: number[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => 0)); - for (let l = 3; l <= n; ++l) { - for (let i = 0; i + l - 1 < n; ++i) { - const j = i + l - 1; - f[i][j] = 1 << 30; - for (let k = i + 1; k < j; ++k) { - f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); - } + const dfs = (i: number, j: number): number => { + if (i + 1 === j) { + return 0; } - } - return f[0][n - 1]; + if (f[i][j] > 0) { + return f[i][j]; + } + let ans = 1 << 30; + for (let k = i + 1; k < j; ++k) { + ans = Math.min(ans, dfs(i, k) + dfs(k, j) + values[i] * values[k] * values[j]); + } + f[i][j] = ans; + return ans; + }; + return dfs(0, n - 1); } diff --git a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution2.cpp b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution2.cpp new file mode 100644 index 0000000000000..23e259fe20509 --- /dev/null +++ b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int minScoreTriangulation(vector& values) { + int n = values.size(); + int f[n][n]; + memset(f, 0, sizeof(f)); + for (int i = n - 3; i >= 0; --i) { + for (int j = i + 2; j < n; ++j) { + f[i][j] = 1 << 30; + for (int k = i + 1; k < j; ++k) { + f[i][j] = min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); + } + } + } + return f[0][n - 1]; + } +}; \ No newline at end of file diff --git a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution2.go b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution2.go new file mode 100644 index 0000000000000..31695ce2674b5 --- /dev/null +++ b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution2.go @@ -0,0 +1,13 @@ +func minScoreTriangulation(values []int) int { + n := len(values) + f := [50][50]int{} + for i := n - 3; i >= 0; i-- { + for j := i + 2; j < n; j++ { + f[i][j] = 1 << 30 + for k := i + 1; k < j; k++ { + f[i][j] = min(f[i][j], f[i][k]+f[k][j]+values[i]*values[k]*values[j]) + } + } + } + return f[0][n-1] +} \ No newline at end of file diff --git a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution2.java b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution2.java new file mode 100644 index 0000000000000..a4f067c9e1982 --- /dev/null +++ b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public int minScoreTriangulation(int[] values) { + int n = values.length; + int[][] f = new int[n][n]; + for (int i = n - 3; i >= 0; --i) { + for (int j = i + 2; j < n; ++j) { + f[i][j] = 1 << 30; + for (int k = i + 1; k < j; ++k) { + f[i][j] + = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); + } + } + } + return f[0][n - 1]; + } +} \ No newline at end of file diff --git a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution2.py b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution2.py new file mode 100644 index 0000000000000..0c410b6bde83b --- /dev/null +++ b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def minScoreTriangulation(self, values: List[int]) -> int: + n = len(values) + f = [[0] * n for _ in range(n)] + for i in range(n - 3, -1, -1): + for j in range(i + 2, n): + f[i][j] = min( + f[i][k] + f[k][j] + values[i] * values[k] * values[j] + for k in range(i + 1, j) + ) + return f[0][-1] diff --git a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution2.ts b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution2.ts new file mode 100644 index 0000000000000..011f564192ccf --- /dev/null +++ b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution2.ts @@ -0,0 +1,13 @@ +function minScoreTriangulation(values: number[]): number { + const n = values.length; + const f: number[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => 0)); + for (let i = n - 3; i >= 0; --i) { + for (let j = i + 2; j < n; ++j) { + f[i][j] = 1 << 30; + for (let k = i + 1; k < j; ++k) { + f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); + } + } + } + return f[0][n - 1]; +} diff --git a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution3.cpp b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution3.cpp new file mode 100644 index 0000000000000..2070c7c4975ec --- /dev/null +++ b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution3.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int minScoreTriangulation(vector& values) { + int n = values.size(); + int f[n][n]; + memset(f, 0, sizeof(f)); + for (int l = 3; l <= n; ++l) { + for (int i = 0; i + l - 1 < n; ++i) { + int j = i + l - 1; + f[i][j] = 1 << 30; + for (int k = i + 1; k < j; ++k) { + f[i][j] = min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); + } + } + } + return f[0][n - 1]; + } +}; \ No newline at end of file diff --git a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution3.go b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution3.go new file mode 100644 index 0000000000000..8fe243fb8323d --- /dev/null +++ b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution3.go @@ -0,0 +1,14 @@ +func minScoreTriangulation(values []int) int { + n := len(values) + f := [50][50]int{} + for l := 3; l <= n; l++ { + for i := 0; i+l-1 < n; i++ { + j := i + l - 1 + f[i][j] = 1 << 30 + for k := i + 1; k < j; k++ { + f[i][j] = min(f[i][j], f[i][k]+f[k][j]+values[i]*values[k]*values[j]) + } + } + } + return f[0][n-1] +} \ No newline at end of file diff --git a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution3.java b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution3.java new file mode 100644 index 0000000000000..2e49104126ecc --- /dev/null +++ b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution3.java @@ -0,0 +1,17 @@ +class Solution { + public int minScoreTriangulation(int[] values) { + int n = values.length; + int[][] f = new int[n][n]; + for (int l = 3; l <= n; ++l) { + for (int i = 0; i + l - 1 < n; ++i) { + int j = i + l - 1; + f[i][j] = 1 << 30; + for (int k = i + 1; k < j; ++k) { + f[i][j] + = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); + } + } + } + return f[0][n - 1]; + } +} \ No newline at end of file diff --git a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution3.py b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution3.py new file mode 100644 index 0000000000000..a4f879997bc6e --- /dev/null +++ b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution3.py @@ -0,0 +1,12 @@ +class Solution: + def minScoreTriangulation(self, values: List[int]) -> int: + n = len(values) + f = [[0] * n for _ in range(n)] + for l in range(3, n + 1): + for i in range(n - l + 1): + j = i + l - 1 + f[i][j] = min( + f[i][k] + f[k][j] + values[i] * values[k] * values[j] + for k in range(i + 1, j) + ) + return f[0][-1] diff --git a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution3.ts b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution3.ts new file mode 100644 index 0000000000000..2ead0a9a14d3a --- /dev/null +++ b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution3.ts @@ -0,0 +1,14 @@ +function minScoreTriangulation(values: number[]): number { + const n = values.length; + const f: number[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => 0)); + for (let l = 3; l <= n; ++l) { + for (let i = 0; i + l - 1 < n; ++i) { + const j = i + l - 1; + f[i][j] = 1 << 30; + for (let k = i + 1; k < j; ++k) { + f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); + } + } + } + return f[0][n - 1]; +} diff --git a/solution/1000-1099/1047.Remove All Adjacent Duplicates In String/Solution.c b/solution/1000-1099/1047.Remove All Adjacent Duplicates In String/Solution.c index 82fe8b9696360..d9bedc0828282 100644 --- a/solution/1000-1099/1047.Remove All Adjacent Duplicates In String/Solution.c +++ b/solution/1000-1099/1047.Remove All Adjacent Duplicates In String/Solution.c @@ -12,4 +12,4 @@ char* removeDuplicates(char* s) { } stack[i] = '\0'; return stack; -} +} \ No newline at end of file diff --git a/solution/1000-1099/1048.Longest String Chain/Solution2.py b/solution/1000-1099/1048.Longest String Chain/Solution2.py new file mode 100644 index 0000000000000..fad789c9c8335 --- /dev/null +++ b/solution/1000-1099/1048.Longest String Chain/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def longestStrChain(self, words: List[str]) -> int: + words.sort(key=lambda x: len(x)) + res = 0 + mp = {} + for word in words: + x = 1 + for i in range(len(word)): + pre = word[:i] + word[i + 1 :] + x = max(x, mp.get(pre, 0) + 1) + mp[word] = x + res = max(res, x) + return res diff --git a/solution/1000-1099/1049.Last Stone Weight II/Solution.cpp b/solution/1000-1099/1049.Last Stone Weight II/Solution.cpp index 9310e89866528..66ce117eca862 100644 --- a/solution/1000-1099/1049.Last Stone Weight II/Solution.cpp +++ b/solution/1000-1099/1049.Last Stone Weight II/Solution.cpp @@ -1,12 +1,15 @@ -class Solution { -public: - int lastStoneWeightII(vector& stones) { - int s = accumulate(stones.begin(), stones.end(), 0); - int n = s >> 1; - vector dp(n + 1); - for (int& v : stones) - for (int j = n; j >= v; --j) - dp[j] = max(dp[j], dp[j - v] + v); - return s - dp[n] * 2; - } +class Solution { +public: + int lastStoneWeightII(vector& stones) { + int s = accumulate(stones.begin(), stones.end(), 0); + int m = stones.size(), n = s >> 1; + vector> dp(m + 1, vector(n + 1)); + for (int i = 1; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + dp[i][j] = dp[i - 1][j]; + if (stones[i - 1] <= j) dp[i][j] = max(dp[i][j], dp[i - 1][j - stones[i - 1]] + stones[i - 1]); + } + } + return s - dp[m][n] * 2; + } }; \ No newline at end of file diff --git a/solution/1000-1099/1049.Last Stone Weight II/Solution.go b/solution/1000-1099/1049.Last Stone Weight II/Solution.go index e4eafc748c7a6..3350a9bf1fc80 100644 --- a/solution/1000-1099/1049.Last Stone Weight II/Solution.go +++ b/solution/1000-1099/1049.Last Stone Weight II/Solution.go @@ -3,12 +3,18 @@ func lastStoneWeightII(stones []int) int { for _, v := range stones { s += v } - n := s >> 1 - dp := make([]int, n+1) - for _, v := range stones { - for j := n; j >= v; j-- { - dp[j] = max(dp[j], dp[j-v]+v) + m, n := len(stones), s>>1 + dp := make([][]int, m+1) + for i := range dp { + dp[i] = make([]int, n+1) + } + for i := 1; i <= m; i++ { + for j := 0; j <= n; j++ { + dp[i][j] = dp[i-1][j] + if stones[i-1] <= j { + dp[i][j] = max(dp[i][j], dp[i-1][j-stones[i-1]]+stones[i-1]) + } } } - return s - dp[n]*2 + return s - dp[m][n]*2 } \ No newline at end of file diff --git a/solution/1000-1099/1049.Last Stone Weight II/Solution.java b/solution/1000-1099/1049.Last Stone Weight II/Solution.java index c4a5f7451f919..e4f560a7b72cf 100644 --- a/solution/1000-1099/1049.Last Stone Weight II/Solution.java +++ b/solution/1000-1099/1049.Last Stone Weight II/Solution.java @@ -1,17 +1,20 @@ -class Solution { - public int lastStoneWeightII(int[] stones) { - int s = 0; - for (int v : stones) { - s += v; - } - int m = stones.length; - int n = s >> 1; - int[] dp = new int[n + 1]; - for (int v : stones) { - for (int j = n; j >= v; --j) { - dp[j] = Math.max(dp[j], dp[j - v] + v); - } - } - return s - dp[n] * 2; - } +class Solution { + public int lastStoneWeightII(int[] stones) { + int s = 0; + for (int v : stones) { + s += v; + } + int m = stones.length; + int n = s >> 1; + int[][] dp = new int[m + 1][n + 1]; + for (int i = 1; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + dp[i][j] = dp[i - 1][j]; + if (stones[i - 1] <= j) { + dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - stones[i - 1]] + stones[i - 1]); + } + } + } + return s - dp[m][n] * 2; + } } \ No newline at end of file diff --git a/solution/1000-1099/1049.Last Stone Weight II/Solution.py b/solution/1000-1099/1049.Last Stone Weight II/Solution.py index 741759ae7d9f5..a988f89503ea8 100644 --- a/solution/1000-1099/1049.Last Stone Weight II/Solution.py +++ b/solution/1000-1099/1049.Last Stone Weight II/Solution.py @@ -1,9 +1,13 @@ -class Solution: - def lastStoneWeightII(self, stones: List[int]) -> int: - s = sum(stones) - m, n = len(stones), s >> 1 - dp = [0] * (n + 1) - for v in stones: - for j in range(n, v - 1, -1): - dp[j] = max(dp[j], dp[j - v] + v) - return s - dp[-1] * 2 +class Solution: + def lastStoneWeightII(self, stones: List[int]) -> int: + s = sum(stones) + m, n = len(stones), s >> 1 + dp = [[0] * (n + 1) for _ in range(m + 1)] + for i in range(1, m + 1): + for j in range(n + 1): + dp[i][j] = dp[i - 1][j] + if stones[i - 1] <= j: + dp[i][j] = max( + dp[i][j], dp[i - 1][j - stones[i - 1]] + stones[i - 1] + ) + return s - 2 * dp[-1][-1] diff --git a/solution/1000-1099/1049.Last Stone Weight II/Solution2.cpp b/solution/1000-1099/1049.Last Stone Weight II/Solution2.cpp new file mode 100644 index 0000000000000..d70c2ae127090 --- /dev/null +++ b/solution/1000-1099/1049.Last Stone Weight II/Solution2.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int lastStoneWeightII(vector& stones) { + int s = accumulate(stones.begin(), stones.end(), 0); + int n = s >> 1; + vector dp(n + 1); + for (int& v : stones) + for (int j = n; j >= v; --j) + dp[j] = max(dp[j], dp[j - v] + v); + return s - dp[n] * 2; + } +}; \ No newline at end of file diff --git a/solution/1000-1099/1049.Last Stone Weight II/Solution2.go b/solution/1000-1099/1049.Last Stone Weight II/Solution2.go new file mode 100644 index 0000000000000..e4eafc748c7a6 --- /dev/null +++ b/solution/1000-1099/1049.Last Stone Weight II/Solution2.go @@ -0,0 +1,14 @@ +func lastStoneWeightII(stones []int) int { + s := 0 + for _, v := range stones { + s += v + } + n := s >> 1 + dp := make([]int, n+1) + for _, v := range stones { + for j := n; j >= v; j-- { + dp[j] = max(dp[j], dp[j-v]+v) + } + } + return s - dp[n]*2 +} \ No newline at end of file diff --git a/solution/1000-1099/1049.Last Stone Weight II/Solution2.java b/solution/1000-1099/1049.Last Stone Weight II/Solution2.java new file mode 100644 index 0000000000000..d2ff7530beeb0 --- /dev/null +++ b/solution/1000-1099/1049.Last Stone Weight II/Solution2.java @@ -0,0 +1,17 @@ +class Solution { + public int lastStoneWeightII(int[] stones) { + int s = 0; + for (int v : stones) { + s += v; + } + int m = stones.length; + int n = s >> 1; + int[] dp = new int[n + 1]; + for (int v : stones) { + for (int j = n; j >= v; --j) { + dp[j] = Math.max(dp[j], dp[j - v] + v); + } + } + return s - dp[n] * 2; + } +} \ No newline at end of file diff --git a/solution/1000-1099/1049.Last Stone Weight II/Solution2.py b/solution/1000-1099/1049.Last Stone Weight II/Solution2.py new file mode 100644 index 0000000000000..392a99e99dfed --- /dev/null +++ b/solution/1000-1099/1049.Last Stone Weight II/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def lastStoneWeightII(self, stones: List[int]) -> int: + s = sum(stones) + m, n = len(stones), s >> 1 + dp = [0] * (n + 1) + for v in stones: + for j in range(n, v - 1, -1): + dp[j] = max(dp[j], dp[j - v] + v) + return s - dp[-1] * 2 diff --git a/solution/1000-1099/1051.Height Checker/Solution2.cpp b/solution/1000-1099/1051.Height Checker/Solution2.cpp new file mode 100644 index 0000000000000..a94a4ba514e14 --- /dev/null +++ b/solution/1000-1099/1051.Height Checker/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int heightChecker(vector& heights) { + vector cnt(101); + for (int& h : heights) ++cnt[h]; + int ans = 0; + for (int i = 0, j = 0; i < 101; ++i) { + while (cnt[i]) { + --cnt[i]; + if (heights[j++] != i) ++ans; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1000-1099/1051.Height Checker/Solution2.go b/solution/1000-1099/1051.Height Checker/Solution2.go new file mode 100644 index 0000000000000..6f0d4f84d24a8 --- /dev/null +++ b/solution/1000-1099/1051.Height Checker/Solution2.go @@ -0,0 +1,17 @@ +func heightChecker(heights []int) int { + cnt := make([]int, 101) + for _, h := range heights { + cnt[h]++ + } + ans := 0 + for i, j := 0, 0; i < 101; i++ { + for cnt[i] > 0 { + cnt[i]-- + if heights[j] != i { + ans++ + } + j++ + } + } + return ans +} \ No newline at end of file diff --git a/solution/1000-1099/1051.Height Checker/Solution2.java b/solution/1000-1099/1051.Height Checker/Solution2.java new file mode 100644 index 0000000000000..8c969d71c4255 --- /dev/null +++ b/solution/1000-1099/1051.Height Checker/Solution2.java @@ -0,0 +1,18 @@ +class Solution { + public int heightChecker(int[] heights) { + int[] cnt = new int[101]; + for (int h : heights) { + ++cnt[h]; + } + int ans = 0; + for (int i = 0, j = 0; i < 101; ++i) { + while (cnt[i] > 0) { + --cnt[i]; + if (heights[j++] != i) { + ++ans; + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1000-1099/1051.Height Checker/Solution2.py b/solution/1000-1099/1051.Height Checker/Solution2.py new file mode 100644 index 0000000000000..3509aae8274a0 --- /dev/null +++ b/solution/1000-1099/1051.Height Checker/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def heightChecker(self, heights: List[int]) -> int: + cnt = [0] * 101 + for h in heights: + cnt[h] += 1 + ans = i = 0 + for j in range(1, 101): + while cnt[j]: + cnt[j] -= 1 + if heights[i] != j: + ans += 1 + i += 1 + return ans diff --git a/solution/1000-1099/1056.Confusing Number/Solution.php b/solution/1000-1099/1056.Confusing Number/Solution.php index 22c5667039525..fb0b38605a163 100644 --- a/solution/1000-1099/1056.Confusing Number/Solution.php +++ b/solution/1000-1099/1056.Confusing Number/Solution.php @@ -17,4 +17,4 @@ function confusingNumber($n) { } return $y != $n; } -} \ No newline at end of file +} diff --git a/solution/1000-1099/1063.Number of Valid Subarrays/Solution.cpp b/solution/1000-1099/1063.Number of Valid Subarrays/Solution.cpp index 0ba5cd54e9998..fe3f32bf26a64 100644 --- a/solution/1000-1099/1063.Number of Valid Subarrays/Solution.cpp +++ b/solution/1000-1099/1063.Number of Valid Subarrays/Solution.cpp @@ -1,16 +1,22 @@ -class Solution { -public: - int validSubarrays(vector& nums) { - int n = nums.size(); - stack stk; - int ans = 0; - for (int i = n - 1; ~i; --i) { - while (stk.size() && nums[stk.top()] >= nums[i]) { - stk.pop(); - } - ans += (stk.size() ? stk.top() : n) - i; - stk.push(i); - } - return ans; - } +class Solution { +public: + int validSubarrays(vector& nums) { + int n = nums.size(); + vector right(n, n); + stack stk; + for (int i = n - 1; ~i; --i) { + while (stk.size() && nums[stk.top()] >= nums[i]) { + stk.pop(); + } + if (stk.size()) { + right[i] = stk.top(); + } + stk.push(i); + } + int ans = 0; + for (int i = 0; i < n; ++i) { + ans += right[i] - i; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1000-1099/1063.Number of Valid Subarrays/Solution.go b/solution/1000-1099/1063.Number of Valid Subarrays/Solution.go index d98e0a5a0db6c..753f8511979cb 100644 --- a/solution/1000-1099/1063.Number of Valid Subarrays/Solution.go +++ b/solution/1000-1099/1063.Number of Valid Subarrays/Solution.go @@ -1,17 +1,21 @@ func validSubarrays(nums []int) (ans int) { n := len(nums) + right := make([]int, n) + for i := range right { + right[i] = n + } stk := []int{} for i := n - 1; i >= 0; i-- { for len(stk) > 0 && nums[stk[len(stk)-1]] >= nums[i] { stk = stk[:len(stk)-1] } - ans -= i if len(stk) > 0 { - ans += stk[len(stk)-1] - } else { - ans += n + right[i] = stk[len(stk)-1] } stk = append(stk, i) } + for i, j := range right { + ans += j - i + } return } \ No newline at end of file diff --git a/solution/1000-1099/1063.Number of Valid Subarrays/Solution.java b/solution/1000-1099/1063.Number of Valid Subarrays/Solution.java index dcad67b9b9ad1..cd7ca20032854 100644 --- a/solution/1000-1099/1063.Number of Valid Subarrays/Solution.java +++ b/solution/1000-1099/1063.Number of Valid Subarrays/Solution.java @@ -1,16 +1,22 @@ -class Solution { - public int validSubarrays(int[] nums) { - int n = nums.length; - Deque stk = new ArrayDeque<>(); - int ans = 0; - for (int i = n - 1; i >= 0; --i) { - while (!stk.isEmpty() && nums[stk.peek()] >= nums[i]) { - stk.pop(); - } - ans += (stk.isEmpty() ? n : stk.peek()) - i; - - stk.push(i); - } - return ans; - } +class Solution { + public int validSubarrays(int[] nums) { + int n = nums.length; + int[] right = new int[n]; + Arrays.fill(right, n); + Deque stk = new ArrayDeque<>(); + for (int i = n - 1; i >= 0; --i) { + while (!stk.isEmpty() && nums[stk.peek()] >= nums[i]) { + stk.pop(); + } + if (!stk.isEmpty()) { + right[i] = stk.peek(); + } + stk.push(i); + } + int ans = 0; + for (int i = 0; i < n; ++i) { + ans += right[i] - i; + } + return ans; + } } \ No newline at end of file diff --git a/solution/1000-1099/1063.Number of Valid Subarrays/Solution.py b/solution/1000-1099/1063.Number of Valid Subarrays/Solution.py index 442af425e4be6..d14b865027070 100644 --- a/solution/1000-1099/1063.Number of Valid Subarrays/Solution.py +++ b/solution/1000-1099/1063.Number of Valid Subarrays/Solution.py @@ -1,11 +1,12 @@ -class Solution: - def validSubarrays(self, nums: List[int]) -> int: - n = len(nums) - stk = [] - ans = 0 - for i in range(n - 1, -1, -1): - while stk and nums[stk[-1]] >= nums[i]: - stk.pop() - ans += (stk[-1] if stk else n) - i - stk.append(i) - return ans +class Solution: + def validSubarrays(self, nums: List[int]) -> int: + n = len(nums) + right = [n] * n + stk = [] + for i in range(n - 1, -1, -1): + while stk and nums[stk[-1]] >= nums[i]: + stk.pop() + if stk: + right[i] = stk[-1] + stk.append(i) + return sum(j - i for i, j in enumerate(right)) diff --git a/solution/1000-1099/1063.Number of Valid Subarrays/Solution.ts b/solution/1000-1099/1063.Number of Valid Subarrays/Solution.ts index 07d1e9d470fbf..eed5173f318b6 100644 --- a/solution/1000-1099/1063.Number of Valid Subarrays/Solution.ts +++ b/solution/1000-1099/1063.Number of Valid Subarrays/Solution.ts @@ -1,13 +1,19 @@ function validSubarrays(nums: number[]): number { const n = nums.length; + const right: number[] = Array(n).fill(n); const stk: number[] = []; - let ans = 0; for (let i = n - 1; ~i; --i) { - while (stk.length && nums[stk.at(-1)!] >= nums[i]) { + while (stk.length && nums[stk.at(-1)] >= nums[i]) { stk.pop(); } - ans += (stk.at(-1) ?? n) - i; + if (stk.length) { + right[i] = stk.at(-1)!; + } stk.push(i); } + let ans = 0; + for (let i = 0; i < n; ++i) { + ans += right[i] - i; + } return ans; } diff --git a/solution/1000-1099/1063.Number of Valid Subarrays/Solution2.cpp b/solution/1000-1099/1063.Number of Valid Subarrays/Solution2.cpp new file mode 100644 index 0000000000000..9ad671a411533 --- /dev/null +++ b/solution/1000-1099/1063.Number of Valid Subarrays/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int validSubarrays(vector& nums) { + int n = nums.size(); + stack stk; + int ans = 0; + for (int i = n - 1; ~i; --i) { + while (stk.size() && nums[stk.top()] >= nums[i]) { + stk.pop(); + } + ans += (stk.size() ? stk.top() : n) - i; + stk.push(i); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1000-1099/1063.Number of Valid Subarrays/Solution2.go b/solution/1000-1099/1063.Number of Valid Subarrays/Solution2.go new file mode 100644 index 0000000000000..d98e0a5a0db6c --- /dev/null +++ b/solution/1000-1099/1063.Number of Valid Subarrays/Solution2.go @@ -0,0 +1,17 @@ +func validSubarrays(nums []int) (ans int) { + n := len(nums) + stk := []int{} + for i := n - 1; i >= 0; i-- { + for len(stk) > 0 && nums[stk[len(stk)-1]] >= nums[i] { + stk = stk[:len(stk)-1] + } + ans -= i + if len(stk) > 0 { + ans += stk[len(stk)-1] + } else { + ans += n + } + stk = append(stk, i) + } + return +} \ No newline at end of file diff --git a/solution/1000-1099/1063.Number of Valid Subarrays/Solution2.java b/solution/1000-1099/1063.Number of Valid Subarrays/Solution2.java new file mode 100644 index 0000000000000..ab96fc7528609 --- /dev/null +++ b/solution/1000-1099/1063.Number of Valid Subarrays/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public int validSubarrays(int[] nums) { + int n = nums.length; + Deque stk = new ArrayDeque<>(); + int ans = 0; + for (int i = n - 1; i >= 0; --i) { + while (!stk.isEmpty() && nums[stk.peek()] >= nums[i]) { + stk.pop(); + } + ans += (stk.isEmpty() ? n : stk.peek()) - i; + + stk.push(i); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1000-1099/1063.Number of Valid Subarrays/Solution2.py b/solution/1000-1099/1063.Number of Valid Subarrays/Solution2.py new file mode 100644 index 0000000000000..3a8baecc13962 --- /dev/null +++ b/solution/1000-1099/1063.Number of Valid Subarrays/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def validSubarrays(self, nums: List[int]) -> int: + n = len(nums) + stk = [] + ans = 0 + for i in range(n - 1, -1, -1): + while stk and nums[stk[-1]] >= nums[i]: + stk.pop() + ans += (stk[-1] if stk else n) - i + stk.append(i) + return ans diff --git a/solution/1000-1099/1063.Number of Valid Subarrays/Solution2.ts b/solution/1000-1099/1063.Number of Valid Subarrays/Solution2.ts new file mode 100644 index 0000000000000..07d1e9d470fbf --- /dev/null +++ b/solution/1000-1099/1063.Number of Valid Subarrays/Solution2.ts @@ -0,0 +1,13 @@ +function validSubarrays(nums: number[]): number { + const n = nums.length; + const stk: number[] = []; + let ans = 0; + for (let i = n - 1; ~i; --i) { + while (stk.length && nums[stk.at(-1)!] >= nums[i]) { + stk.pop(); + } + ans += (stk.at(-1) ?? n) - i; + stk.push(i); + } + return ans; +} diff --git a/solution/1000-1099/1065.Index Pairs of a String/Solution.py b/solution/1000-1099/1065.Index Pairs of a String/Solution.py index 6398612c768a9..08228a53f9bec 100644 --- a/solution/1000-1099/1065.Index Pairs of a String/Solution.py +++ b/solution/1000-1099/1065.Index Pairs of a String/Solution.py @@ -1,32 +1,7 @@ -class Trie: - def __init__(self): - self.children = [None] * 26 - self.is_end = False - - def insert(self, word): - node = self - for c in word: - idx = ord(c) - ord('a') - if node.children[idx] is None: - node.children[idx] = Trie() - node = node.children[idx] - node.is_end = True - - class Solution: def indexPairs(self, text: str, words: List[str]) -> List[List[int]]: - trie = Trie() - for w in words: - trie.insert(w) + words = set(words) n = len(text) - ans = [] - for i in range(n): - node = trie - for j in range(i, n): - idx = ord(text[j]) - ord('a') - if node.children[idx] is None: - break - node = node.children[idx] - if node.is_end: - ans.append([i, j]) - return ans + return [ + [i, j] for i in range(n) for j in range(i, n) if text[i : j + 1] in words + ] diff --git a/solution/1000-1099/1065.Index Pairs of a String/Solution2.py b/solution/1000-1099/1065.Index Pairs of a String/Solution2.py new file mode 100644 index 0000000000000..6398612c768a9 --- /dev/null +++ b/solution/1000-1099/1065.Index Pairs of a String/Solution2.py @@ -0,0 +1,32 @@ +class Trie: + def __init__(self): + self.children = [None] * 26 + self.is_end = False + + def insert(self, word): + node = self + for c in word: + idx = ord(c) - ord('a') + if node.children[idx] is None: + node.children[idx] = Trie() + node = node.children[idx] + node.is_end = True + + +class Solution: + def indexPairs(self, text: str, words: List[str]) -> List[List[int]]: + trie = Trie() + for w in words: + trie.insert(w) + n = len(text) + ans = [] + for i in range(n): + node = trie + for j in range(i, n): + idx = ord(text[j]) - ord('a') + if node.children[idx] is None: + break + node = node.children[idx] + if node.is_end: + ans.append([i, j]) + return ans diff --git a/solution/1000-1099/1070.Product Sales Analysis III/Solution.sql b/solution/1000-1099/1070.Product Sales Analysis III/Solution.sql index a4248aa86df71..76645ec4ce003 100644 --- a/solution/1000-1099/1070.Product Sales Analysis III/Solution.sql +++ b/solution/1000-1099/1070.Product Sales Analysis III/Solution.sql @@ -1,14 +1,15 @@ # Write your MySQL query statement below -WITH - T AS ( +SELECT + product_id, + year AS first_year, + quantity, + price +FROM Sales +WHERE + (product_id, year) IN ( SELECT - *, - RANK() OVER ( - PARTITION BY product_id - ORDER BY year - ) AS rk + product_id, + MIN(year) AS year FROM Sales - ) -SELECT product_id, year AS first_year, quantity, price -FROM T -WHERE rk = 1; + GROUP BY product_id + ); diff --git a/solution/1000-1099/1070.Product Sales Analysis III/Solution2.sql b/solution/1000-1099/1070.Product Sales Analysis III/Solution2.sql new file mode 100644 index 0000000000000..a4248aa86df71 --- /dev/null +++ b/solution/1000-1099/1070.Product Sales Analysis III/Solution2.sql @@ -0,0 +1,14 @@ +# Write your MySQL query statement below +WITH + T AS ( + SELECT + *, + RANK() OVER ( + PARTITION BY product_id + ORDER BY year + ) AS rk + FROM Sales + ) +SELECT product_id, year AS first_year, quantity, price +FROM T +WHERE rk = 1; diff --git a/solution/1000-1099/1071.Greatest Common Divisor of Strings/Solution.java b/solution/1000-1099/1071.Greatest Common Divisor of Strings/Solution.java index ce12f96ea2cc2..5276149026dcf 100644 --- a/solution/1000-1099/1071.Greatest Common Divisor of Strings/Solution.java +++ b/solution/1000-1099/1071.Greatest Common Divisor of Strings/Solution.java @@ -10,4 +10,4 @@ public String gcdOfStrings(String str1, String str2) { private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } -} +} \ No newline at end of file diff --git a/solution/1000-1099/1071.Greatest Common Divisor of Strings/Solution.py b/solution/1000-1099/1071.Greatest Common Divisor of Strings/Solution.py index a77eb8d037812..30bdef8ec189c 100644 --- a/solution/1000-1099/1071.Greatest Common Divisor of Strings/Solution.py +++ b/solution/1000-1099/1071.Greatest Common Divisor of Strings/Solution.py @@ -1,6 +1,13 @@ class Solution: def gcdOfStrings(self, str1: str, str2: str) -> str: - if str1 + str2 != str2 + str1: - return '' - n = gcd(len(str1), len(str2)) - return str1[:n] + def check(a, b): + c = "" + while len(c) < len(b): + c += a + return c == b + + for i in range(min(len(str1), len(str2)), 0, -1): + t = str1[:i] + if check(t, str1) and check(t, str2): + return t + return '' diff --git a/solution/1000-1099/1071.Greatest Common Divisor of Strings/Solution2.py b/solution/1000-1099/1071.Greatest Common Divisor of Strings/Solution2.py new file mode 100644 index 0000000000000..a77eb8d037812 --- /dev/null +++ b/solution/1000-1099/1071.Greatest Common Divisor of Strings/Solution2.py @@ -0,0 +1,6 @@ +class Solution: + def gcdOfStrings(self, str1: str, str2: str) -> str: + if str1 + str2 != str2 + str1: + return '' + n = gcd(len(str1), len(str2)) + return str1[:n] diff --git a/solution/1000-1099/1073.Adding Two Negabinary Numbers/Solution.cs b/solution/1000-1099/1073.Adding Two Negabinary Numbers/Solution.cs index e830ea7b30d14..7624f1e66eefb 100644 --- a/solution/1000-1099/1073.Adding Two Negabinary Numbers/Solution.cs +++ b/solution/1000-1099/1073.Adding Two Negabinary Numbers/Solution.cs @@ -22,4 +22,4 @@ public int[] AddNegabinary(int[] arr1, int[] arr2) { ans.Reverse(); return ans.ToArray(); } -} \ No newline at end of file +} diff --git a/solution/1000-1099/1076.Project Employees II/Solution.sql b/solution/1000-1099/1076.Project Employees II/Solution.sql index fe5891819ae71..86539f3005ecc 100644 --- a/solution/1000-1099/1076.Project Employees II/Solution.sql +++ b/solution/1000-1099/1076.Project Employees II/Solution.sql @@ -1,12 +1,10 @@ # Write your MySQL query statement below -WITH - T AS ( - SELECT - project_id, - RANK() OVER (ORDER BY COUNT(employee_id) DESC) AS rk - FROM Project - GROUP BY 1 - ) SELECT project_id -FROM T -WHERE rk = 1; +FROM Project +GROUP BY 1 +HAVING + COUNT(1) >= ALL ( + SELECT COUNT(1) + FROM Project + GROUP BY project_id + ); diff --git a/solution/1000-1099/1076.Project Employees II/Solution2.sql b/solution/1000-1099/1076.Project Employees II/Solution2.sql new file mode 100644 index 0000000000000..fe5891819ae71 --- /dev/null +++ b/solution/1000-1099/1076.Project Employees II/Solution2.sql @@ -0,0 +1,12 @@ +# Write your MySQL query statement below +WITH + T AS ( + SELECT + project_id, + RANK() OVER (ORDER BY COUNT(employee_id) DESC) AS rk + FROM Project + GROUP BY 1 + ) +SELECT project_id +FROM T +WHERE rk = 1; diff --git a/solution/1000-1099/1078.Occurrences After Bigram/Solution.java b/solution/1000-1099/1078.Occurrences After Bigram/Solution.java index b621f71fecff6..8d7578073aa3b 100644 --- a/solution/1000-1099/1078.Occurrences After Bigram/Solution.java +++ b/solution/1000-1099/1078.Occurrences After Bigram/Solution.java @@ -1,4 +1,5 @@ class Solution { + public String[] findOcurrences(String text, String first, String second) { String[] words = text.split(" "); List ans = new ArrayList<>(); diff --git a/solution/1000-1099/1081.Smallest Subsequence of Distinct Characters/Solution.java b/solution/1000-1099/1081.Smallest Subsequence of Distinct Characters/Solution.java index 11eac9727c85f..e4a9eab1c6db8 100644 --- a/solution/1000-1099/1081.Smallest Subsequence of Distinct Characters/Solution.java +++ b/solution/1000-1099/1081.Smallest Subsequence of Distinct Characters/Solution.java @@ -19,4 +19,4 @@ public String smallestSubsequence(String text) { } return String.valueOf(cs, 0, top + 1); } -} +} \ No newline at end of file diff --git a/solution/1000-1099/1081.Smallest Subsequence of Distinct Characters/Solution2.java b/solution/1000-1099/1081.Smallest Subsequence of Distinct Characters/Solution2.java new file mode 100644 index 0000000000000..c943153f8103e --- /dev/null +++ b/solution/1000-1099/1081.Smallest Subsequence of Distinct Characters/Solution2.java @@ -0,0 +1,27 @@ +class Solution { + public String smallestSubsequence(String s) { + int n = s.length(); + int[] last = new int[26]; + for (int i = 0; i < n; ++i) { + last[s.charAt(i) - 'a'] = i; + } + Deque stk = new ArrayDeque<>(); + int mask = 0; + for (int i = 0; i < n; ++i) { + char c = s.charAt(i); + if (((mask >> (c - 'a')) & 1) == 1) { + continue; + } + while (!stk.isEmpty() && stk.peek() > c && last[stk.peek() - 'a'] > i) { + mask ^= 1 << (stk.pop() - 'a'); + } + stk.push(c); + mask |= 1 << (c - 'a'); + } + StringBuilder ans = new StringBuilder(); + for (char c : stk) { + ans.append(c); + } + return ans.reverse().toString(); + } +} \ No newline at end of file diff --git a/solution/1000-1099/1082.Sales Analysis I/Solution.sql b/solution/1000-1099/1082.Sales Analysis I/Solution.sql index 9bee619e096dd..279b914870c35 100644 --- a/solution/1000-1099/1082.Sales Analysis I/Solution.sql +++ b/solution/1000-1099/1082.Sales Analysis I/Solution.sql @@ -1,12 +1,10 @@ -WITH - T AS ( - SELECT - seller_id, - SUM(price) AS tot, - RANK() OVER (ORDER BY SUM(price) DESC) AS rk +# Write your MySQL query statement below +SELECT seller_id +FROM Sales +GROUP BY seller_id +HAVING + SUM(price) >= ALL ( + SELECT SUM(price) FROM Sales GROUP BY seller_id - ) -SELECT seller_id -FROM T -WHERE rk = 1; + ); diff --git a/solution/1000-1099/1082.Sales Analysis I/Solution2.sql b/solution/1000-1099/1082.Sales Analysis I/Solution2.sql new file mode 100644 index 0000000000000..c44d29ba8f363 --- /dev/null +++ b/solution/1000-1099/1082.Sales Analysis I/Solution2.sql @@ -0,0 +1,13 @@ +# Write your MySQL query statement below +WITH + T AS ( + SELECT + seller_id, + SUM(price) AS tot, + RANK() OVER (ORDER BY SUM(price) DESC) AS rk + FROM Sales + GROUP BY seller_id + ) +SELECT seller_id +FROM T +WHERE rk = 1; diff --git a/solution/1000-1099/1085.Sum of Digits in the Minimum Number/Solution.cpp b/solution/1000-1099/1085.Sum of Digits in the Minimum Number/Solution.cpp index 90e5cc6f0ba7c..388a24ffff640 100644 --- a/solution/1000-1099/1085.Sum of Digits in the Minimum Number/Solution.cpp +++ b/solution/1000-1099/1085.Sum of Digits in the Minimum Number/Solution.cpp @@ -1,11 +1,11 @@ -class Solution { -public: - int sumOfDigits(vector& nums) { - int x = *min_element(nums.begin(), nums.end()); - int s = 0; - for (; x > 0; x /= 10) { - s += x % 10; - } - return s & 1 ^ 1; - } +class Solution { +public: + int sumOfDigits(vector& nums) { + int x = *min_element(nums.begin(), nums.end()); + int s = 0; + for (; x > 0; x /= 10) { + s += x % 10; + } + return s & 1 ^ 1; + } }; \ No newline at end of file diff --git a/solution/1000-1099/1085.Sum of Digits in the Minimum Number/Solution.java b/solution/1000-1099/1085.Sum of Digits in the Minimum Number/Solution.java index b3a57955ac1a0..5ee5cf3ba4735 100644 --- a/solution/1000-1099/1085.Sum of Digits in the Minimum Number/Solution.java +++ b/solution/1000-1099/1085.Sum of Digits in the Minimum Number/Solution.java @@ -1,13 +1,13 @@ -class Solution { - public int sumOfDigits(int[] nums) { - int x = 100; - for (int v : nums) { - x = Math.min(x, v); - } - int s = 0; - for (; x > 0; x /= 10) { - s += x % 10; - } - return s & 1 ^ 1; - } +class Solution { + public int sumOfDigits(int[] nums) { + int x = 100; + for (int v : nums) { + x = Math.min(x, v); + } + int s = 0; + for (; x > 0; x /= 10) { + s += x % 10; + } + return s & 1 ^ 1; + } } \ No newline at end of file diff --git a/solution/1000-1099/1085.Sum of Digits in the Minimum Number/Solution.py b/solution/1000-1099/1085.Sum of Digits in the Minimum Number/Solution.py index 58f614cd7679c..9c788fd47a9ce 100644 --- a/solution/1000-1099/1085.Sum of Digits in the Minimum Number/Solution.py +++ b/solution/1000-1099/1085.Sum of Digits in the Minimum Number/Solution.py @@ -1,8 +1,8 @@ -class Solution: - def sumOfDigits(self, nums: List[int]) -> int: - x = min(nums) - s = 0 - while x: - s += x % 10 - x //= 10 - return s & 1 ^ 1 +class Solution: + def sumOfDigits(self, nums: List[int]) -> int: + x = min(nums) + s = 0 + while x: + s += x % 10 + x //= 10 + return s & 1 ^ 1 diff --git a/solution/1000-1099/1086.High Five/Solution.java b/solution/1000-1099/1086.High Five/Solution.java index f4686508c87fc..31a5257ccf250 100644 --- a/solution/1000-1099/1086.High Five/Solution.java +++ b/solution/1000-1099/1086.High Five/Solution.java @@ -1,25 +1,37 @@ class Solution { public int[][] highFive(int[][] items) { - List[] d = new List[1001]; - Arrays.setAll(d, k -> new ArrayList<>()); - for (var item : items) { - int i = item[0], x = item[1]; - d[i].add(x); - } - for (var xs : d) { - xs.sort((a, b) -> b - a); + int size = 0; + PriorityQueue[] s = new PriorityQueue[101]; + int n = 5; + for (int[] item : items) { + int i = item[0], score = item[1]; + if (s[i] == null) { + ++size; + s[i] = new PriorityQueue<>(n); + } + s[i].offer(score); + if (s[i].size() > n) { + s[i].poll(); + } } - List ans = new ArrayList<>(); - for (int i = 1; i <= 1000; ++i) { - var xs = d[i]; - if (!xs.isEmpty()) { - int s = 0; - for (int j = 0; j < 5; ++j) { - s += xs.get(j); - } - ans.add(new int[] {i, s / 5}); + int[][] res = new int[size][2]; + int j = 0; + for (int i = 0; i < 101; ++i) { + if (s[i] == null) { + continue; } + int avg = sum(s[i]) / n; + res[j][0] = i; + res[j++][1] = avg; + } + return res; + } + + private int sum(PriorityQueue q) { + int s = 0; + while (!q.isEmpty()) { + s += q.poll(); } - return ans.toArray(new int[0][]); + return s; } } \ No newline at end of file diff --git a/solution/1000-1099/1091.Shortest Path in Binary Matrix/Solution.py b/solution/1000-1099/1091.Shortest Path in Binary Matrix/Solution.py index 46697a6e661d5..dfd8b25540d2d 100644 --- a/solution/1000-1099/1091.Shortest Path in Binary Matrix/Solution.py +++ b/solution/1000-1099/1091.Shortest Path in Binary Matrix/Solution.py @@ -1,20 +1,20 @@ -class Solution: - def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int: - if grid[0][0]: - return -1 - n = len(grid) - grid[0][0] = 1 - q = deque([(0, 0)]) - ans = 1 - while q: - for _ in range(len(q)): - i, j = q.popleft() - if i == j == n - 1: - return ans - for x in range(i - 1, i + 2): - for y in range(j - 1, j + 2): - if 0 <= x < n and 0 <= y < n and grid[x][y] == 0: - grid[x][y] = 1 - q.append((x, y)) - ans += 1 - return -1 +class Solution: + def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int: + if grid[0][0]: + return -1 + n = len(grid) + grid[0][0] = 1 + q = deque([(0, 0)]) + ans = 1 + while q: + for _ in range(len(q)): + i, j = q.popleft() + if i == j == n - 1: + return ans + for x in range(i - 1, i + 2): + for y in range(j - 1, j + 2): + if 0 <= x < n and 0 <= y < n and grid[x][y] == 0: + grid[x][y] = 1 + q.append((x, y)) + ans += 1 + return -1 diff --git a/solution/1000-1099/1094.Car Pooling/Solution.cs b/solution/1000-1099/1094.Car Pooling/Solution.cs index 3cefdc57eb99f..0aab4dc770599 100644 --- a/solution/1000-1099/1094.Car Pooling/Solution.cs +++ b/solution/1000-1099/1094.Car Pooling/Solution.cs @@ -1,19 +1,19 @@ -public class Solution { - public bool CarPooling(int[][] trips, int capacity) { - int mx = trips.Max(x => x[2]); - int[] d = new int[mx + 1]; - foreach (var trip in trips) { - int x = trip[0], f = trip[1], t = trip[2]; - d[f] += x; - d[t] -= x; - } - int s = 0; - foreach (var x in d) { - s += x; - if (s > capacity) { - return false; - } - } - return true; - } -} \ No newline at end of file +public class Solution { + public bool CarPooling(int[][] trips, int capacity) { + int mx = trips.Max(x => x[2]); + int[] d = new int[mx + 1]; + foreach (var trip in trips) { + int x = trip[0], f = trip[1], t = trip[2]; + d[f] += x; + d[t] -= x; + } + int s = 0; + foreach (var x in d) { + s += x; + if (s > capacity) { + return false; + } + } + return true; + } +} diff --git a/solution/1000-1099/1094.Car Pooling/Solution.go b/solution/1000-1099/1094.Car Pooling/Solution.go index 1ee5596dd56c8..95c9c3d009eab 100644 --- a/solution/1000-1099/1094.Car Pooling/Solution.go +++ b/solution/1000-1099/1094.Car Pooling/Solution.go @@ -1,6 +1,5 @@ func carPooling(trips [][]int, capacity int) bool { - mx := slices.Max(trips, func(i int) int { return trips[i][2] }) - d := make([]int, mx+1) + d := [1001]int{} for _, trip := range trips { x, f, t := trip[0], trip[1], trip[2] d[f] += x diff --git a/solution/1000-1099/1094.Car Pooling/Solution.py b/solution/1000-1099/1094.Car Pooling/Solution.py index a21c5887681fb..24eb02c6139e3 100644 --- a/solution/1000-1099/1094.Car Pooling/Solution.py +++ b/solution/1000-1099/1094.Car Pooling/Solution.py @@ -1,8 +1,8 @@ -class Solution: - def carPooling(self, trips: List[List[int]], capacity: int) -> bool: - mx = max(e[2] for e in trips) - d = [0] * (mx + 1) - for x, f, t in trips: - d[f] += x - d[t] -= x - return all(s <= capacity for s in accumulate(d)) +class Solution: + def carPooling(self, trips: List[List[int]], capacity: int) -> bool: + mx = max(e[2] for e in trips) + d = [0] * (mx + 1) + for x, f, t in trips: + d[f] += x + d[t] -= x + return all(s <= capacity for s in accumulate(d)) diff --git a/solution/1000-1099/1099.Two Sum Less Than K/Solution.cpp b/solution/1000-1099/1099.Two Sum Less Than K/Solution.cpp index 76e32836b61d2..11834c6937180 100644 --- a/solution/1000-1099/1099.Two Sum Less Than K/Solution.cpp +++ b/solution/1000-1099/1099.Two Sum Less Than K/Solution.cpp @@ -2,14 +2,11 @@ class Solution { public: int twoSumLessThanK(vector& nums, int k) { sort(nums.begin(), nums.end()); - int ans = -1; - for (int i = 0, j = nums.size() - 1; i < j;) { - int s = nums[i] + nums[j]; - if (s < k) { - ans = max(ans, s); - ++i; - } else { - --j; + int ans = -1, n = nums.size(); + for (int i = 0; i < n; ++i) { + int j = lower_bound(nums.begin() + i + 1, nums.end(), k - nums[i]) - nums.begin() - 1; + if (i < j) { + ans = max(ans, nums[i] + nums[j]); } } return ans; diff --git a/solution/1000-1099/1099.Two Sum Less Than K/Solution.go b/solution/1000-1099/1099.Two Sum Less Than K/Solution.go index 16310759686fa..3788fbbc41f7a 100644 --- a/solution/1000-1099/1099.Two Sum Less Than K/Solution.go +++ b/solution/1000-1099/1099.Two Sum Less Than K/Solution.go @@ -1,12 +1,10 @@ func twoSumLessThanK(nums []int, k int) int { sort.Ints(nums) ans := -1 - for i, j := 0, len(nums)-1; i < j; { - if s := nums[i] + nums[j]; s < k { - ans = max(ans, s) - i++ - } else { - j-- + for i, x := range nums { + j := sort.SearchInts(nums[i+1:], k-x) + i + if v := nums[i] + nums[j]; i < j && ans < v { + ans = v } } return ans diff --git a/solution/1000-1099/1099.Two Sum Less Than K/Solution.java b/solution/1000-1099/1099.Two Sum Less Than K/Solution.java index c1a88d773a6fb..97ae609bd3694 100644 --- a/solution/1000-1099/1099.Two Sum Less Than K/Solution.java +++ b/solution/1000-1099/1099.Two Sum Less Than K/Solution.java @@ -2,15 +2,25 @@ class Solution { public int twoSumLessThanK(int[] nums, int k) { Arrays.sort(nums); int ans = -1; - for (int i = 0, j = nums.length - 1; i < j;) { - int s = nums[i] + nums[j]; - if (s < k) { - ans = Math.max(ans, s); - ++i; - } else { - --j; + int n = nums.length; + for (int i = 0; i < n; ++i) { + int j = search(nums, k - nums[i], i + 1, n) - 1; + if (i < j) { + ans = Math.max(ans, nums[i] + nums[j]); } } return ans; } + + private int search(int[] nums, int x, int l, int r) { + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } } \ No newline at end of file diff --git a/solution/1000-1099/1099.Two Sum Less Than K/Solution.py b/solution/1000-1099/1099.Two Sum Less Than K/Solution.py index 7eeeba9b0ec8e..9eccfd09b8b3f 100644 --- a/solution/1000-1099/1099.Two Sum Less Than K/Solution.py +++ b/solution/1000-1099/1099.Two Sum Less Than K/Solution.py @@ -1,12 +1,9 @@ class Solution: def twoSumLessThanK(self, nums: List[int], k: int) -> int: nums.sort() - i, j = 0, len(nums) - 1 ans = -1 - while i < j: - if (s := nums[i] + nums[j]) < k: - ans = max(ans, s) - i += 1 - else: - j -= 1 + for i, x in enumerate(nums): + j = bisect_left(nums, k - x, lo=i + 1) - 1 + if i < j: + ans = max(ans, x + nums[j]) return ans diff --git a/solution/1000-1099/1099.Two Sum Less Than K/Solution2.cpp b/solution/1000-1099/1099.Two Sum Less Than K/Solution2.cpp new file mode 100644 index 0000000000000..76e32836b61d2 --- /dev/null +++ b/solution/1000-1099/1099.Two Sum Less Than K/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int twoSumLessThanK(vector& nums, int k) { + sort(nums.begin(), nums.end()); + int ans = -1; + for (int i = 0, j = nums.size() - 1; i < j;) { + int s = nums[i] + nums[j]; + if (s < k) { + ans = max(ans, s); + ++i; + } else { + --j; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1000-1099/1099.Two Sum Less Than K/Solution2.go b/solution/1000-1099/1099.Two Sum Less Than K/Solution2.go new file mode 100644 index 0000000000000..16310759686fa --- /dev/null +++ b/solution/1000-1099/1099.Two Sum Less Than K/Solution2.go @@ -0,0 +1,13 @@ +func twoSumLessThanK(nums []int, k int) int { + sort.Ints(nums) + ans := -1 + for i, j := 0, len(nums)-1; i < j; { + if s := nums[i] + nums[j]; s < k { + ans = max(ans, s) + i++ + } else { + j-- + } + } + return ans +} \ No newline at end of file diff --git a/solution/1000-1099/1099.Two Sum Less Than K/Solution2.java b/solution/1000-1099/1099.Two Sum Less Than K/Solution2.java new file mode 100644 index 0000000000000..c1a88d773a6fb --- /dev/null +++ b/solution/1000-1099/1099.Two Sum Less Than K/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public int twoSumLessThanK(int[] nums, int k) { + Arrays.sort(nums); + int ans = -1; + for (int i = 0, j = nums.length - 1; i < j;) { + int s = nums[i] + nums[j]; + if (s < k) { + ans = Math.max(ans, s); + ++i; + } else { + --j; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1000-1099/1099.Two Sum Less Than K/Solution2.py b/solution/1000-1099/1099.Two Sum Less Than K/Solution2.py new file mode 100644 index 0000000000000..7eeeba9b0ec8e --- /dev/null +++ b/solution/1000-1099/1099.Two Sum Less Than K/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def twoSumLessThanK(self, nums: List[int], k: int) -> int: + nums.sort() + i, j = 0, len(nums) - 1 + ans = -1 + while i < j: + if (s := nums[i] + nums[j]) < k: + ans = max(ans, s) + i += 1 + else: + j -= 1 + return ans diff --git a/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/Solution.php b/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/Solution.php index c964b19cefb1b..6944cf9fd5e20 100644 --- a/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/Solution.php +++ b/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/Solution.php @@ -19,4 +19,4 @@ function numKLenSubstrNoRepeats($s, $k) { } return $cnt; } -} \ No newline at end of file +} diff --git a/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/Solution2.cpp b/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/Solution2.cpp new file mode 100644 index 0000000000000..98d5940439546 --- /dev/null +++ b/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/Solution2.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int numKLenSubstrNoRepeats(string s, int k) { + int n = s.size(); + if (k > n) { + return 0; + } + unordered_map cnt; + for (int i = 0; i < k; ++i) { + cnt[s[i]]++; + } + int ans = cnt.size() == k ? 1 : 0; + for (int i = k; i < n; ++i) { + cnt[s[i]]++; + cnt[s[i - k]]--; + if (cnt[s[i - k]] == 0) { + cnt.erase(s[i - k]); + } + ans += cnt.size() == k ? 1 : 0; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/Solution2.go b/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/Solution2.go new file mode 100644 index 0000000000000..ef6cea2bd1638 --- /dev/null +++ b/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/Solution2.go @@ -0,0 +1,24 @@ +func numKLenSubstrNoRepeats(s string, k int) (ans int) { + n := len(s) + if k > n { + return 0 + } + cnt := map[byte]int{} + for i := 0; i < k; i++ { + cnt[s[i]]++ + } + if len(cnt) == k { + ans++ + } + for i := k; i < n; i++ { + cnt[s[i]]++ + cnt[s[i-k]]-- + if cnt[s[i-k]] == 0 { + delete(cnt, s[i-k]) + } + if len(cnt) == k { + ans++ + } + } + return +} \ No newline at end of file diff --git a/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/Solution2.java b/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/Solution2.java new file mode 100644 index 0000000000000..ff196695151bf --- /dev/null +++ b/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/Solution2.java @@ -0,0 +1,21 @@ +class Solution { + public int numKLenSubstrNoRepeats(String s, int k) { + int n = s.length(); + if (k > n) { + return 0; + } + Map cnt = new HashMap<>(k); + for (int i = 0; i < k; ++i) { + cnt.merge(s.charAt(i), 1, Integer::sum); + } + int ans = cnt.size() == k ? 1 : 0; + for (int i = k; i < n; ++i) { + cnt.merge(s.charAt(i), 1, Integer::sum); + if (cnt.merge(s.charAt(i - k), -1, Integer::sum) == 0) { + cnt.remove(s.charAt(i - k)); + } + ans += cnt.size() == k ? 1 : 0; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/Solution2.py b/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/Solution2.py new file mode 100644 index 0000000000000..9ddf835b97cf6 --- /dev/null +++ b/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def numKLenSubstrNoRepeats(self, s: str, k: int) -> int: + n = len(s) + if k > n: + return 0 + cnt = Counter(s[:k]) + ans = int(len(cnt) == k) + for i in range(k, n): + cnt[s[i]] += 1 + cnt[s[i - k]] -= 1 + if cnt[s[i - k]] == 0: + cnt.pop(s[i - k]) + ans += len(cnt) == k + return ans diff --git a/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution2.cpp b/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution2.cpp new file mode 100644 index 0000000000000..7f6f21dc9dcf2 --- /dev/null +++ b/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution2.cpp @@ -0,0 +1,48 @@ +class UnionFind { +public: + UnionFind(int n) { + p = vector(n); + size = vector(n, 1); + iota(p.begin(), p.end(), 0); + } + + bool unite(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) { + return false; + } + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + return true; + } + + int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + +private: + vector p, size; +}; + +class Solution { +public: + int earliestAcq(vector>& logs, int n) { + sort(logs.begin(), logs.end()); + UnionFind uf(n); + for (auto& log : logs) { + int t = log[0], x = log[1], y = log[2]; + if (uf.unite(x, y) && --n == 1) { + return t; + } + } + return -1; + } +}; \ No newline at end of file diff --git a/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution2.go b/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution2.go new file mode 100644 index 0000000000000..92def63e583a7 --- /dev/null +++ b/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution2.go @@ -0,0 +1,50 @@ +type unionFind struct { + p, size []int +} + +func newUnionFind(n int) *unionFind { + p := make([]int, n) + size := make([]int, n) + for i := range p { + p[i] = i + size[i] = 1 + } + return &unionFind{p, size} +} + +func (uf *unionFind) find(x int) int { + if uf.p[x] != x { + uf.p[x] = uf.find(uf.p[x]) + } + return uf.p[x] +} + +func (uf *unionFind) union(a, b int) bool { + pa, pb := uf.find(a), uf.find(b) + if pa == pb { + return false + } + if uf.size[pa] > uf.size[pb] { + uf.p[pb] = pa + uf.size[pa] += uf.size[pb] + } else { + uf.p[pa] = pb + uf.size[pb] += uf.size[pa] + } + return true +} + +func earliestAcq(logs [][]int, n int) int { + sort.Slice(logs, func(i, j int) bool { return logs[i][0] < logs[j][0] }) + uf := newUnionFind(n) + for _, log := range logs { + t, x, y := log[0], log[1], log[2] + if uf.union(x, y) { + n-- + if n == 1 { + return t + } + } + } + return -1 +} \ No newline at end of file diff --git a/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution2.java b/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution2.java new file mode 100644 index 0000000000000..f1e8e6b9dbdee --- /dev/null +++ b/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution2.java @@ -0,0 +1,49 @@ +class UnionFind { + private int[] p; + private int[] size; + + public UnionFind(int n) { + p = new int[n]; + size = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + size[i] = 1; + } + } + + public int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + + public boolean union(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) { + return false; + } + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + return true; + } +} + +class Solution { + public int earliestAcq(int[][] logs, int n) { + Arrays.sort(logs, (a, b) -> a[0] - b[0]); + UnionFind uf = new UnionFind(n); + for (int[] log : logs) { + int t = log[0], x = log[1], y = log[2]; + if (uf.union(x, y) && --n == 1) { + return t; + } + } + return -1; + } +} \ No newline at end of file diff --git a/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution2.py b/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution2.py new file mode 100644 index 0000000000000..c8d5e193be523 --- /dev/null +++ b/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution2.py @@ -0,0 +1,34 @@ +class UnionFind: + __slots__ = ('p', 'size') + + def __init__(self, n): + self.p = list(range(n)) + self.size = [1] * n + + def find(self, x: int) -> int: + if self.p[x] != x: + self.p[x] = self.find(self.p[x]) + return self.p[x] + + def union(self, a: int, b: int) -> bool: + pa, pb = self.find(a), self.find(b) + if pa == pb: + return False + if self.size[pa] > self.size[pb]: + self.p[pb] = pa + self.size[pa] += self.size[pb] + else: + self.p[pa] = pb + self.size[pb] += self.size[pa] + return True + + +class Solution: + def earliestAcq(self, logs: List[List[int]], n: int) -> int: + uf = UnionFind(n) + for t, x, y in sorted(logs): + if uf.union(x, y): + n -= 1 + if n == 1: + return t + return -1 diff --git a/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution2.ts b/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution2.ts new file mode 100644 index 0000000000000..11c7ba8b9b928 --- /dev/null +++ b/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution2.ts @@ -0,0 +1,45 @@ +class UnionFind { + private p: number[]; + private size: number[]; + + constructor(n: number) { + this.p = Array(n) + .fill(0) + .map((_, i) => i); + this.size = Array(n).fill(1); + } + + find(x: number): number { + if (this.p[x] !== x) { + this.p[x] = this.find(this.p[x]); + } + return this.p[x]; + } + + union(a: number, b: number): boolean { + const pa = this.find(a); + const pb = this.find(b); + if (pa === pb) { + return false; + } + if (this.size[pa] > this.size[pb]) { + this.p[pb] = pa; + this.size[pa] += this.size[pb]; + } else { + this.p[pa] = pb; + this.size[pb] += this.size[pa]; + } + return true; + } +} + +function earliestAcq(logs: number[][], n: number): number { + logs.sort((a, b) => a[0] - b[0]); + const uf = new UnionFind(n); + for (const [t, x, y] of logs) { + if (uf.union(x, y) && --n === 1) { + return t; + } + } + return -1; +} diff --git a/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution.py b/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution.py index 7776ce6aa0c86..df2f788f21f80 100644 --- a/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution.py +++ b/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution.py @@ -1,23 +1,23 @@ -class Solution: - def maximumMinimumPath(self, grid: List[List[int]]) -> int: - def find(x: int) -> int: - if p[x] != x: - p[x] = find(p[x]) - return p[x] - - m, n = len(grid), len(grid[0]) - p = list(range(m * n)) - q = [(v, i, j) for i, row in enumerate(grid) for j, v in enumerate(row)] - q.sort() - ans = 0 - dirs = (-1, 0, 1, 0, -1) - vis = set() - while find(0) != find(m * n - 1): - v, i, j = q.pop() - ans = v - vis.add((i, j)) - for a, b in pairwise(dirs): - x, y = i + a, j + b - if (x, y) in vis: - p[find(i * n + j)] = find(x * n + y) - return ans +class Solution: + def maximumMinimumPath(self, grid: List[List[int]]) -> int: + def find(x: int) -> int: + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + m, n = len(grid), len(grid[0]) + p = list(range(m * n)) + q = [(v, i, j) for i, row in enumerate(grid) for j, v in enumerate(row)] + q.sort() + ans = 0 + dirs = (-1, 0, 1, 0, -1) + vis = set() + while find(0) != find(m * n - 1): + v, i, j = q.pop() + ans = v + vis.add((i, j)) + for a, b in pairwise(dirs): + x, y = i + a, j + b + if (x, y) in vis: + p[find(i * n + j)] = find(x * n + y) + return ans diff --git a/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution2.cpp b/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution2.cpp new file mode 100644 index 0000000000000..ba515204fa97f --- /dev/null +++ b/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution2.cpp @@ -0,0 +1,64 @@ +class UnionFind { +public: + UnionFind(int n) { + p = vector(n); + size = vector(n, 1); + iota(p.begin(), p.end(), 0); + } + + void unite(int a, int b) { + int pa = find(a), pb = find(b); + if (pa != pb) { + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + } + } + + int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + +private: + vector p, size; +}; + +class Solution { +public: + int maximumMinimumPath(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + vector> q; + UnionFind uf(m * n); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + q.emplace_back(grid[i][j], i, j); + } + } + sort(q.begin(), q.end(), greater>()); + int ans = 0; + int dirs[5] = {-1, 0, 1, 0, -1}; + bool vis[m][n]; + memset(vis, false, sizeof(vis)); + for (auto& [v, i, j] : q) { + vis[i][j] = true; + ans = v; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && vis[x][y]) { + uf.unite(x * n + y, i * n + j); + } + } + if (uf.find(0) == uf.find(m * n - 1)) { + break; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution2.go b/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution2.go new file mode 100644 index 0000000000000..c2be711ba5399 --- /dev/null +++ b/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution2.go @@ -0,0 +1,63 @@ +type unionFind struct { + p, size []int +} + +func newUnionFind(n int) *unionFind { + p := make([]int, n) + size := make([]int, n) + for i := range p { + p[i] = i + size[i] = 1 + } + return &unionFind{p, size} +} + +func (uf *unionFind) find(x int) int { + if uf.p[x] != x { + uf.p[x] = uf.find(uf.p[x]) + } + return uf.p[x] +} + +func (uf *unionFind) union(a, b int) { + pa, pb := uf.find(a), uf.find(b) + if pa != pb { + if uf.size[pa] > uf.size[pb] { + uf.p[pb] = pa + uf.size[pa] += uf.size[pb] + } else { + uf.p[pa] = pb + uf.size[pb] += uf.size[pa] + } + } +} + +func maximumMinimumPath(grid [][]int) (ans int) { + m, n := len(grid), len(grid[0]) + uf := newUnionFind(m * n) + vis := make([][]bool, m) + q := [][3]int{} + for i, row := range grid { + vis[i] = make([]bool, n) + for j, v := range row { + q = append(q, [3]int{v, i, j}) + } + } + sort.Slice(q, func(i, j int) bool { return q[i][0] > q[j][0] }) + dirs := [5]int{-1, 0, 1, 0, -1} + for _, t := range q { + v, i, j := t[0], t[1], t[2] + ans = v + vis[i][j] = true + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if 0 <= x && x < m && 0 <= y && y < n && vis[x][y] { + uf.union(x*n+y, i*n+j) + } + } + if uf.find(0) == uf.find(m*n-1) { + break + } + } + return +} \ No newline at end of file diff --git a/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution2.java b/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution2.java new file mode 100644 index 0000000000000..6c1d3cb457a06 --- /dev/null +++ b/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution2.java @@ -0,0 +1,62 @@ +class UnionFind { + private int[] p; + private int[] size; + + public UnionFind(int n) { + p = new int[n]; + size = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + size[i] = 1; + } + } + + public int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + + public void union(int a, int b) { + int pa = find(a), pb = find(b); + if (pa != pb) { + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + } + } +} + +class Solution { + public int maximumMinimumPath(int[][] grid) { + int m = grid.length, n = grid[0].length; + UnionFind uf = new UnionFind(m * n); + List q = new ArrayList<>(); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + q.add(new int[] {grid[i][j], i, j}); + } + } + q.sort((a, b) -> b[0] - a[0]); + boolean[][] vis = new boolean[m][n]; + int[] dirs = {-1, 0, 1, 0, -1}; + int ans = 0; + for (int i = 0; uf.find(0) != uf.find(m * n - 1); ++i) { + int[] t = q.get(i); + vis[t[1]][t[2]] = true; + ans = t[0]; + for (int k = 0; k < 4; ++k) { + int x = t[1] + dirs[k], y = t[2] + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && vis[x][y]) { + uf.union(x * n + y, t[1] * n + t[2]); + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution2.py b/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution2.py new file mode 100644 index 0000000000000..20c45f775a199 --- /dev/null +++ b/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution2.py @@ -0,0 +1,43 @@ +class UnionFind: + __slots__ = ("p", "size") + + def __init__(self, n): + self.p = list(range(n)) + self.size = [1] * n + + def find(self, x: int) -> int: + if self.p[x] != x: + self.p[x] = self.find(self.p[x]) + return self.p[x] + + def union(self, a: int, b: int) -> bool: + pa, pb = self.find(a), self.find(b) + if pa == pb: + return False + if self.size[pa] > self.size[pb]: + self.p[pb] = pa + self.size[pa] += self.size[pb] + else: + self.p[pa] = pb + self.size[pb] += self.size[pa] + return True + + +class Solution: + def maximumMinimumPath(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + uf = UnionFind(m * n) + q = [(v, i, j) for i, row in enumerate(grid) for j, v in enumerate(row)] + q.sort() + ans = 0 + vis = set() + dirs = (-1, 0, 1, 0, -1) + while uf.find(0) != uf.find(m * n - 1): + v, i, j = q.pop() + ans = v + vis.add((i, j)) + for a, b in pairwise(dirs): + x, y = i + a, j + b + if (x, y) in vis: + uf.union(x * n + y, i * n + j) + return ans diff --git a/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution2.ts b/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution2.ts new file mode 100644 index 0000000000000..60b8bdba99749 --- /dev/null +++ b/solution/1100-1199/1102.Path With Maximum Minimum Value/Solution2.ts @@ -0,0 +1,64 @@ +class UnionFind { + private p: number[]; + private size: number[]; + + constructor(n: number) { + this.p = Array(n) + .fill(0) + .map((_, i) => i); + this.size = Array(n).fill(1); + } + + find(x: number): number { + if (this.p[x] !== x) { + this.p[x] = this.find(this.p[x]); + } + return this.p[x]; + } + + union(a: number, b: number): boolean { + const pa = this.find(a); + const pb = this.find(b); + if (pa === pb) { + return false; + } + if (this.size[pa] > this.size[pb]) { + this.p[pb] = pa; + this.size[pa] += this.size[pb]; + } else { + this.p[pa] = pb; + this.size[pb] += this.size[pa]; + } + return true; + } +} + +function maximumMinimumPath(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const q: number[][] = []; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + q.push([grid[i][j], i, j]); + } + } + q.sort((a, b) => b[0] - a[0]); + const dirs: number[] = [-1, 0, 1, 0, -1]; + const vis: boolean[][] = Array(m) + .fill(0) + .map(() => Array(n).fill(false)); + let ans = 0; + const uf = new UnionFind(m * n); + for (let k = 0; uf.find(0) !== uf.find(m * n - 1); ++k) { + const [t, i, j] = q[k]; + ans = t; + vis[i][j] = true; + for (let d = 0; d < 4; ++d) { + const [x, y] = [i + dirs[d], j + dirs[d + 1]]; + if (x >= 0 && x < m && y >= 0 && y < n && vis[x][y]) { + uf.union(i * n + j, x * n + y); + } + } + } + return ans; +} diff --git a/solution/1100-1199/1105.Filling Bookcase Shelves/Solution.cs b/solution/1100-1199/1105.Filling Bookcase Shelves/Solution.cs index 51d7db8e21ab0..9a0e89bd67564 100644 --- a/solution/1100-1199/1105.Filling Bookcase Shelves/Solution.cs +++ b/solution/1100-1199/1105.Filling Bookcase Shelves/Solution.cs @@ -16,4 +16,4 @@ public int MinHeightShelves(int[][] books, int shelfWidth) { } return f[n]; } -} \ No newline at end of file +} diff --git a/solution/1100-1199/1109.Corporate Flight Bookings/Solution.py b/solution/1100-1199/1109.Corporate Flight Bookings/Solution.py index 18cf4b64a441f..03a97fa06d70e 100644 --- a/solution/1100-1199/1109.Corporate Flight Bookings/Solution.py +++ b/solution/1100-1199/1109.Corporate Flight Bookings/Solution.py @@ -1,8 +1,8 @@ -class Solution: - def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: - ans = [0] * n - for first, last, seats in bookings: - ans[first - 1] += seats - if last < n: - ans[last] -= seats - return list(accumulate(ans)) +class Solution: + def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: + ans = [0] * n + for first, last, seats in bookings: + ans[first - 1] += seats + if last < n: + ans[last] -= seats + return list(accumulate(ans)) diff --git a/solution/1100-1199/1109.Corporate Flight Bookings/Solution2.cpp b/solution/1100-1199/1109.Corporate Flight Bookings/Solution2.cpp new file mode 100644 index 0000000000000..03bc222e8082c --- /dev/null +++ b/solution/1100-1199/1109.Corporate Flight Bookings/Solution2.cpp @@ -0,0 +1,43 @@ +class BinaryIndexedTree { +public: + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + int query(int x) { + int s = 0; + while (x) { + s += c[x]; + x -= x & -x; + } + return s; + } + +private: + int n; + vector c; +}; + +class Solution { +public: + vector corpFlightBookings(vector>& bookings, int n) { + BinaryIndexedTree* tree = new BinaryIndexedTree(n); + for (auto& e : bookings) { + int first = e[0], last = e[1], seats = e[2]; + tree->update(first, seats); + tree->update(last + 1, -seats); + } + vector ans(n); + for (int i = 0; i < n; ++i) { + ans[i] = tree->query(i + 1); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1100-1199/1109.Corporate Flight Bookings/Solution2.go b/solution/1100-1199/1109.Corporate Flight Bookings/Solution2.go new file mode 100644 index 0000000000000..5582c1d715d0b --- /dev/null +++ b/solution/1100-1199/1109.Corporate Flight Bookings/Solution2.go @@ -0,0 +1,39 @@ +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) update(x, delta int) { + for x <= this.n { + this.c[x] += delta + x += x & -x + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= x & -x + } + return s +} + +func corpFlightBookings(bookings [][]int, n int) []int { + tree := newBinaryIndexedTree(n) + for _, e := range bookings { + first, last, seats := e[0], e[1], e[2] + tree.update(first, seats) + tree.update(last+1, -seats) + } + ans := make([]int, n) + for i := range ans { + ans[i] = tree.query(i + 1) + } + return ans +} \ No newline at end of file diff --git a/solution/1100-1199/1109.Corporate Flight Bookings/Solution2.java b/solution/1100-1199/1109.Corporate Flight Bookings/Solution2.java new file mode 100644 index 0000000000000..cdc5af7fb5800 --- /dev/null +++ b/solution/1100-1199/1109.Corporate Flight Bookings/Solution2.java @@ -0,0 +1,41 @@ +class Solution { + public int[] corpFlightBookings(int[][] bookings, int n) { + BinaryIndexedTree tree = new BinaryIndexedTree(n); + for (var e : bookings) { + int first = e[0], last = e[1], seats = e[2]; + tree.update(first, seats); + tree.update(last + 1, -seats); + } + int[] ans = new int[n]; + for (int i = 0; i < n; ++i) { + ans[i] = tree.query(i + 1); + } + return ans; + } +} + +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +} \ No newline at end of file diff --git a/solution/1100-1199/1109.Corporate Flight Bookings/Solution2.py b/solution/1100-1199/1109.Corporate Flight Bookings/Solution2.py new file mode 100644 index 0000000000000..6f843e71ebfe9 --- /dev/null +++ b/solution/1100-1199/1109.Corporate Flight Bookings/Solution2.py @@ -0,0 +1,25 @@ +class BinaryIndexedTree: + def __init__(self, n): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x, delta): + while x <= self.n: + self.c[x] += delta + x += x & -x + + def query(self, x): + s = 0 + while x: + s += self.c[x] + x -= x & -x + return s + + +class Solution: + def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: + tree = BinaryIndexedTree(n) + for first, last, seats in bookings: + tree.update(first, seats) + tree.update(last + 1, -seats) + return [tree.query(i + 1) for i in range(n)] diff --git a/solution/1100-1199/1112.Highest Grade For Each Student/Solution2.sql b/solution/1100-1199/1112.Highest Grade For Each Student/Solution2.sql new file mode 100644 index 0000000000000..66d405c496c17 --- /dev/null +++ b/solution/1100-1199/1112.Highest Grade For Each Student/Solution2.sql @@ -0,0 +1,11 @@ +# Write your MySQL query statement below +SELECT student_id, MIN(course_id) AS course_id, grade +FROM Enrollments +WHERE + (student_id, grade) IN ( + SELECT student_id, MAX(grade) AS grade + FROM Enrollments + GROUP BY 1 + ) +GROUP BY 1 +ORDER BY 1; diff --git a/solution/1100-1199/1114.Print in Order/Solution.cpp b/solution/1100-1199/1114.Print in Order/Solution.cpp index 63d2be83584d8..f47f961078829 100644 --- a/solution/1100-1199/1114.Print in Order/Solution.cpp +++ b/solution/1100-1199/1114.Print in Order/Solution.cpp @@ -1,34 +1,26 @@ -#include - class Foo { private: - sem_t a, b, c; + mutex m2, m3; public: Foo() { - sem_init(&a, 0, 1); - sem_init(&b, 0, 0); - sem_init(&c, 0, 0); + m2.lock(); + m3.lock(); } void first(function printFirst) { - sem_wait(&a); - // printFirst() outputs "first". Do not change or remove this line. printFirst(); - sem_post(&b); + m2.unlock(); } void second(function printSecond) { - sem_wait(&b); - // printSecond() outputs "second". Do not change or remove this line. + m2.lock(); printSecond(); - sem_post(&c); + m3.unlock(); } void third(function printThird) { - sem_wait(&c); - // printThird() outputs "third". Do not change or remove this line. + m3.lock(); printThird(); - sem_post(&a); } }; \ No newline at end of file diff --git a/solution/1100-1199/1114.Print in Order/Solution.py b/solution/1100-1199/1114.Print in Order/Solution.py index 917e611ccd92a..a69130bc2d379 100644 --- a/solution/1100-1199/1114.Print in Order/Solution.py +++ b/solution/1100-1199/1114.Print in Order/Solution.py @@ -1,26 +1,19 @@ -from threading import Semaphore - - class Foo: def __init__(self): - self.a = Semaphore(1) - self.b = Semaphore(0) - self.c = Semaphore(0) + self.l2 = threading.Lock() + self.l3 = threading.Lock() + self.l2.acquire() + self.l3.acquire() - def first(self, printFirst: "Callable[[], None]") -> None: - self.a.acquire() - # printFirst() outputs "first". Do not change or remove this line. + def first(self, printFirst: 'Callable[[], None]') -> None: printFirst() - self.b.release() + self.l2.release() - def second(self, printSecond: "Callable[[], None]") -> None: - self.b.acquire() - # printSecond() outputs "second". Do not change or remove this line. + def second(self, printSecond: 'Callable[[], None]') -> None: + self.l2.acquire() printSecond() - self.c.release() + self.l3.release() - def third(self, printThird: "Callable[[], None]") -> None: - self.c.acquire() - # printThird() outputs "third". Do not change or remove this line. + def third(self, printThird: 'Callable[[], None]') -> None: + self.l3.acquire() printThird() - self.a.release() diff --git a/solution/1100-1199/1114.Print in Order/Solution2.cpp b/solution/1100-1199/1114.Print in Order/Solution2.cpp new file mode 100644 index 0000000000000..63d2be83584d8 --- /dev/null +++ b/solution/1100-1199/1114.Print in Order/Solution2.cpp @@ -0,0 +1,34 @@ +#include + +class Foo { +private: + sem_t a, b, c; + +public: + Foo() { + sem_init(&a, 0, 1); + sem_init(&b, 0, 0); + sem_init(&c, 0, 0); + } + + void first(function printFirst) { + sem_wait(&a); + // printFirst() outputs "first". Do not change or remove this line. + printFirst(); + sem_post(&b); + } + + void second(function printSecond) { + sem_wait(&b); + // printSecond() outputs "second". Do not change or remove this line. + printSecond(); + sem_post(&c); + } + + void third(function printThird) { + sem_wait(&c); + // printThird() outputs "third". Do not change or remove this line. + printThird(); + sem_post(&a); + } +}; \ No newline at end of file diff --git a/solution/1100-1199/1114.Print in Order/Solution2.py b/solution/1100-1199/1114.Print in Order/Solution2.py new file mode 100644 index 0000000000000..fc862b0112d8a --- /dev/null +++ b/solution/1100-1199/1114.Print in Order/Solution2.py @@ -0,0 +1,26 @@ +from threading import Semaphore + + +class Foo: + def __init__(self): + self.a = Semaphore(1) + self.b = Semaphore(0) + self.c = Semaphore(0) + + def first(self, printFirst: 'Callable[[], None]') -> None: + self.a.acquire() + # printFirst() outputs "first". Do not change or remove this line. + printFirst() + self.b.release() + + def second(self, printSecond: 'Callable[[], None]') -> None: + self.b.acquire() + # printSecond() outputs "second". Do not change or remove this line. + printSecond() + self.c.release() + + def third(self, printThird: 'Callable[[], None]') -> None: + self.c.acquire() + # printThird() outputs "third". Do not change or remove this line. + printThird() + self.a.release() diff --git a/solution/1100-1199/1121.Divide Array Into Increasing Sequences/Solution.java b/solution/1100-1199/1121.Divide Array Into Increasing Sequences/Solution.java index 08d5563cfb91e..bd2af6943666c 100644 --- a/solution/1100-1199/1121.Divide Array Into Increasing Sequences/Solution.java +++ b/solution/1100-1199/1121.Divide Array Into Increasing Sequences/Solution.java @@ -1,14 +1,10 @@ class Solution { public boolean canDivideIntoSubsequences(int[] nums, int k) { - int cnt = 0; - int a = 0; - for (int b : nums) { - cnt = a == b ? cnt + 1 : 1; - if (cnt * k > nums.length) { - return false; - } - a = b; + Map cnt = new HashMap<>(); + int mx = 0; + for (int x : nums) { + mx = Math.max(mx, cnt.merge(x, 1, Integer::sum)); } - return true; + return mx * k <= nums.length; } } \ No newline at end of file diff --git a/solution/1100-1199/1121.Divide Array Into Increasing Sequences/Solution2.java b/solution/1100-1199/1121.Divide Array Into Increasing Sequences/Solution2.java new file mode 100644 index 0000000000000..08d5563cfb91e --- /dev/null +++ b/solution/1100-1199/1121.Divide Array Into Increasing Sequences/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public boolean canDivideIntoSubsequences(int[] nums, int k) { + int cnt = 0; + int a = 0; + for (int b : nums) { + cnt = a == b ? cnt + 1 : 1; + if (cnt * k > nums.length) { + return false; + } + a = b; + } + return true; + } +} \ No newline at end of file diff --git a/solution/1100-1199/1126.Active Businesses/Solution.sql b/solution/1100-1199/1126.Active Businesses/Solution.sql index f1d2acff6d660..3bfa5fbb953d7 100644 --- a/solution/1100-1199/1126.Active Businesses/Solution.sql +++ b/solution/1100-1199/1126.Active Businesses/Solution.sql @@ -1,13 +1,15 @@ # Write your MySQL query statement below -WITH - T AS ( - SELECT - business_id, - occurences > AVG(occurences) OVER (PARTITION BY event_type) AS mark - FROM Events - ) SELECT business_id -FROM T -WHERE mark = 1 -GROUP BY 1 +FROM + EVENTS AS t1 + JOIN ( + SELECT + event_type, + AVG(occurences) AS occurences + FROM EVENTS + GROUP BY event_type + ) AS t2 + ON t1.event_type = t2.event_type +WHERE t1.occurences > t2.occurences +GROUP BY business_id HAVING COUNT(1) > 1; diff --git a/solution/1100-1199/1126.Active Businesses/Solution2.sql b/solution/1100-1199/1126.Active Businesses/Solution2.sql new file mode 100644 index 0000000000000..f1d2acff6d660 --- /dev/null +++ b/solution/1100-1199/1126.Active Businesses/Solution2.sql @@ -0,0 +1,13 @@ +# Write your MySQL query statement below +WITH + T AS ( + SELECT + business_id, + occurences > AVG(occurences) OVER (PARTITION BY event_type) AS mark + FROM Events + ) +SELECT business_id +FROM T +WHERE mark = 1 +GROUP BY 1 +HAVING COUNT(1) > 1; diff --git a/solution/1100-1199/1128.Number of Equivalent Domino Pairs/Solution.py b/solution/1100-1199/1128.Number of Equivalent Domino Pairs/Solution.py index 83a30d80b1733..0faa01dc2463c 100644 --- a/solution/1100-1199/1128.Number of Equivalent Domino Pairs/Solution.py +++ b/solution/1100-1199/1128.Number of Equivalent Domino Pairs/Solution.py @@ -3,7 +3,8 @@ def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int: cnt = Counter() ans = 0 for a, b in dominoes: - x = a * 10 + b if a < b else b * 10 + a - ans += cnt[x] - cnt[x] += 1 + ans += cnt[(a, b)] + cnt[(a, b)] += 1 + if a != b: + cnt[(b, a)] += 1 return ans diff --git a/solution/1100-1199/1128.Number of Equivalent Domino Pairs/Solution2.py b/solution/1100-1199/1128.Number of Equivalent Domino Pairs/Solution2.py new file mode 100644 index 0000000000000..83a30d80b1733 --- /dev/null +++ b/solution/1100-1199/1128.Number of Equivalent Domino Pairs/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int: + cnt = Counter() + ans = 0 + for a, b in dominoes: + x = a * 10 + b if a < b else b * 10 + a + ans += cnt[x] + cnt[x] += 1 + return ans diff --git a/solution/1100-1199/1129.Shortest Path with Alternating Colors/Solution.cpp b/solution/1100-1199/1129.Shortest Path with Alternating Colors/Solution.cpp index 928c0940d191c..d32f0be6b321b 100644 --- a/solution/1100-1199/1129.Shortest Path with Alternating Colors/Solution.cpp +++ b/solution/1100-1199/1129.Shortest Path with Alternating Colors/Solution.cpp @@ -1,37 +1,37 @@ -class Solution { -public: - vector shortestAlternatingPaths(int n, vector>& redEdges, vector>& blueEdges) { - vector>> g(2, vector>(n)); - for (auto& e : redEdges) { - g[0][e[0]].push_back(e[1]); - } - for (auto& e : blueEdges) { - g[1][e[0]].push_back(e[1]); - } - queue> q; - q.emplace(0, 0); - q.emplace(0, 1); - bool vis[n][2]; - memset(vis, false, sizeof vis); - vector ans(n, -1); - int d = 0; - while (!q.empty()) { - for (int k = q.size(); k; --k) { - auto [i, c] = q.front(); - q.pop(); - if (ans[i] == -1) { - ans[i] = d; - } - vis[i][c] = true; - c ^= 1; - for (int& j : g[c][i]) { - if (!vis[j][c]) { - q.emplace(j, c); - } - } - } - ++d; - } - return ans; - } +class Solution { +public: + vector shortestAlternatingPaths(int n, vector>& redEdges, vector>& blueEdges) { + vector>> g(2, vector>(n)); + for (auto& e : redEdges) { + g[0][e[0]].push_back(e[1]); + } + for (auto& e : blueEdges) { + g[1][e[0]].push_back(e[1]); + } + queue> q; + q.emplace(0, 0); + q.emplace(0, 1); + bool vis[n][2]; + memset(vis, false, sizeof vis); + vector ans(n, -1); + int d = 0; + while (!q.empty()) { + for (int k = q.size(); k; --k) { + auto [i, c] = q.front(); + q.pop(); + if (ans[i] == -1) { + ans[i] = d; + } + vis[i][c] = true; + c ^= 1; + for (int& j : g[c][i]) { + if (!vis[j][c]) { + q.emplace(j, c); + } + } + } + ++d; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1100-1199/1129.Shortest Path with Alternating Colors/Solution.java b/solution/1100-1199/1129.Shortest Path with Alternating Colors/Solution.java index 371ccc35f7fa3..5973d87a23cb8 100644 --- a/solution/1100-1199/1129.Shortest Path with Alternating Colors/Solution.java +++ b/solution/1100-1199/1129.Shortest Path with Alternating Colors/Solution.java @@ -1,39 +1,39 @@ -class Solution { - public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) { - List[][] g = new List[2][n]; - for (var f : g) { - Arrays.setAll(f, k -> new ArrayList<>()); - } - for (var e : redEdges) { - g[0][e[0]].add(e[1]); - } - for (var e : blueEdges) { - g[1][e[0]].add(e[1]); - } - Deque q = new ArrayDeque<>(); - q.offer(new int[] {0, 0}); - q.offer(new int[] {0, 1}); - boolean[][] vis = new boolean[n][2]; - int[] ans = new int[n]; - Arrays.fill(ans, -1); - int d = 0; - while (!q.isEmpty()) { - for (int k = q.size(); k > 0; --k) { - var p = q.poll(); - int i = p[0], c = p[1]; - if (ans[i] == -1) { - ans[i] = d; - } - vis[i][c] = true; - c ^= 1; - for (int j : g[c][i]) { - if (!vis[j][c]) { - q.offer(new int[] {j, c}); - } - } - } - ++d; - } - return ans; - } +class Solution { + public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) { + List[][] g = new List[2][n]; + for (var f : g) { + Arrays.setAll(f, k -> new ArrayList<>()); + } + for (var e : redEdges) { + g[0][e[0]].add(e[1]); + } + for (var e : blueEdges) { + g[1][e[0]].add(e[1]); + } + Deque q = new ArrayDeque<>(); + q.offer(new int[] {0, 0}); + q.offer(new int[] {0, 1}); + boolean[][] vis = new boolean[n][2]; + int[] ans = new int[n]; + Arrays.fill(ans, -1); + int d = 0; + while (!q.isEmpty()) { + for (int k = q.size(); k > 0; --k) { + var p = q.poll(); + int i = p[0], c = p[1]; + if (ans[i] == -1) { + ans[i] = d; + } + vis[i][c] = true; + c ^= 1; + for (int j : g[c][i]) { + if (!vis[j][c]) { + q.offer(new int[] {j, c}); + } + } + } + ++d; + } + return ans; + } } \ No newline at end of file diff --git a/solution/1100-1199/1129.Shortest Path with Alternating Colors/Solution.py b/solution/1100-1199/1129.Shortest Path with Alternating Colors/Solution.py index f373974abde90..6ddfe42ea5cb5 100644 --- a/solution/1100-1199/1129.Shortest Path with Alternating Colors/Solution.py +++ b/solution/1100-1199/1129.Shortest Path with Alternating Colors/Solution.py @@ -1,25 +1,25 @@ -class Solution: - def shortestAlternatingPaths( - self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]] - ) -> List[int]: - g = [defaultdict(list), defaultdict(list)] - for i, j in redEdges: - g[0][i].append(j) - for i, j in blueEdges: - g[1][i].append(j) - ans = [-1] * n - vis = set() - q = deque([(0, 0), (0, 1)]) - d = 0 - while q: - for _ in range(len(q)): - i, c = q.popleft() - if ans[i] == -1: - ans[i] = d - vis.add((i, c)) - c ^= 1 - for j in g[c][i]: - if (j, c) not in vis: - q.append((j, c)) - d += 1 - return ans +class Solution: + def shortestAlternatingPaths( + self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]] + ) -> List[int]: + g = [defaultdict(list), defaultdict(list)] + for i, j in redEdges: + g[0][i].append(j) + for i, j in blueEdges: + g[1][i].append(j) + ans = [-1] * n + vis = set() + q = deque([(0, 0), (0, 1)]) + d = 0 + while q: + for _ in range(len(q)): + i, c = q.popleft() + if ans[i] == -1: + ans[i] = d + vis.add((i, c)) + c ^= 1 + for j in g[c][i]: + if (j, c) not in vis: + q.append((j, c)) + d += 1 + return ans diff --git a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.cpp b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.cpp index 68a8621ca1e33..d8dcad5a616eb 100644 --- a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.cpp +++ b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.cpp @@ -9,12 +9,21 @@ class Solution { g[i][i] = arr[i]; for (int j = i + 1; j < n; ++j) { g[i][j] = max(g[i][j - 1], arr[j]); - f[i][j] = 1 << 30; - for (int k = i; k < j; ++k) { - f[i][j] = min(f[i][j], f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j]); - } } } - return f[0][n - 1]; + function dfs = [&](int i, int j) -> int { + if (i == j) { + return 0; + } + if (f[i][j] > 0) { + return f[i][j]; + } + int ans = 1 << 30; + for (int k = i; k < j; ++k) { + ans = min(ans, dfs(i, k) + dfs(k + 1, j) + g[i][k] * g[k + 1][j]); + } + return f[i][j] = ans; + }; + return dfs(0, n - 1); } }; \ No newline at end of file diff --git a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.go b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.go index 42364a8cdb3a5..6ce0b12ef6928 100644 --- a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.go +++ b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.go @@ -5,16 +5,24 @@ func mctFromLeafValues(arr []int) int { for i := range g { f[i] = make([]int, n) g[i] = make([]int, n) - } - for i := n - 1; i >= 0; i-- { g[i][i] = arr[i] for j := i + 1; j < n; j++ { g[i][j] = max(g[i][j-1], arr[j]) - f[i][j] = 1 << 30 - for k := i; k < j; k++ { - f[i][j] = min(f[i][j], f[i][k]+f[k+1][j]+g[i][k]*g[k+1][j]) - } } } - return f[0][n-1] + var dfs func(int, int) int + dfs = func(i, j int) int { + if i == j { + return 0 + } + if f[i][j] > 0 { + return f[i][j] + } + f[i][j] = 1 << 30 + for k := i; k < j; k++ { + f[i][j] = min(f[i][j], dfs(i, k)+dfs(k+1, j)+g[i][k]*g[k+1][j]) + } + return f[i][j] + } + return dfs(0, n-1) } \ No newline at end of file diff --git a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.java b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.java index bfe8e2879a339..16def8a59a6bd 100644 --- a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.java +++ b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.java @@ -1,18 +1,31 @@ class Solution { + private Integer[][] f; + private int[][] g; + public int mctFromLeafValues(int[] arr) { int n = arr.length; - int[][] f = new int[n][n]; - int[][] g = new int[n][n]; + f = new Integer[n][n]; + g = new int[n][n]; for (int i = n - 1; i >= 0; --i) { g[i][i] = arr[i]; for (int j = i + 1; j < n; ++j) { g[i][j] = Math.max(g[i][j - 1], arr[j]); - f[i][j] = 1 << 30; - for (int k = i; k < j; ++k) { - f[i][j] = Math.min(f[i][j], f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j]); - } } } - return f[0][n - 1]; + return dfs(0, n - 1); + } + + private int dfs(int i, int j) { + if (i == j) { + return 0; + } + if (f[i][j] != null) { + return f[i][j]; + } + int ans = 1 << 30; + for (int k = i; k < j; k++) { + ans = Math.min(ans, dfs(i, k) + dfs(k + 1, j) + g[i][k] * g[k + 1][j]); + } + return f[i][j] = ans; } } \ No newline at end of file diff --git a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.py b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.py index be8b49424d9b6..b713228ec7344 100644 --- a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.py +++ b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.py @@ -1,13 +1,17 @@ class Solution: def mctFromLeafValues(self, arr: List[int]) -> int: - n = len(arr) - f = [[0] * n for _ in range(n)] - g = [[0] * n for _ in range(n)] - for i in range(n - 1, -1, -1): - g[i][i] = arr[i] - for j in range(i + 1, n): - g[i][j] = max(g[i][j - 1], arr[j]) - f[i][j] = min( - f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j] for k in range(i, j) - ) - return f[0][n - 1] + @cache + def dfs(i: int, j: int) -> Tuple: + if i == j: + return 0, arr[i] + s, mx = inf, -1 + for k in range(i, j): + s1, mx1 = dfs(i, k) + s2, mx2 = dfs(k + 1, j) + t = s1 + s2 + mx1 * mx2 + if s > t: + s = t + mx = max(mx1, mx2) + return s, mx + + return dfs(0, len(arr) - 1)[0] diff --git a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.ts b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.ts index a33bafabfc325..92db84c026779 100644 --- a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.ts +++ b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution.ts @@ -6,11 +6,20 @@ function mctFromLeafValues(arr: number[]): number { g[i][i] = arr[i]; for (let j = i + 1; j < n; ++j) { g[i][j] = Math.max(g[i][j - 1], arr[j]); - f[i][j] = 1 << 30; - for (let k = i; k < j; ++k) { - f[i][j] = Math.min(f[i][j], f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j]); - } } } - return f[0][n - 1]; + const dfs = (i: number, j: number): number => { + if (i === j) { + return 0; + } + if (f[i][j] > 0) { + return f[i][j]; + } + let ans = 1 << 30; + for (let k = i; k < j; ++k) { + ans = Math.min(ans, dfs(i, k) + dfs(k + 1, j) + g[i][k] * g[k + 1][j]); + } + return (f[i][j] = ans); + }; + return dfs(0, n - 1); } diff --git a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution2.cpp b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution2.cpp new file mode 100644 index 0000000000000..68a8621ca1e33 --- /dev/null +++ b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution2.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int mctFromLeafValues(vector& arr) { + int n = arr.size(); + int f[n][n]; + int g[n][n]; + memset(f, 0, sizeof(f)); + for (int i = n - 1; ~i; --i) { + g[i][i] = arr[i]; + for (int j = i + 1; j < n; ++j) { + g[i][j] = max(g[i][j - 1], arr[j]); + f[i][j] = 1 << 30; + for (int k = i; k < j; ++k) { + f[i][j] = min(f[i][j], f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j]); + } + } + } + return f[0][n - 1]; + } +}; \ No newline at end of file diff --git a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution2.go b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution2.go new file mode 100644 index 0000000000000..42364a8cdb3a5 --- /dev/null +++ b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution2.go @@ -0,0 +1,20 @@ +func mctFromLeafValues(arr []int) int { + n := len(arr) + f := make([][]int, n) + g := make([][]int, n) + for i := range g { + f[i] = make([]int, n) + g[i] = make([]int, n) + } + for i := n - 1; i >= 0; i-- { + g[i][i] = arr[i] + for j := i + 1; j < n; j++ { + g[i][j] = max(g[i][j-1], arr[j]) + f[i][j] = 1 << 30 + for k := i; k < j; k++ { + f[i][j] = min(f[i][j], f[i][k]+f[k+1][j]+g[i][k]*g[k+1][j]) + } + } + } + return f[0][n-1] +} \ No newline at end of file diff --git a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution2.java b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution2.java new file mode 100644 index 0000000000000..bfe8e2879a339 --- /dev/null +++ b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution2.java @@ -0,0 +1,18 @@ +class Solution { + public int mctFromLeafValues(int[] arr) { + int n = arr.length; + int[][] f = new int[n][n]; + int[][] g = new int[n][n]; + for (int i = n - 1; i >= 0; --i) { + g[i][i] = arr[i]; + for (int j = i + 1; j < n; ++j) { + g[i][j] = Math.max(g[i][j - 1], arr[j]); + f[i][j] = 1 << 30; + for (int k = i; k < j; ++k) { + f[i][j] = Math.min(f[i][j], f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j]); + } + } + } + return f[0][n - 1]; + } +} \ No newline at end of file diff --git a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution2.py b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution2.py new file mode 100644 index 0000000000000..74e1d6f2f8649 --- /dev/null +++ b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def mctFromLeafValues(self, arr: List[int]) -> int: + @cache + def dfs(i: int, j: int) -> int: + if i == j: + return 0 + return min( + dfs(i, k) + dfs(k + 1, j) + g[i][k] * g[k + 1][j] for k in range(i, j) + ) + + n = len(arr) + g = [[0] * n for _ in range(n)] + for i in range(n - 1, -1, -1): + g[i][i] = arr[i] + for j in range(i + 1, n): + g[i][j] = max(g[i][j - 1], arr[j]) + return dfs(0, n - 1) diff --git a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution2.ts b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution2.ts new file mode 100644 index 0000000000000..a33bafabfc325 --- /dev/null +++ b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution2.ts @@ -0,0 +1,16 @@ +function mctFromLeafValues(arr: number[]): number { + const n = arr.length; + const f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(0)); + const g: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(0)); + for (let i = n - 1; i >= 0; --i) { + g[i][i] = arr[i]; + for (let j = i + 1; j < n; ++j) { + g[i][j] = Math.max(g[i][j - 1], arr[j]); + f[i][j] = 1 << 30; + for (let k = i; k < j; ++k) { + f[i][j] = Math.min(f[i][j], f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j]); + } + } + } + return f[0][n - 1]; +} diff --git a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution3.py b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution3.py new file mode 100644 index 0000000000000..be8b49424d9b6 --- /dev/null +++ b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution3.py @@ -0,0 +1,13 @@ +class Solution: + def mctFromLeafValues(self, arr: List[int]) -> int: + n = len(arr) + f = [[0] * n for _ in range(n)] + g = [[0] * n for _ in range(n)] + for i in range(n - 1, -1, -1): + g[i][i] = arr[i] + for j in range(i + 1, n): + g[i][j] = max(g[i][j - 1], arr[j]) + f[i][j] = min( + f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j] for k in range(i, j) + ) + return f[0][n - 1] diff --git a/solution/1100-1199/1133.Largest Unique Number/Solution2.py b/solution/1100-1199/1133.Largest Unique Number/Solution2.py new file mode 100644 index 0000000000000..b1a20dd4c8e21 --- /dev/null +++ b/solution/1100-1199/1133.Largest Unique Number/Solution2.py @@ -0,0 +1,4 @@ +class Solution: + def largestUniqueNumber(self, nums: List[int]) -> int: + cnt = Counter(nums) + return max((x for x, v in cnt.items() if v == 1), default=-1) diff --git a/solution/1100-1199/1137.N-th Tribonacci Number/Solution.cpp b/solution/1100-1199/1137.N-th Tribonacci Number/Solution.cpp index 28a2cbfccf3d1..03324e8183c79 100644 --- a/solution/1100-1199/1137.N-th Tribonacci Number/Solution.cpp +++ b/solution/1100-1199/1137.N-th Tribonacci Number/Solution.cpp @@ -1,41 +1,13 @@ -class Solution { -public: - int tribonacci(int n) { - if (n == 0) { - return 0; - } - if (n < 3) { - return 1; - } - vector> a = {{1, 1, 0}, {1, 0, 1}, {1, 0, 0}}; - vector> res = pow(a, n - 3); - return accumulate(res[0].begin(), res[0].end(), 0); - } - -private: - using ll = long long; - vector> mul(vector>& a, vector>& b) { - int m = a.size(), n = b[0].size(); - vector> c(m, vector(n)); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - for (int k = 0; k < b.size(); ++k) { - c[i][j] += a[i][k] * b[k][j]; - } - } - } - return c; - } - - vector> pow(vector>& a, int n) { - vector> res = {{1, 1, 0}}; - while (n) { - if (n & 1) { - res = mul(res, a); - } - a = mul(a, a); - n >>= 1; - } - return res; - } +class Solution { +public: + int tribonacci(int n) { + long long a = 0, b = 1, c = 1; + while (n--) { + long long d = a + b + c; + a = b; + b = c; + c = d; + } + return (int) a; + } }; \ No newline at end of file diff --git a/solution/1100-1199/1137.N-th Tribonacci Number/Solution.go b/solution/1100-1199/1137.N-th Tribonacci Number/Solution.go index 0679ce8462987..63382cb825179 100644 --- a/solution/1100-1199/1137.N-th Tribonacci Number/Solution.go +++ b/solution/1100-1199/1137.N-th Tribonacci Number/Solution.go @@ -1,42 +1,7 @@ -func tribonacci(n int) (ans int) { - if n == 0 { - return 0 +func tribonacci(n int) int { + a, b, c := 0, 1, 1 + for i := 0; i < n; i++ { + a, b, c = b, c, a+b+c } - if n < 3 { - return 1 - } - a := [][]int{{1, 1, 0}, {1, 0, 1}, {1, 0, 0}} - res := pow(a, n-3) - for _, x := range res[0] { - ans += x - } - return -} - -func mul(a, b [][]int) [][]int { - m, n := len(a), len(b[0]) - c := make([][]int, m) - for i := range c { - c[i] = make([]int, n) - } - for i := 0; i < m; i++ { - for j := 0; j < n; j++ { - for k := 0; k < len(b); k++ { - c[i][j] += a[i][k] * b[k][j] - } - } - } - return c -} - -func pow(a [][]int, n int) [][]int { - res := [][]int{{1, 1, 0}} - for n > 0 { - if n&1 == 1 { - res = mul(res, a) - } - a = mul(a, a) - n >>= 1 - } - return res + return a } \ No newline at end of file diff --git a/solution/1100-1199/1137.N-th Tribonacci Number/Solution.java b/solution/1100-1199/1137.N-th Tribonacci Number/Solution.java index 816c33ab7a2ae..8a35e2b1d8849 100644 --- a/solution/1100-1199/1137.N-th Tribonacci Number/Solution.java +++ b/solution/1100-1199/1137.N-th Tribonacci Number/Solution.java @@ -1,42 +1,12 @@ -class Solution { - public int tribonacci(int n) { - if (n == 0) { - return 0; - } - if (n < 3) { - return 1; - } - int[][] a = {{1, 1, 0}, {1, 0, 1}, {1, 0, 0}}; - int[][] res = pow(a, n - 3); - int ans = 0; - for (int x : res[0]) { - ans += x; - } - return ans; - } - - private int[][] mul(int[][] a, int[][] b) { - int m = a.length, n = b[0].length; - int[][] c = new int[m][n]; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - for (int k = 0; k < b.length; ++k) { - c[i][j] += a[i][k] * b[k][j]; - } - } - } - return c; - } - - private int[][] pow(int[][] a, int n) { - int[][] res = {{1, 1, 0}}; - while (n > 0) { - if ((n & 1) == 1) { - res = mul(res, a); - } - a = mul(a, a); - n >>= 1; - } - return res; - } +class Solution { + public int tribonacci(int n) { + int a = 0, b = 1, c = 1; + while (n-- > 0) { + int d = a + b + c; + a = b; + b = c; + c = d; + } + return a; + } } \ No newline at end of file diff --git a/solution/1100-1199/1137.N-th Tribonacci Number/Solution.js b/solution/1100-1199/1137.N-th Tribonacci Number/Solution.js index ec4768040079f..8af290bb9d571 100644 --- a/solution/1100-1199/1137.N-th Tribonacci Number/Solution.js +++ b/solution/1100-1199/1137.N-th Tribonacci Number/Solution.js @@ -3,41 +3,14 @@ * @return {number} */ var tribonacci = function (n) { - if (n === 0) { - return 0; + let a = 0; + let b = 1; + let c = 1; + while (n--) { + let d = a + b + c; + a = b; + b = c; + c = d; } - if (n < 3) { - return 1; - } - const a = [ - [1, 1, 0], - [1, 0, 1], - [1, 0, 0], - ]; - return pow(a, n - 3)[0].reduce((a, b) => a + b); + return a; }; - -function mul(a, b) { - const [m, n] = [a.length, b[0].length]; - const c = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - for (let k = 0; k < b.length; ++k) { - c[i][j] += a[i][k] * b[k][j]; - } - } - } - return c; -} - -function pow(a, n) { - let res = [[1, 1, 0]]; - while (n) { - if (n & 1) { - res = mul(res, a); - } - a = mul(a, a); - n >>= 1; - } - return res; -} diff --git a/solution/1100-1199/1137.N-th Tribonacci Number/Solution.php b/solution/1100-1199/1137.N-th Tribonacci Number/Solution.php index 48d0fb04c6de6..e1ccd36d8f62b 100644 --- a/solution/1100-1199/1137.N-th Tribonacci Number/Solution.php +++ b/solution/1100-1199/1137.N-th Tribonacci Number/Solution.php @@ -15,4 +15,4 @@ function tribonacci($n) { } return $dp[$n]; } -} \ No newline at end of file +} diff --git a/solution/1100-1199/1137.N-th Tribonacci Number/Solution.py b/solution/1100-1199/1137.N-th Tribonacci Number/Solution.py index 90e2296913b8f..a3938c3a74409 100644 --- a/solution/1100-1199/1137.N-th Tribonacci Number/Solution.py +++ b/solution/1100-1199/1137.N-th Tribonacci Number/Solution.py @@ -1,18 +1,6 @@ -import numpy as np - - -class Solution: - def tribonacci(self, n: int) -> int: - if n == 0: - return 0 - if n < 3: - return 1 - factor = np.mat([(1, 1, 0), (1, 0, 1), (1, 0, 0)], np.dtype("O")) - res = np.mat([(1, 1, 0)], np.dtype("O")) - n -= 3 - while n: - if n & 1: - res *= factor - factor *= factor - n >>= 1 - return res.sum() +class Solution: + def tribonacci(self, n: int) -> int: + a, b, c = 0, 1, 1 + for _ in range(n): + a, b, c = b, c, a + b + c + return a diff --git a/solution/1100-1199/1137.N-th Tribonacci Number/Solution2.cpp b/solution/1100-1199/1137.N-th Tribonacci Number/Solution2.cpp new file mode 100644 index 0000000000000..aaa1de9331f2b --- /dev/null +++ b/solution/1100-1199/1137.N-th Tribonacci Number/Solution2.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + int tribonacci(int n) { + if (n == 0) { + return 0; + } + if (n < 3) { + return 1; + } + vector> a = {{1, 1, 0}, {1, 0, 1}, {1, 0, 0}}; + vector> res = pow(a, n - 3); + return accumulate(res[0].begin(), res[0].end(), 0); + } + +private: + using ll = long long; + vector> mul(vector>& a, vector>& b) { + int m = a.size(), n = b[0].size(); + vector> c(m, vector(n)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k < b.size(); ++k) { + c[i][j] += a[i][k] * b[k][j]; + } + } + } + return c; + } + + vector> pow(vector>& a, int n) { + vector> res = {{1, 1, 0}}; + while (n) { + if (n & 1) { + res = mul(res, a); + } + a = mul(a, a); + n >>= 1; + } + return res; + } +}; \ No newline at end of file diff --git a/solution/1100-1199/1137.N-th Tribonacci Number/Solution2.go b/solution/1100-1199/1137.N-th Tribonacci Number/Solution2.go new file mode 100644 index 0000000000000..0679ce8462987 --- /dev/null +++ b/solution/1100-1199/1137.N-th Tribonacci Number/Solution2.go @@ -0,0 +1,42 @@ +func tribonacci(n int) (ans int) { + if n == 0 { + return 0 + } + if n < 3 { + return 1 + } + a := [][]int{{1, 1, 0}, {1, 0, 1}, {1, 0, 0}} + res := pow(a, n-3) + for _, x := range res[0] { + ans += x + } + return +} + +func mul(a, b [][]int) [][]int { + m, n := len(a), len(b[0]) + c := make([][]int, m) + for i := range c { + c[i] = make([]int, n) + } + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + for k := 0; k < len(b); k++ { + c[i][j] += a[i][k] * b[k][j] + } + } + } + return c +} + +func pow(a [][]int, n int) [][]int { + res := [][]int{{1, 1, 0}} + for n > 0 { + if n&1 == 1 { + res = mul(res, a) + } + a = mul(a, a) + n >>= 1 + } + return res +} \ No newline at end of file diff --git a/solution/1100-1199/1137.N-th Tribonacci Number/Solution2.java b/solution/1100-1199/1137.N-th Tribonacci Number/Solution2.java new file mode 100644 index 0000000000000..64a372c55c67c --- /dev/null +++ b/solution/1100-1199/1137.N-th Tribonacci Number/Solution2.java @@ -0,0 +1,42 @@ +class Solution { + public int tribonacci(int n) { + if (n == 0) { + return 0; + } + if (n < 3) { + return 1; + } + int[][] a = {{1, 1, 0}, {1, 0, 1}, {1, 0, 0}}; + int[][] res = pow(a, n - 3); + int ans = 0; + for (int x : res[0]) { + ans += x; + } + return ans; + } + + private int[][] mul(int[][] a, int[][] b) { + int m = a.length, n = b[0].length; + int[][] c = new int[m][n]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k < b.length; ++k) { + c[i][j] += a[i][k] * b[k][j]; + } + } + } + return c; + } + + private int[][] pow(int[][] a, int n) { + int[][] res = {{1, 1, 0}}; + while (n > 0) { + if ((n & 1) == 1) { + res = mul(res, a); + } + a = mul(a, a); + n >>= 1; + } + return res; + } +} \ No newline at end of file diff --git a/solution/1100-1199/1137.N-th Tribonacci Number/Solution2.js b/solution/1100-1199/1137.N-th Tribonacci Number/Solution2.js new file mode 100644 index 0000000000000..ec4768040079f --- /dev/null +++ b/solution/1100-1199/1137.N-th Tribonacci Number/Solution2.js @@ -0,0 +1,43 @@ +/** + * @param {number} n + * @return {number} + */ +var tribonacci = function (n) { + if (n === 0) { + return 0; + } + if (n < 3) { + return 1; + } + const a = [ + [1, 1, 0], + [1, 0, 1], + [1, 0, 0], + ]; + return pow(a, n - 3)[0].reduce((a, b) => a + b); +}; + +function mul(a, b) { + const [m, n] = [a.length, b[0].length]; + const c = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + for (let k = 0; k < b.length; ++k) { + c[i][j] += a[i][k] * b[k][j]; + } + } + } + return c; +} + +function pow(a, n) { + let res = [[1, 1, 0]]; + while (n) { + if (n & 1) { + res = mul(res, a); + } + a = mul(a, a); + n >>= 1; + } + return res; +} diff --git a/solution/1100-1199/1137.N-th Tribonacci Number/Solution2.py b/solution/1100-1199/1137.N-th Tribonacci Number/Solution2.py new file mode 100644 index 0000000000000..87ffef8a51d06 --- /dev/null +++ b/solution/1100-1199/1137.N-th Tribonacci Number/Solution2.py @@ -0,0 +1,26 @@ +class Solution: + def tribonacci(self, n: int) -> int: + def mul(a: List[List[int]], b: List[List[int]]) -> List[List[int]]: + m, n = len(a), len(b[0]) + c = [[0] * n for _ in range(m)] + for i in range(m): + for j in range(n): + for k in range(len(a[0])): + c[i][j] = c[i][j] + a[i][k] * b[k][j] + return c + + def pow(a: List[List[int]], n: int) -> List[List[int]]: + res = [[1, 1, 0]] + while n: + if n & 1: + res = mul(res, a) + n >>= 1 + a = mul(a, a) + return res + + if n == 0: + return 0 + if n < 3: + return 1 + a = [[1, 1, 0], [1, 0, 1], [1, 0, 0]] + return sum(pow(a, n - 3)[0]) diff --git a/solution/1100-1199/1137.N-th Tribonacci Number/Solution3.py b/solution/1100-1199/1137.N-th Tribonacci Number/Solution3.py new file mode 100644 index 0000000000000..df667a1579603 --- /dev/null +++ b/solution/1100-1199/1137.N-th Tribonacci Number/Solution3.py @@ -0,0 +1,18 @@ +import numpy as np + + +class Solution: + def tribonacci(self, n: int) -> int: + if n == 0: + return 0 + if n < 3: + return 1 + factor = np.mat([(1, 1, 0), (1, 0, 1), (1, 0, 0)], np.dtype("O")) + res = np.mat([(1, 1, 0)], np.dtype("O")) + n -= 3 + while n: + if n & 1: + res *= factor + factor *= factor + n >>= 1 + return res.sum() diff --git a/solution/1100-1199/1140.Stone Game II/Solution2.py b/solution/1100-1199/1140.Stone Game II/Solution2.py new file mode 100644 index 0000000000000..8ad1cf60bb872 --- /dev/null +++ b/solution/1100-1199/1140.Stone Game II/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def stoneGameII(self, piles: List[int]) -> int: + @cache + def dfs(i: int, m: int = 1) -> int: + if i >= len(piles): + return 0 + t = inf + for x in range(1, m << 1 | 1): + t = min(t, dfs(i + x, max(m, x))) + return s[-1] - s[i] - t + + s = list(accumulate(piles, initial=0)) + return dfs(0) diff --git a/solution/1100-1199/1142.User Activity for the Past 30 Days II/Solution2.sql b/solution/1100-1199/1142.User Activity for the Past 30 Days II/Solution2.sql new file mode 100644 index 0000000000000..6f8597e5a5b96 --- /dev/null +++ b/solution/1100-1199/1142.User Activity for the Past 30 Days II/Solution2.sql @@ -0,0 +1,7 @@ +SELECT + IFNULL( + ROUND(COUNT(DISTINCT session_id) / COUNT(DISTINCT user_id), 2), + 0 + ) AS average_sessions_per_user +FROM Activity +WHERE DATEDIFF('2019-07-27', activity_date) < 30; diff --git a/solution/1100-1199/1143.Longest Common Subsequence/Solution.cs b/solution/1100-1199/1143.Longest Common Subsequence/Solution.cs index 8def4f8a6143c..f49aff4668bbf 100644 --- a/solution/1100-1199/1143.Longest Common Subsequence/Solution.cs +++ b/solution/1100-1199/1143.Longest Common Subsequence/Solution.cs @@ -13,4 +13,4 @@ public int LongestCommonSubsequence(string text1, string text2) { } return f[m, n]; } -} \ No newline at end of file +} diff --git a/solution/1100-1199/1143.Longest Common Subsequence/Solution.kt b/solution/1100-1199/1143.Longest Common Subsequence/Solution.kt index 8febd0c4b2acf..11a90f48b155b 100644 --- a/solution/1100-1199/1143.Longest Common Subsequence/Solution.kt +++ b/solution/1100-1199/1143.Longest Common Subsequence/Solution.kt @@ -1,17 +1,17 @@ -class Solution { - fun longestCommonSubsequence(text1: String, text2: String): Int { - val m = text1.length - val n = text2.length - val f = Array(m + 1) { IntArray(n + 1) } - for (i in 1..m) { - for (j in 1..n) { - if (text1[i - 1] == text2[j - 1]) { - f[i][j] = f[i - 1][j - 1] + 1 - } else { - f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]) - } - } - } - return f[m][n] - } -} \ No newline at end of file +class Solution { + fun longestCommonSubsequence(text1: String, text2: String): Int { + val m = text1.length + val n = text2.length + val f = Array(m + 1) { IntArray(n + 1) } + for (i in 1..m) { + for (j in 1..n) { + if (text1[i - 1] == text2[j - 1]) { + f[i][j] = f[i - 1][j - 1] + 1 + } else { + f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]) + } + } + } + return f[m][n] + } +} diff --git a/solution/1100-1199/1144.Decrease Elements To Make Array Zigzag/Solution.cs b/solution/1100-1199/1144.Decrease Elements To Make Array Zigzag/Solution.cs index 47ee52ae84d53..26df8a5a9f3f3 100644 --- a/solution/1100-1199/1144.Decrease Elements To Make Array Zigzag/Solution.cs +++ b/solution/1100-1199/1144.Decrease Elements To Make Array Zigzag/Solution.cs @@ -16,4 +16,4 @@ public int MovesToMakeZigzag(int[] nums) { } return Math.Min(ans[0], ans[1]); } -} \ No newline at end of file +} diff --git a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution.cpp b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution.cpp index 3ebb1231799b9..f085d23656770 100644 --- a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution.cpp +++ b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution.cpp @@ -1,31 +1,13 @@ class Solution { public: int longestDecomposition(string text) { - int ans = 0; - auto check = [&](int i, int j, int k) -> bool { - while (k--) { - if (text[i++] != text[j++]) { - return false; - } - } - return true; - }; - for (int i = 0, j = text.size() - 1; i <= j;) { - bool ok = false; - for (int k = 1; i + k - 1 < j - k + 1; ++k) { - if (check(i, j - k + 1, k)) { - ans += 2; - i += k; - j -= k; - ok = true; - break; - } - } - if (!ok) { - ans += 1; - break; + int n = text.size(); + if (n < 2) return n; + for (int i = 1; i <= n >> 1; ++i) { + if (text.substr(0, i) == text.substr(n - i)) { + return 2 + longestDecomposition(text.substr(i, n - i - i)); } } - return ans; + return 1; } }; \ No newline at end of file diff --git a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution.go b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution.go index 0c9364120ce05..4c5d65be86ca3 100644 --- a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution.go +++ b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution.go @@ -1,19 +1,12 @@ -func longestDecomposition(text string) (ans int) { - for i, j := 0, len(text)-1; i <= j; { - ok := false - for k := 1; i+k-1 < j-k+1; k++ { - if text[i:i+k] == text[j-k+1:j+1] { - ans += 2 - i += k - j -= k - ok = true - break - } - } - if !ok { - ans++ - break +func longestDecomposition(text string) int { + n := len(text) + if n < 2 { + return n + } + for i := 1; i <= n>>1; i++ { + if text[:i] == text[n-i:] { + return 2 + longestDecomposition(text[i:n-i]) } } - return + return 1 } \ No newline at end of file diff --git a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution.java b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution.java index 60208724249d1..0c9e6fd429a40 100644 --- a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution.java +++ b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution.java @@ -1,31 +1,14 @@ class Solution { public int longestDecomposition(String text) { - int ans = 0; - for (int i = 0, j = text.length() - 1; i <= j;) { - boolean ok = false; - for (int k = 1; i + k - 1 < j - k + 1; ++k) { - if (check(text, i, j - k + 1, k)) { - ans += 2; - i += k; - j -= k; - ok = true; - break; - } - } - if (!ok) { - ++ans; - break; - } + int n = text.length(); + if (n < 2) { + return n; } - return ans; - } - - private boolean check(String s, int i, int j, int k) { - while (k-- > 0) { - if (s.charAt(i++) != s.charAt(j++)) { - return false; + for (int i = 1; i <= n >> 1; ++i) { + if (text.substring(0, i).equals(text.substring(n - i))) { + return 2 + longestDecomposition(text.substring(i, n - i)); } } - return true; + return 1; } } \ No newline at end of file diff --git a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution.py b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution.py index 30f40ad4ac566..20fba192cdbc7 100644 --- a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution.py +++ b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution.py @@ -1,19 +1,9 @@ class Solution: def longestDecomposition(self, text: str) -> int: - ans = 0 - i, j = 0, len(text) - 1 - while i <= j: - k = 1 - ok = False - while i + k - 1 < j - k + 1: - if text[i : i + k] == text[j - k + 1 : j + 1]: - ans += 2 - i += k - j -= k - ok = True - break - k += 1 - if not ok: - ans += 1 - break - return ans + n = len(text) + if n < 2: + return n + for i in range(n // 2 + 1): + if text[:i] == text[-i:]: + return 2 + self.longestDecomposition(text[i:-i]) + return 1 diff --git a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution2.cpp b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution2.cpp new file mode 100644 index 0000000000000..3ebb1231799b9 --- /dev/null +++ b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution2.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int longestDecomposition(string text) { + int ans = 0; + auto check = [&](int i, int j, int k) -> bool { + while (k--) { + if (text[i++] != text[j++]) { + return false; + } + } + return true; + }; + for (int i = 0, j = text.size() - 1; i <= j;) { + bool ok = false; + for (int k = 1; i + k - 1 < j - k + 1; ++k) { + if (check(i, j - k + 1, k)) { + ans += 2; + i += k; + j -= k; + ok = true; + break; + } + } + if (!ok) { + ans += 1; + break; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution2.go b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution2.go new file mode 100644 index 0000000000000..0c9364120ce05 --- /dev/null +++ b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution2.go @@ -0,0 +1,19 @@ +func longestDecomposition(text string) (ans int) { + for i, j := 0, len(text)-1; i <= j; { + ok := false + for k := 1; i+k-1 < j-k+1; k++ { + if text[i:i+k] == text[j-k+1:j+1] { + ans += 2 + i += k + j -= k + ok = true + break + } + } + if !ok { + ans++ + break + } + } + return +} \ No newline at end of file diff --git a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution2.java b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution2.java new file mode 100644 index 0000000000000..60208724249d1 --- /dev/null +++ b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution2.java @@ -0,0 +1,31 @@ +class Solution { + public int longestDecomposition(String text) { + int ans = 0; + for (int i = 0, j = text.length() - 1; i <= j;) { + boolean ok = false; + for (int k = 1; i + k - 1 < j - k + 1; ++k) { + if (check(text, i, j - k + 1, k)) { + ans += 2; + i += k; + j -= k; + ok = true; + break; + } + } + if (!ok) { + ++ans; + break; + } + } + return ans; + } + + private boolean check(String s, int i, int j, int k) { + while (k-- > 0) { + if (s.charAt(i++) != s.charAt(j++)) { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution2.py b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution2.py new file mode 100644 index 0000000000000..30f40ad4ac566 --- /dev/null +++ b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution2.py @@ -0,0 +1,19 @@ +class Solution: + def longestDecomposition(self, text: str) -> int: + ans = 0 + i, j = 0, len(text) - 1 + while i <= j: + k = 1 + ok = False + while i + k - 1 < j - k + 1: + if text[i : i + k] == text[j - k + 1 : j + 1]: + ans += 2 + i += k + j -= k + ok = True + break + k += 1 + if not ok: + ans += 1 + break + return ans diff --git a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution2.ts b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution2.ts new file mode 100644 index 0000000000000..a413f70e20fb5 --- /dev/null +++ b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution2.ts @@ -0,0 +1,20 @@ +function longestDecomposition(text: string): number { + let ans = 0; + for (let i = 0, j = text.length - 1; i <= j; ) { + let ok = false; + for (let k = 1; i + k - 1 < j - k + 1; ++k) { + if (text.slice(i, i + k) === text.slice(j - k + 1, j + 1)) { + ans += 2; + i += k; + j -= k; + ok = true; + break; + } + } + if (!ok) { + ++ans; + break; + } + } + return ans; +} diff --git a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution3.cpp b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution3.cpp new file mode 100644 index 0000000000000..1130d50a83db6 --- /dev/null +++ b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution3.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int longestDecomposition(string text) { + using ull = unsigned long long; + int n = text.size(); + int base = 131; + ull p[n + 10]; + ull h[n + 10]; + p[0] = 1; + h[0] = 0; + for (int i = 0; i < n; ++i) { + int t = text[i] - 'a' + 1; + p[i + 1] = p[i] * base; + h[i + 1] = h[i] * base + t; + } + + int ans = 0; + auto get = [&](int l, int r) { + return h[r] - h[l - 1] * p[r - l + 1]; + }; + for (int i = 0, j = n - 1; i <= j;) { + bool ok = false; + for (int k = 1; i + k - 1 < j - k + 1; ++k) { + if (get(i + 1, i + k) == get(j - k + 2, j + 1)) { + ans += 2; + i += k; + j -= k; + ok = true; + break; + } + } + if (!ok) { + ++ans; + break; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution3.go b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution3.go new file mode 100644 index 0000000000000..a708cefe76019 --- /dev/null +++ b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution3.go @@ -0,0 +1,33 @@ +func longestDecomposition(text string) (ans int) { + n := len(text) + base := 131 + h := make([]int, n+10) + p := make([]int, n+10) + p[0] = 1 + for i, c := range text { + t := int(c-'a') + 1 + p[i+1] = p[i] * base + h[i+1] = h[i]*base + t + } + get := func(l, r int) int { + return h[r] - h[l-1]*p[r-l+1] + } + + for i, j := 0, n-1; i <= j; { + ok := false + for k := 1; i+k-1 < j-k+1; k++ { + if get(i+1, i+k) == get(j-k+2, j+1) { + ans += 2 + i += k + j -= k + ok = true + break + } + } + if !ok { + ans++ + break + } + } + return +} \ No newline at end of file diff --git a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution3.java b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution3.java new file mode 100644 index 0000000000000..fc0350ab7f2d9 --- /dev/null +++ b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution3.java @@ -0,0 +1,39 @@ +class Solution { + private long[] h; + private long[] p; + + public int longestDecomposition(String text) { + int n = text.length(); + int base = 131; + h = new long[n + 10]; + p = new long[n + 10]; + p[0] = 1; + for (int i = 0; i < n; ++i) { + int t = text.charAt(i) - 'a' + 1; + h[i + 1] = h[i] * base + t; + p[i + 1] = p[i] * base; + } + int ans = 0; + for (int i = 0, j = n - 1; i <= j;) { + boolean ok = false; + for (int k = 1; i + k - 1 < j - k + 1; ++k) { + if (get(i + 1, i + k) == get(j - k + 2, j + 1)) { + ans += 2; + i += k; + j -= k; + ok = true; + break; + } + } + if (!ok) { + ++ans; + break; + } + } + return ans; + } + + private long get(int i, int j) { + return h[j] - h[i - 1] * p[j - i + 1]; + } +} \ No newline at end of file diff --git a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution3.py b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution3.py new file mode 100644 index 0000000000000..2024fa6706a30 --- /dev/null +++ b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/Solution3.py @@ -0,0 +1,32 @@ +class Solution: + def longestDecomposition(self, text: str) -> int: + def get(l, r): + return (h[r] - h[l - 1] * p[r - l + 1]) % mod + + n = len(text) + base = 131 + mod = int(1e9) + 7 + h = [0] * (n + 10) + p = [1] * (n + 10) + for i, c in enumerate(text): + t = ord(c) - ord('a') + 1 + h[i + 1] = (h[i] * base) % mod + t + p[i + 1] = (p[i] * base) % mod + + ans = 0 + i, j = 0, n - 1 + while i <= j: + k = 1 + ok = False + while i + k - 1 < j - k + 1: + if get(i + 1, i + k) == get(j - k + 2, j + 1): + ans += 2 + i += k + j -= k + ok = True + break + k += 1 + if not ok: + ans += 1 + break + return ans diff --git a/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution.py b/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution.py index 35b108e9b3e27..4c57d40dd7c0e 100644 --- a/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution.py +++ b/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution.py @@ -1,5 +1,5 @@ -class Solution: - def isMajorityElement(self, nums: List[int], target: int) -> bool: - left = bisect_left(nums, target) - right = bisect_right(nums, target) - return right - left > len(nums) // 2 +class Solution: + def isMajorityElement(self, nums: List[int], target: int) -> bool: + left = bisect_left(nums, target) + right = bisect_right(nums, target) + return right - left > len(nums) // 2 diff --git a/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution2.cpp b/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution2.cpp new file mode 100644 index 0000000000000..6b844aa286cb0 --- /dev/null +++ b/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution2.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + bool isMajorityElement(vector& nums, int target) { + int n = nums.size(); + int left = lower_bound(nums.begin(), nums.end(), target) - nums.begin(); + int right = left + n / 2; + return right < n && nums[right] == target; + } +}; \ No newline at end of file diff --git a/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution2.go b/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution2.go new file mode 100644 index 0000000000000..4060454d74753 --- /dev/null +++ b/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution2.go @@ -0,0 +1,6 @@ +func isMajorityElement(nums []int, target int) bool { + n := len(nums) + left := sort.SearchInts(nums, target) + right := left + n/2 + return right < n && nums[right] == target +} \ No newline at end of file diff --git a/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution2.java b/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution2.java new file mode 100644 index 0000000000000..b2eda85b4cedb --- /dev/null +++ b/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution2.java @@ -0,0 +1,21 @@ +class Solution { + public boolean isMajorityElement(int[] nums, int target) { + int n = nums.length; + int left = search(nums, target); + int right = left + n / 2; + return right < n && nums[right] == target; + } + + private int search(int[] nums, int x) { + int left = 0, right = nums.length; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} \ No newline at end of file diff --git a/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution2.py b/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution2.py new file mode 100644 index 0000000000000..de0135a2608bc --- /dev/null +++ b/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution2.py @@ -0,0 +1,5 @@ +class Solution: + def isMajorityElement(self, nums: List[int], target: int) -> bool: + left = bisect_left(nums, target) + right = left + len(nums) // 2 + return right < len(nums) and nums[right] == target diff --git a/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution2.ts b/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution2.ts new file mode 100644 index 0000000000000..82d31213a4332 --- /dev/null +++ b/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution2.ts @@ -0,0 +1,19 @@ +function isMajorityElement(nums: number[], target: number): boolean { + const search = (x: number) => { + let left = 0; + let right = n; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + }; + const n = nums.length; + const left = search(target); + const right = left + (n >> 1); + return right < n && nums[right] === target; +} diff --git a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.cpp b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.cpp index 4ef52dc6a9f0f..1211e2fe0527a 100644 --- a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.cpp +++ b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.cpp @@ -1,18 +1,17 @@ -class Solution { -public: - int numRollsToTarget(int n, int k, int target) { - const int mod = 1e9 + 7; - vector f(target + 1); - f[0] = 1; - for (int i = 1; i <= n; ++i) { - vector g(target + 1); - for (int j = 1; j <= min(target, i * k); ++j) { - for (int h = 1; h <= min(j, k); ++h) { - g[j] = (g[j] + f[j - h]) % mod; - } - } - f = move(g); - } - return f[target]; - } +class Solution { +public: + int numRollsToTarget(int n, int k, int target) { + const int mod = 1e9 + 7; + int f[n + 1][target + 1]; + memset(f, 0, sizeof f); + f[0][0] = 1; + for (int i = 1; i <= n; ++i) { + for (int j = 1; j <= min(target, i * k); ++j) { + for (int h = 1; h <= min(j, k); ++h) { + f[i][j] = (f[i][j] + f[i - 1][j - h]) % mod; + } + } + } + return f[n][target]; + } }; \ No newline at end of file diff --git a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.go b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.go index 9b153861eed01..41052f53ec4bf 100644 --- a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.go +++ b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.go @@ -1,15 +1,16 @@ func numRollsToTarget(n int, k int, target int) int { const mod int = 1e9 + 7 - f := make([]int, target+1) - f[0] = 1 + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, target+1) + } + f[0][0] = 1 for i := 1; i <= n; i++ { - g := make([]int, target+1) for j := 1; j <= min(target, i*k); j++ { for h := 1; h <= min(j, k); h++ { - g[j] = (g[j] + f[j-h]) % mod + f[i][j] = (f[i][j] + f[i-1][j-h]) % mod } } - f = g } - return f[target] + return f[n][target] } \ No newline at end of file diff --git a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.java b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.java index 9b1cb488f82f7..6abe7d99e599a 100644 --- a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.java +++ b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.java @@ -1,17 +1,15 @@ -class Solution { - public int numRollsToTarget(int n, int k, int target) { - final int mod = (int) 1e9 + 7; - int[] f = new int[target + 1]; - f[0] = 1; - for (int i = 1; i <= n; ++i) { - int[] g = new int[target + 1]; - for (int j = 1; j <= Math.min(target, i * k); ++j) { - for (int h = 1; h <= Math.min(j, k); ++h) { - g[j] = (g[j] + f[j - h]) % mod; - } - } - f = g; - } - return f[target]; - } +class Solution { + public int numRollsToTarget(int n, int k, int target) { + final int mod = (int) 1e9 + 7; + int[][] f = new int[n + 1][target + 1]; + f[0][0] = 1; + for (int i = 1; i <= n; ++i) { + for (int j = 1; j <= Math.min(target, i * k); ++j) { + for (int h = 1; h <= Math.min(j, k); ++h) { + f[i][j] = (f[i][j] + f[i - 1][j - h]) % mod; + } + } + } + return f[n][target]; + } } \ No newline at end of file diff --git a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.py b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.py index 55b735815d696..d6c1708c98482 100644 --- a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.py +++ b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.py @@ -1,11 +1,10 @@ -class Solution: - def numRollsToTarget(self, n: int, k: int, target: int) -> int: - f = [1] + [0] * target - mod = 10**9 + 7 - for i in range(1, n + 1): - g = [0] * (target + 1) - for j in range(1, min(i * k, target) + 1): - for h in range(1, min(j, k) + 1): - g[j] = (g[j] + f[j - h]) % mod - f = g - return f[target] +class Solution: + def numRollsToTarget(self, n: int, k: int, target: int) -> int: + f = [[0] * (target + 1) for _ in range(n + 1)] + f[0][0] = 1 + mod = 10**9 + 7 + for i in range(1, n + 1): + for j in range(1, min(i * k, target) + 1): + for h in range(1, min(j, k) + 1): + f[i][j] = (f[i][j] + f[i - 1][j - h]) % mod + return f[n][target] diff --git a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.rs b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.rs index 4bb8d9e961086..80c035ae81461 100644 --- a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.rs +++ b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.rs @@ -4,19 +4,17 @@ impl Solution { let n = n as usize; let k = k as usize; let target = target as usize; - let mut f = vec![0; target + 1]; - f[0] = 1; + let mut f = vec![vec![0; target + 1]; n + 1]; + f[0][0] = 1; for i in 1..=n { - let mut g = vec![0; target + 1]; - for j in 1..=target { + for j in 1..=target.min(i * k) { for h in 1..=j.min(k) { - g[j] = (g[j] + f[j - h]) % _mod; + f[i][j] = (f[i][j] + f[i - 1][j - h]) % _mod; } } - f = g; } - f[target] + f[n][target] } } diff --git a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.ts b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.ts index 705b0c1cb1b1a..2c2c5199b9549 100644 --- a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.ts +++ b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.ts @@ -1,15 +1,13 @@ function numRollsToTarget(n: number, k: number, target: number): number { - const f = Array(target + 1).fill(0); - f[0] = 1; + const f = Array.from({ length: n + 1 }, () => Array(target + 1).fill(0)); + f[0][0] = 1; const mod = 1e9 + 7; for (let i = 1; i <= n; ++i) { - const g = Array(target + 1).fill(0); for (let j = 1; j <= Math.min(i * k, target); ++j) { for (let h = 1; h <= Math.min(j, k); ++h) { - g[j] = (g[j] + f[j - h]) % mod; + f[i][j] = (f[i][j] + f[i - 1][j - h]) % mod; } } - f.splice(0, target + 1, ...g); } - return f[target]; + return f[n][target]; } diff --git a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution2.cpp b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution2.cpp new file mode 100644 index 0000000000000..063d031a29ee1 --- /dev/null +++ b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution2.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int numRollsToTarget(int n, int k, int target) { + const int mod = 1e9 + 7; + vector f(target + 1); + f[0] = 1; + for (int i = 1; i <= n; ++i) { + vector g(target + 1); + for (int j = 1; j <= min(target, i * k); ++j) { + for (int h = 1; h <= min(j, k); ++h) { + g[j] = (g[j] + f[j - h]) % mod; + } + } + f = move(g); + } + return f[target]; + } +}; \ No newline at end of file diff --git a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution2.go b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution2.go new file mode 100644 index 0000000000000..9b153861eed01 --- /dev/null +++ b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution2.go @@ -0,0 +1,15 @@ +func numRollsToTarget(n int, k int, target int) int { + const mod int = 1e9 + 7 + f := make([]int, target+1) + f[0] = 1 + for i := 1; i <= n; i++ { + g := make([]int, target+1) + for j := 1; j <= min(target, i*k); j++ { + for h := 1; h <= min(j, k); h++ { + g[j] = (g[j] + f[j-h]) % mod + } + } + f = g + } + return f[target] +} \ No newline at end of file diff --git a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution2.java b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution2.java new file mode 100644 index 0000000000000..271cc882bf62a --- /dev/null +++ b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution2.java @@ -0,0 +1,17 @@ +class Solution { + public int numRollsToTarget(int n, int k, int target) { + final int mod = (int) 1e9 + 7; + int[] f = new int[target + 1]; + f[0] = 1; + for (int i = 1; i <= n; ++i) { + int[] g = new int[target + 1]; + for (int j = 1; j <= Math.min(target, i * k); ++j) { + for (int h = 1; h <= Math.min(j, k); ++h) { + g[j] = (g[j] + f[j - h]) % mod; + } + } + f = g; + } + return f[target]; + } +} \ No newline at end of file diff --git a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution2.py b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution2.py new file mode 100644 index 0000000000000..9949794daead7 --- /dev/null +++ b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def numRollsToTarget(self, n: int, k: int, target: int) -> int: + f = [1] + [0] * target + mod = 10**9 + 7 + for i in range(1, n + 1): + g = [0] * (target + 1) + for j in range(1, min(i * k, target) + 1): + for h in range(1, min(j, k) + 1): + g[j] = (g[j] + f[j - h]) % mod + f = g + return f[target] diff --git a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution2.rs b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution2.rs new file mode 100644 index 0000000000000..4bb8d9e961086 --- /dev/null +++ b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution2.rs @@ -0,0 +1,22 @@ +impl Solution { + pub fn num_rolls_to_target(n: i32, k: i32, target: i32) -> i32 { + let _mod = 1_000_000_007; + let n = n as usize; + let k = k as usize; + let target = target as usize; + let mut f = vec![0; target + 1]; + f[0] = 1; + + for i in 1..=n { + let mut g = vec![0; target + 1]; + for j in 1..=target { + for h in 1..=j.min(k) { + g[j] = (g[j] + f[j - h]) % _mod; + } + } + f = g; + } + + f[target] + } +} diff --git a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution2.ts b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution2.ts new file mode 100644 index 0000000000000..705b0c1cb1b1a --- /dev/null +++ b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution2.ts @@ -0,0 +1,15 @@ +function numRollsToTarget(n: number, k: number, target: number): number { + const f = Array(target + 1).fill(0); + f[0] = 1; + const mod = 1e9 + 7; + for (let i = 1; i <= n; ++i) { + const g = Array(target + 1).fill(0); + for (let j = 1; j <= Math.min(i * k, target); ++j) { + for (let h = 1; h <= Math.min(j, k); ++h) { + g[j] = (g[j] + f[j - h]) % mod; + } + } + f.splice(0, target + 1, ...g); + } + return f[target]; +} diff --git a/solution/1100-1199/1157.Online Majority Element In Subarray/Solution.py b/solution/1100-1199/1157.Online Majority Element In Subarray/Solution.py index f014296c4d8ac..715a076d6c595 100644 --- a/solution/1100-1199/1157.Online Majority Element In Subarray/Solution.py +++ b/solution/1100-1199/1157.Online Majority Element In Subarray/Solution.py @@ -1,72 +1,72 @@ -class Node: - __slots__ = ("l", "r", "x", "cnt") - - def __init__(self): - self.l = self.r = 0 - self.x = self.cnt = 0 - - -class SegmentTree: - def __init__(self, nums): - self.nums = nums - n = len(nums) - self.tr = [Node() for _ in range(n << 2)] - self.build(1, 1, n) - - def build(self, u, l, r): - self.tr[u].l, self.tr[u].r = l, r - if l == r: - self.tr[u].x = self.nums[l - 1] - self.tr[u].cnt = 1 - return - mid = (l + r) >> 1 - self.build(u << 1, l, mid) - self.build(u << 1 | 1, mid + 1, r) - self.pushup(u) - - def query(self, u, l, r): - if self.tr[u].l >= l and self.tr[u].r <= r: - return self.tr[u].x, self.tr[u].cnt - mid = (self.tr[u].l + self.tr[u].r) >> 1 - if r <= mid: - return self.query(u << 1, l, r) - if l > mid: - return self.query(u << 1 | 1, l, r) - x1, cnt1 = self.query(u << 1, l, r) - x2, cnt2 = self.query(u << 1 | 1, l, r) - if x1 == x2: - return x1, cnt1 + cnt2 - if cnt1 >= cnt2: - return x1, cnt1 - cnt2 - else: - return x2, cnt2 - cnt1 - - def pushup(self, u): - if self.tr[u << 1].x == self.tr[u << 1 | 1].x: - self.tr[u].x = self.tr[u << 1].x - self.tr[u].cnt = self.tr[u << 1].cnt + self.tr[u << 1 | 1].cnt - elif self.tr[u << 1].cnt >= self.tr[u << 1 | 1].cnt: - self.tr[u].x = self.tr[u << 1].x - self.tr[u].cnt = self.tr[u << 1].cnt - self.tr[u << 1 | 1].cnt - else: - self.tr[u].x = self.tr[u << 1 | 1].x - self.tr[u].cnt = self.tr[u << 1 | 1].cnt - self.tr[u << 1].cnt - - -class MajorityChecker: - def __init__(self, arr: List[int]): - self.tree = SegmentTree(arr) - self.d = defaultdict(list) - for i, x in enumerate(arr): - self.d[x].append(i) - - def query(self, left: int, right: int, threshold: int) -> int: - x, _ = self.tree.query(1, left + 1, right + 1) - l = bisect_left(self.d[x], left) - r = bisect_left(self.d[x], right + 1) - return x if r - l >= threshold else -1 - - -# Your MajorityChecker object will be instantiated and called as such: -# obj = MajorityChecker(arr) -# param_1 = obj.query(left,right,threshold) +class Node: + __slots__ = ("l", "r", "x", "cnt") + + def __init__(self): + self.l = self.r = 0 + self.x = self.cnt = 0 + + +class SegmentTree: + def __init__(self, nums): + self.nums = nums + n = len(nums) + self.tr = [Node() for _ in range(n << 2)] + self.build(1, 1, n) + + def build(self, u, l, r): + self.tr[u].l, self.tr[u].r = l, r + if l == r: + self.tr[u].x = self.nums[l - 1] + self.tr[u].cnt = 1 + return + mid = (l + r) >> 1 + self.build(u << 1, l, mid) + self.build(u << 1 | 1, mid + 1, r) + self.pushup(u) + + def query(self, u, l, r): + if self.tr[u].l >= l and self.tr[u].r <= r: + return self.tr[u].x, self.tr[u].cnt + mid = (self.tr[u].l + self.tr[u].r) >> 1 + if r <= mid: + return self.query(u << 1, l, r) + if l > mid: + return self.query(u << 1 | 1, l, r) + x1, cnt1 = self.query(u << 1, l, r) + x2, cnt2 = self.query(u << 1 | 1, l, r) + if x1 == x2: + return x1, cnt1 + cnt2 + if cnt1 >= cnt2: + return x1, cnt1 - cnt2 + else: + return x2, cnt2 - cnt1 + + def pushup(self, u): + if self.tr[u << 1].x == self.tr[u << 1 | 1].x: + self.tr[u].x = self.tr[u << 1].x + self.tr[u].cnt = self.tr[u << 1].cnt + self.tr[u << 1 | 1].cnt + elif self.tr[u << 1].cnt >= self.tr[u << 1 | 1].cnt: + self.tr[u].x = self.tr[u << 1].x + self.tr[u].cnt = self.tr[u << 1].cnt - self.tr[u << 1 | 1].cnt + else: + self.tr[u].x = self.tr[u << 1 | 1].x + self.tr[u].cnt = self.tr[u << 1 | 1].cnt - self.tr[u << 1].cnt + + +class MajorityChecker: + def __init__(self, arr: List[int]): + self.tree = SegmentTree(arr) + self.d = defaultdict(list) + for i, x in enumerate(arr): + self.d[x].append(i) + + def query(self, left: int, right: int, threshold: int) -> int: + x, _ = self.tree.query(1, left + 1, right + 1) + l = bisect_left(self.d[x], left) + r = bisect_left(self.d[x], right + 1) + return x if r - l >= threshold else -1 + + +# Your MajorityChecker object will be instantiated and called as such: +# obj = MajorityChecker(arr) +# param_1 = obj.query(left,right,threshold) diff --git a/solution/1100-1199/1158.Market Analysis I/Solution.sql b/solution/1100-1199/1158.Market Analysis I/Solution.sql index 975977bb202a6..8b0c42b92a0ee 100644 --- a/solution/1100-1199/1158.Market Analysis I/Solution.sql +++ b/solution/1100-1199/1158.Market Analysis I/Solution.sql @@ -1,9 +1,9 @@ # Write your MySQL query statement below SELECT - user_id AS buyer_id, - join_date, - IFNULL(SUM(YEAR(order_date) = 2019), 0) AS orders_in_2019 + u.user_id AS buyer_id, + u.join_date, + COUNT(order_id) AS orders_in_2019 FROM Users AS u - LEFT JOIN Orders AS o ON u.user_id = buyer_id -GROUP BY 1; + LEFT JOIN Orders AS o ON u.user_id = o.buyer_id AND YEAR(order_date) = 2019 +GROUP BY user_id; diff --git a/solution/1100-1199/1158.Market Analysis I/Solution2.sql b/solution/1100-1199/1158.Market Analysis I/Solution2.sql new file mode 100644 index 0000000000000..975977bb202a6 --- /dev/null +++ b/solution/1100-1199/1158.Market Analysis I/Solution2.sql @@ -0,0 +1,9 @@ +# Write your MySQL query statement below +SELECT + user_id AS buyer_id, + join_date, + IFNULL(SUM(YEAR(order_date) = 2019), 0) AS orders_in_2019 +FROM + Users AS u + LEFT JOIN Orders AS o ON u.user_id = buyer_id +GROUP BY 1; diff --git a/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/Solution.php b/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/Solution.php index 0e52dd5dde1f5..b1133c549762d 100644 --- a/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/Solution.php +++ b/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/Solution.php @@ -22,4 +22,4 @@ function countCharacters($words, $chars) { } return $sum; } -} \ No newline at end of file +} diff --git a/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/Solution2.cpp b/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/Solution2.cpp new file mode 100644 index 0000000000000..b85bc85f0a0a3 --- /dev/null +++ b/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/Solution2.cpp @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int maxLevelSum(TreeNode* root) { + vector s; + dfs(root, 0, s); + int mx = INT_MIN; + int ans = 0; + for (int i = 0; i < s.size(); ++i) + if (mx < s[i]) mx = s[i], ans = i + 1; + return ans; + } + + void dfs(TreeNode* root, int i, vector& s) { + if (!root) return; + if (s.size() == i) + s.push_back(root->val); + else + s[i] += root->val; + dfs(root->left, i + 1, s); + dfs(root->right, i + 1, s); + } +}; \ No newline at end of file diff --git a/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/Solution2.go b/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/Solution2.go new file mode 100644 index 0000000000000..dc11254d9d443 --- /dev/null +++ b/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/Solution2.go @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func maxLevelSum(root *TreeNode) int { + s := []int{} + var dfs func(*TreeNode, int) + dfs = func(root *TreeNode, i int) { + if root == nil { + return + } + if len(s) == i { + s = append(s, root.Val) + } else { + s[i] += root.Val + } + dfs(root.Left, i+1) + dfs(root.Right, i+1) + } + dfs(root, 0) + ans, mx := 0, -0x3f3f3f3f + for i, v := range s { + if mx < v { + mx = v + ans = i + 1 + } + } + return ans +} \ No newline at end of file diff --git a/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/Solution2.java b/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/Solution2.java new file mode 100644 index 0000000000000..abd36a5c16c7b --- /dev/null +++ b/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/Solution2.java @@ -0,0 +1,44 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private List s = new ArrayList<>(); + + public int maxLevelSum(TreeNode root) { + dfs(root, 0); + int mx = Integer.MIN_VALUE; + int ans = 0; + for (int i = 0; i < s.size(); ++i) { + if (mx < s.get(i)) { + mx = s.get(i); + ans = i + 1; + } + } + return ans; + } + + private void dfs(TreeNode root, int i) { + if (root == null) { + return; + } + if (i == s.size()) { + s.add(root.val); + } else { + s.set(i, s.get(i) + root.val); + } + dfs(root.left, i + 1); + dfs(root.right, i + 1); + } +} \ No newline at end of file diff --git a/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/Solution2.py b/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/Solution2.py new file mode 100644 index 0000000000000..7db9142eae343 --- /dev/null +++ b/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/Solution2.py @@ -0,0 +1,21 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def maxLevelSum(self, root: Optional[TreeNode]) -> int: + def dfs(node, i): + if node is None: + return + if i == len(s): + s.append(node.val) + else: + s[i] += node.val + dfs(node.left, i + 1) + dfs(node.right, i + 1) + + s = [] + dfs(root, 0) + return s.index(max(s)) + 1 diff --git a/solution/1100-1199/1162.As Far from Land as Possible/Solution.py b/solution/1100-1199/1162.As Far from Land as Possible/Solution.py index b575e164a72c9..482e66bd8a3e2 100644 --- a/solution/1100-1199/1162.As Far from Land as Possible/Solution.py +++ b/solution/1100-1199/1162.As Far from Land as Possible/Solution.py @@ -1,18 +1,18 @@ -class Solution: - def maxDistance(self, grid: List[List[int]]) -> int: - n = len(grid) - q = deque((i, j) for i in range(n) for j in range(n) if grid[i][j]) - ans = -1 - if len(q) in (0, n * n): - return ans - dirs = (-1, 0, 1, 0, -1) - while q: - for _ in range(len(q)): - i, j = q.popleft() - for a, b in pairwise(dirs): - x, y = i + a, j + b - if 0 <= x < n and 0 <= y < n and grid[x][y] == 0: - grid[x][y] = 1 - q.append((x, y)) - ans += 1 - return ans +class Solution: + def maxDistance(self, grid: List[List[int]]) -> int: + n = len(grid) + q = deque((i, j) for i in range(n) for j in range(n) if grid[i][j]) + ans = -1 + if len(q) in (0, n * n): + return ans + dirs = (-1, 0, 1, 0, -1) + while q: + for _ in range(len(q)): + i, j = q.popleft() + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < n and 0 <= y < n and grid[x][y] == 0: + grid[x][y] = 1 + q.append((x, y)) + ans += 1 + return ans diff --git a/solution/1100-1199/1164.Product Price at a Given Date/Solution2.sql b/solution/1100-1199/1164.Product Price at a Given Date/Solution2.sql new file mode 100644 index 0000000000000..3fd9654261903 --- /dev/null +++ b/solution/1100-1199/1164.Product Price at a Given Date/Solution2.sql @@ -0,0 +1,24 @@ +# Write your MySQL query statement below +WITH + P AS ( + SELECT p1.product_id, new_price, change_date + FROM + ( + SELECT DISTINCT product_id + FROM Products + ) AS p1 + LEFT JOIN Products AS p2 + ON p1.product_id = p2.product_id AND p2.change_date <= '2019-08-16' + ), + T AS ( + SELECT + *, + RANK() OVER ( + PARTITION BY product_id + ORDER BY change_date DESC + ) AS rk + FROM P + ) +SELECT product_id, IFNULL(new_price, 10) AS price +FROM T +WHERE rk = 1; diff --git a/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.cpp b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.cpp index 52191b474e2b5..3a7e3f9d74766 100644 --- a/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.cpp +++ b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.cpp @@ -1,56 +1,32 @@ -class UnionFind { -public: - UnionFind(int n) { - p = vector(n); - size = vector(n, 1); - iota(p.begin(), p.end(), 0); - } - - bool unite(int a, int b) { - int pa = find(a), pb = find(b); - if (pa == pb) { - return false; - } - if (size[pa] > size[pb]) { - p[pb] = pa; - size[pa] += size[pb]; - } else { - p[pa] = pb; - size[pb] += size[pa]; - } - return true; - } - - int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } - -private: - vector p, size; -}; - -class Solution { -public: - int minCostToSupplyWater(int n, vector& wells, vector>& pipes) { - for (int i = 0; i < n; ++i) { - pipes.push_back({0, i + 1, wells[i]}); - } - sort(pipes.begin(), pipes.end(), [](const vector& a, const vector& b) { - return a[2] < b[2]; - }); - UnionFind uf(n + 1); - int ans = 0; - for (const auto& x : pipes) { - if (uf.unite(x[0], x[1])) { - ans += x[2]; - if (--n == 0) { - break; - } - } - } - return ans; - } +class Solution { +public: + int minCostToSupplyWater(int n, vector& wells, vector>& pipes) { + for (int i = 0; i < n; ++i) { + pipes.push_back({0, i + 1, wells[i]}); + } + sort(pipes.begin(), pipes.end(), [](const vector& a, const vector& b) { + return a[2] < b[2]; + }); + int p[n + 1]; + iota(p, p + n + 1, 0); + function find = [&](int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + }; + int ans = 0; + for (const auto& x : pipes) { + int pa = find(x[0]), pb = find(x[1]); + if (pa == pb) { + continue; + } + p[pa] = pb; + ans += x[2]; + if (--n == 0) { + break; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.go b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.go index 3eb383b687e91..d5eb9ff9bae59 100644 --- a/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.go +++ b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.go @@ -1,52 +1,30 @@ -type unionFind struct { - p, size []int -} - -func newUnionFind(n int) *unionFind { - p := make([]int, n) - size := make([]int, n) - for i := range p { - p[i] = i - size[i] = 1 - } - return &unionFind{p, size} -} - -func (uf *unionFind) find(x int) int { - if uf.p[x] != x { - uf.p[x] = uf.find(uf.p[x]) - } - return uf.p[x] -} - -func (uf *unionFind) union(a, b int) bool { - pa, pb := uf.find(a), uf.find(b) - if pa == pb { - return false - } - if uf.size[pa] > uf.size[pb] { - uf.p[pb] = pa - uf.size[pa] += uf.size[pb] - } else { - uf.p[pa] = pb - uf.size[pb] += uf.size[pa] - } - return true -} - func minCostToSupplyWater(n int, wells []int, pipes [][]int) (ans int) { for i, w := range wells { pipes = append(pipes, []int{0, i + 1, w}) } sort.Slice(pipes, func(i, j int) bool { return pipes[i][2] < pipes[j][2] }) - uf := newUnionFind(n + 1) + p := make([]int, n+1) + for i := range p { + p[i] = i + } + var find func(int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + for _, x := range pipes { - if uf.union(x[0], x[1]) { - ans += x[2] - n-- - if n == 0 { - break - } + pa, pb := find(x[0]), find(x[1]) + if pa == pb { + continue + } + p[pa] = pb + ans += x[2] + n-- + if n == 0 { + break } } return diff --git a/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.java b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.java index 81ffcd208ea4c..2af4b9c4c24e0 100644 --- a/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.java +++ b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.java @@ -1,57 +1,35 @@ -class UnionFind { - private int[] p; - private int[] size; - - public UnionFind(int n) { - p = new int[n]; - size = new int[n]; - for (int i = 0; i < n; ++i) { - p[i] = i; - size[i] = 1; - } - } - - public int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } - - public boolean union(int a, int b) { - int pa = find(a), pb = find(b); - if (pa == pb) { - return false; - } - if (size[pa] > size[pb]) { - p[pb] = pa; - size[pa] += size[pb]; - } else { - p[pa] = pb; - size[pb] += size[pa]; - } - return true; - } -} - -class Solution { - public int minCostToSupplyWater(int n, int[] wells, int[][] pipes) { - int[][] nums = Arrays.copyOf(pipes, pipes.length + n); - for (int i = 0; i < n; i++) { - nums[pipes.length + i] = new int[] {0, i + 1, wells[i]}; - } - Arrays.sort(nums, (a, b) -> a[2] - b[2]); - UnionFind uf = new UnionFind(n + 1); - int ans = 0; - for (var x : nums) { - int a = x[0], b = x[1], c = x[2]; - if (uf.union(a, b)) { - ans += c; - if (--n == 0) { - break; - } - } - } - return ans; - } +class Solution { + private int[] p; + + public int minCostToSupplyWater(int n, int[] wells, int[][] pipes) { + int[][] nums = Arrays.copyOf(pipes, pipes.length + n); + for (int i = 0; i < n; i++) { + nums[pipes.length + i] = new int[] {0, i + 1, wells[i]}; + } + Arrays.sort(nums, (a, b) -> a[2] - b[2]); + p = new int[n + 1]; + for (int i = 0; i <= n; i++) { + p[i] = i; + } + int ans = 0; + for (var x : nums) { + int a = x[0], b = x[1], c = x[2]; + int pa = find(a), pb = find(b); + if (pa != pb) { + p[pa] = pb; + ans += c; + if (--n == 0) { + return ans; + } + } + } + return ans; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } } \ No newline at end of file diff --git a/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.py b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.py index d86abcec57cee..c407a7e6528d9 100644 --- a/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.py +++ b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.py @@ -1,40 +1,22 @@ -class UnionFind: - __slots__ = ("p", "size") - - def __init__(self, n): - self.p = list(range(n)) - self.size = [1] * n - - def find(self, x: int) -> int: - if self.p[x] != x: - self.p[x] = self.find(self.p[x]) - return self.p[x] - - def union(self, a: int, b: int) -> bool: - pa, pb = self.find(a), self.find(b) - if pa == pb: - return False - if self.size[pa] > self.size[pb]: - self.p[pb] = pa - self.size[pa] += self.size[pb] - else: - self.p[pa] = pb - self.size[pb] += self.size[pa] - return True - - -class Solution: - def minCostToSupplyWater( - self, n: int, wells: List[int], pipes: List[List[int]] - ) -> int: - for i, w in enumerate(wells, 1): - pipes.append([0, i, w]) - pipes.sort(key=lambda x: x[2]) - uf = UnionFind(n + 1) - ans = 0 - for a, b, c in pipes: - if uf.union(a, b): - ans += c - n -= 1 - if n == 0: - return ans +class Solution: + def minCostToSupplyWater( + self, n: int, wells: List[int], pipes: List[List[int]] + ) -> int: + def find(x: int) -> int: + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + for i, w in enumerate(wells, 1): + pipes.append([0, i, w]) + pipes.sort(key=lambda x: x[2]) + p = list(range(n + 1)) + ans = 0 + for a, b, c in pipes: + pa, pb = find(a), find(b) + if pa != pb: + p[pa] = pb + n -= 1 + ans += c + if n == 0: + return ans diff --git a/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.ts b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.ts index 0369acc03dc6e..b5bc243dd9083 100644 --- a/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.ts +++ b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution.ts @@ -1,51 +1,28 @@ -class UnionFind { - private p: number[]; - private size: number[]; - - constructor(n: number) { - this.p = Array(n) - .fill(0) - .map((_, i) => i); - this.size = Array(n).fill(1); - } - - find(x: number): number { - if (this.p[x] !== x) { - this.p[x] = this.find(this.p[x]); - } - return this.p[x]; - } - - union(a: number, b: number): boolean { - const pa = this.find(a); - const pb = this.find(b); - if (pa === pb) { - return false; - } - if (this.size[pa] > this.size[pb]) { - this.p[pb] = pa; - this.size[pa] += this.size[pb]; - } else { - this.p[pa] = pb; - this.size[pb] += this.size[pa]; - } - return true; - } -} - function minCostToSupplyWater(n: number, wells: number[], pipes: number[][]): number { for (let i = 0; i < n; ++i) { pipes.push([0, i + 1, wells[i]]); } pipes.sort((a, b) => a[2] - b[2]); - const uf = new UnionFind(n + 1); + const p = Array(n + 1) + .fill(0) + .map((_, i) => i); + const find = (x: number): number => { + if (p[x] !== x) { + p[x] = find(p[x]); + } + return p[x]; + }; let ans = 0; for (const [a, b, c] of pipes) { - if (uf.union(a, b)) { - ans += c; - if (--n === 0) { - break; - } + const pa = find(a); + const pb = find(b); + if (pa === pb) { + continue; + } + p[pa] = pb; + ans += c; + if (--n === 0) { + break; } } return ans; diff --git a/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution2.cpp b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution2.cpp new file mode 100644 index 0000000000000..07202c901df3a --- /dev/null +++ b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution2.cpp @@ -0,0 +1,56 @@ +class UnionFind { +public: + UnionFind(int n) { + p = vector(n); + size = vector(n, 1); + iota(p.begin(), p.end(), 0); + } + + bool unite(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) { + return false; + } + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + return true; + } + + int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + +private: + vector p, size; +}; + +class Solution { +public: + int minCostToSupplyWater(int n, vector& wells, vector>& pipes) { + for (int i = 0; i < n; ++i) { + pipes.push_back({0, i + 1, wells[i]}); + } + sort(pipes.begin(), pipes.end(), [](const vector& a, const vector& b) { + return a[2] < b[2]; + }); + UnionFind uf(n + 1); + int ans = 0; + for (const auto& x : pipes) { + if (uf.unite(x[0], x[1])) { + ans += x[2]; + if (--n == 0) { + break; + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution2.go b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution2.go new file mode 100644 index 0000000000000..3eb383b687e91 --- /dev/null +++ b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution2.go @@ -0,0 +1,53 @@ +type unionFind struct { + p, size []int +} + +func newUnionFind(n int) *unionFind { + p := make([]int, n) + size := make([]int, n) + for i := range p { + p[i] = i + size[i] = 1 + } + return &unionFind{p, size} +} + +func (uf *unionFind) find(x int) int { + if uf.p[x] != x { + uf.p[x] = uf.find(uf.p[x]) + } + return uf.p[x] +} + +func (uf *unionFind) union(a, b int) bool { + pa, pb := uf.find(a), uf.find(b) + if pa == pb { + return false + } + if uf.size[pa] > uf.size[pb] { + uf.p[pb] = pa + uf.size[pa] += uf.size[pb] + } else { + uf.p[pa] = pb + uf.size[pb] += uf.size[pa] + } + return true +} + +func minCostToSupplyWater(n int, wells []int, pipes [][]int) (ans int) { + for i, w := range wells { + pipes = append(pipes, []int{0, i + 1, w}) + } + sort.Slice(pipes, func(i, j int) bool { return pipes[i][2] < pipes[j][2] }) + uf := newUnionFind(n + 1) + for _, x := range pipes { + if uf.union(x[0], x[1]) { + ans += x[2] + n-- + if n == 0 { + break + } + } + } + return +} \ No newline at end of file diff --git a/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution2.java b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution2.java new file mode 100644 index 0000000000000..f9c7e13f529bb --- /dev/null +++ b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution2.java @@ -0,0 +1,57 @@ +class UnionFind { + private int[] p; + private int[] size; + + public UnionFind(int n) { + p = new int[n]; + size = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + size[i] = 1; + } + } + + public int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + + public boolean union(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) { + return false; + } + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + return true; + } +} + +class Solution { + public int minCostToSupplyWater(int n, int[] wells, int[][] pipes) { + int[][] nums = Arrays.copyOf(pipes, pipes.length + n); + for (int i = 0; i < n; i++) { + nums[pipes.length + i] = new int[] {0, i + 1, wells[i]}; + } + Arrays.sort(nums, (a, b) -> a[2] - b[2]); + UnionFind uf = new UnionFind(n + 1); + int ans = 0; + for (var x : nums) { + int a = x[0], b = x[1], c = x[2]; + if (uf.union(a, b)) { + ans += c; + if (--n == 0) { + break; + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution2.py b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution2.py new file mode 100644 index 0000000000000..98b152386abf8 --- /dev/null +++ b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution2.py @@ -0,0 +1,40 @@ +class UnionFind: + __slots__ = ("p", "size") + + def __init__(self, n): + self.p = list(range(n)) + self.size = [1] * n + + def find(self, x: int) -> int: + if self.p[x] != x: + self.p[x] = self.find(self.p[x]) + return self.p[x] + + def union(self, a: int, b: int) -> bool: + pa, pb = self.find(a), self.find(b) + if pa == pb: + return False + if self.size[pa] > self.size[pb]: + self.p[pb] = pa + self.size[pa] += self.size[pb] + else: + self.p[pa] = pb + self.size[pb] += self.size[pa] + return True + + +class Solution: + def minCostToSupplyWater( + self, n: int, wells: List[int], pipes: List[List[int]] + ) -> int: + for i, w in enumerate(wells, 1): + pipes.append([0, i, w]) + pipes.sort(key=lambda x: x[2]) + uf = UnionFind(n + 1) + ans = 0 + for a, b, c in pipes: + if uf.union(a, b): + ans += c + n -= 1 + if n == 0: + return ans diff --git a/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution2.ts b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution2.ts new file mode 100644 index 0000000000000..0369acc03dc6e --- /dev/null +++ b/solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution2.ts @@ -0,0 +1,52 @@ +class UnionFind { + private p: number[]; + private size: number[]; + + constructor(n: number) { + this.p = Array(n) + .fill(0) + .map((_, i) => i); + this.size = Array(n).fill(1); + } + + find(x: number): number { + if (this.p[x] !== x) { + this.p[x] = this.find(this.p[x]); + } + return this.p[x]; + } + + union(a: number, b: number): boolean { + const pa = this.find(a); + const pb = this.find(b); + if (pa === pb) { + return false; + } + if (this.size[pa] > this.size[pb]) { + this.p[pb] = pa; + this.size[pa] += this.size[pb]; + } else { + this.p[pa] = pb; + this.size[pb] += this.size[pa]; + } + return true; + } +} + +function minCostToSupplyWater(n: number, wells: number[], pipes: number[][]): number { + for (let i = 0; i < n; ++i) { + pipes.push([0, i + 1, wells[i]]); + } + pipes.sort((a, b) => a[2] - b[2]); + const uf = new UnionFind(n + 1); + let ans = 0; + for (const [a, b, c] of pipes) { + if (uf.union(a, b)) { + ans += c; + if (--n === 0) { + break; + } + } + } + return ans; +} diff --git a/solution/1100-1199/1174.Immediate Food Delivery II/Solution2.sql b/solution/1100-1199/1174.Immediate Food Delivery II/Solution2.sql new file mode 100644 index 0000000000000..afc2276a03956 --- /dev/null +++ b/solution/1100-1199/1174.Immediate Food Delivery II/Solution2.sql @@ -0,0 +1,15 @@ +# Write your MySQL query statement below +WITH + T AS ( + SELECT + *, + RANK() OVER ( + PARTITION BY customer_id + ORDER BY order_date + ) AS rk + FROM Delivery + ) +SELECT + ROUND(AVG(order_date = customer_pref_delivery_date) * 100, 2) AS immediate_percentage +FROM T +WHERE rk = 1; diff --git a/solution/1100-1199/1176.Diet Plan Performance/Solution.cpp b/solution/1100-1199/1176.Diet Plan Performance/Solution.cpp index e1fa70133689c..a4a8f6cd908a3 100644 --- a/solution/1100-1199/1176.Diet Plan Performance/Solution.cpp +++ b/solution/1100-1199/1176.Diet Plan Performance/Solution.cpp @@ -2,18 +2,17 @@ class Solution { public: int dietPlanPerformance(vector& calories, int k, int lower, int upper) { int n = calories.size(); - int s = accumulate(calories.begin(), calories.begin() + k, 0); - int ans = 0; - if (s < lower) { - --ans; - } else if (s > upper) { - ++ans; + int s[n + 1]; + s[0] = 0; + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + calories[i]; } - for (int i = k; i < n; ++i) { - s += calories[i] - calories[i - k]; - if (s < lower) { + int ans = 0; + for (int i = 0; i < n - k + 1; ++i) { + int t = s[i + k] - s[i]; + if (t < lower) { --ans; - } else if (s > upper) { + } else if (t > upper) { ++ans; } } diff --git a/solution/1100-1199/1176.Diet Plan Performance/Solution.go b/solution/1100-1199/1176.Diet Plan Performance/Solution.go index 5fb40eb29f8e7..b84e235529487 100644 --- a/solution/1100-1199/1176.Diet Plan Performance/Solution.go +++ b/solution/1100-1199/1176.Diet Plan Performance/Solution.go @@ -1,19 +1,14 @@ func dietPlanPerformance(calories []int, k int, lower int, upper int) (ans int) { n := len(calories) - s := 0 - for _, x := range calories[:k] { - s += x + s := make([]int, n+1) + for i, x := range calories { + s[i+1] = s[i] + x } - if s < lower { - ans-- - } else if s > upper { - ans++ - } - for i := k; i < n; i++ { - s += calories[i] - calories[i-k] - if s < lower { + for i := 0; i < n-k+1; i++ { + t := s[i+k] - s[i] + if t < lower { ans-- - } else if s > upper { + } else if t > upper { ans++ } } diff --git a/solution/1100-1199/1176.Diet Plan Performance/Solution.java b/solution/1100-1199/1176.Diet Plan Performance/Solution.java index 3fc05b222eade..548bdb7255193 100644 --- a/solution/1100-1199/1176.Diet Plan Performance/Solution.java +++ b/solution/1100-1199/1176.Diet Plan Performance/Solution.java @@ -1,20 +1,16 @@ class Solution { public int dietPlanPerformance(int[] calories, int k, int lower, int upper) { - int s = 0, n = calories.length; - for (int i = 0; i < k; ++i) { - s += calories[i]; + int n = calories.length; + int[] s = new int[n + 1]; + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + calories[i]; } int ans = 0; - if (s < lower) { - --ans; - } else if (s > upper) { - ++ans; - } - for (int i = k; i < n; ++i) { - s += calories[i] - calories[i - k]; - if (s < lower) { + for (int i = 0; i < n - k + 1; ++i) { + int t = s[i + k] - s[i]; + if (t < lower) { --ans; - } else if (s > upper) { + } else if (t > upper) { ++ans; } } diff --git a/solution/1100-1199/1176.Diet Plan Performance/Solution.py b/solution/1100-1199/1176.Diet Plan Performance/Solution.py index 8122ddd73fef6..5859ed5e8dd56 100644 --- a/solution/1100-1199/1176.Diet Plan Performance/Solution.py +++ b/solution/1100-1199/1176.Diet Plan Performance/Solution.py @@ -2,16 +2,12 @@ class Solution: def dietPlanPerformance( self, calories: List[int], k: int, lower: int, upper: int ) -> int: - def check(s): - if s < lower: - return -1 - if s > upper: - return 1 - return 0 - - s, n = sum(calories[:k]), len(calories) - ans = check(s) - for i in range(k, n): - s += calories[i] - calories[i - k] - ans += check(s) + s = list(accumulate(calories, initial=0)) + ans, n = 0, len(calories) + for i in range(n - k + 1): + t = s[i + k] - s[i] + if t < lower: + ans -= 1 + elif t > upper: + ans += 1 return ans diff --git a/solution/1100-1199/1176.Diet Plan Performance/Solution.ts b/solution/1100-1199/1176.Diet Plan Performance/Solution.ts index 32058c13c49a8..4887793c1f051 100644 --- a/solution/1100-1199/1176.Diet Plan Performance/Solution.ts +++ b/solution/1100-1199/1176.Diet Plan Performance/Solution.ts @@ -1,17 +1,15 @@ function dietPlanPerformance(calories: number[], k: number, lower: number, upper: number): number { const n = calories.length; - let s = calories.slice(0, k).reduce((a, b) => a + b); - let ans = 0; - if (s < lower) { - --ans; - } else if (s > upper) { - ++ans; + const s: number[] = new Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + s[i + 1] = s[i] + calories[i]; } - for (let i = k; i < n; ++i) { - s += calories[i] - calories[i - k]; - if (s < lower) { + let ans = 0; + for (let i = 0; i < n - k + 1; ++i) { + const t = s[i + k] - s[i]; + if (t < lower) { --ans; - } else if (s > upper) { + } else if (t > upper) { ++ans; } } diff --git a/solution/1100-1199/1176.Diet Plan Performance/Solution2.cpp b/solution/1100-1199/1176.Diet Plan Performance/Solution2.cpp new file mode 100644 index 0000000000000..e1fa70133689c --- /dev/null +++ b/solution/1100-1199/1176.Diet Plan Performance/Solution2.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int dietPlanPerformance(vector& calories, int k, int lower, int upper) { + int n = calories.size(); + int s = accumulate(calories.begin(), calories.begin() + k, 0); + int ans = 0; + if (s < lower) { + --ans; + } else if (s > upper) { + ++ans; + } + for (int i = k; i < n; ++i) { + s += calories[i] - calories[i - k]; + if (s < lower) { + --ans; + } else if (s > upper) { + ++ans; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1100-1199/1176.Diet Plan Performance/Solution2.go b/solution/1100-1199/1176.Diet Plan Performance/Solution2.go new file mode 100644 index 0000000000000..5fb40eb29f8e7 --- /dev/null +++ b/solution/1100-1199/1176.Diet Plan Performance/Solution2.go @@ -0,0 +1,21 @@ +func dietPlanPerformance(calories []int, k int, lower int, upper int) (ans int) { + n := len(calories) + s := 0 + for _, x := range calories[:k] { + s += x + } + if s < lower { + ans-- + } else if s > upper { + ans++ + } + for i := k; i < n; i++ { + s += calories[i] - calories[i-k] + if s < lower { + ans-- + } else if s > upper { + ans++ + } + } + return +} \ No newline at end of file diff --git a/solution/1100-1199/1176.Diet Plan Performance/Solution2.java b/solution/1100-1199/1176.Diet Plan Performance/Solution2.java new file mode 100644 index 0000000000000..3fc05b222eade --- /dev/null +++ b/solution/1100-1199/1176.Diet Plan Performance/Solution2.java @@ -0,0 +1,23 @@ +class Solution { + public int dietPlanPerformance(int[] calories, int k, int lower, int upper) { + int s = 0, n = calories.length; + for (int i = 0; i < k; ++i) { + s += calories[i]; + } + int ans = 0; + if (s < lower) { + --ans; + } else if (s > upper) { + ++ans; + } + for (int i = k; i < n; ++i) { + s += calories[i] - calories[i - k]; + if (s < lower) { + --ans; + } else if (s > upper) { + ++ans; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1100-1199/1176.Diet Plan Performance/Solution2.py b/solution/1100-1199/1176.Diet Plan Performance/Solution2.py new file mode 100644 index 0000000000000..8122ddd73fef6 --- /dev/null +++ b/solution/1100-1199/1176.Diet Plan Performance/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def dietPlanPerformance( + self, calories: List[int], k: int, lower: int, upper: int + ) -> int: + def check(s): + if s < lower: + return -1 + if s > upper: + return 1 + return 0 + + s, n = sum(calories[:k]), len(calories) + ans = check(s) + for i in range(k, n): + s += calories[i] - calories[i - k] + ans += check(s) + return ans diff --git a/solution/1100-1199/1176.Diet Plan Performance/Solution2.ts b/solution/1100-1199/1176.Diet Plan Performance/Solution2.ts new file mode 100644 index 0000000000000..32058c13c49a8 --- /dev/null +++ b/solution/1100-1199/1176.Diet Plan Performance/Solution2.ts @@ -0,0 +1,19 @@ +function dietPlanPerformance(calories: number[], k: number, lower: number, upper: number): number { + const n = calories.length; + let s = calories.slice(0, k).reduce((a, b) => a + b); + let ans = 0; + if (s < lower) { + --ans; + } else if (s > upper) { + ++ans; + } + for (let i = k; i < n; ++i) { + s += calories[i] - calories[i - k]; + if (s < lower) { + --ans; + } else if (s > upper) { + ++ans; + } + } + return ans; +} diff --git a/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/Solution2.cpp b/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/Solution2.cpp new file mode 100644 index 0000000000000..467aceaf92e57 --- /dev/null +++ b/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int countLetters(string s) { + int ans = 0; + int i = 0, n = s.size(); + while (i < n) { + int j = i; + int cnt = 0; + while (j < n && s[j] == s[i]) { + ++j; + ans += ++cnt; + } + i = j; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/Solution2.go b/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/Solution2.go new file mode 100644 index 0000000000000..1725f31850873 --- /dev/null +++ b/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/Solution2.go @@ -0,0 +1,14 @@ +func countLetters(s string) (ans int) { + i, n := 0, len(s) + for i < n { + j := i + cnt := 0 + for j < n && s[j] == s[i] { + j++ + cnt++ + ans += cnt + } + i = j + } + return +} \ No newline at end of file diff --git a/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/Solution2.java b/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/Solution2.java new file mode 100644 index 0000000000000..23f80fa5a4bbe --- /dev/null +++ b/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public int countLetters(String s) { + int ans = 0; + int i = 0, n = s.length(); + while (i < n) { + int j = i; + int cnt = 0; + while (j < n && s.charAt(j) == s.charAt(i)) { + ++j; + ans += ++cnt; + } + i = j; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/Solution2.py b/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/Solution2.py new file mode 100644 index 0000000000000..c4128b36dab4d --- /dev/null +++ b/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def countLetters(self, s: str) -> int: + ans = 0 + i, n = 0, len(s) + while i < n: + j = i + cnt = 0 + while j < n and s[j] == s[i]: + j += 1 + cnt += 1 + ans += cnt + i = j + return ans diff --git a/solution/1100-1199/1185.Day of the Week/Solution.java b/solution/1100-1199/1185.Day of the Week/Solution.java index 52a55ba2123f5..04927e763349d 100644 --- a/solution/1100-1199/1185.Day of the Week/Solution.java +++ b/solution/1100-1199/1185.Day of the Week/Solution.java @@ -1,4 +1,5 @@ import java.util.Calendar; + class Solution { private static final String[] WEEK = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; @@ -8,4 +9,4 @@ public static String dayOfTheWeek(int day, int month, int year) { calendar.set(year, month - 1, day); return WEEK[calendar.get(Calendar.DAY_OF_WEEK) - 1]; } -} +} \ No newline at end of file diff --git a/solution/1100-1199/1185.Day of the Week/Solution2.java b/solution/1100-1199/1185.Day of the Week/Solution2.java new file mode 100644 index 0000000000000..bb326def857d8 --- /dev/null +++ b/solution/1100-1199/1185.Day of the Week/Solution2.java @@ -0,0 +1,13 @@ +class Solution { + public String dayOfTheWeek(int d, int m, int y) { + if (m < 3) { + m += 12; + y -= 1; + } + int c = y / 100; + y %= 100; + int w = (c / 4 - 2 * c + y + y / 4 + 13 * (m + 1) / 5 + d - 1) % 7; + return new String[] {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", + "Saturday"}[(w + 7) % 7]; + } +} \ No newline at end of file diff --git a/solution/1100-1199/1185.Day of the Week/Solution2.py b/solution/1100-1199/1185.Day of the Week/Solution2.py new file mode 100644 index 0000000000000..0a3a5b4ab505a --- /dev/null +++ b/solution/1100-1199/1185.Day of the Week/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def dayOfTheWeek(self, d: int, m: int, y: int) -> str: + if m < 3: + m += 12 + y -= 1 + c = y // 100 + y = y % 100 + w = (c // 4 - 2 * c + y + y // 4 + 13 * (m + 1) // 5 + d - 1) % 7 + return [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + ][w] diff --git a/solution/1100-1199/1187.Make Array Strictly Increasing/Solution.cs b/solution/1100-1199/1187.Make Array Strictly Increasing/Solution.cs index 73cd2007c2af0..3e032cae8e976 100644 --- a/solution/1100-1199/1187.Make Array Strictly Increasing/Solution.cs +++ b/solution/1100-1199/1187.Make Array Strictly Increasing/Solution.cs @@ -43,4 +43,4 @@ private int search(int[] nums, int x, int n) { } return l; } -} \ No newline at end of file +} diff --git a/solution/1100-1199/1189.Maximum Number of Balloons/Solution.php b/solution/1100-1199/1189.Maximum Number of Balloons/Solution.php index 834c4ca1fdb62..845b38017fe35 100644 --- a/solution/1100-1199/1189.Maximum Number of Balloons/Solution.php +++ b/solution/1100-1199/1189.Maximum Number of Balloons/Solution.php @@ -22,4 +22,4 @@ function maxNumberOfBalloons($text) { $cnt4 = floor($cnt4 / 2); return min($cnt1, $cnt2, $cnt3, $cnt4, $cnt5); } -} \ No newline at end of file +} diff --git a/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution.cpp b/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution.cpp index 696b49d2a9f3a..fc762de8e2ec4 100644 --- a/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution.cpp +++ b/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution.cpp @@ -1,30 +1,20 @@ class Solution { public: string reverseParentheses(string s) { - int n = s.size(); - vector d(n); - stack stk; - for (int i = 0; i < n; ++i) { - if (s[i] == '(') { - stk.push(i); - } else if (s[i] == ')') { - int j = stk.top(); - stk.pop(); - d[i] = j; - d[j] = i; - } - } - int i = 0, x = 1; - string ans; - while (i < n) { - if (s[i] == '(' || s[i] == ')') { - i = d[i]; - x = -x; + string stk; + for (char& c : s) { + if (c == ')') { + string t; + while (stk.back() != '(') { + t.push_back(stk.back()); + stk.pop_back(); + } + stk.pop_back(); + stk += t; } else { - ans.push_back(s[i]); + stk.push_back(c); } - i += x; } - return ans; + return stk; } }; \ No newline at end of file diff --git a/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution.go b/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution.go index 1dc16778ebb10..8711590a9afc8 100644 --- a/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution.go +++ b/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution.go @@ -1,26 +1,17 @@ func reverseParentheses(s string) string { - n := len(s) - d := make([]int, n) - stk := []int{} - for i, c := range s { - if c == '(' { - stk = append(stk, i) - } else if c == ')' { - j := stk[len(stk)-1] + stk := []byte{} + for i := range s { + if s[i] == ')' { + t := []byte{} + for stk[len(stk)-1] != '(' { + t = append(t, stk[len(stk)-1]) + stk = stk[:len(stk)-1] + } stk = stk[:len(stk)-1] - d[i], d[j] = j, i - } - } - ans := []byte{} - i, x := 0, 1 - for i < n { - if s[i] == '(' || s[i] == ')' { - i = d[i] - x = -x + stk = append(stk, t...) } else { - ans = append(ans, s[i]) + stk = append(stk, s[i]) } - i += x } - return string(ans) + return string(stk) } \ No newline at end of file diff --git a/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution.py b/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution.py index dbd8e08776a9b..7ae106bbea4a0 100644 --- a/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution.py +++ b/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution.py @@ -1,21 +1,13 @@ class Solution: def reverseParentheses(self, s: str) -> str: - n = len(s) - d = [0] * n stk = [] - for i, c in enumerate(s): - if c == '(': - stk.append(i) - elif c == ')': - j = stk.pop() - d[i], d[j] = j, i - i, x = 0, 1 - ans = [] - while i < n: - if s[i] in '()': - i = d[i] - x = -x + for c in s: + if c == ')': + t = [] + while stk[-1] != '(': + t.append(stk.pop()) + stk.pop() + stk.extend(t) else: - ans.append(s[i]) - i += x - return ''.join(ans) + stk.append(c) + return ''.join(stk) diff --git a/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution2.cpp b/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution2.cpp new file mode 100644 index 0000000000000..696b49d2a9f3a --- /dev/null +++ b/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution2.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + string reverseParentheses(string s) { + int n = s.size(); + vector d(n); + stack stk; + for (int i = 0; i < n; ++i) { + if (s[i] == '(') { + stk.push(i); + } else if (s[i] == ')') { + int j = stk.top(); + stk.pop(); + d[i] = j; + d[j] = i; + } + } + int i = 0, x = 1; + string ans; + while (i < n) { + if (s[i] == '(' || s[i] == ')') { + i = d[i]; + x = -x; + } else { + ans.push_back(s[i]); + } + i += x; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution2.go b/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution2.go new file mode 100644 index 0000000000000..1dc16778ebb10 --- /dev/null +++ b/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution2.go @@ -0,0 +1,26 @@ +func reverseParentheses(s string) string { + n := len(s) + d := make([]int, n) + stk := []int{} + for i, c := range s { + if c == '(' { + stk = append(stk, i) + } else if c == ')' { + j := stk[len(stk)-1] + stk = stk[:len(stk)-1] + d[i], d[j] = j, i + } + } + ans := []byte{} + i, x := 0, 1 + for i < n { + if s[i] == '(' || s[i] == ')' { + i = d[i] + x = -x + } else { + ans = append(ans, s[i]) + } + i += x + } + return string(ans) +} \ No newline at end of file diff --git a/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution2.py b/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution2.py new file mode 100644 index 0000000000000..dbd8e08776a9b --- /dev/null +++ b/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/Solution2.py @@ -0,0 +1,21 @@ +class Solution: + def reverseParentheses(self, s: str) -> str: + n = len(s) + d = [0] * n + stk = [] + for i, c in enumerate(s): + if c == '(': + stk.append(i) + elif c == ')': + j = stk.pop() + d[i], d[j] = j, i + i, x = 0, 1 + ans = [] + while i < n: + if s[i] in '()': + i = d[i] + x = -x + else: + ans.append(s[i]) + i += x + return ''.join(ans) diff --git a/solution/1100-1199/1195.Fizz Buzz Multithreaded/Solution.cpp b/solution/1100-1199/1195.Fizz Buzz Multithreaded/Solution.cpp index f6f049e38e2f1..4a0fe7aadcf3a 100644 --- a/solution/1100-1199/1195.Fizz Buzz Multithreaded/Solution.cpp +++ b/solution/1100-1199/1195.Fizz Buzz Multithreaded/Solution.cpp @@ -4,13 +4,14 @@ class FizzBuzz { atomic index; int n; + // 这里主要运用到了C++11中的RAII锁(lock_guard)的知识。 + // 需要强调的一点是,在进入循环后,要时刻不忘加入index <= n的逻辑 public: FizzBuzz(int n) { this->n = n; index = 1; } - // printFizz() outputs "fizz". void fizz(function printFizz) { while (index <= n) { std::lock_guard lk(mtx); @@ -21,7 +22,6 @@ class FizzBuzz { } } - // printBuzz() outputs "buzz". void buzz(function printBuzz) { while (index <= n) { std::lock_guard lk(mtx); @@ -32,7 +32,6 @@ class FizzBuzz { } } - // printFizzBuzz() outputs "fizzbuzz". void fizzbuzz(function printFizzBuzz) { while (index <= n) { std::lock_guard lk(mtx); @@ -43,7 +42,6 @@ class FizzBuzz { } } - // printNumber(x) outputs "x", where x is an integer. void number(function printNumber) { while (index <= n) { std::lock_guard lk(mtx); diff --git a/solution/1100-1199/1195.Fizz Buzz Multithreaded/Solution.java b/solution/1100-1199/1195.Fizz Buzz Multithreaded/Solution.java index 81d5497d8423a..905e5af07b8ac 100644 --- a/solution/1100-1199/1195.Fizz Buzz Multithreaded/Solution.java +++ b/solution/1100-1199/1195.Fizz Buzz Multithreaded/Solution.java @@ -57,4 +57,4 @@ public void number(IntConsumer printNumber) throws InterruptedException { } } } -} +} \ No newline at end of file diff --git a/solution/1100-1199/1197.Minimum Knight Moves/Solution.py b/solution/1100-1199/1197.Minimum Knight Moves/Solution.py index f8ee3acae1a08..a5d24422b0f4e 100644 --- a/solution/1100-1199/1197.Minimum Knight Moves/Solution.py +++ b/solution/1100-1199/1197.Minimum Knight Moves/Solution.py @@ -1,18 +1,18 @@ -class Solution: - def minKnightMoves(self, x: int, y: int) -> int: - q = deque([(0, 0)]) - ans = 0 - vis = {(0, 0)} - dirs = ((-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1)) - while q: - for _ in range(len(q)): - i, j = q.popleft() - if (i, j) == (x, y): - return ans - for a, b in dirs: - c, d = i + a, j + b - if (c, d) not in vis: - vis.add((c, d)) - q.append((c, d)) - ans += 1 - return -1 +class Solution: + def minKnightMoves(self, x: int, y: int) -> int: + q = deque([(0, 0)]) + ans = 0 + vis = {(0, 0)} + dirs = ((-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1)) + while q: + for _ in range(len(q)): + i, j = q.popleft() + if (i, j) == (x, y): + return ans + for a, b in dirs: + c, d = i + a, j + b + if (c, d) not in vis: + vis.add((c, d)) + q.append((c, d)) + ans += 1 + return -1 diff --git a/solution/1100-1199/1197.Minimum Knight Moves/Solution2.cpp b/solution/1100-1199/1197.Minimum Knight Moves/Solution2.cpp new file mode 100644 index 0000000000000..eff36241974c0 --- /dev/null +++ b/solution/1100-1199/1197.Minimum Knight Moves/Solution2.cpp @@ -0,0 +1,43 @@ +typedef pair PII; + +class Solution { +public: + int n = 700; + + int minKnightMoves(int x, int y) { + if (x == 0 && y == 0) return 0; + x += 310; + y += 310; + unordered_map m1; + unordered_map m2; + m1[310 * n + 310] = 0; + m2[x * n + y] = 0; + queue q1; + queue q2; + q1.push({310, 310}); + q2.push({x, y}); + while (!q1.empty() && !q2.empty()) { + int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); + if (t != -1) return t; + } + return -1; + } + + int extend(unordered_map& m1, unordered_map& m2, queue& q) { + vector> dirs = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}}; + for (int k = q.size(); k > 0; --k) { + auto p = q.front(); + q.pop(); + int i = p.first, j = p.second; + int step = m1[i * n + j]; + for (auto& dir : dirs) { + int x = i + dir[0], y = j + dir[1]; + if (m1.count(x * n + y)) continue; + if (m2.count(x * n + y)) return step + 1 + m2[x * n + y]; + m1[x * n + y] = step + 1; + q.push({x, y}); + } + } + return -1; + } +}; \ No newline at end of file diff --git a/solution/1100-1199/1197.Minimum Knight Moves/Solution2.go b/solution/1100-1199/1197.Minimum Knight Moves/Solution2.go new file mode 100644 index 0000000000000..39e185dd51952 --- /dev/null +++ b/solution/1100-1199/1197.Minimum Knight Moves/Solution2.go @@ -0,0 +1,42 @@ +func minKnightMoves(x int, y int) int { + if x == 0 && y == 0 { + return 0 + } + n := 700 + x, y = x+310, y+310 + q1, q2 := []int{310*700 + 310}, []int{x*n + y} + m1, m2 := map[int]int{310*700 + 310: 0}, map[int]int{x*n + y: 0} + dirs := [][]int{{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}} + extend := func() int { + for k := len(q1); k > 0; k-- { + p := q1[0] + q1 = q1[1:] + i, j := p/n, p%n + step := m1[i*n+j] + for _, dir := range dirs { + x, y := i+dir[0], j+dir[1] + t := x*n + y + if _, ok := m1[t]; ok { + continue + } + if v, ok := m2[t]; ok { + return step + 1 + v + } + m1[t] = step + 1 + q1 = append(q1, t) + } + } + return -1 + } + for len(q1) > 0 && len(q2) > 0 { + if len(q1) <= len(q2) { + q1, q2 = q2, q1 + m1, m2 = m2, m1 + } + t := extend() + if t != -1 { + return t + } + } + return -1 +} \ No newline at end of file diff --git a/solution/1100-1199/1197.Minimum Knight Moves/Solution2.java b/solution/1100-1199/1197.Minimum Knight Moves/Solution2.java new file mode 100644 index 0000000000000..6289ff6781325 --- /dev/null +++ b/solution/1100-1199/1197.Minimum Knight Moves/Solution2.java @@ -0,0 +1,47 @@ +class Solution { + private int n = 700; + + public int minKnightMoves(int x, int y) { + if (x == 0 && y == 0) { + return 0; + } + x += 310; + y += 310; + Map m1 = new HashMap<>(); + Map m2 = new HashMap<>(); + m1.put(310 * n + 310, 0); + m2.put(x * n + y, 0); + Queue q1 = new ArrayDeque<>(); + Queue q2 = new ArrayDeque<>(); + q1.offer(new int[] {310, 310}); + q2.offer(new int[] {x, y}); + while (!q1.isEmpty() && !q2.isEmpty()) { + int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); + if (t != -1) { + return t; + } + } + return -1; + } + + private int extend(Map m1, Map m2, Queue q) { + int[][] dirs = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}}; + for (int k = q.size(); k > 0; --k) { + int[] p = q.poll(); + int step = m1.get(p[0] * n + p[1]); + for (int[] dir : dirs) { + int x = p[0] + dir[0]; + int y = p[1] + dir[1]; + if (m1.containsKey(x * n + y)) { + continue; + } + if (m2.containsKey(x * n + y)) { + return step + 1 + m2.get(x * n + y); + } + m1.put(x * n + y, step + 1); + q.offer(new int[] {x, y}); + } + } + return -1; + } +} \ No newline at end of file diff --git a/solution/1100-1199/1197.Minimum Knight Moves/Solution2.py b/solution/1100-1199/1197.Minimum Knight Moves/Solution2.py new file mode 100644 index 0000000000000..c819b0436ed97 --- /dev/null +++ b/solution/1100-1199/1197.Minimum Knight Moves/Solution2.py @@ -0,0 +1,34 @@ +class Solution: + def minKnightMoves(self, x: int, y: int) -> int: + def extend(m1, m2, q): + for _ in range(len(q)): + i, j = q.popleft() + step = m1[(i, j)] + for a, b in ( + (-2, 1), + (-1, 2), + (1, 2), + (2, 1), + (2, -1), + (1, -2), + (-1, -2), + (-2, -1), + ): + x, y = i + a, j + b + if (x, y) in m1: + continue + if (x, y) in m2: + return step + 1 + m2[(x, y)] + q.append((x, y)) + m1[(x, y)] = step + 1 + return -1 + + if (x, y) == (0, 0): + return 0 + q1, q2 = deque([(0, 0)]), deque([(x, y)]) + m1, m2 = {(0, 0): 0}, {(x, y): 0} + while q1 and q2: + t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) + if t != -1: + return t + return -1 diff --git a/solution/1100-1199/1197.Minimum Knight Moves/Solution2.rs b/solution/1100-1199/1197.Minimum Knight Moves/Solution2.rs new file mode 100644 index 0000000000000..3152bf5c8a186 --- /dev/null +++ b/solution/1100-1199/1197.Minimum Knight Moves/Solution2.rs @@ -0,0 +1,94 @@ +use std::collections::VecDeque; +use std::collections::HashMap; + +const DIR: [(i32, i32); 8] = [ + (-2, 1), + (2, 1), + (-1, 2), + (1, 2), + (2, -1), + (-2, -1), + (1, -2), + (-1, -2), +]; + +impl Solution { + #[allow(dead_code)] + pub fn min_knight_moves(x: i32, y: i32) -> i32 { + if x == 0 && y == 0 { + return 0; + } + // Otherwise, let's shift from [-300, 300] -> [0, 600] + let x = x + 300; + let y = y + 300; + let mut ret = -1; + // Initialize the two hash map, used to track if a node has been visited + let mut map_to: HashMap = HashMap::new(); + let mut map_from: HashMap = HashMap::new(); + // Input the original status + map_to.insert(601 * 300 + 300, 0); + map_from.insert(601 * x + y, 0); + let mut q_to: VecDeque<(i32, i32)> = VecDeque::new(); + let mut q_from: VecDeque<(i32, i32)> = VecDeque::new(); + // Initialize the two queue + q_to.push_back((300, 300)); + q_from.push_back((x, y)); + + while !q_to.is_empty() && !q_from.is_empty() { + let step = if q_to.len() < q_from.len() { + Self::extend(&mut map_to, &mut map_from, &mut q_to) + } else { + Self::extend(&mut map_from, &mut map_to, &mut q_from) + }; + if step != -1 { + ret = step; + break; + } + } + + ret + } + + #[allow(dead_code)] + fn extend( + map_to: &mut HashMap, + map_from: &mut HashMap, + cur_q: &mut VecDeque<(i32, i32)> + ) -> i32 { + let n = cur_q.len(); + for _ in 0..n { + let (i, j) = cur_q.front().unwrap().clone(); + cur_q.pop_front(); + // The cur_step here must exist + let cur_step = map_to + .get(&(601 * i + j)) + .unwrap() + .clone(); + for (dx, dy) in DIR { + let x = i + dx; + let y = j + dy; + // Check if this node has been visited + if map_to.contains_key(&(601 * x + y)) { + // Just ignore this node + continue; + } + // Check if this node has been visited by the other side + if map_from.contains_key(&(601 * x + y)) { + // We found the node + return ( + cur_step + + 1 + + map_from + .get(&(601 * x + y)) + .unwrap() + .clone() + ); + } + // Otherwise, update map_to and push the new node to queue + map_to.insert(601 * x + y, cur_step + 1); + cur_q.push_back((x, y)); + } + } + -1 + } +} diff --git a/solution/1200-1299/1204.Last Person to Fit in the Bus/Solution.sql b/solution/1200-1299/1204.Last Person to Fit in the Bus/Solution.sql index a117e6e2df58e..1fe9b1d6334d5 100644 --- a/solution/1200-1299/1204.Last Person to Fit in the Bus/Solution.sql +++ b/solution/1200-1299/1204.Last Person to Fit in the Bus/Solution.sql @@ -1,13 +1,10 @@ # Write your MySQL query statement below -WITH - T AS ( - SELECT - person_name, - SUM(weight) OVER (ORDER BY turn) AS s - FROM Queue - ) -SELECT person_name -FROM T -WHERE s <= 1000 -ORDER BY s DESC +SELECT a.person_name +FROM + Queue AS a, + Queue AS b +WHERE a.turn >= b.turn +GROUP BY a.person_id +HAVING SUM(b.weight) <= 1000 +ORDER BY a.turn DESC LIMIT 1; diff --git a/solution/1200-1299/1204.Last Person to Fit in the Bus/Solution2.sql b/solution/1200-1299/1204.Last Person to Fit in the Bus/Solution2.sql new file mode 100644 index 0000000000000..a117e6e2df58e --- /dev/null +++ b/solution/1200-1299/1204.Last Person to Fit in the Bus/Solution2.sql @@ -0,0 +1,13 @@ +# Write your MySQL query statement below +WITH + T AS ( + SELECT + person_name, + SUM(weight) OVER (ORDER BY turn) AS s + FROM Queue + ) +SELECT person_name +FROM T +WHERE s <= 1000 +ORDER BY s DESC +LIMIT 1; diff --git a/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution.cpp b/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution.cpp index a0e0f72698fd4..cfc84fab7049a 100644 --- a/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution.cpp +++ b/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution.cpp @@ -2,15 +2,29 @@ class Solution { public: int equalSubstring(string s, string t, int maxCost) { int n = s.size(); - int ans = 0, sum = 0; - for (int i = 0, j = 0; i < n; ++i) { - sum += abs(s[i] - t[i]); - while (sum > maxCost) { - sum -= abs(s[j] - t[j]); - ++j; + int f[n + 1]; + f[0] = 0; + for (int i = 0; i < n; ++i) { + f[i + 1] = f[i] + abs(s[i] - t[i]); + } + auto check = [&](int x) -> bool { + for (int i = 0; i + x - 1 < n; ++i) { + int j = i + x - 1; + if (f[j + 1] - f[i] <= maxCost) { + return true; + } + } + return false; + }; + int l = 0, r = n; + while (l < r) { + int mid = (l + r + 1) >> 1; + if (check(mid)) { + l = mid; + } else { + r = mid - 1; } - ans = max(ans, i - j + 1); } - return ans; + return l; } }; \ No newline at end of file diff --git a/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution.go b/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution.go index 71c258812a475..1b879b8467b49 100644 --- a/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution.go +++ b/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution.go @@ -1,15 +1,27 @@ -func equalSubstring(s string, t string, maxCost int) (ans int) { - var sum, j int - for i := range s { - sum += abs(int(s[i]) - int(t[i])) - for ; sum > maxCost; j++ { - sum -= abs(int(s[j]) - int(t[j])) +func equalSubstring(s string, t string, maxCost int) int { + n := len(s) + f := make([]int, n+1) + for i, a := range s { + f[i+1] = f[i] + abs(int(a)-int(t[i])) + } + check := func(x int) bool { + for i := 0; i+x-1 < n; i++ { + if f[i+x]-f[i] <= maxCost { + return true + } } - if ans < i-j+1 { - ans = i - j + 1 + return false + } + l, r := 0, n + for l < r { + mid := (l + r + 1) >> 1 + if check(mid) { + l = mid + } else { + r = mid - 1 } } - return + return l } func abs(x int) int { diff --git a/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution.java b/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution.java index 032910aacb4f8..ae584d124ff84 100644 --- a/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution.java +++ b/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution.java @@ -1,16 +1,35 @@ class Solution { + private int maxCost; + private int[] f; + private int n; + public int equalSubstring(String s, String t, int maxCost) { - int n = s.length(); - int sum = 0; - int ans = 0; - for (int i = 0, j = 0; i < n; ++i) { - sum += Math.abs(s.charAt(i) - t.charAt(i)); - while (sum > maxCost) { - sum -= Math.abs(s.charAt(j) - t.charAt(j)); - ++j; + n = s.length(); + f = new int[n + 1]; + this.maxCost = maxCost; + for (int i = 0; i < n; ++i) { + int x = Math.abs(s.charAt(i) - t.charAt(i)); + f[i + 1] = f[i] + x; + } + int l = 0, r = n; + while (l < r) { + int mid = (l + r + 1) >>> 1; + if (check(mid)) { + l = mid; + } else { + r = mid - 1; + } + } + return l; + } + + private boolean check(int x) { + for (int i = 0; i + x - 1 < n; ++i) { + int j = i + x - 1; + if (f[j + 1] - f[i] <= maxCost) { + return true; } - ans = Math.max(ans, i - j + 1); } - return ans; + return false; } } \ No newline at end of file diff --git a/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution.py b/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution.py index 0abac53fc8bb8..f6a5e5bb8bb15 100644 --- a/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution.py +++ b/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution.py @@ -1,12 +1,19 @@ class Solution: def equalSubstring(self, s: str, t: str, maxCost: int) -> int: + def check(x): + for i in range(n): + j = i + mid - 1 + if j < n and f[j + 1] - f[i] <= maxCost: + return True + return False + n = len(s) - sum = j = 0 - ans = 0 - for i in range(n): - sum += abs(ord(s[i]) - ord(t[i])) - while sum > maxCost: - sum -= abs(ord(s[j]) - ord(t[j])) - j += 1 - ans = max(ans, i - j + 1) - return ans + f = list(accumulate((abs(ord(a) - ord(b)) for a, b in zip(s, t)), initial=0)) + l, r = 0, n + while l < r: + mid = (l + r + 1) >> 1 + if check(mid): + l = mid + else: + r = mid - 1 + return l diff --git a/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution2.cpp b/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution2.cpp new file mode 100644 index 0000000000000..a0e0f72698fd4 --- /dev/null +++ b/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int equalSubstring(string s, string t, int maxCost) { + int n = s.size(); + int ans = 0, sum = 0; + for (int i = 0, j = 0; i < n; ++i) { + sum += abs(s[i] - t[i]); + while (sum > maxCost) { + sum -= abs(s[j] - t[j]); + ++j; + } + ans = max(ans, i - j + 1); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution2.go b/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution2.go new file mode 100644 index 0000000000000..71c258812a475 --- /dev/null +++ b/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution2.go @@ -0,0 +1,20 @@ +func equalSubstring(s string, t string, maxCost int) (ans int) { + var sum, j int + for i := range s { + sum += abs(int(s[i]) - int(t[i])) + for ; sum > maxCost; j++ { + sum -= abs(int(s[j]) - int(t[j])) + } + if ans < i-j+1 { + ans = i - j + 1 + } + } + return +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} \ No newline at end of file diff --git a/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution2.java b/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution2.java new file mode 100644 index 0000000000000..032910aacb4f8 --- /dev/null +++ b/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public int equalSubstring(String s, String t, int maxCost) { + int n = s.length(); + int sum = 0; + int ans = 0; + for (int i = 0, j = 0; i < n; ++i) { + sum += Math.abs(s.charAt(i) - t.charAt(i)); + while (sum > maxCost) { + sum -= Math.abs(s.charAt(j) - t.charAt(j)); + ++j; + } + ans = Math.max(ans, i - j + 1); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution2.py b/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution2.py new file mode 100644 index 0000000000000..0abac53fc8bb8 --- /dev/null +++ b/solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def equalSubstring(self, s: str, t: str, maxCost: int) -> int: + n = len(s) + sum = j = 0 + ans = 0 + for i in range(n): + sum += abs(ord(s[i]) - ord(t[i])) + while sum > maxCost: + sum -= abs(ord(s[j]) - ord(t[j])) + j += 1 + ans = max(ans, i - j + 1) + return ans diff --git a/solution/1200-1299/1209.Remove All Adjacent Duplicates in String II/Solution.py b/solution/1200-1299/1209.Remove All Adjacent Duplicates in String II/Solution.py index 2657e15378750..a87d02fe6813d 100644 --- a/solution/1200-1299/1209.Remove All Adjacent Duplicates in String II/Solution.py +++ b/solution/1200-1299/1209.Remove All Adjacent Duplicates in String II/Solution.py @@ -1,12 +1,19 @@ class Solution: def removeDuplicates(self, s: str, k: int) -> str: - stk = [] - for c in s: - if stk and stk[-1][0] == c: - stk[-1][1] = (stk[-1][1] + 1) % k - if stk[-1][1] == 0: - stk.pop() - else: - stk.append([c, 1]) - ans = [c * v for c, v in stk] + t = [] + i, n = 0, len(s) + while i < n: + j = i + while j < n and s[j] == s[i]: + j += 1 + cnt = j - i + cnt %= k + if t and t[-1][0] == s[i]: + t[-1][1] = (t[-1][1] + cnt) % k + if t[-1][1] == 0: + t.pop() + elif cnt: + t.append([s[i], cnt]) + i = j + ans = [c * v for c, v in t] return "".join(ans) diff --git a/solution/1200-1299/1209.Remove All Adjacent Duplicates in String II/Solution2.py b/solution/1200-1299/1209.Remove All Adjacent Duplicates in String II/Solution2.py new file mode 100644 index 0000000000000..2657e15378750 --- /dev/null +++ b/solution/1200-1299/1209.Remove All Adjacent Duplicates in String II/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def removeDuplicates(self, s: str, k: int) -> str: + stk = [] + for c in s: + if stk and stk[-1][0] == c: + stk[-1][1] = (stk[-1][1] + 1) % k + if stk[-1][1] == 0: + stk.pop() + else: + stk.append([c, 1]) + ans = [c * v for c, v in stk] + return "".join(ans) diff --git a/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.cpp b/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.cpp index 21aa39565f7e9..330e2e3fa319d 100644 --- a/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.cpp +++ b/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.cpp @@ -31,11 +31,15 @@ class Solution { auto [a, b] = p; int i1 = a / n, j1 = a % n; int i2 = b / n, j2 = b % n; + // 尝试向右平移(保持身体水平/垂直状态) move(i1, j1 + 1, i2, j2 + 1); + // 尝试向下平移(保持身体水平/垂直状态) move(i1 + 1, j1, i2 + 1, j2); + // 当前处于水平状态,且 grid[i1 + 1][j2] 无障碍,尝试顺时针旋转90° if (i1 == i2 && i1 + 1 < n && grid[i1 + 1][j2] == 0) { move(i1, j1, i1 + 1, j1); } + // 当前处于垂直状态,且 grid[i2][j1 + 1] 无障碍,尝试逆时针旋转90° if (j1 == j2 && j1 + 1 < n && grid[i2][j1 + 1] == 0) { move(i1, j1, i1, j1 + 1); } diff --git a/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.go b/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.go index c64ae24098828..8b24075c8911b 100644 --- a/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.go +++ b/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.go @@ -31,11 +31,15 @@ func minimumMoves(grid [][]int) int { a, b := p.a, p.b i1, j1 := a/n, a%n i2, j2 := b/n, b%n + // 尝试向右平移(保持身体水平/垂直状态) move(i1, j1+1, i2, j2+1) + // 尝试向下平移(保持身体水平/垂直状态) move(i1+1, j1, i2+1, j2) + // 当前处于水平状态,且 grid[i1 + 1][j2] 无障碍,尝试顺时针旋转90° if i1 == i2 && i1+1 < n && grid[i1+1][j2] == 0 { move(i1, j1, i1+1, j1) } + // 当前处于垂直状态,且 grid[i2][j1 + 1] 无障碍,尝试逆时针旋转90° if j1 == j2 && j1+1 < n && grid[i2][j1+1] == 0 { move(i1, j1, i1, j1+1) } diff --git a/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.java b/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.java index 94b076904e134..01464245fb772 100644 --- a/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.java +++ b/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.java @@ -20,11 +20,15 @@ public int minimumMoves(int[][] grid) { } int i1 = p[0] / n, j1 = p[0] % n; int i2 = p[1] / n, j2 = p[1] % n; + // 尝试向右平移(保持身体水平/垂直状态) move(i1, j1 + 1, i2, j2 + 1); + // 尝试向下平移(保持身体水平/垂直状态) move(i1 + 1, j1, i2 + 1, j2); + // 当前处于水平状态,且 grid[i1 + 1][j2] 无障碍,尝试顺时针旋转90° if (i1 == i2 && i1 + 1 < n && grid[i1 + 1][j2] == 0) { move(i1, j1, i1 + 1, j1); } + // 当前处于垂直状态,且 grid[i2][j1 + 1] 无障碍,尝试逆时针旋转90° if (j1 == j2 && j1 + 1 < n && grid[i2][j1 + 1] == 0) { move(i1, j1, i1, j1 + 1); } diff --git a/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.js b/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.js index 34926ef6635db..75e9a03d2dc6b 100644 --- a/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.js +++ b/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.js @@ -30,11 +30,15 @@ var minimumMoves = function (grid) { } const [i1, j1] = [~~(p[0] / n), p[0] % n]; const [i2, j2] = [~~(p[1] / n), p[1] % n]; + // 尝试向右平移(保持身体水平/垂直状态) move(i1, j1 + 1, i2, j2 + 1); + // 尝试向下平移(保持身体水平/垂直状态) move(i1 + 1, j1, i2 + 1, j2); + // 当前处于水平状态,且 grid[i1 + 1][j2] 无障碍,尝试顺时针旋转90° if (i1 == i2 && i1 + 1 < n && grid[i1 + 1][j2] == 0) { move(i1, j1, i1 + 1, j1); } + // 当前处于垂直状态,且 grid[i2][j1 + 1] 无障碍,尝试逆时针旋转90° if (j1 == j2 && j1 + 1 < n && grid[i2][j1 + 1] == 0) { move(i1, j1, i1, j1 + 1); } diff --git a/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.py b/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.py index 0968435e0ebb2..ba06e38cd1bba 100644 --- a/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.py +++ b/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.py @@ -20,10 +20,14 @@ def move(i1, j1, i2, j2): return ans i1, j1 = a // n, a % n i2, j2 = b // n, b % n + # 尝试向右平移(保持身体水平/垂直状态) move(i1, j1 + 1, i2, j2 + 1) + # 尝试向下平移(保持身体水平/垂直状态) move(i1 + 1, j1, i2 + 1, j2) + # 当前处于水平状态,且 grid[i1 + 1][j2] 无障碍,尝试顺时针旋转90° if i1 == i2 and i1 + 1 < n and grid[i1 + 1][j2] == 0: move(i1, j1, i1 + 1, j1) + # 当前处于垂直状态,且 grid[i2][j1 + 1] 无障碍,尝试逆时针旋转90° if j1 == j2 and j1 + 1 < n and grid[i2][j1 + 1] == 0: move(i1, j1, i1, j1 + 1) ans += 1 diff --git a/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.ts b/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.ts index 8f09763bd2873..d56ab2fd004fe 100644 --- a/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.ts +++ b/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.ts @@ -26,11 +26,15 @@ function minimumMoves(grid: number[][]): number { } const [i1, j1] = [~~(p[0] / n), p[0] % n]; const [i2, j2] = [~~(p[1] / n), p[1] % n]; + // 尝试向右平移(保持身体水平/垂直状态) move(i1, j1 + 1, i2, j2 + 1); + // 尝试向下平移(保持身体水平/垂直状态) move(i1 + 1, j1, i2 + 1, j2); + // 当前处于水平状态,且 grid[i1 + 1][j2] 无障碍,尝试顺时针旋转90° if (i1 == i2 && i1 + 1 < n && grid[i1 + 1][j2] == 0) { move(i1, j1, i1 + 1, j1); } + // 当前处于垂直状态,且 grid[i2][j1 + 1] 无障碍,尝试逆时针旋转90° if (j1 == j2 && j1 + 1 < n && grid[i2][j1 + 1] == 0) { move(i1, j1, i1, j1 + 1); } diff --git a/solution/1200-1299/1213.Intersection of Three Sorted Arrays/Solution.php b/solution/1200-1299/1213.Intersection of Three Sorted Arrays/Solution.php index 29794601e1399..fc6a9f2360c6e 100644 --- a/solution/1200-1299/1213.Intersection of Three Sorted Arrays/Solution.php +++ b/solution/1200-1299/1213.Intersection of Three Sorted Arrays/Solution.php @@ -16,4 +16,4 @@ function arraysIntersection($arr1, $arr2, $arr3) { } return $rs; } -} \ No newline at end of file +} diff --git a/solution/1200-1299/1213.Intersection of Three Sorted Arrays/Solution2.cpp b/solution/1200-1299/1213.Intersection of Three Sorted Arrays/Solution2.cpp new file mode 100644 index 0000000000000..9178a8e42216e --- /dev/null +++ b/solution/1200-1299/1213.Intersection of Three Sorted Arrays/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + vector arraysIntersection(vector& arr1, vector& arr2, vector& arr3) { + vector ans; + for (int x : arr1) { + auto i = lower_bound(arr2.begin(), arr2.end(), x); + auto j = lower_bound(arr3.begin(), arr3.end(), x); + if (*i == x && *j == x) { + ans.push_back(x); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1200-1299/1213.Intersection of Three Sorted Arrays/Solution2.go b/solution/1200-1299/1213.Intersection of Three Sorted Arrays/Solution2.go new file mode 100644 index 0000000000000..cfbfe8d0214fe --- /dev/null +++ b/solution/1200-1299/1213.Intersection of Three Sorted Arrays/Solution2.go @@ -0,0 +1,10 @@ +func arraysIntersection(arr1 []int, arr2 []int, arr3 []int) (ans []int) { + for _, x := range arr1 { + i := sort.SearchInts(arr2, x) + j := sort.SearchInts(arr3, x) + if i < len(arr2) && j < len(arr3) && arr2[i] == x && arr3[j] == x { + ans = append(ans, x) + } + } + return +} \ No newline at end of file diff --git a/solution/1200-1299/1213.Intersection of Three Sorted Arrays/Solution2.java b/solution/1200-1299/1213.Intersection of Three Sorted Arrays/Solution2.java new file mode 100644 index 0000000000000..426fcaef0adfb --- /dev/null +++ b/solution/1200-1299/1213.Intersection of Three Sorted Arrays/Solution2.java @@ -0,0 +1,13 @@ +class Solution { + public List arraysIntersection(int[] arr1, int[] arr2, int[] arr3) { + List ans = new ArrayList<>(); + for (int x : arr1) { + int i = Arrays.binarySearch(arr2, x); + int j = Arrays.binarySearch(arr3, x); + if (i >= 0 && j >= 0) { + ans.add(x); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1200-1299/1213.Intersection of Three Sorted Arrays/Solution2.py b/solution/1200-1299/1213.Intersection of Three Sorted Arrays/Solution2.py new file mode 100644 index 0000000000000..14e6ba77ee8fc --- /dev/null +++ b/solution/1200-1299/1213.Intersection of Three Sorted Arrays/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def arraysIntersection( + self, arr1: List[int], arr2: List[int], arr3: List[int] + ) -> List[int]: + ans = [] + for x in arr1: + i = bisect_left(arr2, x) + j = bisect_left(arr3, x) + if i < len(arr2) and j < len(arr3) and arr2[i] == x and arr3[j] == x: + ans.append(x) + return ans diff --git a/solution/1200-1299/1215.Stepping Numbers/Solution.cpp b/solution/1200-1299/1215.Stepping Numbers/Solution.cpp index 66a18172067ba..7bbe7c8ba0ae9 100644 --- a/solution/1200-1299/1215.Stepping Numbers/Solution.cpp +++ b/solution/1200-1299/1215.Stepping Numbers/Solution.cpp @@ -1,31 +1,31 @@ -class Solution { -public: - vector countSteppingNumbers(int low, int high) { - vector ans; - if (low == 0) { - ans.push_back(0); - } - queue q; - for (int i = 1; i < 10; ++i) { - q.push(i); - } - while (!q.empty()) { - long long v = q.front(); - q.pop(); - if (v > high) { - break; - } - if (v >= low) { - ans.push_back(v); - } - int x = v % 10; - if (x > 0) { - q.push(v * 10 + x - 1); - } - if (x < 9) { - q.push(v * 10 + x + 1); - } - } - return ans; - } +class Solution { +public: + vector countSteppingNumbers(int low, int high) { + vector ans; + if (low == 0) { + ans.push_back(0); + } + queue q; + for (int i = 1; i < 10; ++i) { + q.push(i); + } + while (!q.empty()) { + long long v = q.front(); + q.pop(); + if (v > high) { + break; + } + if (v >= low) { + ans.push_back(v); + } + int x = v % 10; + if (x > 0) { + q.push(v * 10 + x - 1); + } + if (x < 9) { + q.push(v * 10 + x + 1); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/Solution.cpp b/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/Solution.cpp index c2336fec7a6d3..0ae932bf68e11 100644 --- a/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/Solution.cpp +++ b/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/Solution.cpp @@ -1,12 +1,12 @@ -class Solution { -public: - int longestSubsequence(vector& arr, int difference) { - unordered_map f; - int ans = 0; - for (int x : arr) { - f[x] = f[x - difference] + 1; - ans = max(ans, f[x]); - } - return ans; - } -}; +class Solution { +public: + int longestSubsequence(vector& arr, int difference) { + unordered_map f; + int ans = 0; + for (int x : arr) { + f[x] = f[x - difference] + 1; + ans = max(ans, f[x]); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/Solution.java b/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/Solution.java index 8ab016e19020c..13f3b2e638671 100644 --- a/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/Solution.java +++ b/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/Solution.java @@ -1,11 +1,11 @@ -class Solution { - public int longestSubsequence(int[] arr, int difference) { - Map f = new HashMap<>(); - int ans = 0; - for (int x : arr) { - f.put(x, f.getOrDefault(x - difference, 0) + 1); - ans = Math.max(ans, f.get(x)); - } - return ans; - } -} +class Solution { + public int longestSubsequence(int[] arr, int difference) { + Map f = new HashMap<>(); + int ans = 0; + for (int x : arr) { + f.put(x, f.getOrDefault(x - difference, 0) + 1); + ans = Math.max(ans, f.get(x)); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/Solution.py b/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/Solution.py index 548b7df089ce3..89049239893f8 100644 --- a/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/Solution.py +++ b/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/Solution.py @@ -1,6 +1,6 @@ -class Solution: - def longestSubsequence(self, arr: List[int], difference: int) -> int: - f = defaultdict(int) - for x in arr: - f[x] = f[x - difference] + 1 - return max(f.values()) +class Solution: + def longestSubsequence(self, arr: List[int], difference: int) -> int: + f = defaultdict(int) + for x in arr: + f[x] = f[x - difference] + 1 + return max(f.values()) diff --git a/solution/1200-1299/1219.Path with Maximum Gold/Solution.cpp b/solution/1200-1299/1219.Path with Maximum Gold/Solution.cpp index d2fc3d599d707..6d36dd06e9a73 100644 --- a/solution/1200-1299/1219.Path with Maximum Gold/Solution.cpp +++ b/solution/1200-1299/1219.Path with Maximum Gold/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - int getMaximumGold(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - function dfs = [&](int i, int j) { - if (i < 0 || i >= m || j < 0 || j >= n || !grid[i][j]) { - return 0; - } - int v = grid[i][j]; - grid[i][j] = 0; - int ans = v + max({dfs(i - 1, j), dfs(i + 1, j), dfs(i, j - 1), dfs(i, j + 1)}); - grid[i][j] = v; - return ans; - }; - int ans = 0; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - ans = max(ans, dfs(i, j)); - } - } - return ans; - } +class Solution { +public: + int getMaximumGold(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + function dfs = [&](int i, int j) { + if (i < 0 || i >= m || j < 0 || j >= n || !grid[i][j]) { + return 0; + } + int v = grid[i][j]; + grid[i][j] = 0; + int ans = v + max({dfs(i - 1, j), dfs(i + 1, j), dfs(i, j - 1), dfs(i, j + 1)}); + grid[i][j] = v; + return ans; + }; + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans = max(ans, dfs(i, j)); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1200-1299/1219.Path with Maximum Gold/Solution.java b/solution/1200-1299/1219.Path with Maximum Gold/Solution.java index d31e9dbcfcd2c..63b009fe2cb00 100644 --- a/solution/1200-1299/1219.Path with Maximum Gold/Solution.java +++ b/solution/1200-1299/1219.Path with Maximum Gold/Solution.java @@ -1,33 +1,33 @@ -class Solution { - private final int[] dirs = {-1, 0, 1, 0, -1}; - private int[][] grid; - private int m; - private int n; - - public int getMaximumGold(int[][] grid) { - m = grid.length; - n = grid[0].length; - this.grid = grid; - int ans = 0; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - ans = Math.max(ans, dfs(i, j)); - } - } - return ans; - } - - private int dfs(int i, int j) { - if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) { - return 0; - } - int v = grid[i][j]; - grid[i][j] = 0; - int ans = 0; - for (int k = 0; k < 4; ++k) { - ans = Math.max(ans, v + dfs(i + dirs[k], j + dirs[k + 1])); - } - grid[i][j] = v; - return ans; - } +class Solution { + private final int[] dirs = {-1, 0, 1, 0, -1}; + private int[][] grid; + private int m; + private int n; + + public int getMaximumGold(int[][] grid) { + m = grid.length; + n = grid[0].length; + this.grid = grid; + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans = Math.max(ans, dfs(i, j)); + } + } + return ans; + } + + private int dfs(int i, int j) { + if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) { + return 0; + } + int v = grid[i][j]; + grid[i][j] = 0; + int ans = 0; + for (int k = 0; k < 4; ++k) { + ans = Math.max(ans, v + dfs(i + dirs[k], j + dirs[k + 1])); + } + grid[i][j] = v; + return ans; + } } \ No newline at end of file diff --git a/solution/1200-1299/1219.Path with Maximum Gold/Solution.py b/solution/1200-1299/1219.Path with Maximum Gold/Solution.py index 1e518f39a5a7e..7d0fb4b2f8093 100644 --- a/solution/1200-1299/1219.Path with Maximum Gold/Solution.py +++ b/solution/1200-1299/1219.Path with Maximum Gold/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def getMaximumGold(self, grid: List[List[int]]) -> int: - def dfs(i: int, j: int) -> int: - if not (0 <= i < m and 0 <= j < n and grid[i][j]): - return 0 - v = grid[i][j] - grid[i][j] = 0 - ans = max(dfs(i + a, j + b) for a, b in pairwise(dirs)) + v - grid[i][j] = v - return ans - - m, n = len(grid), len(grid[0]) - dirs = (-1, 0, 1, 0, -1) - return max(dfs(i, j) for i in range(m) for j in range(n)) +class Solution: + def getMaximumGold(self, grid: List[List[int]]) -> int: + def dfs(i: int, j: int) -> int: + if not (0 <= i < m and 0 <= j < n and grid[i][j]): + return 0 + v = grid[i][j] + grid[i][j] = 0 + ans = max(dfs(i + a, j + b) for a, b in pairwise(dirs)) + v + grid[i][j] = v + return ans + + m, n = len(grid), len(grid[0]) + dirs = (-1, 0, 1, 0, -1) + return max(dfs(i, j) for i in range(m) for j in range(n)) diff --git a/solution/1200-1299/1220.Count Vowels Permutation/Solution.cpp b/solution/1200-1299/1220.Count Vowels Permutation/Solution.cpp index e94ebd6560621..97001629f5f7e 100644 --- a/solution/1200-1299/1220.Count Vowels Permutation/Solution.cpp +++ b/solution/1200-1299/1220.Count Vowels Permutation/Solution.cpp @@ -1,43 +1,18 @@ -class Solution { -public: - int countVowelPermutation(int n) { - vector> a = { - {0, 1, 0, 0, 0}, - {1, 0, 1, 0, 0}, - {1, 1, 0, 1, 1}, - {0, 0, 1, 0, 1}, - {1, 0, 0, 0, 0}}; - vector> res = pow(a, n - 1); - return accumulate(res[0].begin(), res[0].end(), 0LL) % mod; - } - -private: - using ll = long long; - const int mod = 1e9 + 7; - - vector> mul(vector>& a, vector>& b) { - int m = a.size(), n = b[0].size(); - vector> c(m, vector(n)); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - for (int k = 0; k < b.size(); ++k) { - c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % mod; - } - } - } - return c; - } - - vector> pow(vector>& a, int n) { - vector> res; - res.push_back({1, 1, 1, 1, 1}); - while (n) { - if (n & 1) { - res = mul(res, a); - } - a = mul(a, a); - n >>= 1; - } - return res; - } +class Solution { +public: + int countVowelPermutation(int n) { + using ll = long long; + vector f(5, 1); + const int mod = 1e9 + 7; + for (int i = 1; i < n; ++i) { + vector g(5); + g[0] = (f[1] + f[2] + f[4]) % mod; + g[1] = (f[0] + f[2]) % mod; + g[2] = (f[1] + f[3]) % mod; + g[3] = f[2]; + g[4] = (f[2] + f[3]) % mod; + f = move(g); + } + return accumulate(f.begin(), f.end(), 0LL) % mod; + } }; \ No newline at end of file diff --git a/solution/1200-1299/1220.Count Vowels Permutation/Solution.go b/solution/1200-1299/1220.Count Vowels Permutation/Solution.go index 270c79eff9bae..017bf6b87fe61 100644 --- a/solution/1200-1299/1220.Count Vowels Permutation/Solution.go +++ b/solution/1200-1299/1220.Count Vowels Permutation/Solution.go @@ -1,43 +1,20 @@ -const mod = 1e9 + 7 - func countVowelPermutation(n int) (ans int) { - a := [][]int{ - {0, 1, 0, 0, 0}, - {1, 0, 1, 0, 0}, - {1, 1, 0, 1, 1}, - {0, 0, 1, 0, 1}, - {1, 0, 0, 0, 0}} - res := pow(a, n-1) - for _, x := range res[0] { - ans = (ans + x) % mod - } - return -} - -func mul(a, b [][]int) [][]int { - m, n := len(a), len(b[0]) - c := make([][]int, m) - for i := range c { - c[i] = make([]int, n) + const mod int = 1e9 + 7 + f := make([]int, 5) + for i := range f { + f[i] = 1 } - for i := 0; i < m; i++ { - for j := 0; j < n; j++ { - for k := 0; k < len(b); k++ { - c[i][j] = (c[i][j] + a[i][k]*b[k][j]) % mod - } - } + for i := 1; i < n; i++ { + g := make([]int, 5) + g[0] = (f[1] + f[2] + f[4]) % mod + g[1] = (f[0] + f[2]) % mod + g[2] = (f[1] + f[3]) % mod + g[3] = f[2] % mod + g[4] = (f[2] + f[3]) % mod + f = g } - return c -} - -func pow(a [][]int, n int) [][]int { - res := [][]int{{1, 1, 1, 1, 1}} - for n > 0 { - if n&1 == 1 { - res = mul(res, a) - } - a = mul(a, a) - n >>= 1 + for _, x := range f { + ans = (ans + x) % mod } - return res + return } \ No newline at end of file diff --git a/solution/1200-1299/1220.Count Vowels Permutation/Solution.java b/solution/1200-1299/1220.Count Vowels Permutation/Solution.java index 86dcd13560c50..2c8bfd99a391e 100644 --- a/solution/1200-1299/1220.Count Vowels Permutation/Solution.java +++ b/solution/1200-1299/1220.Count Vowels Permutation/Solution.java @@ -1,40 +1,21 @@ -class Solution { - private final int mod = (int) 1e9 + 7; - - public int countVowelPermutation(int n) { - long[][] a - = {{0, 1, 0, 0, 0}, {1, 0, 1, 0, 0}, {1, 1, 0, 1, 1}, {0, 0, 1, 0, 1}, {1, 0, 0, 0, 0}}; - long[][] res = pow(a, n - 1); - long ans = 0; - for (long x : res[0]) { - ans = (ans + x) % mod; - } - return (int) ans; - } - - private long[][] mul(long[][] a, long[][] b) { - int m = a.length, n = b[0].length; - long[][] c = new long[m][n]; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - for (int k = 0; k < b.length; ++k) { - c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % mod; - } - } - } - return c; - } - - private long[][] pow(long[][] a, int n) { - long[][] res = new long[1][a.length]; - Arrays.fill(res[0], 1); - while (n > 0) { - if ((n & 1) == 1) { - res = mul(res, a); - } - a = mul(a, a); - n >>= 1; - } - return res; - } +class Solution { + public int countVowelPermutation(int n) { + long[] f = new long[5]; + Arrays.fill(f, 1); + final int mod = (int) 1e9 + 7; + for (int i = 1; i < n; ++i) { + long[] g = new long[5]; + g[0] = (f[1] + f[2] + f[4]) % mod; + g[1] = (f[0] + f[2]) % mod; + g[2] = (f[1] + f[3]) % mod; + g[3] = f[2]; + g[4] = (f[2] + f[3]) % mod; + f = g; + } + long ans = 0; + for (long x : f) { + ans = (ans + x) % mod; + } + return (int) ans; + } } \ No newline at end of file diff --git a/solution/1200-1299/1220.Count Vowels Permutation/Solution.js b/solution/1200-1299/1220.Count Vowels Permutation/Solution.js index 75d397ff870a5..43a39e68c7a59 100644 --- a/solution/1200-1299/1220.Count Vowels Permutation/Solution.js +++ b/solution/1200-1299/1220.Count Vowels Permutation/Solution.js @@ -2,43 +2,17 @@ * @param {number} n * @return {number} */ - -const mod = 1e9 + 7; - var countVowelPermutation = function (n) { - const a = [ - [0, 1, 0, 0, 0], - [1, 0, 1, 0, 0], - [1, 1, 0, 1, 1], - [0, 0, 1, 0, 1], - [1, 0, 0, 0, 0], - ]; - const res = pow(a, n - 1); - return res[0].reduce((a, b) => (a + b) % mod); -}; - -function mul(a, b) { - const [m, n] = [a.length, b[0].length]; - const c = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - for (let k = 0; k < b.length; ++k) { - c[i][j] = - (c[i][j] + Number((BigInt(a[i][k]) * BigInt(b[k][j])) % BigInt(mod))) % mod; - } - } - } - return c; -} - -function pow(a, n) { - let res = [[1, 1, 1, 1, 1]]; - while (n) { - if (n & 1) { - res = mul(res, a); - } - a = mul(a, a); - n >>>= 1; + const mod = 1e9 + 7; + const f = Array(5).fill(1); + for (let i = 1; i < n; ++i) { + const g = Array(5).fill(0); + g[0] = (f[1] + f[2] + f[4]) % mod; + g[1] = (f[0] + f[2]) % mod; + g[2] = (f[1] + f[3]) % mod; + g[3] = f[2]; + g[4] = (f[2] + f[3]) % mod; + f.splice(0, 5, ...g); } - return res; -} + return f.reduce((a, b) => (a + b) % mod); +}; diff --git a/solution/1200-1299/1220.Count Vowels Permutation/Solution.py b/solution/1200-1299/1220.Count Vowels Permutation/Solution.py index b2381421ef077..c4e9dba249fe4 100644 --- a/solution/1200-1299/1220.Count Vowels Permutation/Solution.py +++ b/solution/1200-1299/1220.Count Vowels Permutation/Solution.py @@ -1,24 +1,13 @@ -import numpy as np - - -class Solution: - def countVowelPermutation(self, n: int) -> int: - mod = 10**9 + 7 - factor = np.mat( - [ - (0, 1, 0, 0, 0), - (1, 0, 1, 0, 0), - (1, 1, 0, 1, 1), - (0, 0, 1, 0, 1), - (1, 0, 0, 0, 0), - ], - np.dtype("O"), - ) - res = np.mat([(1, 1, 1, 1, 1)], np.dtype("O")) - n -= 1 - while n: - if n & 1: - res = res * factor % mod - factor = factor * factor % mod - n >>= 1 - return res.sum() % mod +class Solution: + def countVowelPermutation(self, n: int) -> int: + f = [1] * 5 + mod = 10**9 + 7 + for _ in range(n - 1): + g = [0] * 5 + g[0] = (f[1] + f[2] + f[4]) % mod + g[1] = (f[0] + f[2]) % mod + g[2] = (f[1] + f[3]) % mod + g[3] = f[2] + g[4] = (f[2] + f[3]) % mod + f = g + return sum(f) % mod diff --git a/solution/1200-1299/1220.Count Vowels Permutation/Solution.ts b/solution/1200-1299/1220.Count Vowels Permutation/Solution.ts index d99cbe8938406..7e38b2acf0471 100644 --- a/solution/1200-1299/1220.Count Vowels Permutation/Solution.ts +++ b/solution/1200-1299/1220.Count Vowels Permutation/Solution.ts @@ -1,39 +1,14 @@ -const mod = 1e9 + 7; - function countVowelPermutation(n: number): number { - const a: number[][] = [ - [0, 1, 0, 0, 0], - [1, 0, 1, 0, 0], - [1, 1, 0, 1, 1], - [0, 0, 1, 0, 1], - [1, 0, 0, 0, 0], - ]; - const res = pow(a, n - 1); - return res[0].reduce((a, b) => (a + b) % mod); -} - -function mul(a: number[][], b: number[][]): number[][] { - const [m, n] = [a.length, b[0].length]; - const c = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - for (let k = 0; k < b.length; ++k) { - c[i][j] = - (c[i][j] + Number((BigInt(a[i][k]) * BigInt(b[k][j])) % BigInt(mod))) % mod; - } - } - } - return c; -} - -function pow(a: number[][], n: number): number[][] { - let res: number[][] = [[1, 1, 1, 1, 1]]; - while (n) { - if (n & 1) { - res = mul(res, a); - } - a = mul(a, a); - n >>>= 1; + const f: number[] = Array(5).fill(1); + const mod = 1e9 + 7; + for (let i = 1; i < n; ++i) { + const g: number[] = Array(5).fill(0); + g[0] = (f[1] + f[2] + f[4]) % mod; + g[1] = (f[0] + f[2]) % mod; + g[2] = (f[1] + f[3]) % mod; + g[3] = f[2]; + g[4] = (f[2] + f[3]) % mod; + f.splice(0, 5, ...g); } - return res; + return f.reduce((a, b) => (a + b) % mod); } diff --git a/solution/1200-1299/1220.Count Vowels Permutation/Solution2.cpp b/solution/1200-1299/1220.Count Vowels Permutation/Solution2.cpp new file mode 100644 index 0000000000000..26716f21ac183 --- /dev/null +++ b/solution/1200-1299/1220.Count Vowels Permutation/Solution2.cpp @@ -0,0 +1,43 @@ +class Solution { +public: + int countVowelPermutation(int n) { + vector> a = { + {0, 1, 0, 0, 0}, + {1, 0, 1, 0, 0}, + {1, 1, 0, 1, 1}, + {0, 0, 1, 0, 1}, + {1, 0, 0, 0, 0}}; + vector> res = pow(a, n - 1); + return accumulate(res[0].begin(), res[0].end(), 0LL) % mod; + } + +private: + using ll = long long; + const int mod = 1e9 + 7; + + vector> mul(vector>& a, vector>& b) { + int m = a.size(), n = b[0].size(); + vector> c(m, vector(n)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k < b.size(); ++k) { + c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % mod; + } + } + } + return c; + } + + vector> pow(vector>& a, int n) { + vector> res; + res.push_back({1, 1, 1, 1, 1}); + while (n) { + if (n & 1) { + res = mul(res, a); + } + a = mul(a, a); + n >>= 1; + } + return res; + } +}; \ No newline at end of file diff --git a/solution/1200-1299/1220.Count Vowels Permutation/Solution2.go b/solution/1200-1299/1220.Count Vowels Permutation/Solution2.go new file mode 100644 index 0000000000000..270c79eff9bae --- /dev/null +++ b/solution/1200-1299/1220.Count Vowels Permutation/Solution2.go @@ -0,0 +1,43 @@ +const mod = 1e9 + 7 + +func countVowelPermutation(n int) (ans int) { + a := [][]int{ + {0, 1, 0, 0, 0}, + {1, 0, 1, 0, 0}, + {1, 1, 0, 1, 1}, + {0, 0, 1, 0, 1}, + {1, 0, 0, 0, 0}} + res := pow(a, n-1) + for _, x := range res[0] { + ans = (ans + x) % mod + } + return +} + +func mul(a, b [][]int) [][]int { + m, n := len(a), len(b[0]) + c := make([][]int, m) + for i := range c { + c[i] = make([]int, n) + } + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + for k := 0; k < len(b); k++ { + c[i][j] = (c[i][j] + a[i][k]*b[k][j]) % mod + } + } + } + return c +} + +func pow(a [][]int, n int) [][]int { + res := [][]int{{1, 1, 1, 1, 1}} + for n > 0 { + if n&1 == 1 { + res = mul(res, a) + } + a = mul(a, a) + n >>= 1 + } + return res +} \ No newline at end of file diff --git a/solution/1200-1299/1220.Count Vowels Permutation/Solution2.java b/solution/1200-1299/1220.Count Vowels Permutation/Solution2.java new file mode 100644 index 0000000000000..559a7d314e1f9 --- /dev/null +++ b/solution/1200-1299/1220.Count Vowels Permutation/Solution2.java @@ -0,0 +1,40 @@ +class Solution { + private final int mod = (int) 1e9 + 7; + + public int countVowelPermutation(int n) { + long[][] a + = {{0, 1, 0, 0, 0}, {1, 0, 1, 0, 0}, {1, 1, 0, 1, 1}, {0, 0, 1, 0, 1}, {1, 0, 0, 0, 0}}; + long[][] res = pow(a, n - 1); + long ans = 0; + for (long x : res[0]) { + ans = (ans + x) % mod; + } + return (int) ans; + } + + private long[][] mul(long[][] a, long[][] b) { + int m = a.length, n = b[0].length; + long[][] c = new long[m][n]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k < b.length; ++k) { + c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % mod; + } + } + } + return c; + } + + private long[][] pow(long[][] a, int n) { + long[][] res = new long[1][a.length]; + Arrays.fill(res[0], 1); + while (n > 0) { + if ((n & 1) == 1) { + res = mul(res, a); + } + a = mul(a, a); + n >>= 1; + } + return res; + } +} \ No newline at end of file diff --git a/solution/1200-1299/1220.Count Vowels Permutation/Solution2.js b/solution/1200-1299/1220.Count Vowels Permutation/Solution2.js new file mode 100644 index 0000000000000..75d397ff870a5 --- /dev/null +++ b/solution/1200-1299/1220.Count Vowels Permutation/Solution2.js @@ -0,0 +1,44 @@ +/** + * @param {number} n + * @return {number} + */ + +const mod = 1e9 + 7; + +var countVowelPermutation = function (n) { + const a = [ + [0, 1, 0, 0, 0], + [1, 0, 1, 0, 0], + [1, 1, 0, 1, 1], + [0, 0, 1, 0, 1], + [1, 0, 0, 0, 0], + ]; + const res = pow(a, n - 1); + return res[0].reduce((a, b) => (a + b) % mod); +}; + +function mul(a, b) { + const [m, n] = [a.length, b[0].length]; + const c = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + for (let k = 0; k < b.length; ++k) { + c[i][j] = + (c[i][j] + Number((BigInt(a[i][k]) * BigInt(b[k][j])) % BigInt(mod))) % mod; + } + } + } + return c; +} + +function pow(a, n) { + let res = [[1, 1, 1, 1, 1]]; + while (n) { + if (n & 1) { + res = mul(res, a); + } + a = mul(a, a); + n >>>= 1; + } + return res; +} diff --git a/solution/1200-1299/1220.Count Vowels Permutation/Solution2.py b/solution/1200-1299/1220.Count Vowels Permutation/Solution2.py new file mode 100644 index 0000000000000..33ebef87259db --- /dev/null +++ b/solution/1200-1299/1220.Count Vowels Permutation/Solution2.py @@ -0,0 +1,31 @@ +class Solution: + def countVowelPermutation(self, n: int) -> int: + mod = 10**9 + 7 + + def mul(a: List[List[int]], b: List[List[int]]) -> List[List[int]]: + m, n = len(a), len(b[0]) + c = [[0] * n for _ in range(m)] + for i in range(m): + for j in range(n): + for k in range(len(b)): + c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % mod + return c + + def pow(a: List[List[int]], n: int) -> List[int]: + res = [[1] * len(a)] + while n: + if n & 1: + res = mul(res, a) + a = mul(a, a) + n >>= 1 + return res + + a = [ + [0, 1, 0, 0, 0], + [1, 0, 1, 0, 0], + [1, 1, 0, 1, 1], + [0, 0, 1, 0, 1], + [1, 0, 0, 0, 0], + ] + res = pow(a, n - 1) + return sum(map(sum, res)) % mod diff --git a/solution/1200-1299/1220.Count Vowels Permutation/Solution2.ts b/solution/1200-1299/1220.Count Vowels Permutation/Solution2.ts new file mode 100644 index 0000000000000..d99cbe8938406 --- /dev/null +++ b/solution/1200-1299/1220.Count Vowels Permutation/Solution2.ts @@ -0,0 +1,39 @@ +const mod = 1e9 + 7; + +function countVowelPermutation(n: number): number { + const a: number[][] = [ + [0, 1, 0, 0, 0], + [1, 0, 1, 0, 0], + [1, 1, 0, 1, 1], + [0, 0, 1, 0, 1], + [1, 0, 0, 0, 0], + ]; + const res = pow(a, n - 1); + return res[0].reduce((a, b) => (a + b) % mod); +} + +function mul(a: number[][], b: number[][]): number[][] { + const [m, n] = [a.length, b[0].length]; + const c = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + for (let k = 0; k < b.length; ++k) { + c[i][j] = + (c[i][j] + Number((BigInt(a[i][k]) * BigInt(b[k][j])) % BigInt(mod))) % mod; + } + } + } + return c; +} + +function pow(a: number[][], n: number): number[][] { + let res: number[][] = [[1, 1, 1, 1, 1]]; + while (n) { + if (n & 1) { + res = mul(res, a); + } + a = mul(a, a); + n >>>= 1; + } + return res; +} diff --git a/solution/1200-1299/1220.Count Vowels Permutation/Solution3.java b/solution/1200-1299/1220.Count Vowels Permutation/Solution3.java new file mode 100644 index 0000000000000..0d0736cf81b26 --- /dev/null +++ b/solution/1200-1299/1220.Count Vowels Permutation/Solution3.java @@ -0,0 +1,23 @@ +class Solution { + public int countVowelPermutation(int n) { + final int mod = 1000000007; + long countA = 1, countE = 1, countI = 1, countO = 1, countU = 1; + for (int length = 1; length < n; length++) { + // Calculate the next counts for each vowel based on the previous counts + long nextCountA = countE; + long nextCountE = (countA + countI) % mod; + long nextCountI = (countA + countE + countO + countU) % mod; + long nextCountO = (countI + countU) % mod; + long nextCountU = countA; + // Update the counts with the newly calculated values for the next length + countA = nextCountA; + countE = nextCountE; + countI = nextCountI; + countO = nextCountO; + countU = nextCountU; + } + // Calculate the total count of valid strings for length n + long totalCount = (countA + countE + countI + countO + countU) % mod; + return (int) totalCount; + } +} \ No newline at end of file diff --git a/solution/1200-1299/1220.Count Vowels Permutation/Solution3.py b/solution/1200-1299/1220.Count Vowels Permutation/Solution3.py new file mode 100644 index 0000000000000..47eaa67aeaf8d --- /dev/null +++ b/solution/1200-1299/1220.Count Vowels Permutation/Solution3.py @@ -0,0 +1,24 @@ +import numpy as np + + +class Solution: + def countVowelPermutation(self, n: int) -> int: + mod = 10**9 + 7 + factor = np.mat( + [ + (0, 1, 0, 0, 0), + (1, 0, 1, 0, 0), + (1, 1, 0, 1, 1), + (0, 0, 1, 0, 1), + (1, 0, 0, 0, 0), + ], + np.dtype("O"), + ) + res = np.mat([(1, 1, 1, 1, 1)], np.dtype("O")) + n -= 1 + while n: + if n & 1: + res = res * factor % mod + factor = factor * factor % mod + n >>= 1 + return res.sum() % mod diff --git a/solution/1200-1299/1222.Queens That Can Attack the King/Solution.cpp b/solution/1200-1299/1222.Queens That Can Attack the King/Solution.cpp index 76db8d705d371..a8a7a45fec122 100644 --- a/solution/1200-1299/1222.Queens That Can Attack the King/Solution.cpp +++ b/solution/1200-1299/1222.Queens That Can Attack the King/Solution.cpp @@ -1,27 +1,27 @@ -class Solution { -public: - vector> queensAttacktheKing(vector>& queens, vector& king) { - int n = 8; - bool s[8][8]{}; - for (auto& q : queens) { - s[q[0]][q[1]] = true; - } - vector> ans; - for (int a = -1; a <= 1; ++a) { - for (int b = -1; b <= 1; ++b) { - if (a || b) { - int x = king[0] + a, y = king[1] + b; - while (x >= 0 && x < n && y >= 0 && y < n) { - if (s[x][y]) { - ans.push_back({x, y}); - break; - } - x += a; - y += b; - } - } - } - } - return ans; - } +class Solution { +public: + vector> queensAttacktheKing(vector>& queens, vector& king) { + int n = 8; + bool s[8][8]{}; + for (auto& q : queens) { + s[q[0]][q[1]] = true; + } + vector> ans; + for (int a = -1; a <= 1; ++a) { + for (int b = -1; b <= 1; ++b) { + if (a || b) { + int x = king[0] + a, y = king[1] + b; + while (x >= 0 && x < n && y >= 0 && y < n) { + if (s[x][y]) { + ans.push_back({x, y}); + break; + } + x += a; + y += b; + } + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1200-1299/1222.Queens That Can Attack the King/Solution.java b/solution/1200-1299/1222.Queens That Can Attack the King/Solution.java index 7b4a0857e3b30..3ab9b8c1d4796 100644 --- a/solution/1200-1299/1222.Queens That Can Attack the King/Solution.java +++ b/solution/1200-1299/1222.Queens That Can Attack the King/Solution.java @@ -1,26 +1,26 @@ -class Solution { - public List> queensAttacktheKing(int[][] queens, int[] king) { - final int n = 8; - var s = new boolean[n][n]; - for (var q : queens) { - s[q[0]][q[1]] = true; - } - List> ans = new ArrayList<>(); - for (int a = -1; a <= 1; ++a) { - for (int b = -1; b <= 1; ++b) { - if (a != 0 || b != 0) { - int x = king[0] + a, y = king[1] + b; - while (x >= 0 && x < n && y >= 0 && y < n) { - if (s[x][y]) { - ans.add(List.of(x, y)); - break; - } - x += a; - y += b; - } - } - } - } - return ans; - } +class Solution { + public List> queensAttacktheKing(int[][] queens, int[] king) { + final int n = 8; + var s = new boolean[n][n]; + for (var q : queens) { + s[q[0]][q[1]] = true; + } + List> ans = new ArrayList<>(); + for (int a = -1; a <= 1; ++a) { + for (int b = -1; b <= 1; ++b) { + if (a != 0 || b != 0) { + int x = king[0] + a, y = king[1] + b; + while (x >= 0 && x < n && y >= 0 && y < n) { + if (s[x][y]) { + ans.add(List.of(x, y)); + break; + } + x += a; + y += b; + } + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1200-1299/1222.Queens That Can Attack the King/Solution.py b/solution/1200-1299/1222.Queens That Can Attack the King/Solution.py index 471805c2a3fc4..c7bdbc7b65860 100644 --- a/solution/1200-1299/1222.Queens That Can Attack the King/Solution.py +++ b/solution/1200-1299/1222.Queens That Can Attack the King/Solution.py @@ -1,17 +1,17 @@ -class Solution: - def queensAttacktheKing( - self, queens: List[List[int]], king: List[int] - ) -> List[List[int]]: - n = 8 - s = {(i, j) for i, j in queens} - ans = [] - for a in range(-1, 2): - for b in range(-1, 2): - if a or b: - x, y = king - while 0 <= x + a < n and 0 <= y + b < n: - x, y = x + a, y + b - if (x, y) in s: - ans.append([x, y]) - break - return ans +class Solution: + def queensAttacktheKing( + self, queens: List[List[int]], king: List[int] + ) -> List[List[int]]: + n = 8 + s = {(i, j) for i, j in queens} + ans = [] + for a in range(-1, 2): + for b in range(-1, 2): + if a or b: + x, y = king + while 0 <= x + a < n and 0 <= y + b < n: + x, y = x + a, y + b + if (x, y) in s: + ans.append([x, y]) + break + return ans diff --git a/solution/1200-1299/1223.Dice Roll Simulation/Solution2.cpp b/solution/1200-1299/1223.Dice Roll Simulation/Solution2.cpp new file mode 100644 index 0000000000000..9514f1636fefd --- /dev/null +++ b/solution/1200-1299/1223.Dice Roll Simulation/Solution2.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int dieSimulator(int n, vector& rollMax) { + int f[n + 1][7][16]; + memset(f, 0, sizeof f); + for (int j = 1; j <= 6; ++j) { + f[1][j][1] = 1; + } + const int mod = 1e9 + 7; + for (int i = 2; i <= n; ++i) { + for (int j = 1; j <= 6; ++j) { + for (int x = 1; x <= rollMax[j - 1]; ++x) { + for (int k = 1; k <= 6; ++k) { + if (k != j) { + f[i][k][1] = (f[i][k][1] + f[i - 1][j][x]) % mod; + } else if (x + 1 <= rollMax[j - 1]) { + f[i][j][x + 1] = (f[i][j][x + 1] + f[i - 1][j][x]) % mod; + } + } + } + } + } + int ans = 0; + for (int j = 1; j <= 6; ++j) { + for (int x = 1; x <= rollMax[j - 1]; ++x) { + ans = (ans + f[n][j][x]) % mod; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1200-1299/1223.Dice Roll Simulation/Solution2.go b/solution/1200-1299/1223.Dice Roll Simulation/Solution2.go new file mode 100644 index 0000000000000..464278de5a211 --- /dev/null +++ b/solution/1200-1299/1223.Dice Roll Simulation/Solution2.go @@ -0,0 +1,26 @@ +func dieSimulator(n int, rollMax []int) (ans int) { + f := make([][7][16]int, n+1) + for j := 1; j <= 6; j++ { + f[1][j][1] = 1 + } + const mod = 1e9 + 7 + for i := 2; i <= n; i++ { + for j := 1; j <= 6; j++ { + for x := 1; x <= rollMax[j-1]; x++ { + for k := 1; k <= 6; k++ { + if k != j { + f[i][k][1] = (f[i][k][1] + f[i-1][j][x]) % mod + } else if x+1 <= rollMax[j-1] { + f[i][j][x+1] = (f[i][j][x+1] + f[i-1][j][x]) % mod + } + } + } + } + } + for j := 1; j <= 6; j++ { + for x := 1; x <= rollMax[j-1]; x++ { + ans = (ans + f[n][j][x]) % mod + } + } + return +} \ No newline at end of file diff --git a/solution/1200-1299/1223.Dice Roll Simulation/Solution2.java b/solution/1200-1299/1223.Dice Roll Simulation/Solution2.java new file mode 100644 index 0000000000000..7e7bdbc500fd3 --- /dev/null +++ b/solution/1200-1299/1223.Dice Roll Simulation/Solution2.java @@ -0,0 +1,29 @@ +class Solution { + public int dieSimulator(int n, int[] rollMax) { + int[][][] f = new int[n + 1][7][16]; + for (int j = 1; j <= 6; ++j) { + f[1][j][1] = 1; + } + final int mod = (int) 1e9 + 7; + for (int i = 2; i <= n; ++i) { + for (int j = 1; j <= 6; ++j) { + for (int x = 1; x <= rollMax[j - 1]; ++x) { + for (int k = 1; k <= 6; ++k) { + if (k != j) { + f[i][k][1] = (f[i][k][1] + f[i - 1][j][x]) % mod; + } else if (x + 1 <= rollMax[j - 1]) { + f[i][j][x + 1] = (f[i][j][x + 1] + f[i - 1][j][x]) % mod; + } + } + } + } + } + int ans = 0; + for (int j = 1; j <= 6; ++j) { + for (int x = 1; x <= rollMax[j - 1]; ++x) { + ans = (ans + f[n][j][x]) % mod; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1200-1299/1223.Dice Roll Simulation/Solution2.py b/solution/1200-1299/1223.Dice Roll Simulation/Solution2.py new file mode 100644 index 0000000000000..c6e0cf6e838ce --- /dev/null +++ b/solution/1200-1299/1223.Dice Roll Simulation/Solution2.py @@ -0,0 +1,19 @@ +class Solution: + def dieSimulator(self, n: int, rollMax: List[int]) -> int: + f = [[[0] * 16 for _ in range(7)] for _ in range(n + 1)] + for j in range(1, 7): + f[1][j][1] = 1 + for i in range(2, n + 1): + for j in range(1, 7): + for x in range(1, rollMax[j - 1] + 1): + for k in range(1, 7): + if k != j: + f[i][k][1] += f[i - 1][j][x] + elif x + 1 <= rollMax[j - 1]: + f[i][j][x + 1] += f[i - 1][j][x] + mod = 10**9 + 7 + ans = 0 + for j in range(1, 7): + for x in range(1, rollMax[j - 1] + 1): + ans = (ans + f[n][j][x]) % mod + return ans diff --git a/solution/1200-1299/1226.The Dining Philosophers/Solution.cpp b/solution/1200-1299/1226.The Dining Philosophers/Solution.cpp index 159a2f8dc854d..ff605649aa7f2 100644 --- a/solution/1200-1299/1226.The Dining Philosophers/Solution.cpp +++ b/solution/1200-1299/1226.The Dining Philosophers/Solution.cpp @@ -3,6 +3,9 @@ class DiningPhilosophers { using Act = function; void wantsToEat(int philosopher, Act pickLeftFork, Act pickRightFork, Act eat, Act putLeftFork, Act putRightFork) { + /* 这一题实际上是用到了C++17中的scoped_lock知识。 + 作用是传入scoped_lock(mtx1, mtx2)两个锁,然后在作用范围内,依次顺序上锁mtx1和mtx2;然后在作用范围结束时,再反续解锁mtx2和mtx1。 + 从而保证了philosopher1有动作的时候,philosopher2无法操作;但是philosopher3和philosopher4不受影响 */ std::scoped_lock lock(mutexes_[philosopher], mutexes_[philosopher >= 4 ? 0 : philosopher + 1]); pickLeftFork(); pickRightFork(); diff --git a/solution/1200-1299/1228.Missing Number In Arithmetic Progression/Solution.go b/solution/1200-1299/1228.Missing Number In Arithmetic Progression/Solution.go index c25776af4140c..db6075cfc2e2d 100644 --- a/solution/1200-1299/1228.Missing Number In Arithmetic Progression/Solution.go +++ b/solution/1200-1299/1228.Missing Number In Arithmetic Progression/Solution.go @@ -1,9 +1,10 @@ func missingNumber(arr []int) int { n := len(arr) - x := (arr[0] + arr[n-1]) * (n + 1) / 2 - y := 0 - for _, v := range arr { - y += v + d := (arr[n-1] - arr[0]) / n + for i := 1; i < n; i++ { + if arr[i] != arr[i-1]+d { + return arr[i-1] + d + } } - return x - y + return arr[0] } \ No newline at end of file diff --git a/solution/1200-1299/1228.Missing Number In Arithmetic Progression/Solution2.cpp b/solution/1200-1299/1228.Missing Number In Arithmetic Progression/Solution2.cpp new file mode 100644 index 0000000000000..e6e938d6ab51b --- /dev/null +++ b/solution/1200-1299/1228.Missing Number In Arithmetic Progression/Solution2.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + int missingNumber(vector& arr) { + int n = arr.size(); + int d = (arr[n - 1] - arr[0]) / n; + for (int i = 1; i < n; ++i) + if (arr[i] != arr[i - 1] + d) return arr[i - 1] + d; + return arr[0]; + } +}; \ No newline at end of file diff --git a/solution/1200-1299/1228.Missing Number In Arithmetic Progression/Solution2.java b/solution/1200-1299/1228.Missing Number In Arithmetic Progression/Solution2.java new file mode 100644 index 0000000000000..ddf2b0f39d06f --- /dev/null +++ b/solution/1200-1299/1228.Missing Number In Arithmetic Progression/Solution2.java @@ -0,0 +1,12 @@ +class Solution { + public int missingNumber(int[] arr) { + int n = arr.length; + int d = (arr[n - 1] - arr[0]) / n; + for (int i = 1; i < n; ++i) { + if (arr[i] != arr[i - 1] + d) { + return arr[i - 1] + d; + } + } + return arr[0]; + } +} \ No newline at end of file diff --git a/solution/1200-1299/1228.Missing Number In Arithmetic Progression/Solution2.py b/solution/1200-1299/1228.Missing Number In Arithmetic Progression/Solution2.py new file mode 100644 index 0000000000000..ea8460623d10a --- /dev/null +++ b/solution/1200-1299/1228.Missing Number In Arithmetic Progression/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def missingNumber(self, arr: List[int]) -> int: + n = len(arr) + d = (arr[-1] - arr[0]) // n + for i in range(1, n): + if arr[i] != arr[i - 1] + d: + return arr[i - 1] + d + return arr[0] diff --git a/solution/1200-1299/1230.Toss Strange Coins/Solution.cpp b/solution/1200-1299/1230.Toss Strange Coins/Solution.cpp index c1b53c3adc306..e4d7a01f345b8 100644 --- a/solution/1200-1299/1230.Toss Strange Coins/Solution.cpp +++ b/solution/1200-1299/1230.Toss Strange Coins/Solution.cpp @@ -1,17 +1,18 @@ class Solution { public: double probabilityOfHeads(vector& prob, int target) { - double f[target + 1]; + int n = prob.size(); + double f[n + 1][target + 1]; memset(f, 0, sizeof(f)); - f[0] = 1; - for (double p : prob) { - for (int j = target; j >= 0; --j) { - f[j] *= (1 - p); + f[0][0] = 1; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j <= min(i, target); ++j) { + f[i][j] = (1 - prob[i - 1]) * f[i - 1][j]; if (j > 0) { - f[j] += p * f[j - 1]; + f[i][j] += prob[i - 1] * f[i - 1][j - 1]; } } } - return f[target]; + return f[n][target]; } }; \ No newline at end of file diff --git a/solution/1200-1299/1230.Toss Strange Coins/Solution.go b/solution/1200-1299/1230.Toss Strange Coins/Solution.go index d82adc545af61..23724ff2cc8d6 100644 --- a/solution/1200-1299/1230.Toss Strange Coins/Solution.go +++ b/solution/1200-1299/1230.Toss Strange Coins/Solution.go @@ -1,13 +1,17 @@ func probabilityOfHeads(prob []float64, target int) float64 { - f := make([]float64, target+1) - f[0] = 1 - for _, p := range prob { - for j := target; j >= 0; j-- { - f[j] *= (1 - p) + n := len(prob) + f := make([][]float64, n+1) + for i := range f { + f[i] = make([]float64, target+1) + } + f[0][0] = 1 + for i := 1; i <= n; i++ { + for j := 0; j <= i && j <= target; j++ { + f[i][j] = (1 - prob[i-1]) * f[i-1][j] if j > 0 { - f[j] += p * f[j-1] + f[i][j] += prob[i-1] * f[i-1][j-1] } } } - return f[target] + return f[n][target] } \ No newline at end of file diff --git a/solution/1200-1299/1230.Toss Strange Coins/Solution.java b/solution/1200-1299/1230.Toss Strange Coins/Solution.java index 6c1d4accc1e25..7c50f78291d0b 100644 --- a/solution/1200-1299/1230.Toss Strange Coins/Solution.java +++ b/solution/1200-1299/1230.Toss Strange Coins/Solution.java @@ -1,15 +1,16 @@ class Solution { public double probabilityOfHeads(double[] prob, int target) { - double[] f = new double[target + 1]; - f[0] = 1; - for (double p : prob) { - for (int j = target; j >= 0; --j) { - f[j] *= (1 - p); + int n = prob.length; + double[][] f = new double[n + 1][target + 1]; + f[0][0] = 1; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j <= Math.min(i, target); ++j) { + f[i][j] = (1 - prob[i - 1]) * f[i - 1][j]; if (j > 0) { - f[j] += p * f[j - 1]; + f[i][j] += prob[i - 1] * f[i - 1][j - 1]; } } } - return f[target]; + return f[n][target]; } } \ No newline at end of file diff --git a/solution/1200-1299/1230.Toss Strange Coins/Solution.py b/solution/1200-1299/1230.Toss Strange Coins/Solution.py index 1c8c7b4fdc99c..a54cca616b4ea 100644 --- a/solution/1200-1299/1230.Toss Strange Coins/Solution.py +++ b/solution/1200-1299/1230.Toss Strange Coins/Solution.py @@ -1,10 +1,11 @@ class Solution: def probabilityOfHeads(self, prob: List[float], target: int) -> float: - f = [0] * (target + 1) - f[0] = 1 - for p in prob: - for j in range(target, -1, -1): - f[j] *= 1 - p + n = len(prob) + f = [[0] * (target + 1) for _ in range(n + 1)] + f[0][0] = 1 + for i, p in enumerate(prob, 1): + for j in range(min(i, target) + 1): + f[i][j] = (1 - p) * f[i - 1][j] if j: - f[j] += p * f[j - 1] - return f[target] + f[i][j] += p * f[i - 1][j - 1] + return f[n][target] diff --git a/solution/1200-1299/1230.Toss Strange Coins/Solution.ts b/solution/1200-1299/1230.Toss Strange Coins/Solution.ts index 48887d1ed527d..fdce3ddc8507f 100644 --- a/solution/1200-1299/1230.Toss Strange Coins/Solution.ts +++ b/solution/1200-1299/1230.Toss Strange Coins/Solution.ts @@ -1,13 +1,14 @@ function probabilityOfHeads(prob: number[], target: number): number { - const f = new Array(target + 1).fill(0); - f[0] = 1; - for (const p of prob) { - for (let j = target; j >= 0; --j) { - f[j] *= 1 - p; - if (j > 0) { - f[j] += f[j - 1] * p; + const n = prob.length; + const f = new Array(n + 1).fill(0).map(() => new Array(target + 1).fill(0)); + f[0][0] = 1; + for (let i = 1; i <= n; ++i) { + for (let j = 0; j <= target; ++j) { + f[i][j] = f[i - 1][j] * (1 - prob[i - 1]); + if (j) { + f[i][j] += f[i - 1][j - 1] * prob[i - 1]; } } } - return f[target]; + return f[n][target]; } diff --git a/solution/1200-1299/1230.Toss Strange Coins/Solution2.cpp b/solution/1200-1299/1230.Toss Strange Coins/Solution2.cpp new file mode 100644 index 0000000000000..c1b53c3adc306 --- /dev/null +++ b/solution/1200-1299/1230.Toss Strange Coins/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + double probabilityOfHeads(vector& prob, int target) { + double f[target + 1]; + memset(f, 0, sizeof(f)); + f[0] = 1; + for (double p : prob) { + for (int j = target; j >= 0; --j) { + f[j] *= (1 - p); + if (j > 0) { + f[j] += p * f[j - 1]; + } + } + } + return f[target]; + } +}; \ No newline at end of file diff --git a/solution/1200-1299/1230.Toss Strange Coins/Solution2.go b/solution/1200-1299/1230.Toss Strange Coins/Solution2.go new file mode 100644 index 0000000000000..d82adc545af61 --- /dev/null +++ b/solution/1200-1299/1230.Toss Strange Coins/Solution2.go @@ -0,0 +1,13 @@ +func probabilityOfHeads(prob []float64, target int) float64 { + f := make([]float64, target+1) + f[0] = 1 + for _, p := range prob { + for j := target; j >= 0; j-- { + f[j] *= (1 - p) + if j > 0 { + f[j] += p * f[j-1] + } + } + } + return f[target] +} \ No newline at end of file diff --git a/solution/1200-1299/1230.Toss Strange Coins/Solution2.java b/solution/1200-1299/1230.Toss Strange Coins/Solution2.java new file mode 100644 index 0000000000000..6c1d4accc1e25 --- /dev/null +++ b/solution/1200-1299/1230.Toss Strange Coins/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public double probabilityOfHeads(double[] prob, int target) { + double[] f = new double[target + 1]; + f[0] = 1; + for (double p : prob) { + for (int j = target; j >= 0; --j) { + f[j] *= (1 - p); + if (j > 0) { + f[j] += p * f[j - 1]; + } + } + } + return f[target]; + } +} \ No newline at end of file diff --git a/solution/1200-1299/1230.Toss Strange Coins/Solution2.py b/solution/1200-1299/1230.Toss Strange Coins/Solution2.py new file mode 100644 index 0000000000000..1c8c7b4fdc99c --- /dev/null +++ b/solution/1200-1299/1230.Toss Strange Coins/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def probabilityOfHeads(self, prob: List[float], target: int) -> float: + f = [0] * (target + 1) + f[0] = 1 + for p in prob: + for j in range(target, -1, -1): + f[j] *= 1 - p + if j: + f[j] += p * f[j - 1] + return f[target] diff --git a/solution/1200-1299/1230.Toss Strange Coins/Solution2.ts b/solution/1200-1299/1230.Toss Strange Coins/Solution2.ts new file mode 100644 index 0000000000000..48887d1ed527d --- /dev/null +++ b/solution/1200-1299/1230.Toss Strange Coins/Solution2.ts @@ -0,0 +1,13 @@ +function probabilityOfHeads(prob: number[], target: number): number { + const f = new Array(target + 1).fill(0); + f[0] = 1; + for (const p of prob) { + for (let j = target; j >= 0; --j) { + f[j] *= 1 - p; + if (j > 0) { + f[j] += f[j - 1] * p; + } + } + } + return f[target]; +} diff --git a/solution/1200-1299/1231.Divide Chocolate/Solution.cpp b/solution/1200-1299/1231.Divide Chocolate/Solution.cpp index 05e1f2a3257c7..05fdcdb188335 100644 --- a/solution/1200-1299/1231.Divide Chocolate/Solution.cpp +++ b/solution/1200-1299/1231.Divide Chocolate/Solution.cpp @@ -1,26 +1,26 @@ -class Solution { -public: - int maximizeSweetness(vector& sweetness, int k) { - int l = 0, r = accumulate(sweetness.begin(), sweetness.end(), 0); - auto check = [&](int x) { - int s = 0, cnt = 0; - for (int v : sweetness) { - s += v; - if (s >= x) { - s = 0; - ++cnt; - } - } - return cnt > k; - }; - while (l < r) { - int mid = (l + r + 1) >> 1; - if (check(mid)) { - l = mid; - } else { - r = mid - 1; - } - } - return l; - } +class Solution { +public: + int maximizeSweetness(vector& sweetness, int k) { + int l = 0, r = accumulate(sweetness.begin(), sweetness.end(), 0); + auto check = [&](int x) { + int s = 0, cnt = 0; + for (int v : sweetness) { + s += v; + if (s >= x) { + s = 0; + ++cnt; + } + } + return cnt > k; + }; + while (l < r) { + int mid = (l + r + 1) >> 1; + if (check(mid)) { + l = mid; + } else { + r = mid - 1; + } + } + return l; + } }; \ No newline at end of file diff --git a/solution/1200-1299/1231.Divide Chocolate/Solution.java b/solution/1200-1299/1231.Divide Chocolate/Solution.java index 69ac3e4d8561e..48cda5e43b36e 100644 --- a/solution/1200-1299/1231.Divide Chocolate/Solution.java +++ b/solution/1200-1299/1231.Divide Chocolate/Solution.java @@ -1,29 +1,29 @@ -class Solution { - public int maximizeSweetness(int[] sweetness, int k) { - int l = 0, r = 0; - for (int v : sweetness) { - r += v; - } - while (l < r) { - int mid = (l + r + 1) >> 1; - if (check(sweetness, mid, k)) { - l = mid; - } else { - r = mid - 1; - } - } - return l; - } - - private boolean check(int[] nums, int x, int k) { - int s = 0, cnt = 0; - for (int v : nums) { - s += v; - if (s >= x) { - s = 0; - ++cnt; - } - } - return cnt > k; - } +class Solution { + public int maximizeSweetness(int[] sweetness, int k) { + int l = 0, r = 0; + for (int v : sweetness) { + r += v; + } + while (l < r) { + int mid = (l + r + 1) >> 1; + if (check(sweetness, mid, k)) { + l = mid; + } else { + r = mid - 1; + } + } + return l; + } + + private boolean check(int[] nums, int x, int k) { + int s = 0, cnt = 0; + for (int v : nums) { + s += v; + if (s >= x) { + s = 0; + ++cnt; + } + } + return cnt > k; + } } \ No newline at end of file diff --git a/solution/1200-1299/1231.Divide Chocolate/Solution.py b/solution/1200-1299/1231.Divide Chocolate/Solution.py index 30d2b6f12f230..55d6a26841c4f 100644 --- a/solution/1200-1299/1231.Divide Chocolate/Solution.py +++ b/solution/1200-1299/1231.Divide Chocolate/Solution.py @@ -1,19 +1,19 @@ -class Solution: - def maximizeSweetness(self, sweetness: List[int], k: int) -> int: - def check(x: int) -> bool: - s = cnt = 0 - for v in sweetness: - s += v - if s >= x: - s = 0 - cnt += 1 - return cnt > k - - l, r = 0, sum(sweetness) - while l < r: - mid = (l + r + 1) >> 1 - if check(mid): - l = mid - else: - r = mid - 1 - return l +class Solution: + def maximizeSweetness(self, sweetness: List[int], k: int) -> int: + def check(x: int) -> bool: + s = cnt = 0 + for v in sweetness: + s += v + if s >= x: + s = 0 + cnt += 1 + return cnt > k + + l, r = 0, sum(sweetness) + while l < r: + mid = (l + r + 1) >> 1 + if check(mid): + l = mid + else: + r = mid - 1 + return l diff --git a/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/Solution2.cpp b/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/Solution2.cpp new file mode 100644 index 0000000000000..125038062c06d --- /dev/null +++ b/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/Solution2.cpp @@ -0,0 +1,59 @@ +class Trie { +public: + void insert(int fid, string& f) { + Trie* node = this; + vector ps = split(f, '/'); + for (int i = 1; i < ps.size(); ++i) { + auto& p = ps[i]; + if (!node->children.count(p)) { + node->children[p] = new Trie(); + } + node = node->children[p]; + } + node->fid = fid; + } + + vector search() { + vector ans; + function dfs = [&](Trie* root) { + if (root->fid != -1) { + ans.push_back(root->fid); + return; + } + for (auto& [_, child] : root->children) { + dfs(child); + } + }; + dfs(this); + return ans; + } + + vector split(string& s, char delim) { + stringstream ss(s); + string item; + vector res; + while (getline(ss, item, delim)) { + res.emplace_back(item); + } + return res; + } + +private: + unordered_map children; + int fid = -1; +}; + +class Solution { +public: + vector removeSubfolders(vector& folder) { + Trie* trie = new Trie(); + for (int i = 0; i < folder.size(); ++i) { + trie->insert(i, folder[i]); + } + vector ans; + for (int i : trie->search()) { + ans.emplace_back(folder[i]); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/Solution2.go b/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/Solution2.go new file mode 100644 index 0000000000000..5f0a8f90351af --- /dev/null +++ b/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/Solution2.go @@ -0,0 +1,49 @@ +type Trie struct { + children map[string]*Trie + isEnd bool +} + +func newTrie() *Trie { + m := map[string]*Trie{} + return &Trie{children: m} +} + +func (this *Trie) insert(w string) { + node := this + for _, p := range strings.Split(w, "/")[1:] { + if _, ok := node.children[p]; !ok { + node.children[p] = newTrie() + } + node, _ = node.children[p] + } + node.isEnd = true +} + +func (this *Trie) search(w string) bool { + node := this + for _, p := range strings.Split(w, "/")[1:] { + if _, ok := node.children[p]; !ok { + return false + } + node, _ = node.children[p] + if node.isEnd { + return true + } + } + return false +} + +func removeSubfolders(folder []string) []string { + sort.Slice(folder, func(i, j int) bool { + return len(strings.Split(folder[i], "/")) < len(strings.Split(folder[j], "/")) + }) + trie := newTrie() + var ans []string + for _, v := range folder { + if !trie.search(v) { + trie.insert(v) + ans = append(ans, v) + } + } + return ans +} \ No newline at end of file diff --git a/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/Solution2.java b/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/Solution2.java new file mode 100644 index 0000000000000..5b93eecf7b483 --- /dev/null +++ b/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/Solution2.java @@ -0,0 +1,47 @@ +class Trie { + private Map children = new HashMap<>(); + private int fid = -1; + + public void insert(int fid, String f) { + Trie node = this; + String[] ps = f.split("/"); + for (int i = 1; i < ps.length; ++i) { + String p = ps[i]; + if (!node.children.containsKey(p)) { + node.children.put(p, new Trie()); + } + node = node.children.get(p); + } + node.fid = fid; + } + + public List search() { + List ans = new ArrayList<>(); + dfs(this, ans); + return ans; + } + + private void dfs(Trie root, List ans) { + if (root.fid != -1) { + ans.add(root.fid); + return; + } + for (var child : root.children.values()) { + dfs(child, ans); + } + } +} + +class Solution { + public List removeSubfolders(String[] folder) { + Trie trie = new Trie(); + for (int i = 0; i < folder.length; ++i) { + trie.insert(i, folder[i]); + } + List ans = new ArrayList<>(); + for (int i : trie.search()) { + ans.add(folder[i]); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/Solution2.py b/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/Solution2.py new file mode 100644 index 0000000000000..7f3200558c918 --- /dev/null +++ b/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/Solution2.py @@ -0,0 +1,33 @@ +class Trie: + def __init__(self): + self.children = {} + self.fid = -1 + + def insert(self, i, f): + node = self + ps = f.split('/') + for p in ps[1:]: + if p not in node.children: + node.children[p] = Trie() + node = node.children[p] + node.fid = i + + def search(self): + def dfs(root): + if root.fid != -1: + ans.append(root.fid) + return + for child in root.children.values(): + dfs(child) + + ans = [] + dfs(self) + return ans + + +class Solution: + def removeSubfolders(self, folder: List[str]) -> List[str]: + trie = Trie() + for i, f in enumerate(folder): + trie.insert(i, f) + return [folder[i] for i in trie.search()] diff --git a/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/Solution3.go b/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/Solution3.go new file mode 100644 index 0000000000000..9a5f248168d9d --- /dev/null +++ b/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/Solution3.go @@ -0,0 +1,46 @@ +type Trie struct { + children map[string]*Trie + fid int +} + +func newTrie() *Trie { + return &Trie{map[string]*Trie{}, -1} +} + +func (this *Trie) insert(fid int, f string) { + node := this + ps := strings.Split(f, "/") + for _, p := range ps[1:] { + if _, ok := node.children[p]; !ok { + node.children[p] = newTrie() + } + node = node.children[p] + } + node.fid = fid +} + +func (this *Trie) search() (ans []int) { + var dfs func(*Trie) + dfs = func(root *Trie) { + if root.fid != -1 { + ans = append(ans, root.fid) + return + } + for _, child := range root.children { + dfs(child) + } + } + dfs(this) + return +} + +func removeSubfolders(folder []string) (ans []string) { + trie := newTrie() + for i, f := range folder { + trie.insert(i, f) + } + for _, i := range trie.search() { + ans = append(ans, folder[i]) + } + return +} \ No newline at end of file diff --git a/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution.cpp b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution.cpp index 376d93e016872..82b9ff9847409 100644 --- a/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution.cpp +++ b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution.cpp @@ -3,14 +3,19 @@ class Solution { int jobScheduling(vector& startTime, vector& endTime, vector& profit) { int n = profit.size(); vector> jobs(n); - for (int i = 0; i < n; ++i) jobs[i] = {endTime[i], startTime[i], profit[i]}; + for (int i = 0; i < n; ++i) jobs[i] = {startTime[i], endTime[i], profit[i]}; sort(jobs.begin(), jobs.end()); - vector dp(n + 1); - for (int i = 0; i < n; ++i) { - auto [_, s, p] = jobs[i]; - int j = upper_bound(jobs.begin(), jobs.begin() + i, s, [&](int x, auto& job) -> bool { return x < get<0>(job); }) - jobs.begin(); - dp[i + 1] = max(dp[i], dp[j] + p); - } - return dp[n]; + vector f(n); + function dfs = [&](int i) -> int { + if (i >= n) return 0; + if (f[i]) return f[i]; + auto [_, e, p] = jobs[i]; + tuple t{e, 0, 0}; + int j = lower_bound(jobs.begin() + i + 1, jobs.end(), t, [&](auto& l, auto& r) -> bool { return get<0>(l) < get<0>(r); }) - jobs.begin(); + int ans = max(dfs(i + 1), p + dfs(j)); + f[i] = ans; + return ans; + }; + return dfs(0); } }; \ No newline at end of file diff --git a/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution.go b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution.go index d1b9dc3f32cfc..7d16dbe09720d 100644 --- a/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution.go +++ b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution.go @@ -5,11 +5,20 @@ func jobScheduling(startTime []int, endTime []int, profit []int) int { for i, p := range profit { jobs[i] = tuple{startTime[i], endTime[i], p} } - sort.Slice(jobs, func(i, j int) bool { return jobs[i].e < jobs[j].e }) - dp := make([]int, n+1) - for i, job := range jobs { - j := sort.Search(i, func(k int) bool { return jobs[k].e > job.s }) - dp[i+1] = max(dp[i], dp[j]+job.p) + sort.Slice(jobs, func(i, j int) bool { return jobs[i].s < jobs[j].s }) + f := make([]int, n) + var dfs func(int) int + dfs = func(i int) int { + if i >= n { + return 0 + } + if f[i] != 0 { + return f[i] + } + j := sort.Search(n, func(j int) bool { return jobs[j].s >= jobs[i].e }) + ans := max(dfs(i+1), jobs[i].p+dfs(j)) + f[i] = ans + return ans } - return dp[n] + return dfs(0) } \ No newline at end of file diff --git a/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution.java b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution.java index bafdec6f1c1d5..a42ea5679d51c 100644 --- a/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution.java +++ b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution.java @@ -1,24 +1,38 @@ class Solution { + private int[][] jobs; + private int[] f; + private int n; + public int jobScheduling(int[] startTime, int[] endTime, int[] profit) { - int n = profit.length; - int[][] jobs = new int[n][3]; + n = profit.length; + jobs = new int[n][3]; for (int i = 0; i < n; ++i) { jobs[i] = new int[] {startTime[i], endTime[i], profit[i]}; } - Arrays.sort(jobs, (a, b) -> a[1] - b[1]); - int[] dp = new int[n + 1]; - for (int i = 0; i < n; ++i) { - int j = search(jobs, jobs[i][0], i); - dp[i + 1] = Math.max(dp[i], dp[j] + jobs[i][2]); + Arrays.sort(jobs, (a, b) -> a[0] - b[0]); + f = new int[n]; + return dfs(0); + } + + private int dfs(int i) { + if (i >= n) { + return 0; + } + if (f[i] != 0) { + return f[i]; } - return dp[n]; + int e = jobs[i][1], p = jobs[i][2]; + int j = search(jobs, e, i + 1); + int ans = Math.max(dfs(i + 1), p + dfs(j)); + f[i] = ans; + return ans; } - private int search(int[][] jobs, int x, int n) { - int left = 0, right = n; + private int search(int[][] jobs, int x, int i) { + int left = i, right = n; while (left < right) { int mid = (left + right) >> 1; - if (jobs[mid][1] > x) { + if (jobs[mid][0] >= x) { right = mid; } else { left = mid + 1; diff --git a/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution.py b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution.py index 975ba453c8d54..8dbc285ef4ccf 100644 --- a/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution.py +++ b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution.py @@ -2,10 +2,14 @@ class Solution: def jobScheduling( self, startTime: List[int], endTime: List[int], profit: List[int] ) -> int: - jobs = sorted(zip(endTime, startTime, profit)) + @cache + def dfs(i): + if i >= n: + return 0 + _, e, p = jobs[i] + j = bisect_left(jobs, e, lo=i + 1, key=lambda x: x[0]) + return max(dfs(i + 1), p + dfs(j)) + + jobs = sorted(zip(startTime, endTime, profit)) n = len(profit) - dp = [0] * (n + 1) - for i, (_, s, p) in enumerate(jobs): - j = bisect_right(jobs, s, hi=i, key=lambda x: x[0]) - dp[i + 1] = max(dp[i], dp[j] + p) - return dp[n] + return dfs(0) diff --git a/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution2.cpp b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution2.cpp new file mode 100644 index 0000000000000..376d93e016872 --- /dev/null +++ b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int jobScheduling(vector& startTime, vector& endTime, vector& profit) { + int n = profit.size(); + vector> jobs(n); + for (int i = 0; i < n; ++i) jobs[i] = {endTime[i], startTime[i], profit[i]}; + sort(jobs.begin(), jobs.end()); + vector dp(n + 1); + for (int i = 0; i < n; ++i) { + auto [_, s, p] = jobs[i]; + int j = upper_bound(jobs.begin(), jobs.begin() + i, s, [&](int x, auto& job) -> bool { return x < get<0>(job); }) - jobs.begin(); + dp[i + 1] = max(dp[i], dp[j] + p); + } + return dp[n]; + } +}; \ No newline at end of file diff --git a/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution2.go b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution2.go new file mode 100644 index 0000000000000..d1b9dc3f32cfc --- /dev/null +++ b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution2.go @@ -0,0 +1,15 @@ +func jobScheduling(startTime []int, endTime []int, profit []int) int { + n := len(profit) + type tuple struct{ s, e, p int } + jobs := make([]tuple, n) + for i, p := range profit { + jobs[i] = tuple{startTime[i], endTime[i], p} + } + sort.Slice(jobs, func(i, j int) bool { return jobs[i].e < jobs[j].e }) + dp := make([]int, n+1) + for i, job := range jobs { + j := sort.Search(i, func(k int) bool { return jobs[k].e > job.s }) + dp[i+1] = max(dp[i], dp[j]+job.p) + } + return dp[n] +} \ No newline at end of file diff --git a/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution2.java b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution2.java new file mode 100644 index 0000000000000..bafdec6f1c1d5 --- /dev/null +++ b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution2.java @@ -0,0 +1,29 @@ +class Solution { + public int jobScheduling(int[] startTime, int[] endTime, int[] profit) { + int n = profit.length; + int[][] jobs = new int[n][3]; + for (int i = 0; i < n; ++i) { + jobs[i] = new int[] {startTime[i], endTime[i], profit[i]}; + } + Arrays.sort(jobs, (a, b) -> a[1] - b[1]); + int[] dp = new int[n + 1]; + for (int i = 0; i < n; ++i) { + int j = search(jobs, jobs[i][0], i); + dp[i + 1] = Math.max(dp[i], dp[j] + jobs[i][2]); + } + return dp[n]; + } + + private int search(int[][] jobs, int x, int n) { + int left = 0, right = n; + while (left < right) { + int mid = (left + right) >> 1; + if (jobs[mid][1] > x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} \ No newline at end of file diff --git a/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution2.py b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution2.py new file mode 100644 index 0000000000000..4ac53bcae1b43 --- /dev/null +++ b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def jobScheduling( + self, startTime: List[int], endTime: List[int], profit: List[int] + ) -> int: + @cache + def dfs(i: int) -> int: + if i >= n: + return 0 + j = bisect_left(idx, endTime[idx[i]], key=lambda i: startTime[i]) + return max(dfs(i + 1), profit[idx[i]] + dfs(j)) + + n = len(startTime) + idx = sorted(range(n), key=lambda i: startTime[i]) + return dfs(0) diff --git a/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution3.py b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution3.py new file mode 100644 index 0000000000000..975ba453c8d54 --- /dev/null +++ b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution3.py @@ -0,0 +1,11 @@ +class Solution: + def jobScheduling( + self, startTime: List[int], endTime: List[int], profit: List[int] + ) -> int: + jobs = sorted(zip(endTime, startTime, profit)) + n = len(profit) + dp = [0] * (n + 1) + for i, (_, s, p) in enumerate(jobs): + j = bisect_right(jobs, s, hi=i, key=lambda x: x[0]) + dp[i + 1] = max(dp[i], dp[j] + p) + return dp[n] diff --git a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.cpp b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.cpp index bb08d3f812c7f..cecf20f3d95a7 100644 --- a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.cpp +++ b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.cpp @@ -14,15 +14,18 @@ class Solution { public: vector> findSolution(CustomFunction& customfunction, int z) { vector> ans; - int x = 1, y = 1000; - while (x <= 1000 && y) { - int t = customfunction.f(x, y); - if (t < z) { - x++; - } else if (t > z) { - y--; - } else { - ans.push_back({x++, y--}); + for (int x = 1; x <= 1000; ++x) { + int l = 1, r = 1000; + while (l < r) { + int mid = (l + r) >> 1; + if (customfunction.f(x, mid) >= z) { + r = mid; + } else { + l = mid + 1; + } + } + if (customfunction.f(x, l) == z) { + ans.push_back({x, l}); } } return ans; diff --git a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.go b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.go index 08d0bbdca9dd3..0f35c6998a2e8 100644 --- a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.go +++ b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.go @@ -8,16 +8,10 @@ */ func findSolution(customFunction func(int, int) int, z int) (ans [][]int) { - x, y := 1, 1000 - for x <= 1000 && y > 0 { - t := customFunction(x, y) - if t < z { - x++ - } else if t > z { - y-- - } else { + for x := 1; x <= 1000; x++ { + y := 1 + sort.Search(999, func(y int) bool { return customFunction(x, y+1) >= z }) + if customFunction(x, y) == z { ans = append(ans, []int{x, y}) - x, y = x+1, y-1 } } return diff --git a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.java b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.java index 2f5ebfd84b671..92a0aee7d5e65 100644 --- a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.java +++ b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.java @@ -12,15 +12,18 @@ class Solution { public List> findSolution(CustomFunction customfunction, int z) { List> ans = new ArrayList<>(); - int x = 1, y = 1000; - while (x <= 1000 && y > 0) { - int t = customfunction.f(x, y); - if (t < z) { - x++; - } else if (t > z) { - y--; - } else { - ans.add(Arrays.asList(x++, y--)); + for (int x = 1; x <= 1000; ++x) { + int l = 1, r = 1000; + while (l < r) { + int mid = (l + r) >> 1; + if (customfunction.f(x, mid) >= z) { + r = mid; + } else { + l = mid + 1; + } + } + if (customfunction.f(x, l) == z) { + ans.add(Arrays.asList(x, l)); } } return ans; diff --git a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.py b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.py index ec299fcf00cd3..5ded8ceac1b32 100644 --- a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.py +++ b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.py @@ -6,21 +6,17 @@ class CustomFunction: # Note that f(x, y) is increasing with respect to both x and y. # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) def f(self, x, y): - + """ class Solution: def findSolution(self, customfunction: "CustomFunction", z: int) -> List[List[int]]: ans = [] - x, y = 1, 1000 - while x <= 1000 and y: - t = customfunction.f(x, y) - if t < z: - x += 1 - elif t > z: - y -= 1 - else: + for x in range(1, z + 1): + y = 1 + bisect_left( + range(1, z + 1), z, key=lambda y: customfunction.f(x, y) + ) + if customfunction.f(x, y) == z: ans.append([x, y]) - x, y = x + 1, y - 1 return ans diff --git a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.ts b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.ts index d8353aa17520f..8257930e8d09f 100644 --- a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.ts +++ b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.ts @@ -7,17 +7,20 @@ */ function findSolution(customfunction: CustomFunction, z: number): number[][] { - let x = 1; - let y = 1000; const ans: number[][] = []; - while (x <= 1000 && y) { - const t = customfunction.f(x, y); - if (t < z) { - ++x; - } else if (t > z) { - --y; - } else { - ans.push([x--, y--]); + for (let x = 1; x <= 1000; ++x) { + let l = 1; + let r = 1000; + while (l < r) { + const mid = (l + r) >> 1; + if (customfunction.f(x, mid) >= z) { + r = mid; + } else { + l = mid + 1; + } + } + if (customfunction.f(x, l) == z) { + ans.push([x, l]); } } return ans; diff --git a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.cpp b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.cpp new file mode 100644 index 0000000000000..bb08d3f812c7f --- /dev/null +++ b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.cpp @@ -0,0 +1,30 @@ +/* + * // This is the custom function interface. + * // You should not implement it, or speculate about its implementation + * class CustomFunction { + * public: + * // Returns f(x, y) for any given positive integers x and y. + * // Note that f(x, y) is increasing with respect to both x and y. + * // i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + * int f(int x, int y); + * }; + */ + +class Solution { +public: + vector> findSolution(CustomFunction& customfunction, int z) { + vector> ans; + int x = 1, y = 1000; + while (x <= 1000 && y) { + int t = customfunction.f(x, y); + if (t < z) { + x++; + } else if (t > z) { + y--; + } else { + ans.push_back({x++, y--}); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.go b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.go new file mode 100644 index 0000000000000..08d0bbdca9dd3 --- /dev/null +++ b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.go @@ -0,0 +1,24 @@ +/** + * This is the declaration of customFunction API. + * @param x int + * @param x int + * @return Returns f(x, y) for any given positive integers x and y. + * Note that f(x, y) is increasing with respect to both x and y. + * i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + */ + +func findSolution(customFunction func(int, int) int, z int) (ans [][]int) { + x, y := 1, 1000 + for x <= 1000 && y > 0 { + t := customFunction(x, y) + if t < z { + x++ + } else if t > z { + y-- + } else { + ans = append(ans, []int{x, y}) + x, y = x+1, y-1 + } + } + return +} \ No newline at end of file diff --git a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.java b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.java new file mode 100644 index 0000000000000..2f5ebfd84b671 --- /dev/null +++ b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.java @@ -0,0 +1,28 @@ +/* + * // This is the custom function interface. + * // You should not implement it, or speculate about its implementation + * class CustomFunction { + * // Returns f(x, y) for any given positive integers x and y. + * // Note that f(x, y) is increasing with respect to both x and y. + * // i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + * public int f(int x, int y); + * }; + */ + +class Solution { + public List> findSolution(CustomFunction customfunction, int z) { + List> ans = new ArrayList<>(); + int x = 1, y = 1000; + while (x <= 1000 && y > 0) { + int t = customfunction.f(x, y); + if (t < z) { + x++; + } else if (t > z) { + y--; + } else { + ans.add(Arrays.asList(x++, y--)); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.py b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.py new file mode 100644 index 0000000000000..424c1376a9106 --- /dev/null +++ b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.py @@ -0,0 +1,26 @@ +""" + This is the custom function interface. + You should not implement it, or speculate about its implementation + class CustomFunction: + # Returns f(x, y) for any given positive integers x and y. + # Note that f(x, y) is increasing with respect to both x and y. + # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + def f(self, x, y): + +""" + + +class Solution: + def findSolution(self, customfunction: "CustomFunction", z: int) -> List[List[int]]: + ans = [] + x, y = 1, 1000 + while x <= 1000 and y: + t = customfunction.f(x, y) + if t < z: + x += 1 + elif t > z: + y -= 1 + else: + ans.append([x, y]) + x, y = x + 1, y - 1 + return ans diff --git a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.ts b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.ts new file mode 100644 index 0000000000000..d8353aa17520f --- /dev/null +++ b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.ts @@ -0,0 +1,24 @@ +/** + * // This is the CustomFunction's API interface. + * // You should not implement it, or speculate about its implementation + * class CustomFunction { + * f(x: number, y: number): number {} + * } + */ + +function findSolution(customfunction: CustomFunction, z: number): number[][] { + let x = 1; + let y = 1000; + const ans: number[][] = []; + while (x <= 1000 && y) { + const t = customfunction.f(x, y); + if (t < z) { + ++x; + } else if (t > z) { + --y; + } else { + ans.push([x--, y--]); + } + } + return ans; +} diff --git a/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution.cpp b/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution.cpp index 412f0fb61cc92..352c6b38f9563 100644 --- a/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution.cpp +++ b/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution.cpp @@ -1,9 +1,17 @@ class Solution { public: vector circularPermutation(int n, int start) { - vector ans(1 << n); + int g[1 << n]; + int j = 0; for (int i = 0; i < 1 << n; ++i) { - ans[i] = i ^ (i >> 1) ^ start; + g[i] = i ^ (i >> 1); + if (g[i] == start) { + j = i; + } + } + vector ans; + for (int i = j; i < j + (1 << n); ++i) { + ans.push_back(g[i % (1 << n)]); } return ans; } diff --git a/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution.go b/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution.go index 3fc6b9311c79c..8792ecbd99e54 100644 --- a/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution.go +++ b/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution.go @@ -1,6 +1,11 @@ -func circularPermutation(n int, start int) (ans []int) { - for i := 0; i < 1<>1)^start) +func circularPermutation(n int, start int) []int { + g := make([]int, 1<> 1) + if g[i] == start { + j = i + } } - return + return append(g[j:], g[:j]...) } \ No newline at end of file diff --git a/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution.java b/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution.java index 17117fa96f13b..4e26f5ccb6511 100644 --- a/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution.java +++ b/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution.java @@ -1,8 +1,16 @@ class Solution { public List circularPermutation(int n, int start) { - List ans = new ArrayList<>(); + int[] g = new int[1 << n]; + int j = 0; for (int i = 0; i < 1 << n; ++i) { - ans.add(i ^ (i >> 1) ^ start); + g[i] = i ^ (i >> 1); + if (g[i] == start) { + j = i; + } + } + List ans = new ArrayList<>(); + for (int i = j; i < j + (1 << n); ++i) { + ans.add(g[i % (1 << n)]); } return ans; } diff --git a/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution.py b/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution.py index c9faae4878283..bd2b6b757d8ab 100644 --- a/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution.py +++ b/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution.py @@ -1,3 +1,5 @@ class Solution: def circularPermutation(self, n: int, start: int) -> List[int]: - return [i ^ (i >> 1) ^ start for i in range(1 << n)] + g = [i ^ (i >> 1) for i in range(1 << n)] + j = g.index(start) + return g[j:] + g[:j] diff --git a/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution2.cpp b/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution2.cpp new file mode 100644 index 0000000000000..412f0fb61cc92 --- /dev/null +++ b/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution2.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + vector circularPermutation(int n, int start) { + vector ans(1 << n); + for (int i = 0; i < 1 << n; ++i) { + ans[i] = i ^ (i >> 1) ^ start; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution2.go b/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution2.go new file mode 100644 index 0000000000000..3fc6b9311c79c --- /dev/null +++ b/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution2.go @@ -0,0 +1,6 @@ +func circularPermutation(n int, start int) (ans []int) { + for i := 0; i < 1<>1)^start) + } + return +} \ No newline at end of file diff --git a/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution2.java b/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution2.java new file mode 100644 index 0000000000000..17117fa96f13b --- /dev/null +++ b/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution2.java @@ -0,0 +1,9 @@ +class Solution { + public List circularPermutation(int n, int start) { + List ans = new ArrayList<>(); + for (int i = 0; i < 1 << n; ++i) { + ans.add(i ^ (i >> 1) ^ start); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution2.py b/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution2.py new file mode 100644 index 0000000000000..c9faae4878283 --- /dev/null +++ b/solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution2.py @@ -0,0 +1,3 @@ +class Solution: + def circularPermutation(self, n: int, start: int) -> List[int]: + return [i ^ (i >> 1) ^ start for i in range(1 << n)] diff --git a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.cpp b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.cpp index ca2bfd19fe03b..a7c203b9dac03 100644 --- a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.cpp +++ b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.cpp @@ -40,18 +40,16 @@ class Solution { ++c; } int mx = min(r, c); - for (int x = i; x < i + mx; ++x) { - for (int y = j; y < j + mx; ++y) { - filled[x] |= 1 << y; + for (int w = 1; w <= mx; ++w) { + for (int k = 0; k < w; ++k) { + filled[i + w - 1] |= 1 << (j + k); + filled[i + k] |= 1 << (j + w - 1); } - } - for (int w = mx; w; --w) { dfs(i, j + w, t + 1); - for (int k = 0; k < w; ++k) { - filled[i + w - 1] ^= 1 << (j + k); - if (k < w - 1) { - filled[i + k] ^= 1 << (j + w - 1); - } + } + for (int x = i; x < i + mx; ++x) { + for (int y = j; y < j + mx; ++y) { + filled[x] ^= 1 << y; } } } diff --git a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.go b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.go index b91bfb6804981..a4d4cc20d6c78 100644 --- a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.go +++ b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.go @@ -28,18 +28,16 @@ func tilingRectangle(n int, m int) int { c++ } mx := min(r, c) - for x := i; x < i+mx; x++ { - for y := j; y < j+mx; y++ { - filled[x] |= 1 << y + for w := 1; w <= mx; w++ { + for k := 0; k < w; k++ { + filled[i+w-1] |= 1 << (j + k) + filled[i+k] |= 1 << (j + w - 1) } - } - for w := mx; w > 0; w-- { dfs(i, j+w, t+1) - for k := 0; k < w; k++ { - filled[i+w-1] ^= 1 << (j + k) - if k < w-1 { - filled[i+k] ^= 1 << (j + w - 1) - } + } + for x := i; x < i+mx; x++ { + for y := j; y < j+mx; y++ { + filled[x] ^= 1 << y } } } diff --git a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.java b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.java index 7e6d24f985413..e33722adc4cbe 100644 --- a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.java +++ b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.java @@ -39,18 +39,16 @@ private void dfs(int i, int j, int t) { ++c; } int mx = Math.min(r, c); - for (int x = i; x < i + mx; ++x) { - for (int y = j; y < j + mx; ++y) { - filled[x] |= 1 << y; + for (int w = 1; w <= mx; ++w) { + for (int k = 0; k < w; ++k) { + filled[i + w - 1] |= 1 << (j + k); + filled[i + k] |= 1 << (j + w - 1); } - } - for (int w = mx; w > 0; --w) { dfs(i, j + w, t + 1); - for (int k = 0; k < w; ++k) { - filled[i + w - 1] ^= 1 << (j + k); - if (k < w - 1) { - filled[i + k] ^= 1 << (j + w - 1); - } + } + for (int x = i; x < i + mx; ++x) { + for (int y = j; y < j + mx; ++y) { + filled[x] ^= 1 << y; } } } diff --git a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.py b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.py index 3ba82d8ba4a63..ce31b33d3fdb1 100644 --- a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.py +++ b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.py @@ -20,16 +20,15 @@ def dfs(i: int, j: int, t: int): if filled[i] >> k & 1: break c += 1 - mx = min(r, c) + mx = r if r < c else c + for w in range(1, mx + 1): + for k in range(w): + filled[i + w - 1] |= 1 << (j + k) + filled[i + k] |= 1 << (j + w - 1) + dfs(i, j + w, t + 1) for x in range(i, i + mx): for y in range(j, j + mx): - filled[x] |= 1 << y - for w in range(mx, 0, -1): - dfs(i, j + w, t + 1) - for k in range(w): - filled[i + w - 1] ^= 1 << (j + k) - if k < w - 1: - filled[i + k] ^= 1 << (j + w - 1) + filled[x] ^= 1 << y ans = n * m filled = [0] * n diff --git a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.ts b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.ts index 04aa3b8875496..e7abb47c511fa 100644 --- a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.ts +++ b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution.ts @@ -27,18 +27,16 @@ function tilingRectangle(n: number, m: number): number { ++c; } const mx = Math.min(r, c); - for (let x = i; x < i + mx; ++x) { - for (let y = j; y < j + mx; ++y) { - filled[x] |= 1 << y; + for (let w = 1; w <= mx; ++w) { + for (let k = 0; k < w; ++k) { + filled[i + w - 1] |= 1 << (j + k); + filled[i + k] |= 1 << (j + w - 1); } - } - for (let w = mx; w > 0; --w) { dfs(i, j + w, t + 1); - for (let k = 0; k < w; ++k) { - filled[i + w - 1] ^= 1 << (j + k); - if (k < w - 1) { - filled[i + k] ^= 1 << (j + w - 1); - } + } + for (let x = i; x < i + mx; ++x) { + for (let y = j; y < j + mx; ++y) { + filled[x] ^= 1 << y; } } } diff --git a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution2.cpp b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution2.cpp new file mode 100644 index 0000000000000..ca2bfd19fe03b --- /dev/null +++ b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution2.cpp @@ -0,0 +1,59 @@ +class Solution { +public: + int tilingRectangle(int n, int m) { + memset(filled, 0, sizeof(filled)); + this->n = n; + this->m = m; + ans = n * m; + dfs(0, 0, 0); + return ans; + } + +private: + int filled[13]; + int n, m; + int ans; + + void dfs(int i, int j, int t) { + if (j == m) { + ++i; + j = 0; + } + if (i == n) { + ans = t; + return; + } + if (filled[i] >> j & 1) { + dfs(i, j + 1, t); + } else if (t + 1 < ans) { + int r = 0, c = 0; + for (int k = i; k < n; ++k) { + if (filled[k] >> j & 1) { + break; + } + ++r; + } + for (int k = j; k < m; ++k) { + if (filled[i] >> k & 1) { + break; + } + ++c; + } + int mx = min(r, c); + for (int x = i; x < i + mx; ++x) { + for (int y = j; y < j + mx; ++y) { + filled[x] |= 1 << y; + } + } + for (int w = mx; w; --w) { + dfs(i, j + w, t + 1); + for (int k = 0; k < w; ++k) { + filled[i + w - 1] ^= 1 << (j + k); + if (k < w - 1) { + filled[i + k] ^= 1 << (j + w - 1); + } + } + } + } + } +}; \ No newline at end of file diff --git a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution2.go b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution2.go new file mode 100644 index 0000000000000..b91bfb6804981 --- /dev/null +++ b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution2.go @@ -0,0 +1,49 @@ +func tilingRectangle(n int, m int) int { + ans := n * m + filled := make([]int, n) + var dfs func(i, j, t int) + dfs = func(i, j, t int) { + if j == m { + i++ + j = 0 + } + if i == n { + ans = t + return + } + if filled[i]>>j&1 == 1 { + dfs(i, j+1, t) + } else if t+1 < ans { + var r, c int + for k := i; k < n; k++ { + if filled[k]>>j&1 == 1 { + break + } + r++ + } + for k := j; k < m; k++ { + if filled[i]>>k&1 == 1 { + break + } + c++ + } + mx := min(r, c) + for x := i; x < i+mx; x++ { + for y := j; y < j+mx; y++ { + filled[x] |= 1 << y + } + } + for w := mx; w > 0; w-- { + dfs(i, j+w, t+1) + for k := 0; k < w; k++ { + filled[i+w-1] ^= 1 << (j + k) + if k < w-1 { + filled[i+k] ^= 1 << (j + w - 1) + } + } + } + } + } + dfs(0, 0, 0) + return ans +} \ No newline at end of file diff --git a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution2.java b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution2.java new file mode 100644 index 0000000000000..7e6d24f985413 --- /dev/null +++ b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution2.java @@ -0,0 +1,58 @@ +class Solution { + private int n; + private int m; + private int[] filled; + private int ans; + + public int tilingRectangle(int n, int m) { + this.n = n; + this.m = m; + ans = n * m; + filled = new int[n]; + dfs(0, 0, 0); + return ans; + } + + private void dfs(int i, int j, int t) { + if (j == m) { + ++i; + j = 0; + } + if (i == n) { + ans = t; + return; + } + if ((filled[i] >> j & 1) == 1) { + dfs(i, j + 1, t); + } else if (t + 1 < ans) { + int r = 0, c = 0; + for (int k = i; k < n; ++k) { + if ((filled[k] >> j & 1) == 1) { + break; + } + ++r; + } + for (int k = j; k < m; ++k) { + if ((filled[i] >> k & 1) == 1) { + break; + } + ++c; + } + int mx = Math.min(r, c); + for (int x = i; x < i + mx; ++x) { + for (int y = j; y < j + mx; ++y) { + filled[x] |= 1 << y; + } + } + for (int w = mx; w > 0; --w) { + dfs(i, j + w, t + 1); + for (int k = 0; k < w; ++k) { + filled[i + w - 1] ^= 1 << (j + k); + if (k < w - 1) { + filled[i + k] ^= 1 << (j + w - 1); + } + } + } + } + } +} \ No newline at end of file diff --git a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution2.py b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution2.py new file mode 100644 index 0000000000000..3ba82d8ba4a63 --- /dev/null +++ b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution2.py @@ -0,0 +1,37 @@ +class Solution: + def tilingRectangle(self, n: int, m: int) -> int: + def dfs(i: int, j: int, t: int): + nonlocal ans + if j == m: + i += 1 + j = 0 + if i == n: + ans = t + return + if filled[i] >> j & 1: + dfs(i, j + 1, t) + elif t + 1 < ans: + r = c = 0 + for k in range(i, n): + if filled[k] >> j & 1: + break + r += 1 + for k in range(j, m): + if filled[i] >> k & 1: + break + c += 1 + mx = min(r, c) + for x in range(i, i + mx): + for y in range(j, j + mx): + filled[x] |= 1 << y + for w in range(mx, 0, -1): + dfs(i, j + w, t + 1) + for k in range(w): + filled[i + w - 1] ^= 1 << (j + k) + if k < w - 1: + filled[i + k] ^= 1 << (j + w - 1) + + ans = n * m + filled = [0] * n + dfs(0, 0, 0) + return ans diff --git a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution2.ts b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution2.ts new file mode 100644 index 0000000000000..04aa3b8875496 --- /dev/null +++ b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/Solution2.ts @@ -0,0 +1,48 @@ +function tilingRectangle(n: number, m: number): number { + let ans = n * m; + const filled: number[] = new Array(n).fill(0); + const dfs = (i: number, j: number, t: number) => { + if (j === m) { + ++i; + j = 0; + } + if (i === n) { + ans = t; + return; + } + if ((filled[i] >> j) & 1) { + dfs(i, j + 1, t); + } else if (t + 1 < ans) { + let [r, c] = [0, 0]; + for (let k = i; k < n; ++k) { + if ((filled[k] >> j) & 1) { + break; + } + ++r; + } + for (let k = j; k < m; ++k) { + if ((filled[i] >> k) & 1) { + break; + } + ++c; + } + const mx = Math.min(r, c); + for (let x = i; x < i + mx; ++x) { + for (let y = j; y < j + mx; ++y) { + filled[x] |= 1 << y; + } + } + for (let w = mx; w > 0; --w) { + dfs(i, j + w, t + 1); + for (let k = 0; k < w; ++k) { + filled[i + w - 1] ^= 1 << (j + k); + if (k < w - 1) { + filled[i + k] ^= 1 << (j + w - 1); + } + } + } + } + }; + dfs(0, 0, 0); + return ans; +} diff --git a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution.cpp b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution.cpp index 68dddddc2c4ab..4408697fe038b 100644 --- a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution.cpp +++ b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution.cpp @@ -1,16 +1,15 @@ class Solution { public: int oddCells(int m, int n, vector>& indices) { - vector row(m); - vector col(n); + vector> g(m, vector(n)); for (auto& e : indices) { int r = e[0], c = e[1]; - row[r]++; - col[c]++; + for (int i = 0; i < m; ++i) ++g[i][c]; + for (int j = 0; j < n; ++j) ++g[r][j]; } int ans = 0; - for (int i : row) - for (int j : col) ans += (i + j) % 2; + for (auto& row : g) + for (int v : row) ans += v % 2; return ans; } }; \ No newline at end of file diff --git a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution.go b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution.go index 23deabdb29b1c..4b365190bdd53 100644 --- a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution.go +++ b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution.go @@ -1,15 +1,21 @@ func oddCells(m int, n int, indices [][]int) int { - row := make([]int, m) - col := make([]int, n) + g := make([][]int, m) + for i := range g { + g[i] = make([]int, n) + } for _, e := range indices { r, c := e[0], e[1] - row[r]++ - col[c]++ + for i := 0; i < m; i++ { + g[i][c]++ + } + for j := 0; j < n; j++ { + g[r][j]++ + } } ans := 0 - for _, i := range row { - for _, j := range col { - ans += (i + j) % 2 + for _, row := range g { + for _, v := range row { + ans += v % 2 } } return ans diff --git a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution.java b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution.java index a51e35c32ac91..076d3a6fea09b 100644 --- a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution.java +++ b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution.java @@ -1,16 +1,19 @@ class Solution { public int oddCells(int m, int n, int[][] indices) { - int[] row = new int[m]; - int[] col = new int[n]; + int[][] g = new int[m][n]; for (int[] e : indices) { int r = e[0], c = e[1]; - row[r]++; - col[c]++; + for (int i = 0; i < m; ++i) { + g[i][c]++; + } + for (int j = 0; j < n; ++j) { + g[r][j]++; + } } int ans = 0; - for (int i : row) { - for (int j : col) { - ans += (i + j) % 2; + for (int[] row : g) { + for (int v : row) { + ans += v % 2; } } return ans; diff --git a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution.py b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution.py index 6dc2e302c3c1b..3cfc98de5e95a 100644 --- a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution.py +++ b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution.py @@ -1,8 +1,9 @@ class Solution: def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int: - row = [0] * m - col = [0] * n + g = [[0] * n for _ in range(m)] for r, c in indices: - row[r] += 1 - col[c] += 1 - return sum((i + j) % 2 for i in row for j in col) + for i in range(m): + g[i][c] += 1 + for j in range(n): + g[r][j] += 1 + return sum(v % 2 for row in g for v in row) diff --git a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution2.cpp b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution2.cpp new file mode 100644 index 0000000000000..68dddddc2c4ab --- /dev/null +++ b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int oddCells(int m, int n, vector>& indices) { + vector row(m); + vector col(n); + for (auto& e : indices) { + int r = e[0], c = e[1]; + row[r]++; + col[c]++; + } + int ans = 0; + for (int i : row) + for (int j : col) ans += (i + j) % 2; + return ans; + } +}; \ No newline at end of file diff --git a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution2.go b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution2.go new file mode 100644 index 0000000000000..23deabdb29b1c --- /dev/null +++ b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution2.go @@ -0,0 +1,16 @@ +func oddCells(m int, n int, indices [][]int) int { + row := make([]int, m) + col := make([]int, n) + for _, e := range indices { + r, c := e[0], e[1] + row[r]++ + col[c]++ + } + ans := 0 + for _, i := range row { + for _, j := range col { + ans += (i + j) % 2 + } + } + return ans +} \ No newline at end of file diff --git a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution2.java b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution2.java new file mode 100644 index 0000000000000..a51e35c32ac91 --- /dev/null +++ b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution2.java @@ -0,0 +1,18 @@ +class Solution { + public int oddCells(int m, int n, int[][] indices) { + int[] row = new int[m]; + int[] col = new int[n]; + for (int[] e : indices) { + int r = e[0], c = e[1]; + row[r]++; + col[c]++; + } + int ans = 0; + for (int i : row) { + for (int j : col) { + ans += (i + j) % 2; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution2.py b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution2.py new file mode 100644 index 0000000000000..6dc2e302c3c1b --- /dev/null +++ b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int: + row = [0] * m + col = [0] * n + for r, c in indices: + row[r] += 1 + col[c] += 1 + return sum((i + j) % 2 for i in row for j in col) diff --git a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution3.cpp b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution3.cpp new file mode 100644 index 0000000000000..e648b4d8b635f --- /dev/null +++ b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution3.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int oddCells(int m, int n, vector>& indices) { + vector row(m); + vector col(n); + for (auto& e : indices) { + int r = e[0], c = e[1]; + row[r]++; + col[c]++; + } + int cnt1 = 0, cnt2 = 0; + for (int v : row) cnt1 += v % 2; + for (int v : col) cnt2 += v % 2; + return cnt1 * (n - cnt2) + cnt2 * (m - cnt1); + } +}; \ No newline at end of file diff --git a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution3.go b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution3.go new file mode 100644 index 0000000000000..7d7488f61b45f --- /dev/null +++ b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution3.go @@ -0,0 +1,17 @@ +func oddCells(m int, n int, indices [][]int) int { + row := make([]int, m) + col := make([]int, n) + for _, e := range indices { + r, c := e[0], e[1] + row[r]++ + col[c]++ + } + cnt1, cnt2 := 0, 0 + for _, v := range row { + cnt1 += v % 2 + } + for _, v := range col { + cnt2 += v % 2 + } + return cnt1*(n-cnt2) + cnt2*(m-cnt1) +} \ No newline at end of file diff --git a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution3.java b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution3.java new file mode 100644 index 0000000000000..c17c412bdb0bf --- /dev/null +++ b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution3.java @@ -0,0 +1,19 @@ +class Solution { + public int oddCells(int m, int n, int[][] indices) { + int[] row = new int[m]; + int[] col = new int[n]; + for (int[] e : indices) { + int r = e[0], c = e[1]; + row[r]++; + col[c]++; + } + int cnt1 = 0, cnt2 = 0; + for (int v : row) { + cnt1 += v % 2; + } + for (int v : col) { + cnt2 += v % 2; + } + return cnt1 * (n - cnt2) + cnt2 * (m - cnt1); + } +} \ No newline at end of file diff --git a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution3.py b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution3.py new file mode 100644 index 0000000000000..bb0286d800458 --- /dev/null +++ b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution3.py @@ -0,0 +1,10 @@ +class Solution: + def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int: + row = [0] * m + col = [0] * n + for r, c in indices: + row[r] += 1 + col[c] += 1 + cnt1 = sum(v % 2 for v in row) + cnt2 = sum(v % 2 for v in col) + return cnt1 * (n - cnt2) + cnt2 * (m - cnt1) diff --git a/solution/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/Solution.cpp b/solution/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/Solution.cpp index a1908a449dd29..a7158410c506d 100644 --- a/solution/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/Solution.cpp +++ b/solution/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/Solution.cpp @@ -1,27 +1,27 @@ -class Solution { -public: - vector> reconstructMatrix(int upper, int lower, vector& colsum) { - int n = colsum.size(); - vector> ans(2, vector(n)); - for (int j = 0; j < n; ++j) { - if (colsum[j] == 2) { - ans[0][j] = ans[1][j] = 1; - upper--; - lower--; - } - if (colsum[j] == 1) { - if (upper > lower) { - upper--; - ans[0][j] = 1; - } else { - lower--; - ans[1][j] = 1; - } - } - if (upper < 0 || lower < 0) { - break; - } - } - return upper || lower ? vector>() : ans; - } +class Solution { +public: + vector> reconstructMatrix(int upper, int lower, vector& colsum) { + int n = colsum.size(); + vector> ans(2, vector(n)); + for (int j = 0; j < n; ++j) { + if (colsum[j] == 2) { + ans[0][j] = ans[1][j] = 1; + upper--; + lower--; + } + if (colsum[j] == 1) { + if (upper > lower) { + upper--; + ans[0][j] = 1; + } else { + lower--; + ans[1][j] = 1; + } + } + if (upper < 0 || lower < 0) { + break; + } + } + return upper || lower ? vector>() : ans; + } }; \ No newline at end of file diff --git a/solution/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/Solution.java b/solution/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/Solution.java index c76b61b7a6b2b..c820440349cad 100644 --- a/solution/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/Solution.java +++ b/solution/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/Solution.java @@ -1,29 +1,29 @@ -class Solution { - public List> reconstructMatrix(int upper, int lower, int[] colsum) { - int n = colsum.length; - List first = new ArrayList<>(); - List second = new ArrayList<>(); - for (int j = 0; j < n; ++j) { - int a = 0, b = 0; - if (colsum[j] == 2) { - a = b = 1; - upper--; - lower--; - } else if (colsum[j] == 1) { - if (upper > lower) { - upper--; - a = 1; - } else { - lower--; - b = 1; - } - } - if (upper < 0 || lower < 0) { - break; - } - first.add(a); - second.add(b); - } - return upper == 0 && lower == 0 ? List.of(first, second) : List.of(); - } +class Solution { + public List> reconstructMatrix(int upper, int lower, int[] colsum) { + int n = colsum.length; + List first = new ArrayList<>(); + List second = new ArrayList<>(); + for (int j = 0; j < n; ++j) { + int a = 0, b = 0; + if (colsum[j] == 2) { + a = b = 1; + upper--; + lower--; + } else if (colsum[j] == 1) { + if (upper > lower) { + upper--; + a = 1; + } else { + lower--; + b = 1; + } + } + if (upper < 0 || lower < 0) { + break; + } + first.add(a); + second.add(b); + } + return upper == 0 && lower == 0 ? List.of(first, second) : List.of(); + } } \ No newline at end of file diff --git a/solution/1200-1299/1254.Number of Closed Islands/Solution.cs b/solution/1200-1299/1254.Number of Closed Islands/Solution.cs index a0ae079d9a46a..71e36ef5df19a 100644 --- a/solution/1200-1299/1254.Number of Closed Islands/Solution.cs +++ b/solution/1200-1299/1254.Number of Closed Islands/Solution.cs @@ -1,33 +1,33 @@ -public class Solution { - private int m; - private int n; - private int[][] grid; - - public int ClosedIsland(int[][] grid) { - m = grid.Length; - n = grid[0].Length; - this.grid = grid; - int ans = 0; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == 0) { - ans += dfs(i, j); - } - } - } - return ans; - } - - private int dfs(int i, int j) { - int res = i > 0 && i < m - 1 && j > 0 && j < n - 1 ? 1 : 0; - grid[i][j] = 1; - int[] dirs = {-1, 0, 1, 0, -1}; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0) { - res &= dfs(x, y); - } - } - return res; - } -} \ No newline at end of file +public class Solution { + private int m; + private int n; + private int[][] grid; + + public int ClosedIsland(int[][] grid) { + m = grid.Length; + n = grid[0].Length; + this.grid = grid; + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 0) { + ans += dfs(i, j); + } + } + } + return ans; + } + + private int dfs(int i, int j) { + int res = i > 0 && i < m - 1 && j > 0 && j < n - 1 ? 1 : 0; + grid[i][j] = 1; + int[] dirs = {-1, 0, 1, 0, -1}; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0) { + res &= dfs(x, y); + } + } + return res; + } +} diff --git a/solution/1200-1299/1254.Number of Closed Islands/Solution.py b/solution/1200-1299/1254.Number of Closed Islands/Solution.py index 71245575f8469..905ab16d70b29 100644 --- a/solution/1200-1299/1254.Number of Closed Islands/Solution.py +++ b/solution/1200-1299/1254.Number of Closed Islands/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def closedIsland(self, grid: List[List[int]]) -> int: - def dfs(i: int, j: int) -> int: - res = int(0 < i < m - 1 and 0 < j < n - 1) - grid[i][j] = 1 - for a, b in pairwise(dirs): - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n and grid[x][y] == 0: - res &= dfs(x, y) - return res - - m, n = len(grid), len(grid[0]) - dirs = (-1, 0, 1, 0, -1) - return sum(grid[i][j] == 0 and dfs(i, j) for i in range(m) for j in range(n)) +class Solution: + def closedIsland(self, grid: List[List[int]]) -> int: + def dfs(i: int, j: int) -> int: + res = int(0 < i < m - 1 and 0 < j < n - 1) + grid[i][j] = 1 + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n and grid[x][y] == 0: + res &= dfs(x, y) + return res + + m, n = len(grid), len(grid[0]) + dirs = (-1, 0, 1, 0, -1) + return sum(grid[i][j] == 0 and dfs(i, j) for i in range(m) for j in range(n)) diff --git a/solution/1200-1299/1254.Number of Closed Islands/Solution2.cpp b/solution/1200-1299/1254.Number of Closed Islands/Solution2.cpp new file mode 100644 index 0000000000000..06abcce049aac --- /dev/null +++ b/solution/1200-1299/1254.Number of Closed Islands/Solution2.cpp @@ -0,0 +1,61 @@ +class UnionFind { +public: + UnionFind(int n) { + p = vector(n); + size = vector(n, 1); + iota(p.begin(), p.end(), 0); + } + + void unite(int a, int b) { + int pa = find(a), pb = find(b); + if (pa != pb) { + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + } + } + + int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + +private: + vector p, size; +}; + +class Solution { +public: + int closedIsland(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + UnionFind uf(m * n + 1); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { + uf.unite(i * n + j, m * n); + } + if (grid[i][j] == 0) { + if (i + 1 < m && grid[i + 1][j] == 0) { + uf.unite(i * n + j, (i + 1) * n + j); + } + if (j + 1 < n && grid[i][j + 1] == 0) { + uf.unite(i * n + j, i * n + j + 1); + } + } + } + } + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans += grid[i][j] == 0 && uf.find(i * n + j) == i * n + j; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1200-1299/1254.Number of Closed Islands/Solution2.cs b/solution/1200-1299/1254.Number of Closed Islands/Solution2.cs new file mode 100644 index 0000000000000..30ddfa932765e --- /dev/null +++ b/solution/1200-1299/1254.Number of Closed Islands/Solution2.cs @@ -0,0 +1,64 @@ +class UnionFind { + private int[] p; + private int[] size; + + public UnionFind(int n) { + p = new int[n]; + size = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + size[i] = 1; + } + } + + public int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + + public void union(int a, int b) { + int pa = find(a), pb = find(b); + if (pa != pb) { + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + } + } +} + +public class Solution { + public int ClosedIsland(int[][] grid) { + int m = grid.Length, n = grid[0].Length; + UnionFind uf = new UnionFind(m * n + 1); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { + uf.union(i * n + j, m * n); + } + if (grid[i][j] == 0) { + if (i + 1 < m && grid[i + 1][j] == 0) { + uf.union(i * n + j, (i + 1) * n + j); + } + if (j + 1 < n && grid[i][j + 1] == 0) { + uf.union(i * n + j, i * n + j + 1); + } + } + } + } + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 0 && uf.find(i * n + j) == i * n + j) { + ++ans; + } + } + } + return ans; + } +} diff --git a/solution/1200-1299/1254.Number of Closed Islands/Solution2.go b/solution/1200-1299/1254.Number of Closed Islands/Solution2.go new file mode 100644 index 0000000000000..0f19b53142990 --- /dev/null +++ b/solution/1200-1299/1254.Number of Closed Islands/Solution2.go @@ -0,0 +1,61 @@ +type unionFind struct { + p, size []int +} + +func newUnionFind(n int) *unionFind { + p := make([]int, n) + size := make([]int, n) + for i := range p { + p[i] = i + size[i] = 1 + } + return &unionFind{p, size} +} + +func (uf *unionFind) find(x int) int { + if uf.p[x] != x { + uf.p[x] = uf.find(uf.p[x]) + } + return uf.p[x] +} + +func (uf *unionFind) union(a, b int) { + pa, pb := uf.find(a), uf.find(b) + if pa != pb { + if uf.size[pa] > uf.size[pb] { + uf.p[pb] = pa + uf.size[pa] += uf.size[pb] + } else { + uf.p[pa] = pb + uf.size[pb] += uf.size[pa] + } + } +} + +func closedIsland(grid [][]int) (ans int) { + m, n := len(grid), len(grid[0]) + uf := newUnionFind(m*n + 1) + for i, row := range grid { + for j, v := range row { + if i == 0 || i == m-1 || j == 0 || j == n-1 { + uf.union(i*n+j, m*n) + } + if v == 0 { + if i+1 < m && grid[i+1][j] == 0 { + uf.union(i*n+j, (i+1)*n+j) + } + if j+1 < n && grid[i][j+1] == 0 { + uf.union(i*n+j, i*n+j+1) + } + } + } + } + for i, row := range grid { + for j, v := range row { + if v == 0 && uf.find(i*n+j) == i*n+j { + ans++ + } + } + } + return +} \ No newline at end of file diff --git a/solution/1200-1299/1254.Number of Closed Islands/Solution2.java b/solution/1200-1299/1254.Number of Closed Islands/Solution2.java new file mode 100644 index 0000000000000..6b37889a329b6 --- /dev/null +++ b/solution/1200-1299/1254.Number of Closed Islands/Solution2.java @@ -0,0 +1,64 @@ +class UnionFind { + private int[] p; + private int[] size; + + public UnionFind(int n) { + p = new int[n]; + size = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + size[i] = 1; + } + } + + public int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + + public void union(int a, int b) { + int pa = find(a), pb = find(b); + if (pa != pb) { + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + } + } +} + +class Solution { + public int closedIsland(int[][] grid) { + int m = grid.length, n = grid[0].length; + UnionFind uf = new UnionFind(m * n + 1); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { + uf.union(i * n + j, m * n); + } + if (grid[i][j] == 0) { + if (i + 1 < m && grid[i + 1][j] == 0) { + uf.union(i * n + j, (i + 1) * n + j); + } + if (j + 1 < n && grid[i][j + 1] == 0) { + uf.union(i * n + j, i * n + j + 1); + } + } + } + } + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 0 && uf.find(i * n + j) == i * n + j) { + ++ans; + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1200-1299/1254.Number of Closed Islands/Solution2.py b/solution/1200-1299/1254.Number of Closed Islands/Solution2.py new file mode 100644 index 0000000000000..ed83a267d19da --- /dev/null +++ b/solution/1200-1299/1254.Number of Closed Islands/Solution2.py @@ -0,0 +1,39 @@ +class UnionFind: + def __init__(self, n: int): + self.p = list(range(n)) + self.size = [1] * n + + def find(self, x: int) -> int: + if self.p[x] != x: + self.p[x] = self.find(self.p[x]) + return self.p[x] + + def union(self, a: int, b: int): + pa, pb = self.find(a), self.find(b) + if pa != pb: + if self.size[pa] > self.size[pb]: + self.p[pb] = pa + self.size[pa] += self.size[pb] + else: + self.p[pa] = pb + self.size[pb] += self.size[pa] + + +class Solution: + def closedIsland(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + uf = UnionFind(m * n + 1) + for i in range(m): + for j in range(n): + if i == 0 or i == m - 1 or j == 0 or j == n - 1: + uf.union(i * n + j, m * n) + if grid[i][j] == 0: + if i < m - 1 and grid[i + 1][j] == 0: + uf.union(i * n + j, (i + 1) * n + j) + if j < n - 1 and grid[i][j + 1] == 0: + uf.union(i * n + j, i * n + j + 1) + ans = 0 + for i in range(m): + for j in range(n): + ans += grid[i][j] == 0 and uf.find(i * n + j) == i * n + j + return ans diff --git a/solution/1200-1299/1254.Number of Closed Islands/Solution2.ts b/solution/1200-1299/1254.Number of Closed Islands/Solution2.ts new file mode 100644 index 0000000000000..c569ddd2b134e --- /dev/null +++ b/solution/1200-1299/1254.Number of Closed Islands/Solution2.ts @@ -0,0 +1,62 @@ +function closedIsland(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const uf = new UnionFind(m * n + 1); + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (i === 0 || i === m - 1 || j === 0 || j === n - 1) { + uf.union(i * n + j, m * n); + } + if (grid[i][j] === 0) { + if (i + 1 < m && grid[i + 1][j] === 0) { + uf.union(i * n + j, (i + 1) * n + j); + } + if (j + 1 < n && grid[i][j + 1] === 0) { + uf.union(i * n + j, i * n + j + 1); + } + } + } + } + let ans = 0; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === 0 && uf.find(i * n + j) === i * n + j) { + ++ans; + } + } + } + return ans; +} + +class UnionFind { + private p: number[]; + private size: number[]; + + constructor(n: number) { + this.p = Array(n) + .fill(0) + .map((_, i) => i); + this.size = Array(n).fill(1); + } + + find(x: number): number { + if (this.p[x] !== x) { + this.p[x] = this.find(this.p[x]); + } + return this.p[x]; + } + + union(a: number, b: number): void { + const [pa, pb] = [this.find(a), this.find(b)]; + if (pa === pb) { + return; + } + if (this.size[pa] > this.size[pb]) { + this.p[pb] = pa; + this.size[pa] += this.size[pb]; + } else { + this.p[pa] = pb; + this.size[pb] += this.size[pa]; + } + } +} diff --git a/solution/1200-1299/1256.Encode Number/Solution.cpp b/solution/1200-1299/1256.Encode Number/Solution.cpp index e999e714f0af6..3719b808fed1d 100644 --- a/solution/1200-1299/1256.Encode Number/Solution.cpp +++ b/solution/1200-1299/1256.Encode Number/Solution.cpp @@ -1,12 +1,12 @@ -class Solution { -public: - string encode(int num) { - bitset<32> bs(++num); - string ans = bs.to_string(); - int i = 0; - while (ans[i] == '0') { - ++i; - } - return ans.substr(i + 1); - } +class Solution { +public: + string encode(int num) { + bitset<32> bs(++num); + string ans = bs.to_string(); + int i = 0; + while (ans[i] == '0') { + ++i; + } + return ans.substr(i + 1); + } }; \ No newline at end of file diff --git a/solution/1200-1299/1256.Encode Number/Solution.java b/solution/1200-1299/1256.Encode Number/Solution.java index d10cc2f6add57..7537fa7317045 100644 --- a/solution/1200-1299/1256.Encode Number/Solution.java +++ b/solution/1200-1299/1256.Encode Number/Solution.java @@ -1,5 +1,5 @@ -class Solution { - public String encode(int num) { - return Integer.toBinaryString(num + 1).substring(1); - } +class Solution { + public String encode(int num) { + return Integer.toBinaryString(num + 1).substring(1); + } } \ No newline at end of file diff --git a/solution/1200-1299/1256.Encode Number/Solution.py b/solution/1200-1299/1256.Encode Number/Solution.py index 29ccadbf619b6..df29e7672665a 100644 --- a/solution/1200-1299/1256.Encode Number/Solution.py +++ b/solution/1200-1299/1256.Encode Number/Solution.py @@ -1,3 +1,3 @@ -class Solution: - def encode(self, num: int) -> str: - return bin(num + 1)[3:] +class Solution: + def encode(self, num: int) -> str: + return bin(num + 1)[3:] diff --git a/solution/1200-1299/1259.Handshakes That Don't Cross/Solution.cpp b/solution/1200-1299/1259.Handshakes That Don't Cross/Solution.cpp index c4563a735447f..b271bda4d1f68 100644 --- a/solution/1200-1299/1259.Handshakes That Don't Cross/Solution.cpp +++ b/solution/1200-1299/1259.Handshakes That Don't Cross/Solution.cpp @@ -1,22 +1,22 @@ -class Solution { -public: - int numberOfWays(int numPeople) { - const int mod = 1e9 + 7; - int f[numPeople + 1]; - memset(f, 0, sizeof(f)); - function dfs = [&](int i) { - if (i < 2) { - return 1; - } - if (f[i]) { - return f[i]; - } - for (int l = 0; l < i; l += 2) { - int r = i - l - 2; - f[i] = (f[i] + 1LL * dfs(l) * dfs(r) % mod) % mod; - } - return f[i]; - }; - return dfs(numPeople); - } +class Solution { +public: + int numberOfWays(int numPeople) { + const int mod = 1e9 + 7; + int f[numPeople + 1]; + memset(f, 0, sizeof(f)); + function dfs = [&](int i) { + if (i < 2) { + return 1; + } + if (f[i]) { + return f[i]; + } + for (int l = 0; l < i; l += 2) { + int r = i - l - 2; + f[i] = (f[i] + 1LL * dfs(l) * dfs(r) % mod) % mod; + } + return f[i]; + }; + return dfs(numPeople); + } }; \ No newline at end of file diff --git a/solution/1200-1299/1259.Handshakes That Don't Cross/Solution.java b/solution/1200-1299/1259.Handshakes That Don't Cross/Solution.java index 6000c0bc75c6c..aa43fdcec57e6 100644 --- a/solution/1200-1299/1259.Handshakes That Don't Cross/Solution.java +++ b/solution/1200-1299/1259.Handshakes That Don't Cross/Solution.java @@ -1,23 +1,23 @@ -class Solution { - private int[] f; - private final int mod = (int) 1e9 + 7; - - public int numberOfWays(int numPeople) { - f = new int[numPeople + 1]; - return dfs(numPeople); - } - - private int dfs(int i) { - if (i < 2) { - return 1; - } - if (f[i] != 0) { - return f[i]; - } - for (int l = 0; l < i; l += 2) { - int r = i - l - 2; - f[i] = (int) ((f[i] + (1L * dfs(l) * dfs(r) % mod)) % mod); - } - return f[i]; - } +class Solution { + private int[] f; + private final int mod = (int) 1e9 + 7; + + public int numberOfWays(int numPeople) { + f = new int[numPeople + 1]; + return dfs(numPeople); + } + + private int dfs(int i) { + if (i < 2) { + return 1; + } + if (f[i] != 0) { + return f[i]; + } + for (int l = 0; l < i; l += 2) { + int r = i - l - 2; + f[i] = (int) ((f[i] + (1L * dfs(l) * dfs(r) % mod)) % mod); + } + return f[i]; + } } \ No newline at end of file diff --git a/solution/1200-1299/1259.Handshakes That Don't Cross/Solution.py b/solution/1200-1299/1259.Handshakes That Don't Cross/Solution.py index 33c4a554922fc..026fc88ebead2 100644 --- a/solution/1200-1299/1259.Handshakes That Don't Cross/Solution.py +++ b/solution/1200-1299/1259.Handshakes That Don't Cross/Solution.py @@ -1,15 +1,15 @@ -class Solution: - def numberOfWays(self, numPeople: int) -> int: - @cache - def dfs(i: int) -> int: - if i < 2: - return 1 - ans = 0 - for l in range(0, i, 2): - r = i - l - 2 - ans += dfs(l) * dfs(r) - ans %= mod - return ans - - mod = 10**9 + 7 - return dfs(numPeople) +class Solution: + def numberOfWays(self, numPeople: int) -> int: + @cache + def dfs(i: int) -> int: + if i < 2: + return 1 + ans = 0 + for l in range(0, i, 2): + r = i - l - 2 + ans += dfs(l) * dfs(r) + ans %= mod + return ans + + mod = 10**9 + 7 + return dfs(numPeople) diff --git a/solution/1200-1299/1260.Shift 2D Grid/Solution.cpp b/solution/1200-1299/1260.Shift 2D Grid/Solution.cpp index 4998fd26d1a7a..5df963ae076c6 100644 --- a/solution/1200-1299/1260.Shift 2D Grid/Solution.cpp +++ b/solution/1200-1299/1260.Shift 2D Grid/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - vector> shiftGrid(vector>& grid, int k) { - int m = grid.size(), n = grid[0].size(); - vector> ans(m, vector(n)); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - int idx = (i * n + j + k) % (m * n); - int x = idx / n, y = idx % n; - ans[x][y] = grid[i][j]; - } - } - return ans; - } +class Solution { +public: + vector> shiftGrid(vector>& grid, int k) { + int m = grid.size(), n = grid[0].size(); + vector> ans(m, vector(n)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + int idx = (i * n + j + k) % (m * n); + int x = idx / n, y = idx % n; + ans[x][y] = grid[i][j]; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1200-1299/1260.Shift 2D Grid/Solution.java b/solution/1200-1299/1260.Shift 2D Grid/Solution.java index f6d885ee823c9..669f09ac526f7 100644 --- a/solution/1200-1299/1260.Shift 2D Grid/Solution.java +++ b/solution/1200-1299/1260.Shift 2D Grid/Solution.java @@ -1,21 +1,21 @@ -class Solution { - public List> shiftGrid(int[][] grid, int k) { - int m = grid.length, n = grid[0].length; - List> ans = new ArrayList<>(); - for (int i = 0; i < m; ++i) { - List row = new ArrayList<>(); - for (int j = 0; j < n; ++j) { - row.add(0); - } - ans.add(row); - } - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - int idx = (i * n + j + k) % (m * n); - int x = idx / n, y = idx % n; - ans.get(x).set(y, grid[i][j]); - } - } - return ans; - } +class Solution { + public List> shiftGrid(int[][] grid, int k) { + int m = grid.length, n = grid[0].length; + List> ans = new ArrayList<>(); + for (int i = 0; i < m; ++i) { + List row = new ArrayList<>(); + for (int j = 0; j < n; ++j) { + row.add(0); + } + ans.add(row); + } + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + int idx = (i * n + j + k) % (m * n); + int x = idx / n, y = idx % n; + ans.get(x).set(y, grid[i][j]); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1200-1299/1260.Shift 2D Grid/Solution.py b/solution/1200-1299/1260.Shift 2D Grid/Solution.py index 5cbd9008d299a..eaed2df3e5110 100644 --- a/solution/1200-1299/1260.Shift 2D Grid/Solution.py +++ b/solution/1200-1299/1260.Shift 2D Grid/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: - m, n = len(grid), len(grid[0]) - ans = [[0] * n for _ in range(m)] - for i, row in enumerate(grid): - for j, v in enumerate(row): - x, y = divmod((i * n + j + k) % (m * n), n) - ans[x][y] = v - return ans +class Solution: + def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: + m, n = len(grid), len(grid[0]) + ans = [[0] * n for _ in range(m)] + for i, row in enumerate(grid): + for j, v in enumerate(row): + x, y = divmod((i * n + j + k) % (m * n), n) + ans[x][y] = v + return ans diff --git a/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.cpp b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.cpp index 8ba7fe0832f3d..538b4a4f96c8c 100644 --- a/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.cpp +++ b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.cpp @@ -1,15 +1,17 @@ -class Solution { -public: - int maxSumDivThree(vector& nums) { - const int inf = 1 << 30; - vector f = {0, -inf, -inf}; - for (int& x : nums) { - vector g = f; - for (int j = 0; j < 3; ++j) { - g[j] = max(f[j], f[(j - x % 3 + 3) % 3] + x); - } - f = move(g); - } - return f[0]; - } +class Solution { +public: + int maxSumDivThree(vector& nums) { + int n = nums.size(); + const int inf = 1 << 30; + int f[n + 1][3]; + f[0][0] = 0; + f[0][1] = f[0][2] = -inf; + for (int i = 1; i <= n; ++i) { + int x = nums[i - 1]; + for (int j = 0; j < 3; ++j) { + f[i][j] = max(f[i - 1][j], f[i - 1][(j - x % 3 + 3) % 3] + x); + } + } + return f[n][0]; + } }; \ No newline at end of file diff --git a/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.go b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.go index b3d7616aabe48..28f602d8f6bc4 100644 --- a/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.go +++ b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.go @@ -1,12 +1,13 @@ func maxSumDivThree(nums []int) int { + n := len(nums) const inf = 1 << 30 - f := [3]int{0, -inf, -inf} - for _, x := range nums { - g := [3]int{} - for j := range f { - g[j] = max(f[j], f[(j-x%3+3)%3]+x) + f := make([][3]int, n+1) + f[0] = [3]int{0, -inf, -inf} + for i, x := range nums { + i++ + for j := 0; j < 3; j++ { + f[i][j] = max(f[i-1][j], f[i-1][(j-x%3+3)%3]+x) } - f = g } - return f[0] + return f[n][0] } \ No newline at end of file diff --git a/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.java b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.java index 978194597e833..be2b61684de40 100644 --- a/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.java +++ b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.java @@ -1,14 +1,15 @@ -class Solution { - public int maxSumDivThree(int[] nums) { - final int inf = 1 << 30; - int[] f = new int[] {0, -inf, -inf}; - for (int x : nums) { - int[] g = f.clone(); - for (int j = 0; j < 3; ++j) { - g[j] = Math.max(f[j], f[(j - x % 3 + 3) % 3] + x); - } - f = g; - } - return f[0]; - } +class Solution { + public int maxSumDivThree(int[] nums) { + int n = nums.length; + final int inf = 1 << 30; + int[][] f = new int[n + 1][3]; + f[0][1] = f[0][2] = -inf; + for (int i = 1; i <= n; ++i) { + int x = nums[i - 1]; + for (int j = 0; j < 3; ++j) { + f[i][j] = Math.max(f[i - 1][j], f[i - 1][(j - x % 3 + 3) % 3] + x); + } + } + return f[n][0]; + } } \ No newline at end of file diff --git a/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.py b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.py index 48fc4b7b4fc9b..0ce1cb2292c3e 100644 --- a/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.py +++ b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def maxSumDivThree(self, nums: List[int]) -> int: - f = [0, -inf, -inf] - for x in nums: - g = f[:] - for j in range(3): - g[j] = max(f[j], f[(j - x) % 3] + x) - f = g - return f[0] +class Solution: + def maxSumDivThree(self, nums: List[int]) -> int: + n = len(nums) + f = [[-inf] * 3 for _ in range(n + 1)] + f[0][0] = 0 + for i, x in enumerate(nums, 1): + for j in range(3): + f[i][j] = max(f[i - 1][j], f[i - 1][(j - x) % 3] + x) + return f[n][0] diff --git a/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.ts b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.ts index da5649901dba6..25f2329d0a7a8 100644 --- a/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.ts +++ b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.ts @@ -1,11 +1,15 @@ function maxSumDivThree(nums: number[]): number { + const n = nums.length; const inf = 1 << 30; - const f: number[] = [0, -inf, -inf]; - for (const x of nums) { - const g = [...f]; + const f: number[][] = Array(n + 1) + .fill(0) + .map(() => Array(3).fill(-inf)); + f[0][0] = 0; + for (let i = 1; i <= n; ++i) { + const x = nums[i - 1]; for (let j = 0; j < 3; ++j) { - f[j] = Math.max(g[j], g[(j - (x % 3) + 3) % 3] + x); + f[i][j] = Math.max(f[i - 1][j], f[i - 1][(j - (x % 3) + 3) % 3] + x); } } - return f[0]; + return f[n][0]; } diff --git a/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution2.cpp b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution2.cpp new file mode 100644 index 0000000000000..d88be161ae8b4 --- /dev/null +++ b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int maxSumDivThree(vector& nums) { + const int inf = 1 << 30; + vector f = {0, -inf, -inf}; + for (int& x : nums) { + vector g = f; + for (int j = 0; j < 3; ++j) { + g[j] = max(f[j], f[(j - x % 3 + 3) % 3] + x); + } + f = move(g); + } + return f[0]; + } +}; \ No newline at end of file diff --git a/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution2.go b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution2.go new file mode 100644 index 0000000000000..b3d7616aabe48 --- /dev/null +++ b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution2.go @@ -0,0 +1,12 @@ +func maxSumDivThree(nums []int) int { + const inf = 1 << 30 + f := [3]int{0, -inf, -inf} + for _, x := range nums { + g := [3]int{} + for j := range f { + g[j] = max(f[j], f[(j-x%3+3)%3]+x) + } + f = g + } + return f[0] +} \ No newline at end of file diff --git a/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution2.java b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution2.java new file mode 100644 index 0000000000000..96d374972fc17 --- /dev/null +++ b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public int maxSumDivThree(int[] nums) { + final int inf = 1 << 30; + int[] f = new int[] {0, -inf, -inf}; + for (int x : nums) { + int[] g = f.clone(); + for (int j = 0; j < 3; ++j) { + g[j] = Math.max(f[j], f[(j - x % 3 + 3) % 3] + x); + } + f = g; + } + return f[0]; + } +} \ No newline at end of file diff --git a/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution2.py b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution2.py new file mode 100644 index 0000000000000..26c26980896c2 --- /dev/null +++ b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def maxSumDivThree(self, nums: List[int]) -> int: + f = [0, -inf, -inf] + for x in nums: + g = f[:] + for j in range(3): + g[j] = max(f[j], f[(j - x) % 3] + x) + f = g + return f[0] diff --git a/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution2.ts b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution2.ts new file mode 100644 index 0000000000000..da5649901dba6 --- /dev/null +++ b/solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution2.ts @@ -0,0 +1,11 @@ +function maxSumDivThree(nums: number[]): number { + const inf = 1 << 30; + const f: number[] = [0, -inf, -inf]; + for (const x of nums) { + const g = [...f]; + for (let j = 0; j < 3; ++j) { + f[j] = Math.max(g[j], g[(j - (x % 3) + 3) % 3] + x); + } + } + return f[0]; +} diff --git a/solution/1200-1299/1264.Page Recommendations/Solution.sql b/solution/1200-1299/1264.Page Recommendations/Solution.sql index 2af32982d7156..f0b805d38dfa3 100644 --- a/solution/1200-1299/1264.Page Recommendations/Solution.sql +++ b/solution/1200-1299/1264.Page Recommendations/Solution.sql @@ -1,10 +1,12 @@ # Write your MySQL query statement below -SELECT DISTINCT page_id AS recommended_page -FROM Likes -WHERE - user_id IN ( +WITH + T AS ( SELECT user1_id AS user_id FROM Friendship WHERE user2_id = 1 - UNION ALL + UNION SELECT user2_id AS user_id FROM Friendship WHERE user1_id = 1 ) - AND page_id NOT IN (SELECT page_id FROM Likes WHERE user_id = 1); +SELECT DISTINCT page_id AS recommended_page +FROM + T + JOIN Likes USING (user_id) +WHERE page_id NOT IN (SELECT page_id FROM Likes WHERE user_id = 1); diff --git a/solution/1200-1299/1264.Page Recommendations/Solution2.sql b/solution/1200-1299/1264.Page Recommendations/Solution2.sql new file mode 100644 index 0000000000000..2af32982d7156 --- /dev/null +++ b/solution/1200-1299/1264.Page Recommendations/Solution2.sql @@ -0,0 +1,10 @@ +# Write your MySQL query statement below +SELECT DISTINCT page_id AS recommended_page +FROM Likes +WHERE + user_id IN ( + SELECT user1_id AS user_id FROM Friendship WHERE user2_id = 1 + UNION ALL + SELECT user2_id AS user_id FROM Friendship WHERE user1_id = 1 + ) + AND page_id NOT IN (SELECT page_id FROM Likes WHERE user_id = 1); diff --git a/solution/1200-1299/1265.Print Immutable Linked List in Reverse/Solution.cs b/solution/1200-1299/1265.Print Immutable Linked List in Reverse/Solution.cs index 39d5bfcda6730..e4b82e30b022d 100644 --- a/solution/1200-1299/1265.Print Immutable Linked List in Reverse/Solution.cs +++ b/solution/1200-1299/1265.Print Immutable Linked List in Reverse/Solution.cs @@ -1,17 +1,17 @@ -/** - * // This is the ImmutableListNode's API interface. - * // You should not implement it, or speculate about its implementation. - * class ImmutableListNode { - * public void PrintValue(); // print the value of this node. - * public ImmutableListNode GetNext(); // return the next node. - * } - */ - -public class Solution { - public void PrintLinkedListInReverse(ImmutableListNode head) { - if (head != null) { - PrintLinkedListInReverse(head.GetNext()); - head.PrintValue(); - } - } -} \ No newline at end of file +/** + * // This is the ImmutableListNode's API interface. + * // You should not implement it, or speculate about its implementation. + * class ImmutableListNode { + * public void PrintValue(); // print the value of this node. + * public ImmutableListNode GetNext(); // return the next node. + * } + */ + +public class Solution { + public void PrintLinkedListInReverse(ImmutableListNode head) { + if (head != null) { + PrintLinkedListInReverse(head.GetNext()); + head.PrintValue(); + } + } +} diff --git a/solution/1200-1299/1266.Minimum Time Visiting All Points/Solution.c b/solution/1200-1299/1266.Minimum Time Visiting All Points/Solution.c index de0c6c579e8b4..fcbe9bd171632 100644 --- a/solution/1200-1299/1266.Minimum Time Visiting All Points/Solution.c +++ b/solution/1200-1299/1266.Minimum Time Visiting All Points/Solution.c @@ -8,4 +8,4 @@ int minTimeToVisitAllPoints(int** points, int pointsSize, int* pointsColSize) { ans += max(x, y); } return ans; -} +} \ No newline at end of file diff --git a/solution/1200-1299/1276.Number of Burgers with No Waste of Ingredients/Solution.java b/solution/1200-1299/1276.Number of Burgers with No Waste of Ingredients/Solution.java index bbedd042ceaee..ae909fc081e37 100644 --- a/solution/1200-1299/1276.Number of Burgers with No Waste of Ingredients/Solution.java +++ b/solution/1200-1299/1276.Number of Burgers with No Waste of Ingredients/Solution.java @@ -1,8 +1,8 @@ -class Solution { - public List numOfBurgers(int tomatoSlices, int cheeseSlices) { - int k = 4 * cheeseSlices - tomatoSlices; - int y = k / 2; - int x = cheeseSlices - y; - return k % 2 != 0 || y < 0 || x < 0 ? List.of() : List.of(x, y); - } +class Solution { + public List numOfBurgers(int tomatoSlices, int cheeseSlices) { + int k = 4 * cheeseSlices - tomatoSlices; + int y = k / 2; + int x = cheeseSlices - y; + return k % 2 != 0 || y < 0 || x < 0 ? List.of() : List.of(x, y); + } } \ No newline at end of file diff --git a/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.c b/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.c index 91e50a13809f1..dac58a45554f3 100644 --- a/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.c +++ b/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.c @@ -1,10 +1,10 @@ -int subtractProductAndSum(int n) { - int x = 1; - int y = 0; - for (; n > 0; n /= 10) { - int v = n % 10; - x *= v; - y += v; - } - return x - y; -} +int subtractProductAndSum(int n) { + int x = 1; + int y = 0; + for (; n > 0; n /= 10) { + int v = n % 10; + x *= v; + y += v; + } + return x - y; +} \ No newline at end of file diff --git a/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.cpp b/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.cpp index 2ae3b592046e7..821f509ca2e13 100644 --- a/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.cpp +++ b/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.cpp @@ -1,12 +1,12 @@ -class Solution { -public: - int subtractProductAndSum(int n) { - int x = 1, y = 0; - for (; n; n /= 10) { - int v = n % 10; - x *= v; - y += v; - } - return x - y; - } +class Solution { +public: + int subtractProductAndSum(int n) { + int x = 1, y = 0; + for (; n; n /= 10) { + int v = n % 10; + x *= v; + y += v; + } + return x - y; + } }; \ No newline at end of file diff --git a/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.cs b/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.cs index 9ac4ddf05589e..017dfece734a0 100644 --- a/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.cs +++ b/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.cs @@ -1,12 +1,12 @@ -public class Solution { - public int SubtractProductAndSum(int n) { - int x = 1; - int y = 0; - for (; n > 0; n /= 10) { - int v = n % 10; - x *= v; - y += v; - } - return x - y; - } -} \ No newline at end of file +public class Solution { + public int SubtractProductAndSum(int n) { + int x = 1; + int y = 0; + for (; n > 0; n /= 10) { + int v = n % 10; + x *= v; + y += v; + } + return x - y; + } +} diff --git a/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.java b/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.java index f36058052d26f..28a74b36a88e2 100644 --- a/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.java +++ b/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.java @@ -1,11 +1,11 @@ -class Solution { - public int subtractProductAndSum(int n) { - int x = 1, y = 0; - for (; n > 0; n /= 10) { - int v = n % 10; - x *= v; - y += v; - } - return x - y; - } +class Solution { + public int subtractProductAndSum(int n) { + int x = 1, y = 0; + for (; n > 0; n /= 10) { + int v = n % 10; + x *= v; + y += v; + } + return x - y; + } } \ No newline at end of file diff --git a/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.py b/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.py index 21fbb00ed5326..dd8d5ed5a10ba 100644 --- a/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.py +++ b/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.py @@ -1,8 +1,8 @@ -class Solution: - def subtractProductAndSum(self, n: int) -> int: - x, y = 1, 0 - while n: - n, v = divmod(n, 10) - x *= v - y += v - return x - y +class Solution: + def subtractProductAndSum(self, n: int) -> int: + x, y = 1, 0 + while n: + n, v = divmod(n, 10) + x *= v + y += v + return x - y diff --git a/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution2.py b/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution2.py new file mode 100644 index 0000000000000..c724e58f623b5 --- /dev/null +++ b/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution2.py @@ -0,0 +1,4 @@ +class Solution: + def subtractProductAndSum(self, n: int) -> int: + nums = list(map(int, str(n))) + return prod(nums) - sum(nums) diff --git a/solution/1200-1299/1282.Group the People Given the Group Size They Belong To/Solution2.py b/solution/1200-1299/1282.Group the People Given the Group Size They Belong To/Solution2.py new file mode 100644 index 0000000000000..fc7f8fb0241a5 --- /dev/null +++ b/solution/1200-1299/1282.Group the People Given the Group Size They Belong To/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: + g = defaultdict(list) + for i, x in enumerate(groupSizes): + g[x].append(i) + ans = [] + for x, idx in g.items(): + t = [] + for i in idx: + t.append(i) + if len(t) == x: + ans.append(t) + t = [] + return ans diff --git a/solution/1200-1299/1282.Group the People Given the Group Size They Belong To/Solution2.rs b/solution/1200-1299/1282.Group the People Given the Group Size They Belong To/Solution2.rs new file mode 100644 index 0000000000000..5f7f5ca3b2269 --- /dev/null +++ b/solution/1200-1299/1282.Group the People Given the Group Size They Belong To/Solution2.rs @@ -0,0 +1,18 @@ +impl Solution { + #[allow(dead_code)] + pub fn group_the_people(group_sizes: Vec) -> Vec> { + let n = group_sizes.len(); + let mut g = vec![vec![]; n + 1]; + let mut ret = vec![]; + + for i in 0..n { + g[group_sizes[i] as usize].push(i as i32); + if g[group_sizes[i] as usize].len() == (group_sizes[i] as usize) { + ret.push(g[group_sizes[i] as usize].clone()); + g[group_sizes[i] as usize].clear(); + } + } + + ret + } +} diff --git a/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution.cpp b/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution.cpp index d07b19892d210..b7dd861f30086 100644 --- a/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution.cpp +++ b/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - int smallestDivisor(vector& nums, int threshold) { - int l = 1; - int r = *max_element(nums.begin(), nums.end()); - while (l < r) { - int mid = (l + r) >> 1; - int s = 0; - for (int x : nums) { - s += (x + mid - 1) / mid; - } - if (s <= threshold) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } +class Solution { +public: + int smallestDivisor(vector& nums, int threshold) { + int l = 1; + int r = *max_element(nums.begin(), nums.end()); + while (l < r) { + int mid = (l + r) >> 1; + int s = 0; + for (int x : nums) { + s += (x + mid - 1) / mid; + } + if (s <= threshold) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } }; \ No newline at end of file diff --git a/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution.cs b/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution.cs index 80128698f574e..85b95982e0dcc 100644 --- a/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution.cs +++ b/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution.cs @@ -1,19 +1,19 @@ -public class Solution { - public int SmallestDivisor(int[] nums, int threshold) { - int l = 1; - int r = nums.Max(); - while (l < r) { - int mid = (l + r) >> 1; - int s = 0; - foreach (int x in nums) { - s += (x + mid - 1) / mid; - } - if (s <= threshold) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } -} \ No newline at end of file +public class Solution { + public int SmallestDivisor(int[] nums, int threshold) { + int l = 1; + int r = nums.Max(); + while (l < r) { + int mid = (l + r) >> 1; + int s = 0; + foreach (int x in nums) { + s += (x + mid - 1) / mid; + } + if (s <= threshold) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } +} diff --git a/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution.java b/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution.java index 4211a1a6e67db..6aca2a9bfd0a7 100644 --- a/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution.java +++ b/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution.java @@ -1,18 +1,18 @@ -class Solution { - public int smallestDivisor(int[] nums, int threshold) { - int l = 1, r = 1000000; - while (l < r) { - int mid = (l + r) >> 1; - int s = 0; - for (int x : nums) { - s += (x + mid - 1) / mid; - } - if (s <= threshold) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } +class Solution { + public int smallestDivisor(int[] nums, int threshold) { + int l = 1, r = 1000000; + while (l < r) { + int mid = (l + r) >> 1; + int s = 0; + for (int x : nums) { + s += (x + mid - 1) / mid; + } + if (s <= threshold) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } } \ No newline at end of file diff --git a/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution.py b/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution.py index 5844374a3535a..8f9a9fe607214 100644 --- a/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution.py +++ b/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def smallestDivisor(self, nums: List[int], threshold: int) -> int: - l, r = 1, max(nums) - while l < r: - mid = (l + r) >> 1 - if sum((x + mid - 1) // mid for x in nums) <= threshold: - r = mid - else: - l = mid + 1 - return l +class Solution: + def smallestDivisor(self, nums: List[int], threshold: int) -> int: + l, r = 1, max(nums) + while l < r: + mid = (l + r) >> 1 + if sum((x + mid - 1) // mid for x in nums) <= threshold: + r = mid + else: + l = mid + 1 + return l diff --git a/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution2.py b/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution2.py new file mode 100644 index 0000000000000..d93ecd44d43ab --- /dev/null +++ b/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def smallestDivisor(self, nums: List[int], threshold: int) -> int: + def f(v: int) -> bool: + v += 1 + return sum((x + v - 1) // v for x in nums) <= threshold + + return bisect_left(range(max(nums)), True, key=f) + 1 diff --git a/solution/1200-1299/1285.Find the Start and End Number of Continuous Ranges/Solution.sql b/solution/1200-1299/1285.Find the Start and End Number of Continuous Ranges/Solution.sql index 2f0fc29a16d9c..b0e517a4ff029 100644 --- a/solution/1200-1299/1285.Find the Start and End Number of Continuous Ranges/Solution.sql +++ b/solution/1200-1299/1285.Find the Start and End Number of Continuous Ranges/Solution.sql @@ -3,8 +3,14 @@ WITH T AS ( SELECT log_id, - log_id - ROW_NUMBER() OVER (ORDER BY log_id) AS pid - FROM Logs + SUM(delta) OVER (ORDER BY log_id) AS pid + FROM + ( + SELECT + log_id, + IF((log_id - LAG(log_id) OVER (ORDER BY log_id)) = 1, 0, 1) AS delta + FROM Logs + ) AS t ) SELECT MIN(log_id) AS start_id, MAX(log_id) AS end_id FROM T diff --git a/solution/1200-1299/1285.Find the Start and End Number of Continuous Ranges/Solution2.sql b/solution/1200-1299/1285.Find the Start and End Number of Continuous Ranges/Solution2.sql new file mode 100644 index 0000000000000..2f0fc29a16d9c --- /dev/null +++ b/solution/1200-1299/1285.Find the Start and End Number of Continuous Ranges/Solution2.sql @@ -0,0 +1,11 @@ +# Write your MySQL query statement below +WITH + T AS ( + SELECT + log_id, + log_id - ROW_NUMBER() OVER (ORDER BY log_id) AS pid + FROM Logs + ) +SELECT MIN(log_id) AS start_id, MAX(log_id) AS end_id +FROM T +GROUP BY pid; diff --git a/solution/1200-1299/1286.Iterator for Combination/Solution.cpp b/solution/1200-1299/1286.Iterator for Combination/Solution.cpp index 2b362b77f0770..106f288fecd04 100644 --- a/solution/1200-1299/1286.Iterator for Combination/Solution.cpp +++ b/solution/1200-1299/1286.Iterator for Combination/Solution.cpp @@ -1,33 +1,38 @@ class CombinationIterator { public: - int size; - string cs; - int curr; + string characters; + vector cs; + int idx; + int n; + int combinationLength; + string t; CombinationIterator(string characters, int combinationLength) { - int n = characters.size(); - curr = (1 << n) - 1; - reverse(characters.begin(), characters.end()); - cs = characters; - size = combinationLength; + idx = 0; + n = characters.size(); + this->characters = characters; + this->combinationLength = combinationLength; + dfs(0); } string next() { - while (curr >= 0 && __builtin_popcount(curr) != size) --curr; - string ans; - for (int i = 0; i < cs.size(); ++i) { - if ((curr >> i) & 1) { - ans += cs[i]; - } - } - reverse(ans.begin(), ans.end()); - --curr; - return ans; + return cs[idx++]; } bool hasNext() { - while (curr >= 0 && __builtin_popcount(curr) != size) --curr; - return curr >= 0; + return idx < cs.size(); + } + + void dfs(int i) { + if (t.size() == combinationLength) { + cs.push_back(t); + return; + } + if (i == n) return; + t.push_back(characters[i]); + dfs(i + 1); + t.pop_back(); + dfs(i + 1); } }; diff --git a/solution/1200-1299/1286.Iterator for Combination/Solution.go b/solution/1200-1299/1286.Iterator for Combination/Solution.go index b51ee3ad92946..8a7936ed80d63 100644 --- a/solution/1200-1299/1286.Iterator for Combination/Solution.go +++ b/solution/1200-1299/1286.Iterator for Combination/Solution.go @@ -1,42 +1,38 @@ type CombinationIterator struct { - curr int - size int - cs []byte + cs []string + idx int } func Constructor(characters string, combinationLength int) CombinationIterator { + t := []byte{} n := len(characters) - curr := (1 << n) - 1 - size := combinationLength - cs := make([]byte, n) - for i := range characters { - cs[n-i-1] = characters[i] + cs := []string{} + var dfs func(int) + dfs = func(i int) { + if len(t) == combinationLength { + cs = append(cs, string(t)) + return + } + if i == n { + return + } + t = append(t, characters[i]) + dfs(i + 1) + t = t[:len(t)-1] + dfs(i + 1) } - return CombinationIterator{curr, size, cs} + dfs(0) + return CombinationIterator{cs, 0} } func (this *CombinationIterator) Next() string { - for this.curr >= 0 && bits.OnesCount(uint(this.curr)) != this.size { - this.curr-- - } - ans := []byte{} - for i := range this.cs { - if (this.curr >> i & 1) == 1 { - ans = append(ans, this.cs[i]) - } - } - for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 { - ans[i], ans[j] = ans[j], ans[i] - } - this.curr-- - return string(ans) + ans := this.cs[this.idx] + this.idx++ + return ans } func (this *CombinationIterator) HasNext() bool { - for this.curr >= 0 && bits.OnesCount(uint(this.curr)) != this.size { - this.curr-- - } - return this.curr >= 0 + return this.idx < len(this.cs) } /** diff --git a/solution/1200-1299/1286.Iterator for Combination/Solution.java b/solution/1200-1299/1286.Iterator for Combination/Solution.java index d17e5caec9518..35c6ba742cedf 100644 --- a/solution/1200-1299/1286.Iterator for Combination/Solution.java +++ b/solution/1200-1299/1286.Iterator for Combination/Solution.java @@ -1,37 +1,38 @@ class CombinationIterator { - private int curr; - private int size; - private char[] cs; + private int n; + private int combinationLength; + private String characters; + private StringBuilder t = new StringBuilder(); + private List cs = new ArrayList<>(); + private int idx = 0; public CombinationIterator(String characters, int combinationLength) { - int n = characters.length(); - curr = (1 << n) - 1; - size = combinationLength; - cs = new char[n]; - for (int i = 0; i < n; ++i) { - cs[i] = characters.charAt(n - i - 1); - } + n = characters.length(); + this.combinationLength = combinationLength; + this.characters = characters; + dfs(0); } public String next() { - while (curr >= 0 && Integer.bitCount(curr) != size) { - --curr; - } - StringBuilder ans = new StringBuilder(); - for (int i = 0; i < cs.length; ++i) { - if (((curr >> i) & 1) == 1) { - ans.append(cs[i]); - } - } - --curr; - return ans.reverse().toString(); + return cs.get(idx++); } public boolean hasNext() { - while (curr >= 0 && Integer.bitCount(curr) != size) { - --curr; + return idx < cs.size(); + } + + private void dfs(int i) { + if (t.length() == combinationLength) { + cs.add(t.toString()); + return; + } + if (i == n) { + return; } - return curr >= 0; + t.append(characters.charAt(i)); + dfs(i + 1); + t.deleteCharAt(t.length() - 1); + dfs(i + 1); } } diff --git a/solution/1200-1299/1286.Iterator for Combination/Solution.py b/solution/1200-1299/1286.Iterator for Combination/Solution.py index 4982942fe9e82..c3553b28be347 100644 --- a/solution/1200-1299/1286.Iterator for Combination/Solution.py +++ b/solution/1200-1299/1286.Iterator for Combination/Solution.py @@ -1,23 +1,30 @@ class CombinationIterator: def __init__(self, characters: str, combinationLength: int): - self.curr = (1 << len(characters)) - 1 - self.size = combinationLength - self.cs = characters[::-1] + def dfs(i): + if len(t) == combinationLength: + cs.append(''.join(t)) + return + if i == n: + return + t.append(characters[i]) + dfs(i + 1) + t.pop() + dfs(i + 1) + + cs = [] + n = len(characters) + t = [] + dfs(0) + self.cs = cs + self.idx = 0 def next(self) -> str: - while self.curr >= 0 and self.curr.bit_count() != self.size: - self.curr -= 1 - ans = [] - for i in range(len(self.cs)): - if (self.curr >> i) & 1: - ans.append(self.cs[i]) - self.curr -= 1 - return ''.join(ans[::-1]) + ans = self.cs[self.idx] + self.idx += 1 + return ans def hasNext(self) -> bool: - while self.curr >= 0 and self.curr.bit_count() != self.size: - self.curr -= 1 - return self.curr >= 0 + return self.idx < len(self.cs) # Your CombinationIterator object will be instantiated and called as such: diff --git a/solution/1200-1299/1286.Iterator for Combination/Solution2.cpp b/solution/1200-1299/1286.Iterator for Combination/Solution2.cpp new file mode 100644 index 0000000000000..2b362b77f0770 --- /dev/null +++ b/solution/1200-1299/1286.Iterator for Combination/Solution2.cpp @@ -0,0 +1,39 @@ +class CombinationIterator { +public: + int size; + string cs; + int curr; + + CombinationIterator(string characters, int combinationLength) { + int n = characters.size(); + curr = (1 << n) - 1; + reverse(characters.begin(), characters.end()); + cs = characters; + size = combinationLength; + } + + string next() { + while (curr >= 0 && __builtin_popcount(curr) != size) --curr; + string ans; + for (int i = 0; i < cs.size(); ++i) { + if ((curr >> i) & 1) { + ans += cs[i]; + } + } + reverse(ans.begin(), ans.end()); + --curr; + return ans; + } + + bool hasNext() { + while (curr >= 0 && __builtin_popcount(curr) != size) --curr; + return curr >= 0; + } +}; + +/** + * Your CombinationIterator object will be instantiated and called as such: + * CombinationIterator* obj = new CombinationIterator(characters, combinationLength); + * string param_1 = obj->next(); + * bool param_2 = obj->hasNext(); + */ \ No newline at end of file diff --git a/solution/1200-1299/1286.Iterator for Combination/Solution2.go b/solution/1200-1299/1286.Iterator for Combination/Solution2.go new file mode 100644 index 0000000000000..b51ee3ad92946 --- /dev/null +++ b/solution/1200-1299/1286.Iterator for Combination/Solution2.go @@ -0,0 +1,47 @@ +type CombinationIterator struct { + curr int + size int + cs []byte +} + +func Constructor(characters string, combinationLength int) CombinationIterator { + n := len(characters) + curr := (1 << n) - 1 + size := combinationLength + cs := make([]byte, n) + for i := range characters { + cs[n-i-1] = characters[i] + } + return CombinationIterator{curr, size, cs} +} + +func (this *CombinationIterator) Next() string { + for this.curr >= 0 && bits.OnesCount(uint(this.curr)) != this.size { + this.curr-- + } + ans := []byte{} + for i := range this.cs { + if (this.curr >> i & 1) == 1 { + ans = append(ans, this.cs[i]) + } + } + for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 { + ans[i], ans[j] = ans[j], ans[i] + } + this.curr-- + return string(ans) +} + +func (this *CombinationIterator) HasNext() bool { + for this.curr >= 0 && bits.OnesCount(uint(this.curr)) != this.size { + this.curr-- + } + return this.curr >= 0 +} + +/** + * Your CombinationIterator object will be instantiated and called as such: + * obj := Constructor(characters, combinationLength); + * param_1 := obj.Next(); + * param_2 := obj.HasNext(); + */ \ No newline at end of file diff --git a/solution/1200-1299/1286.Iterator for Combination/Solution2.java b/solution/1200-1299/1286.Iterator for Combination/Solution2.java new file mode 100644 index 0000000000000..d17e5caec9518 --- /dev/null +++ b/solution/1200-1299/1286.Iterator for Combination/Solution2.java @@ -0,0 +1,43 @@ +class CombinationIterator { + private int curr; + private int size; + private char[] cs; + + public CombinationIterator(String characters, int combinationLength) { + int n = characters.length(); + curr = (1 << n) - 1; + size = combinationLength; + cs = new char[n]; + for (int i = 0; i < n; ++i) { + cs[i] = characters.charAt(n - i - 1); + } + } + + public String next() { + while (curr >= 0 && Integer.bitCount(curr) != size) { + --curr; + } + StringBuilder ans = new StringBuilder(); + for (int i = 0; i < cs.length; ++i) { + if (((curr >> i) & 1) == 1) { + ans.append(cs[i]); + } + } + --curr; + return ans.reverse().toString(); + } + + public boolean hasNext() { + while (curr >= 0 && Integer.bitCount(curr) != size) { + --curr; + } + return curr >= 0; + } +} + +/** + * Your CombinationIterator object will be instantiated and called as such: + * CombinationIterator obj = new CombinationIterator(characters, combinationLength); + * String param_1 = obj.next(); + * boolean param_2 = obj.hasNext(); + */ \ No newline at end of file diff --git a/solution/1200-1299/1286.Iterator for Combination/Solution2.py b/solution/1200-1299/1286.Iterator for Combination/Solution2.py new file mode 100644 index 0000000000000..4982942fe9e82 --- /dev/null +++ b/solution/1200-1299/1286.Iterator for Combination/Solution2.py @@ -0,0 +1,26 @@ +class CombinationIterator: + def __init__(self, characters: str, combinationLength: int): + self.curr = (1 << len(characters)) - 1 + self.size = combinationLength + self.cs = characters[::-1] + + def next(self) -> str: + while self.curr >= 0 and self.curr.bit_count() != self.size: + self.curr -= 1 + ans = [] + for i in range(len(self.cs)): + if (self.curr >> i) & 1: + ans.append(self.cs[i]) + self.curr -= 1 + return ''.join(ans[::-1]) + + def hasNext(self) -> bool: + while self.curr >= 0 and self.curr.bit_count() != self.size: + self.curr -= 1 + return self.curr >= 0 + + +# Your CombinationIterator object will be instantiated and called as such: +# obj = CombinationIterator(characters, combinationLength) +# param_1 = obj.next() +# param_2 = obj.hasNext() diff --git a/solution/1200-1299/1287.Element Appearing More Than 25% In Sorted Array/Solution.php b/solution/1200-1299/1287.Element Appearing More Than 25% In Sorted Array/Solution.php index 33e6b4aab1911..6666bf36cccb5 100644 --- a/solution/1200-1299/1287.Element Appearing More Than 25% In Sorted Array/Solution.php +++ b/solution/1200-1299/1287.Element Appearing More Than 25% In Sorted Array/Solution.php @@ -12,4 +12,4 @@ function findSpecialInteger($arr) { } return -1; } -} \ No newline at end of file +} diff --git a/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution.cpp b/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution.cpp index e1278a67f4d25..e7f1259a6ba0d 100644 --- a/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution.cpp +++ b/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution.cpp @@ -2,25 +2,20 @@ class Solution { public: int minFallingPathSum(vector>& grid) { int n = grid.size(); - int f = 0, g = 0, fp = -1; + int f[n + 1][n]; + memset(f, 0, sizeof(f)); const int inf = 1 << 30; - for (auto& row : grid) { - int ff = inf, gg = inf; - int ffp = -1; + for (int i = 1; i <= n; ++i) { for (int j = 0; j < n; ++j) { - int s = (fp != j ? f : g) + row[j]; - if (s < ff) { - gg = ff; - ff = s; - ffp = j; - } else if (s < gg) { - gg = s; + int x = inf; + for (int k = 0; k < n; ++k) { + if (k != j) { + x = min(x, f[i - 1][k]); + } } + f[i][j] = grid[i - 1][j] + (x == inf ? 0 : x); } - f = ff; - g = gg; - fp = ffp; } - return f; + return *min_element(f[n], f[n] + n); } -}; +}; \ No newline at end of file diff --git a/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution.go b/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution.go index 676046a11d8be..d433f003dc9c9 100644 --- a/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution.go +++ b/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution.go @@ -1,23 +1,24 @@ func minFallingPathSum(grid [][]int) int { + n := len(grid) + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, n) + } const inf = 1 << 30 - f, g := 0, 0 - fp := -1 - for _, row := range grid { - ff, gg := inf, inf - ffp := -1 + for i, row := range grid { + i++ for j, v := range row { - s := f - if j == fp { - s = g + x := inf + for k := range row { + if k != j { + x = min(x, f[i-1][k]) + } } - s += v - if s < ff { - ff, gg, ffp = s, ff, j - } else if s < gg { - gg = s + if x == inf { + x = 0 } + f[i][j] = v + x } - f, g, fp = ff, gg, ffp } - return f + return slices.Min(f[n]) } \ No newline at end of file diff --git a/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution.java b/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution.java index 270e4c3995dbc..6d0a1d8932781 100644 --- a/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution.java +++ b/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution.java @@ -1,25 +1,23 @@ class Solution { public int minFallingPathSum(int[][] grid) { - int f = 0, g = 0; - int fp = -1; + int n = grid.length; + int[][] f = new int[n + 1][n]; final int inf = 1 << 30; - for (int[] row : grid) { - int ff = inf, gg = inf; - int ffp = -1; - for (int j = 0; j < row.length; ++j) { - int s = (j != fp ? f : g) + row[j]; - if (s < ff) { - gg = ff; - ff = s; - ffp = j; - } else if (s < gg) { - gg = s; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < n; ++j) { + int x = inf; + for (int k = 0; k < n; ++k) { + if (k != j) { + x = Math.min(x, f[i - 1][k]); + } } + f[i][j] = grid[i - 1][j] + (x == inf ? 0 : x); } - f = ff; - g = gg; - fp = ffp; } - return f; + int ans = inf; + for (int x : f[n]) { + ans = Math.min(ans, x); + } + return ans; } } \ No newline at end of file diff --git a/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution.py b/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution.py index 6798c1c2f38f4..11b746546e142 100644 --- a/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution.py +++ b/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution.py @@ -1,17 +1,9 @@ class Solution: def minFallingPathSum(self, grid: List[List[int]]) -> int: - f = g = 0 - fp = -1 - for row in grid: - ff = gg = inf - ffp = -1 + n = len(grid) + f = [[0] * n for _ in range(n + 1)] + for i, row in enumerate(grid, 1): for j, v in enumerate(row): - s = (g if j == fp else f) + v - if s < ff: - gg = ff - ff = s - ffp = j - elif s < gg: - gg = s - f, g, fp = ff, gg, ffp - return f + x = min((f[i - 1][k] for k in range(n) if k != j), default=0) + f[i][j] = v + x + return min(f[n]) diff --git a/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution2.cpp b/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution2.cpp new file mode 100644 index 0000000000000..dd8103dbee49a --- /dev/null +++ b/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution2.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int minFallingPathSum(vector>& grid) { + int n = grid.size(); + int f = 0, g = 0, fp = -1; + const int inf = 1 << 30; + for (auto& row : grid) { + int ff = inf, gg = inf; + int ffp = -1; + for (int j = 0; j < n; ++j) { + int s = (fp != j ? f : g) + row[j]; + if (s < ff) { + gg = ff; + ff = s; + ffp = j; + } else if (s < gg) { + gg = s; + } + } + f = ff; + g = gg; + fp = ffp; + } + return f; + } +}; \ No newline at end of file diff --git a/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution2.go b/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution2.go new file mode 100644 index 0000000000000..676046a11d8be --- /dev/null +++ b/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution2.go @@ -0,0 +1,23 @@ +func minFallingPathSum(grid [][]int) int { + const inf = 1 << 30 + f, g := 0, 0 + fp := -1 + for _, row := range grid { + ff, gg := inf, inf + ffp := -1 + for j, v := range row { + s := f + if j == fp { + s = g + } + s += v + if s < ff { + ff, gg, ffp = s, ff, j + } else if s < gg { + gg = s + } + } + f, g, fp = ff, gg, ffp + } + return f +} \ No newline at end of file diff --git a/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution2.java b/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution2.java new file mode 100644 index 0000000000000..270e4c3995dbc --- /dev/null +++ b/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution2.java @@ -0,0 +1,25 @@ +class Solution { + public int minFallingPathSum(int[][] grid) { + int f = 0, g = 0; + int fp = -1; + final int inf = 1 << 30; + for (int[] row : grid) { + int ff = inf, gg = inf; + int ffp = -1; + for (int j = 0; j < row.length; ++j) { + int s = (j != fp ? f : g) + row[j]; + if (s < ff) { + gg = ff; + ff = s; + ffp = j; + } else if (s < gg) { + gg = s; + } + } + f = ff; + g = gg; + fp = ffp; + } + return f; + } +} \ No newline at end of file diff --git a/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution2.py b/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution2.py new file mode 100644 index 0000000000000..6798c1c2f38f4 --- /dev/null +++ b/solution/1200-1299/1289.Minimum Falling Path Sum II/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def minFallingPathSum(self, grid: List[List[int]]) -> int: + f = g = 0 + fp = -1 + for row in grid: + ff = gg = inf + ffp = -1 + for j, v in enumerate(row): + s = (g if j == fp else f) + v + if s < ff: + gg = ff + ff = s + ffp = j + elif s < gg: + gg = s + f, g, fp = ff, gg, ffp + return f diff --git a/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/Solution.c b/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/Solution.c index 0f79f75979ee4..91c2e54549147 100644 --- a/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/Solution.c +++ b/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/Solution.c @@ -14,4 +14,4 @@ int getDecimalValue(struct ListNode* head) { cur = cur->next; } return ans; -} +} \ No newline at end of file diff --git a/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/Solution.cpp b/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/Solution.cpp index 2da21d36c0049..ef4bca2f8bbba 100644 --- a/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/Solution.cpp +++ b/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/Solution.cpp @@ -1,33 +1,33 @@ -class Solution { -public: - int maxSideLength(vector>& mat, int threshold) { - int m = mat.size(), n = mat[0].size(); - int s[m + 1][n + 1]; - memset(s, 0, sizeof(s)); - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + mat[i - 1][j - 1]; - } - } - auto check = [&](int k) { - for (int i = 0; i < m - k + 1; ++i) { - for (int j = 0; j < n - k + 1; ++j) { - if (s[i + k][j + k] - s[i][j + k] - s[i + k][j] + s[i][j] <= threshold) { - return true; - } - } - } - return false; - }; - int l = 0, r = min(m, n); - while (l < r) { - int mid = (l + r + 1) >> 1; - if (check(mid)) { - l = mid; - } else { - r = mid - 1; - } - } - return l; - } +class Solution { +public: + int maxSideLength(vector>& mat, int threshold) { + int m = mat.size(), n = mat[0].size(); + int s[m + 1][n + 1]; + memset(s, 0, sizeof(s)); + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + mat[i - 1][j - 1]; + } + } + auto check = [&](int k) { + for (int i = 0; i < m - k + 1; ++i) { + for (int j = 0; j < n - k + 1; ++j) { + if (s[i + k][j + k] - s[i][j + k] - s[i + k][j] + s[i][j] <= threshold) { + return true; + } + } + } + return false; + }; + int l = 0, r = min(m, n); + while (l < r) { + int mid = (l + r + 1) >> 1; + if (check(mid)) { + l = mid; + } else { + r = mid - 1; + } + } + return l; + } }; \ No newline at end of file diff --git a/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/Solution.java b/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/Solution.java index 6ce57fdcae375..5bcc9efaf97b1 100644 --- a/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/Solution.java +++ b/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/Solution.java @@ -1,39 +1,39 @@ -class Solution { - private int m; - private int n; - private int threshold; - private int[][] s; - - public int maxSideLength(int[][] mat, int threshold) { - m = mat.length; - n = mat[0].length; - this.threshold = threshold; - s = new int[m + 1][n + 1]; - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + mat[i - 1][j - 1]; - } - } - int l = 0, r = Math.min(m, n); - while (l < r) { - int mid = (l + r + 1) >> 1; - if (check(mid)) { - l = mid; - } else { - r = mid - 1; - } - } - return l; - } - - private boolean check(int k) { - for (int i = 0; i < m - k + 1; ++i) { - for (int j = 0; j < n - k + 1; ++j) { - if (s[i + k][j + k] - s[i][j + k] - s[i + k][j] + s[i][j] <= threshold) { - return true; - } - } - } - return false; - } +class Solution { + private int m; + private int n; + private int threshold; + private int[][] s; + + public int maxSideLength(int[][] mat, int threshold) { + m = mat.length; + n = mat[0].length; + this.threshold = threshold; + s = new int[m + 1][n + 1]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + mat[i - 1][j - 1]; + } + } + int l = 0, r = Math.min(m, n); + while (l < r) { + int mid = (l + r + 1) >> 1; + if (check(mid)) { + l = mid; + } else { + r = mid - 1; + } + } + return l; + } + + private boolean check(int k) { + for (int i = 0; i < m - k + 1; ++i) { + for (int j = 0; j < n - k + 1; ++j) { + if (s[i + k][j + k] - s[i][j + k] - s[i + k][j] + s[i][j] <= threshold) { + return true; + } + } + } + return false; + } } \ No newline at end of file diff --git a/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/Solution.py b/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/Solution.py index ee24d9eb11e53..fc52eb90af084 100644 --- a/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/Solution.py +++ b/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/Solution.py @@ -1,23 +1,23 @@ -class Solution: - def maxSideLength(self, mat: List[List[int]], threshold: int) -> int: - def check(k: int) -> bool: - for i in range(m - k + 1): - for j in range(n - k + 1): - v = s[i + k][j + k] - s[i][j + k] - s[i + k][j] + s[i][j] - if v <= threshold: - return True - return False - - m, n = len(mat), len(mat[0]) - s = [[0] * (n + 1) for _ in range(m + 1)] - for i, row in enumerate(mat, 1): - for j, x in enumerate(row, 1): - s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + x - l, r = 0, min(m, n) - while l < r: - mid = (l + r + 1) >> 1 - if check(mid): - l = mid - else: - r = mid - 1 - return l +class Solution: + def maxSideLength(self, mat: List[List[int]], threshold: int) -> int: + def check(k: int) -> bool: + for i in range(m - k + 1): + for j in range(n - k + 1): + v = s[i + k][j + k] - s[i][j + k] - s[i + k][j] + s[i][j] + if v <= threshold: + return True + return False + + m, n = len(mat), len(mat[0]) + s = [[0] * (n + 1) for _ in range(m + 1)] + for i, row in enumerate(mat, 1): + for j, x in enumerate(row, 1): + s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + x + l, r = 0, min(m, n) + while l < r: + mid = (l + r + 1) >> 1 + if check(mid): + l = mid + else: + r = mid - 1 + return l diff --git a/solution/1200-1299/1293.Shortest Path in a Grid with Obstacles Elimination/Solution.py b/solution/1200-1299/1293.Shortest Path in a Grid with Obstacles Elimination/Solution.py index a8cc93c7bd92b..6df8877513142 100644 --- a/solution/1200-1299/1293.Shortest Path in a Grid with Obstacles Elimination/Solution.py +++ b/solution/1200-1299/1293.Shortest Path in a Grid with Obstacles Elimination/Solution.py @@ -1,24 +1,24 @@ -class Solution: - def shortestPath(self, grid: List[List[int]], k: int) -> int: - m, n = len(grid), len(grid[0]) - if k >= m + n - 3: - return m + n - 2 - q = deque([(0, 0, k)]) - vis = {(0, 0, k)} - ans = 0 - while q: - ans += 1 - for _ in range(len(q)): - i, j, k = q.popleft() - for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]: - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n: - if x == m - 1 and y == n - 1: - return ans - if grid[x][y] == 0 and (x, y, k) not in vis: - q.append((x, y, k)) - vis.add((x, y, k)) - if grid[x][y] == 1 and k > 0 and (x, y, k - 1) not in vis: - q.append((x, y, k - 1)) - vis.add((x, y, k - 1)) - return -1 +class Solution: + def shortestPath(self, grid: List[List[int]], k: int) -> int: + m, n = len(grid), len(grid[0]) + if k >= m + n - 3: + return m + n - 2 + q = deque([(0, 0, k)]) + vis = {(0, 0, k)} + ans = 0 + while q: + ans += 1 + for _ in range(len(q)): + i, j, k = q.popleft() + for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]: + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n: + if x == m - 1 and y == n - 1: + return ans + if grid[x][y] == 0 and (x, y, k) not in vis: + q.append((x, y, k)) + vis.add((x, y, k)) + if grid[x][y] == 1 and k > 0 and (x, y, k - 1) not in vis: + q.append((x, y, k - 1)) + vis.add((x, y, k - 1)) + return -1 diff --git a/solution/1200-1299/1294.Weather Type in Each Country/Solution.sql b/solution/1200-1299/1294.Weather Type in Each Country/Solution.sql index a0944ddc293a9..d61a07a0246da 100644 --- a/solution/1200-1299/1294.Weather Type in Each Country/Solution.sql +++ b/solution/1200-1299/1294.Weather Type in Each Country/Solution.sql @@ -1,3 +1,4 @@ +# Write your MySQL query statement below SELECT country_name, CASE diff --git a/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/Solution2.cpp b/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/Solution2.cpp new file mode 100644 index 0000000000000..8a7c3e252a772 --- /dev/null +++ b/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + bool isPossibleDivide(vector& nums, int k) { + if (nums.size() % k != 0) return false; + map mp; + for (int& h : nums) mp[h] += 1; + while (!mp.empty()) { + int v = mp.begin()->first; + for (int i = v; i < v + k; ++i) { + if (!mp.count(i)) return false; + if (mp[i] == 1) + mp.erase(i); + else + mp[i] -= 1; + } + } + return true; + } +}; \ No newline at end of file diff --git a/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/Solution2.go b/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/Solution2.go new file mode 100644 index 0000000000000..a1a6e92d3d4fe --- /dev/null +++ b/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/Solution2.go @@ -0,0 +1,27 @@ +func isPossibleDivide(nums []int, k int) bool { + if len(nums)%k != 0 { + return false + } + m := treemap.NewWithIntComparator() + for _, h := range nums { + if v, ok := m.Get(h); ok { + m.Put(h, v.(int)+1) + } else { + m.Put(h, 1) + } + } + for !m.Empty() { + v, _ := m.Min() + for i := v.(int); i < v.(int)+k; i++ { + if _, ok := m.Get(i); !ok { + return false + } + if v, _ := m.Get(i); v.(int) == 1 { + m.Remove(i) + } else { + m.Put(i, v.(int)-1) + } + } + } + return true +} \ No newline at end of file diff --git a/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/Solution2.java b/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/Solution2.java new file mode 100644 index 0000000000000..6ed1162b15075 --- /dev/null +++ b/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/Solution2.java @@ -0,0 +1,25 @@ +class Solution { + public boolean isPossibleDivide(int[] nums, int k) { + if (nums.length % k != 0) { + return false; + } + TreeMap tm = new TreeMap<>(); + for (int h : nums) { + tm.put(h, tm.getOrDefault(h, 0) + 1); + } + while (!tm.isEmpty()) { + int v = tm.firstKey(); + for (int i = v; i < v + k; ++i) { + if (!tm.containsKey(i)) { + return false; + } + if (tm.get(i) == 1) { + tm.remove(i); + } else { + tm.put(i, tm.get(i) - 1); + } + } + } + return true; + } +} \ No newline at end of file diff --git a/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/Solution2.py b/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/Solution2.py new file mode 100644 index 0000000000000..f925479ad6afc --- /dev/null +++ b/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/Solution2.py @@ -0,0 +1,23 @@ +from sortedcontainers import SortedDict + + +class Solution: + def isPossibleDivide(self, nums: List[int], k: int) -> bool: + if len(nums) % k != 0: + return False + sd = SortedDict() + for h in nums: + if h in sd: + sd[h] += 1 + else: + sd[h] = 1 + while sd: + v = sd.peekitem(0)[0] + for i in range(v, v + k): + if i not in sd: + return False + if sd[i] == 1: + sd.pop(i) + else: + sd[i] -= 1 + return True diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.cpp b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.cpp index fa5b26442c51b..7b85217a5a1f3 100644 --- a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.cpp +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.cpp @@ -1,39 +1,39 @@ -class Solution { -public: - int maxCandies(vector& status, vector& candies, vector>& keys, vector>& containedBoxes, vector& initialBoxes) { - int ans = 0; - int n = status.size(); - vector has(n); - vector took(n); - queue q; - for (int& i : initialBoxes) { - has[i] = true; - if (status[i]) { - ans += candies[i]; - took[i] = true; - q.push(i); - } - } - while (!q.empty()) { - int i = q.front(); - q.pop(); - for (int k : keys[i]) { - status[k] = 1; - if (has[k] && !took[k]) { - ans += candies[k]; - took[k] = true; - q.push(k); - } - } - for (int j : containedBoxes[i]) { - has[j] = true; - if (status[j] && !took[j]) { - ans += candies[j]; - took[j] = true; - q.push(j); - } - } - } - return ans; - } +class Solution { +public: + int maxCandies(vector& status, vector& candies, vector>& keys, vector>& containedBoxes, vector& initialBoxes) { + int ans = 0; + int n = status.size(); + vector has(n); + vector took(n); + queue q; + for (int& i : initialBoxes) { + has[i] = true; + if (status[i]) { + ans += candies[i]; + took[i] = true; + q.push(i); + } + } + while (!q.empty()) { + int i = q.front(); + q.pop(); + for (int k : keys[i]) { + status[k] = 1; + if (has[k] && !took[k]) { + ans += candies[k]; + took[k] = true; + q.push(k); + } + } + for (int j : containedBoxes[i]) { + has[j] = true; + if (status[j] && !took[j]) { + ans += candies[j]; + took[j] = true; + q.push(j); + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.java b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.java index c56ed1b8b9710..3d9e243bfdfa3 100644 --- a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.java +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.java @@ -1,38 +1,38 @@ -class Solution { - public int maxCandies( - int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes) { - int ans = 0; - int n = status.length; - boolean[] has = new boolean[n]; - boolean[] took = new boolean[n]; - Deque q = new ArrayDeque<>(); - for (int i : initialBoxes) { - has[i] = true; - if (status[i] == 1) { - ans += candies[i]; - took[i] = true; - q.offer(i); - } - } - while (!q.isEmpty()) { - int i = q.poll(); - for (int k : keys[i]) { - status[k] = 1; - if (has[k] && !took[k]) { - ans += candies[k]; - took[k] = true; - q.offer(k); - } - } - for (int j : containedBoxes[i]) { - has[j] = true; - if (status[j] == 1 && !took[j]) { - ans += candies[j]; - took[j] = true; - q.offer(j); - } - } - } - return ans; - } +class Solution { + public int maxCandies( + int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes) { + int ans = 0; + int n = status.length; + boolean[] has = new boolean[n]; + boolean[] took = new boolean[n]; + Deque q = new ArrayDeque<>(); + for (int i : initialBoxes) { + has[i] = true; + if (status[i] == 1) { + ans += candies[i]; + took[i] = true; + q.offer(i); + } + } + while (!q.isEmpty()) { + int i = q.poll(); + for (int k : keys[i]) { + status[k] = 1; + if (has[k] && !took[k]) { + ans += candies[k]; + took[k] = true; + q.offer(k); + } + } + for (int j : containedBoxes[i]) { + has[j] = true; + if (status[j] == 1 && !took[j]) { + ans += candies[j]; + took[j] = true; + q.offer(j); + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.py b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.py index 1de1a408eda3c..fe996159a7a50 100644 --- a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.py +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.py @@ -1,29 +1,29 @@ -class Solution: - def maxCandies( - self, - status: List[int], - candies: List[int], - keys: List[List[int]], - containedBoxes: List[List[int]], - initialBoxes: List[int], - ) -> int: - q = deque([i for i in initialBoxes if status[i] == 1]) - ans = sum(candies[i] for i in initialBoxes if status[i] == 1) - has = set(initialBoxes) - took = {i for i in initialBoxes if status[i] == 1} - - while q: - i = q.popleft() - for k in keys[i]: - status[k] = 1 - if k in has and k not in took: - ans += candies[k] - took.add(k) - q.append(k) - for j in containedBoxes[i]: - has.add(j) - if status[j] and j not in took: - ans += candies[j] - took.add(j) - q.append(j) - return ans +class Solution: + def maxCandies( + self, + status: List[int], + candies: List[int], + keys: List[List[int]], + containedBoxes: List[List[int]], + initialBoxes: List[int], + ) -> int: + q = deque([i for i in initialBoxes if status[i] == 1]) + ans = sum(candies[i] for i in initialBoxes if status[i] == 1) + has = set(initialBoxes) + took = {i for i in initialBoxes if status[i] == 1} + + while q: + i = q.popleft() + for k in keys[i]: + status[k] = 1 + if k in has and k not in took: + ans += candies[k] + took.add(k) + q.append(k) + for j in containedBoxes[i]: + has.add(j) + if status[j] and j not in took: + ans += candies[j] + took.add(j) + q.append(j) + return ans diff --git a/solution/1300-1399/1302.Deepest Leaves Sum/Solution.c b/solution/1300-1399/1302.Deepest Leaves Sum/Solution.c index 57349abc735ff..3afe3ef56e88e 100644 --- a/solution/1300-1399/1302.Deepest Leaves Sum/Solution.c +++ b/solution/1300-1399/1302.Deepest Leaves Sum/Solution.c @@ -30,4 +30,4 @@ int deepestLeavesSum(struct TreeNode* root) { int maxDepth = 0; dfs(root, 0, &maxDepth, &res); return res; -} +} \ No newline at end of file diff --git a/solution/1300-1399/1302.Deepest Leaves Sum/Solution2.cpp b/solution/1300-1399/1302.Deepest Leaves Sum/Solution2.cpp new file mode 100644 index 0000000000000..bfb9745bac2eb --- /dev/null +++ b/solution/1300-1399/1302.Deepest Leaves Sum/Solution2.cpp @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int mx = 0; + int ans = 0; + + int deepestLeavesSum(TreeNode* root) { + dfs(root, 1); + return ans; + } + + void dfs(TreeNode* root, int i) { + if (!root) return; + if (i == mx) { + ans += root->val; + } else if (i > mx) { + mx = i; + ans = root->val; + } + dfs(root->left, i + 1); + dfs(root->right, i + 1); + } +}; \ No newline at end of file diff --git a/solution/1300-1399/1302.Deepest Leaves Sum/Solution2.go b/solution/1300-1399/1302.Deepest Leaves Sum/Solution2.go new file mode 100644 index 0000000000000..7fbf77fa6ae04 --- /dev/null +++ b/solution/1300-1399/1302.Deepest Leaves Sum/Solution2.go @@ -0,0 +1,27 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func deepestLeavesSum(root *TreeNode) int { + ans, mx := 0, 0 + var dfs func(*TreeNode, int) + dfs = func(root *TreeNode, i int) { + if root == nil { + return + } + if i == mx { + ans += root.Val + } else if i > mx { + mx = i + ans = root.Val + } + dfs(root.Left, i+1) + dfs(root.Right, i+1) + } + dfs(root, 1) + return ans +} \ No newline at end of file diff --git a/solution/1300-1399/1302.Deepest Leaves Sum/Solution2.java b/solution/1300-1399/1302.Deepest Leaves Sum/Solution2.java new file mode 100644 index 0000000000000..388370f693a78 --- /dev/null +++ b/solution/1300-1399/1302.Deepest Leaves Sum/Solution2.java @@ -0,0 +1,38 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + int mx; + int ans; + + public int deepestLeavesSum(TreeNode root) { + dfs(root, 1); + return ans; + } + + private void dfs(TreeNode root, int i) { + if (root == null) { + return; + } + if (i > mx) { + mx = i; + ans = root.val; + } else if (i == mx) { + ans += root.val; + } + dfs(root.left, i + 1); + dfs(root.right, i + 1); + } +} \ No newline at end of file diff --git a/solution/1300-1399/1302.Deepest Leaves Sum/Solution2.py b/solution/1300-1399/1302.Deepest Leaves Sum/Solution2.py new file mode 100644 index 0000000000000..130cf99b5a04a --- /dev/null +++ b/solution/1300-1399/1302.Deepest Leaves Sum/Solution2.py @@ -0,0 +1,23 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: + def dfs(root, i): + nonlocal ans, mx + if root is None: + return + if i == mx: + ans += root.val + elif i > mx: + ans = root.val + mx = i + dfs(root.left, i + 1) + dfs(root.right, i + 1) + + ans = mx = 0 + dfs(root, 1) + return ans diff --git a/solution/1300-1399/1302.Deepest Leaves Sum/Solution2.ts b/solution/1300-1399/1302.Deepest Leaves Sum/Solution2.ts new file mode 100644 index 0000000000000..15ce814b4acf0 --- /dev/null +++ b/solution/1300-1399/1302.Deepest Leaves Sum/Solution2.ts @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function deepestLeavesSum(root: TreeNode | null): number { + let res = 0; + let maxDepath = 0; + const dfs = ({ val, left, right }: TreeNode, depth: number) => { + if (left == null && right == null) { + if (depth === maxDepath) { + res += val; + } else if (depth > maxDepath) { + maxDepath = depth; + res = val; + } + return; + } + left && dfs(left, depth + 1); + right && dfs(right, depth + 1); + }; + dfs(root, 0); + return res; +} diff --git a/solution/1300-1399/1303.Find the Team Size/Solution.sql b/solution/1300-1399/1303.Find the Team Size/Solution.sql index 73a15026525e7..abb7cd78c3d4c 100644 --- a/solution/1300-1399/1303.Find the Team Size/Solution.sql +++ b/solution/1300-1399/1303.Find the Team Size/Solution.sql @@ -1,6 +1,11 @@ # Write your MySQL query statement below -SELECT e1.employee_id, COUNT(1) AS team_size +WITH + T AS ( + SELECT team_id, COUNT(1) AS team_size + FROM Employee + GROUP BY 1 + ) +SELECT employee_id, team_size FROM - Employee AS e1 - LEFT JOIN Employee AS e2 USING (team_id) -GROUP BY 1; + Employee + JOIN T USING (team_id); diff --git a/solution/1300-1399/1303.Find the Team Size/Solution2.sql b/solution/1300-1399/1303.Find the Team Size/Solution2.sql new file mode 100644 index 0000000000000..73a15026525e7 --- /dev/null +++ b/solution/1300-1399/1303.Find the Team Size/Solution2.sql @@ -0,0 +1,6 @@ +# Write your MySQL query statement below +SELECT e1.employee_id, COUNT(1) AS team_size +FROM + Employee AS e1 + LEFT JOIN Employee AS e2 USING (team_id) +GROUP BY 1; diff --git a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.cpp b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.cpp index c0f68358bb187..810526aa59a89 100644 --- a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.cpp +++ b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.cpp @@ -2,8 +2,10 @@ class Solution { public: vector sumZero(int n) { vector ans(n); - iota(ans.begin(), ans.end(), 1); - ans[n - 1] = -(n - 1) * n / 2; + for (int i = 1, j = 0; i <= n / 2; ++i) { + ans[j++] = i; + ans[j++] = -i; + } return ans; } }; \ No newline at end of file diff --git a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.go b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.go index 0b38a28257c3a..c72da76c191f6 100644 --- a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.go +++ b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.go @@ -1,8 +1,9 @@ func sumZero(n int) []int { ans := make([]int, n) - for i := 1; i < n; i++ { - ans[i] = i + for i, j := 1, 0; i <= n/2; i, j = i+1, j+1 { + ans[j] = i + j++ + ans[j] = -i } - ans[0] = -n * (n - 1) / 2 return ans } \ No newline at end of file diff --git a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.java b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.java index 6edc7c1b7c1c7..4229ead0e7c55 100644 --- a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.java +++ b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.java @@ -1,10 +1,10 @@ class Solution { public int[] sumZero(int n) { int[] ans = new int[n]; - for (int i = 1; i < n; ++i) { - ans[i] = i; + for (int i = 1, j = 0; i <= n / 2; ++i) { + ans[j++] = i; + ans[j++] = -i; } - ans[0] = -(n * (n - 1) / 2); return ans; } } \ No newline at end of file diff --git a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.py b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.py index 51e480dce8bf3..982a2286fe66b 100644 --- a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.py +++ b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.py @@ -1,5 +1,9 @@ class Solution: def sumZero(self, n: int) -> List[int]: - ans = list(range(1, n)) - ans.append(-sum(ans)) + ans = [] + for i in range(n >> 1): + ans.append(i + 1) + ans.append(-(i + 1)) + if n & 1: + ans.append(0) return ans diff --git a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.ts b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.ts index 66a97469f3fcf..823566474fec6 100644 --- a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.ts +++ b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.ts @@ -1,8 +1,8 @@ function sumZero(n: number): number[] { const ans = new Array(n).fill(0); - for (let i = 1; i < n; ++i) { - ans[i] = i; + for (let i = 1, j = 0; i <= n / 2; ++i) { + ans[j++] = i; + ans[j++] = -i; } - ans[0] = -((n * (n - 1)) / 2); return ans; } diff --git a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution2.cpp b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution2.cpp new file mode 100644 index 0000000000000..c0f68358bb187 --- /dev/null +++ b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution2.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + vector sumZero(int n) { + vector ans(n); + iota(ans.begin(), ans.end(), 1); + ans[n - 1] = -(n - 1) * n / 2; + return ans; + } +}; \ No newline at end of file diff --git a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution2.go b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution2.go new file mode 100644 index 0000000000000..0b38a28257c3a --- /dev/null +++ b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution2.go @@ -0,0 +1,8 @@ +func sumZero(n int) []int { + ans := make([]int, n) + for i := 1; i < n; i++ { + ans[i] = i + } + ans[0] = -n * (n - 1) / 2 + return ans +} \ No newline at end of file diff --git a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution2.java b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution2.java new file mode 100644 index 0000000000000..6edc7c1b7c1c7 --- /dev/null +++ b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution2.java @@ -0,0 +1,10 @@ +class Solution { + public int[] sumZero(int n) { + int[] ans = new int[n]; + for (int i = 1; i < n; ++i) { + ans[i] = i; + } + ans[0] = -(n * (n - 1) / 2); + return ans; + } +} \ No newline at end of file diff --git a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution2.py b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution2.py new file mode 100644 index 0000000000000..51e480dce8bf3 --- /dev/null +++ b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution2.py @@ -0,0 +1,5 @@ +class Solution: + def sumZero(self, n: int) -> List[int]: + ans = list(range(1, n)) + ans.append(-sum(ans)) + return ans diff --git a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution2.ts b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution2.ts new file mode 100644 index 0000000000000..66a97469f3fcf --- /dev/null +++ b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution2.ts @@ -0,0 +1,8 @@ +function sumZero(n: number): number[] { + const ans = new Array(n).fill(0); + for (let i = 1; i < n; ++i) { + ans[i] = i; + } + ans[0] = -((n * (n - 1)) / 2); + return ans; +} diff --git a/solution/1300-1399/1309.Decrypt String from Alphabet to Integer Mapping/Solution.c b/solution/1300-1399/1309.Decrypt String from Alphabet to Integer Mapping/Solution.c index 2f6ca02ed56ff..d0e5ccf6e50db 100644 --- a/solution/1300-1399/1309.Decrypt String from Alphabet to Integer Mapping/Solution.c +++ b/solution/1300-1399/1309.Decrypt String from Alphabet to Integer Mapping/Solution.c @@ -16,4 +16,4 @@ char* freqAlphabets(char* s) { } ans[j] = '\0'; return ans; -} +} \ No newline at end of file diff --git a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution.cpp b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution.cpp index 95b457fe9cc93..2b027beb3de6e 100644 --- a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution.cpp +++ b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution.cpp @@ -3,16 +3,22 @@ class Solution { int minInsertions(string s) { int n = s.size(); int f[n][n]; - memset(f, 0, sizeof(f)); - for (int i = n - 2; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - if (s[i] == s[j]) { - f[i][j] = f[i + 1][j - 1]; - } else { - f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1; - } + memset(f, -1, sizeof(f)); + function dfs = [&](int i, int j) -> int { + if (i >= j) { + return 0; } - } - return f[0][n - 1]; + if (f[i][j] != -1) { + return f[i][j]; + } + int ans = 1 << 30; + if (s[i] == s[j]) { + ans = dfs(i + 1, j - 1); + } else { + ans = min(dfs(i + 1, j), dfs(i, j - 1)) + 1; + } + return f[i][j] = ans; + }; + return dfs(0, n - 1); } }; \ No newline at end of file diff --git a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution.go b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution.go index fdcf235c2aed6..88f4c76471bff 100644 --- a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution.go +++ b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution.go @@ -3,15 +3,26 @@ func minInsertions(s string) int { f := make([][]int, n) for i := range f { f[i] = make([]int, n) + for j := range f[i] { + f[i][j] = -1 + } } - for i := n - 2; i >= 0; i-- { - for j := i + 1; j < n; j++ { - if s[i] == s[j] { - f[i][j] = f[i+1][j-1] - } else { - f[i][j] = min(f[i+1][j], f[i][j-1]) + 1 - } + var dfs func(i, j int) int + dfs = func(i, j int) int { + if i >= j { + return 0 + } + if f[i][j] != -1 { + return f[i][j] + } + ans := 1 << 30 + if s[i] == s[j] { + ans = dfs(i+1, j-1) + } else { + ans = min(dfs(i+1, j), dfs(i, j-1)) + 1 } + f[i][j] = ans + return ans } - return f[0][n-1] + return dfs(0, n-1) } \ No newline at end of file diff --git a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution.java b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution.java index 3aaf5035f13dc..c679d07431b4a 100644 --- a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution.java +++ b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution.java @@ -1,16 +1,27 @@ class Solution { + private Integer[][] f; + private String s; + public int minInsertions(String s) { + this.s = s; int n = s.length(); - int[][] f = new int[n][n]; - for (int i = n - 2; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - if (s.charAt(i) == s.charAt(j)) { - f[i][j] = f[i + 1][j - 1]; - } else { - f[i][j] = Math.min(f[i + 1][j], f[i][j - 1]) + 1; - } - } + f = new Integer[n][n]; + return dfs(0, n - 1); + } + + private int dfs(int i, int j) { + if (i >= j) { + return 0; + } + if (f[i][j] != null) { + return f[i][j]; + } + int ans = 1 << 30; + if (s.charAt(i) == s.charAt(j)) { + ans = dfs(i + 1, j - 1); + } else { + ans = Math.min(dfs(i + 1, j), dfs(i, j - 1)) + 1; } - return f[0][n - 1]; + return f[i][j] = ans; } } \ No newline at end of file diff --git a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution.py b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution.py index f2f3572ee5b6d..aeff28c507dba 100644 --- a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution.py +++ b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution.py @@ -1,11 +1,11 @@ class Solution: def minInsertions(self, s: str) -> int: - n = len(s) - f = [[0] * n for _ in range(n)] - for i in range(n - 2, -1, -1): - for j in range(i + 1, n): - if s[i] == s[j]: - f[i][j] = f[i + 1][j - 1] - else: - f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1 - return f[0][-1] + @cache + def dfs(i: int, j: int) -> int: + if i >= j: + return 0 + if s[i] == s[j]: + return dfs(i + 1, j - 1) + return 1 + min(dfs(i + 1, j), dfs(i, j - 1)) + + return dfs(0, len(s) - 1) diff --git a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution2.cpp b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution2.cpp new file mode 100644 index 0000000000000..95b457fe9cc93 --- /dev/null +++ b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution2.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int minInsertions(string s) { + int n = s.size(); + int f[n][n]; + memset(f, 0, sizeof(f)); + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + if (s[i] == s[j]) { + f[i][j] = f[i + 1][j - 1]; + } else { + f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1; + } + } + } + return f[0][n - 1]; + } +}; \ No newline at end of file diff --git a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution2.go b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution2.go new file mode 100644 index 0000000000000..fdcf235c2aed6 --- /dev/null +++ b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution2.go @@ -0,0 +1,17 @@ +func minInsertions(s string) int { + n := len(s) + f := make([][]int, n) + for i := range f { + f[i] = make([]int, n) + } + for i := n - 2; i >= 0; i-- { + for j := i + 1; j < n; j++ { + if s[i] == s[j] { + f[i][j] = f[i+1][j-1] + } else { + f[i][j] = min(f[i+1][j], f[i][j-1]) + 1 + } + } + } + return f[0][n-1] +} \ No newline at end of file diff --git a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution2.java b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution2.java new file mode 100644 index 0000000000000..3aaf5035f13dc --- /dev/null +++ b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public int minInsertions(String s) { + int n = s.length(); + int[][] f = new int[n][n]; + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + if (s.charAt(i) == s.charAt(j)) { + f[i][j] = f[i + 1][j - 1]; + } else { + f[i][j] = Math.min(f[i + 1][j], f[i][j - 1]) + 1; + } + } + } + return f[0][n - 1]; + } +} \ No newline at end of file diff --git a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution2.py b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution2.py new file mode 100644 index 0000000000000..f2f3572ee5b6d --- /dev/null +++ b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def minInsertions(self, s: str) -> int: + n = len(s) + f = [[0] * n for _ in range(n)] + for i in range(n - 2, -1, -1): + for j in range(i + 1, n): + if s[i] == s[j]: + f[i][j] = f[i + 1][j - 1] + else: + f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1 + return f[0][-1] diff --git a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution3.cpp b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution3.cpp new file mode 100644 index 0000000000000..d98c7969b32f5 --- /dev/null +++ b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution3.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int minInsertions(string s) { + int n = s.size(); + int f[n][n]; + memset(f, 0, sizeof(f)); + for (int k = 2; k <= n; ++k) { + for (int i = 0; i + k - 1 < n; ++i) { + int j = i + k - 1; + if (s[i] == s[j]) { + f[i][j] = f[i + 1][j - 1]; + } else { + f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1; + } + } + } + return f[0][n - 1]; + } +}; \ No newline at end of file diff --git a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution3.go b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution3.go new file mode 100644 index 0000000000000..4cc5e2315b565 --- /dev/null +++ b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution3.go @@ -0,0 +1,18 @@ +func minInsertions(s string) int { + n := len(s) + f := make([][]int, n) + for i := range f { + f[i] = make([]int, n) + } + for k := 2; k <= n; k++ { + for i := 0; i+k-1 < n; i++ { + j := i + k - 1 + if s[i] == s[j] { + f[i][j] = f[i+1][j-1] + } else { + f[i][j] = min(f[i+1][j], f[i][j-1]) + 1 + } + } + } + return f[0][n-1] +} \ No newline at end of file diff --git a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution3.java b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution3.java new file mode 100644 index 0000000000000..f4a3d6cbc92d0 --- /dev/null +++ b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution3.java @@ -0,0 +1,17 @@ +class Solution { + public int minInsertions(String s) { + int n = s.length(); + int[][] f = new int[n][n]; + for (int k = 2; k <= n; ++k) { + for (int i = 0; i + k - 1 < n; ++i) { + int j = i + k - 1; + if (s.charAt(i) == s.charAt(j)) { + f[i][j] = f[i + 1][j - 1]; + } else { + f[i][j] = Math.min(f[i + 1][j], f[i][j - 1]) + 1; + } + } + } + return f[0][n - 1]; + } +} \ No newline at end of file diff --git a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution3.py b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution3.py new file mode 100644 index 0000000000000..3a07eb4646b01 --- /dev/null +++ b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution3.py @@ -0,0 +1,12 @@ +class Solution: + def minInsertions(self, s: str) -> int: + n = len(s) + f = [[0] * n for _ in range(n)] + for k in range(2, n + 1): + for i in range(n - k + 1): + j = i + k - 1 + if s[i] == s[j]: + f[i][j] = f[i + 1][j - 1] + else: + f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1 + return f[0][n - 1] diff --git a/solution/1300-1399/1313.Decompress Run-Length Encoded List/Solution.c b/solution/1300-1399/1313.Decompress Run-Length Encoded List/Solution.c index 724f1dd0e3235..7e0d38c1cd1ab 100644 --- a/solution/1300-1399/1313.Decompress Run-Length Encoded List/Solution.c +++ b/solution/1300-1399/1313.Decompress Run-Length Encoded List/Solution.c @@ -14,4 +14,4 @@ int* decompressRLElist(int* nums, int numsSize, int* returnSize) { } *returnSize = size; return ans; -} +} \ No newline at end of file diff --git a/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/Solution2.cpp b/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/Solution2.cpp new file mode 100644 index 0000000000000..1d4ce017ffb1f --- /dev/null +++ b/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + vector getNoZeroIntegers(int n) { + auto f = [](int x) { + for (; x; x /= 10) { + if (x % 10 == 0) { + return false; + } + } + return true; + }; + for (int a = 1;; ++a) { + int b = n - a; + if (f(a) && f(b)) { + return {a, b}; + } + } + } +}; \ No newline at end of file diff --git a/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/Solution2.go b/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/Solution2.go new file mode 100644 index 0000000000000..25efb125aefe0 --- /dev/null +++ b/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/Solution2.go @@ -0,0 +1,16 @@ +func getNoZeroIntegers(n int) []int { + f := func(x int) bool { + for ; x > 0; x /= 10 { + if x%10 == 0 { + return false + } + } + return true + } + for a := 1; ; a++ { + b := n - a + if f(a) && f(b) { + return []int{a, b} + } + } +} \ No newline at end of file diff --git a/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/Solution2.java b/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/Solution2.java new file mode 100644 index 0000000000000..4311ad68966b6 --- /dev/null +++ b/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/Solution2.java @@ -0,0 +1,19 @@ +class Solution { + public int[] getNoZeroIntegers(int n) { + for (int a = 1;; ++a) { + int b = n - a; + if (f(a) && f(b)) { + return new int[] {a, b}; + } + } + } + + private boolean f(int x) { + for (; x > 0; x /= 10) { + if (x % 10 == 0) { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/Solution2.py b/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/Solution2.py new file mode 100644 index 0000000000000..0cb73e647f401 --- /dev/null +++ b/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def getNoZeroIntegers(self, n: int) -> List[int]: + def f(x): + while x: + if x % 10 == 0: + return False + x //= 10 + return True + + for a in range(1, n): + b = n - a + if f(a) and f(b): + return [a, b] diff --git a/solution/1300-1399/1319.Number of Operations to Make Network Connected/Solution.py b/solution/1300-1399/1319.Number of Operations to Make Network Connected/Solution.py index 7b281058c7fb8..15f7562a9a2dc 100644 --- a/solution/1300-1399/1319.Number of Operations to Make Network Connected/Solution.py +++ b/solution/1300-1399/1319.Number of Operations to Make Network Connected/Solution.py @@ -5,12 +5,12 @@ def find(x): p[x] = find(p[x]) return p[x] - cnt = 0 + cnt, size = 0, n p = list(range(n)) for a, b in connections: if find(a) == find(b): cnt += 1 else: p[find(a)] = find(b) - n -= 1 - return -1 if n - 1 > cnt else n - 1 + size -= 1 + return -1 if size - 1 > cnt else size - 1 diff --git a/solution/1300-1399/1321.Restaurant Growth/Solution2.sql b/solution/1300-1399/1321.Restaurant Growth/Solution2.sql new file mode 100644 index 0000000000000..0c8a121e8782f --- /dev/null +++ b/solution/1300-1399/1321.Restaurant Growth/Solution2.sql @@ -0,0 +1,11 @@ +# Write your MySQL query statement below +SELECT + a.visited_on, + SUM(b.amount) AS amount, + ROUND(SUM(b.amount) / 7, 2) AS average_amount +FROM + (SELECT DISTINCT visited_on FROM customer) AS a + JOIN customer AS b ON DATEDIFF(a.visited_on, b.visited_on) BETWEEN 0 AND 6 +WHERE a.visited_on >= (SELECT MIN(visited_on) FROM customer) + 6 +GROUP BY 1 +ORDER BY 1; diff --git a/solution/1300-1399/1322.Ads Performance/Solution.sql b/solution/1300-1399/1322.Ads Performance/Solution.sql index e475f053f6066..501f37e97c5f0 100644 --- a/solution/1300-1399/1322.Ads Performance/Solution.sql +++ b/solution/1300-1399/1322.Ads Performance/Solution.sql @@ -1,4 +1,3 @@ -# Write your MySQL query statement below SELECT ad_id, ROUND(IFNULL(SUM(action = 'Clicked') / SUM(action IN ('Clicked', 'Viewed')) * 100, 0), 2) AS ctr diff --git a/solution/1300-1399/1323.Maximum 69 Number/Solution.c b/solution/1300-1399/1323.Maximum 69 Number/Solution.c index d4682ee1b345c..943cd0198b029 100644 --- a/solution/1300-1399/1323.Maximum 69 Number/Solution.c +++ b/solution/1300-1399/1323.Maximum 69 Number/Solution.c @@ -10,4 +10,4 @@ int maximum69Number(int num) { t /= 10; } return num + 3 * pow(10, i - 1); -} +} \ No newline at end of file diff --git a/solution/1300-1399/1323.Maximum 69 Number/Solution.php b/solution/1300-1399/1323.Maximum 69 Number/Solution.php index 1917600962649..e02dcb22c922f 100644 --- a/solution/1300-1399/1323.Maximum 69 Number/Solution.php +++ b/solution/1300-1399/1323.Maximum 69 Number/Solution.php @@ -9,4 +9,4 @@ function maximum69Number($num) { $num[$n] = 9; return intval($num); } -} \ No newline at end of file +} diff --git a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.cpp b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.cpp index e906580688985..8c5fc075d8b06 100644 --- a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.cpp +++ b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.cpp @@ -1,28 +1,40 @@ -class Solution { -public: - int findTheCity(int n, vector>& edges, int distanceThreshold) { - int g[n][n]; - memset(g, 0x3f, sizeof(g)); - for (auto& e : edges) { - int f = e[0], t = e[1], w = e[2]; - g[f][t] = g[t][f] = w; - } - for (int k = 0; k < n; ++k) { - g[k][k] = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - g[i][j] = min(g[i][j], g[i][k] + g[k][j]); - } - } - } - int ans = n, cnt = n + 1; - for (int i = n - 1; ~i; --i) { - int t = count_if(g[i], g[i] + n, [&](int x) { return x <= distanceThreshold; }); - if (t < cnt) { - cnt = t; - ans = i; - } - } - return ans; - } +class Solution { +public: + int findTheCity(int n, vector>& edges, int distanceThreshold) { + int g[n][n]; + int dist[n]; + bool vis[n]; + memset(g, 0x3f, sizeof(g)); + for (auto& e : edges) { + int f = e[0], t = e[1], w = e[2]; + g[f][t] = g[t][f] = w; + } + auto dijkstra = [&](int u) { + memset(dist, 0x3f, sizeof(dist)); + memset(vis, 0, sizeof(vis)); + dist[u] = 0; + for (int i = 0; i < n; ++i) { + int k = -1; + for (int j = 0; j < n; ++j) { + if (!vis[j] && (k == -1 || dist[j] < dist[k])) { + k = j; + } + } + vis[k] = true; + for (int j = 0; j < n; ++j) { + dist[j] = min(dist[j], dist[k] + g[k][j]); + } + } + return count_if(dist, dist + n, [&](int d) { return d <= distanceThreshold; }); + }; + int ans = n, cnt = n + 1; + for (int i = n - 1; ~i; --i) { + int t = dijkstra(i); + if (t < cnt) { + cnt = t; + ans = i; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.go b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.go index 6ed6f0b5fb6e8..e8a6b84252429 100644 --- a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.go +++ b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.go @@ -1,5 +1,7 @@ func findTheCity(n int, edges [][]int, distanceThreshold int) int { g := make([][]int, n) + dist := make([]int, n) + vis := make([]bool, n) const inf int = 1e7 for i := range g { g[i] = make([]int, n) @@ -7,33 +9,43 @@ func findTheCity(n int, edges [][]int, distanceThreshold int) int { g[i][j] = inf } } - for _, e := range edges { f, t, w := e[0], e[1], e[2] g[f][t], g[t][f] = w, w } - for k := 0; k < n; k++ { - g[k][k] = 0 + dijkstra := func(u int) (cnt int) { + for i := range vis { + vis[i] = false + dist[i] = inf + } + dist[u] = 0 for i := 0; i < n; i++ { + k := -1 for j := 0; j < n; j++ { - g[i][j] = min(g[i][j], g[i][k]+g[k][j]) + if !vis[j] && (k == -1 || dist[j] < dist[k]) { + k = j + } + } + vis[k] = true + for j := 0; j < n; j++ { + dist[j] = min(dist[j], dist[k]+g[k][j]) } } + for _, d := range dist { + if d <= distanceThreshold { + cnt++ + } + } + return } - ans, cnt := n, n+1 + ans, cnt := n, inf for i := n - 1; i >= 0; i-- { - t := 0 - for _, x := range g[i] { - if x <= distanceThreshold { - t++ - } - } - if t < cnt { - cnt, ans = t, i + if t := dijkstra(i); t < cnt { + cnt = t + ans = i } } - return ans } \ No newline at end of file diff --git a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.java b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.java index eb14f88e7388a..bd5590a9f9743 100644 --- a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.java +++ b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.java @@ -1,36 +1,58 @@ -class Solution { - public int findTheCity(int n, int[][] edges, int distanceThreshold) { - final int inf = 1 << 29; - int[][] g = new int[n][n]; - for (var e : g) { - Arrays.fill(e, inf); - } - for (var e : edges) { - int f = e[0], t = e[1], w = e[2]; - g[f][t] = w; - g[t][f] = w; - } - for (int k = 0; k < n; ++k) { - g[k][k] = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); - } - } - } - int ans = n, cnt = inf; - for (int i = n - 1; i >= 0; --i) { - int t = 0; - for (int d : g[i]) { - if (d <= distanceThreshold) { - ++t; - } - } - if (t < cnt) { - cnt = t; - ans = i; - } - } - return ans; - } +class Solution { + private int n; + private int[][] g; + private int[] dist; + private boolean[] vis; + private final int inf = 1 << 30; + private int distanceThreshold; + + public int findTheCity(int n, int[][] edges, int distanceThreshold) { + this.n = n; + this.distanceThreshold = distanceThreshold; + g = new int[n][n]; + dist = new int[n]; + vis = new boolean[n]; + for (var e : g) { + Arrays.fill(e, inf); + } + for (var e : edges) { + int f = e[0], t = e[1], w = e[2]; + g[f][t] = w; + g[t][f] = w; + } + int ans = n, cnt = inf; + for (int i = n - 1; i >= 0; --i) { + int t = dijkstra(i); + if (t < cnt) { + cnt = t; + ans = i; + } + } + return ans; + } + + private int dijkstra(int u) { + Arrays.fill(dist, inf); + Arrays.fill(vis, false); + dist[u] = 0; + for (int i = 0; i < n; ++i) { + int k = -1; + for (int j = 0; j < n; ++j) { + if (!vis[j] && (k == -1 || dist[k] > dist[j])) { + k = j; + } + } + vis[k] = true; + for (int j = 0; j < n; ++j) { + dist[j] = Math.min(dist[j], dist[k] + g[k][j]); + } + } + int cnt = 0; + for (int d : dist) { + if (d <= distanceThreshold) { + ++cnt; + } + } + return cnt; + } } \ No newline at end of file diff --git a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.py b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.py index d0a78185a08f2..d285944365b6d 100644 --- a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.py +++ b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.py @@ -1,22 +1,28 @@ -class Solution: - def findTheCity( - self, n: int, edges: List[List[int]], distanceThreshold: int - ) -> int: - g = [[inf] * n for _ in range(n)] - for f, t, w in edges: - g[f][t] = g[t][f] = w - - for k in range(n): - g[k][k] = 0 - for i in range(n): - for j in range(n): - # g[i][j] = min(g[i][j], g[i][k] + g[k][j]) - if g[i][k] + g[k][j] < g[i][j]: - g[i][j] = g[i][k] + g[k][j] - - ans, cnt = n, inf - for i in range(n - 1, -1, -1): - t = sum(d <= distanceThreshold for d in g[i]) - if t < cnt: - cnt, ans = t, i - return ans +class Solution: + def findTheCity( + self, n: int, edges: List[List[int]], distanceThreshold: int + ) -> int: + def dijkstra(u: int) -> int: + dist = [inf] * n + dist[u] = 0 + vis = [False] * n + for _ in range(n): + k = -1 + for j in range(n): + if not vis[j] and (k == -1 or dist[k] > dist[j]): + k = j + vis[k] = True + for j in range(n): + # dist[j] = min(dist[j], dist[k] + g[k][j]) + if dist[k] + g[k][j] < dist[j]: + dist[j] = dist[k] + g[k][j] + return sum(d <= distanceThreshold for d in dist) + + g = [[inf] * n for _ in range(n)] + for f, t, w in edges: + g[f][t] = g[t][f] = w + ans, cnt = n, inf + for i in range(n - 1, -1, -1): + if (t := dijkstra(i)) < cnt: + cnt, ans = t, i + return ans diff --git a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.ts b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.ts index 20028a2e9c42e..9609cedfc2621 100644 --- a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.ts +++ b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.ts @@ -1,25 +1,39 @@ function findTheCity(n: number, edges: number[][], distanceThreshold: number): number { const g: number[][] = Array.from({ length: n }, () => Array(n).fill(Infinity)); + const dist: number[] = Array(n).fill(Infinity); + const vis: boolean[] = Array(n).fill(false); for (const [f, t, w] of edges) { g[f][t] = g[t][f] = w; } - for (let k = 0; k < n; ++k) { - g[k][k] = 0; + + const dijkstra = (u: number): number => { + dist.fill(Infinity); + vis.fill(false); + dist[u] = 0; for (let i = 0; i < n; ++i) { + let k = -1; + for (let j = 0; j < n; ++j) { + if (!vis[j] && (k === -1 || dist[j] < dist[k])) { + k = j; + } + } + vis[k] = true; for (let j = 0; j < n; ++j) { - g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); + dist[j] = Math.min(dist[j], dist[k] + g[k][j]); } } - } + return dist.filter(d => d <= distanceThreshold).length; + }; - let ans = n, - cnt = n + 1; + let ans = n; + let cnt = Infinity; for (let i = n - 1; i >= 0; --i) { - const t = g[i].filter(x => x <= distanceThreshold).length; + const t = dijkstra(i); if (t < cnt) { cnt = t; ans = i; } } + return ans; } diff --git a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution2.cpp b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution2.cpp new file mode 100644 index 0000000000000..83ba4579a5c46 --- /dev/null +++ b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution2.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int findTheCity(int n, vector>& edges, int distanceThreshold) { + int g[n][n]; + memset(g, 0x3f, sizeof(g)); + for (auto& e : edges) { + int f = e[0], t = e[1], w = e[2]; + g[f][t] = g[t][f] = w; + } + for (int k = 0; k < n; ++k) { + g[k][k] = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + g[i][j] = min(g[i][j], g[i][k] + g[k][j]); + } + } + } + int ans = n, cnt = n + 1; + for (int i = n - 1; ~i; --i) { + int t = count_if(g[i], g[i] + n, [&](int x) { return x <= distanceThreshold; }); + if (t < cnt) { + cnt = t; + ans = i; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution2.go b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution2.go new file mode 100644 index 0000000000000..6ed6f0b5fb6e8 --- /dev/null +++ b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution2.go @@ -0,0 +1,39 @@ +func findTheCity(n int, edges [][]int, distanceThreshold int) int { + g := make([][]int, n) + const inf int = 1e7 + for i := range g { + g[i] = make([]int, n) + for j := range g[i] { + g[i][j] = inf + } + } + + for _, e := range edges { + f, t, w := e[0], e[1], e[2] + g[f][t], g[t][f] = w, w + } + + for k := 0; k < n; k++ { + g[k][k] = 0 + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + g[i][j] = min(g[i][j], g[i][k]+g[k][j]) + } + } + } + + ans, cnt := n, n+1 + for i := n - 1; i >= 0; i-- { + t := 0 + for _, x := range g[i] { + if x <= distanceThreshold { + t++ + } + } + if t < cnt { + cnt, ans = t, i + } + } + + return ans +} \ No newline at end of file diff --git a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution2.java b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution2.java new file mode 100644 index 0000000000000..d1d38000b5201 --- /dev/null +++ b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution2.java @@ -0,0 +1,36 @@ +class Solution { + public int findTheCity(int n, int[][] edges, int distanceThreshold) { + final int inf = 1 << 29; + int[][] g = new int[n][n]; + for (var e : g) { + Arrays.fill(e, inf); + } + for (var e : edges) { + int f = e[0], t = e[1], w = e[2]; + g[f][t] = w; + g[t][f] = w; + } + for (int k = 0; k < n; ++k) { + g[k][k] = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); + } + } + } + int ans = n, cnt = inf; + for (int i = n - 1; i >= 0; --i) { + int t = 0; + for (int d : g[i]) { + if (d <= distanceThreshold) { + ++t; + } + } + if (t < cnt) { + cnt = t; + ans = i; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution2.py b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution2.py new file mode 100644 index 0000000000000..ebc238883de5b --- /dev/null +++ b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution2.py @@ -0,0 +1,22 @@ +class Solution: + def findTheCity( + self, n: int, edges: List[List[int]], distanceThreshold: int + ) -> int: + g = [[inf] * n for _ in range(n)] + for f, t, w in edges: + g[f][t] = g[t][f] = w + + for k in range(n): + g[k][k] = 0 + for i in range(n): + for j in range(n): + # g[i][j] = min(g[i][j], g[i][k] + g[k][j]) + if g[i][k] + g[k][j] < g[i][j]: + g[i][j] = g[i][k] + g[k][j] + + ans, cnt = n, inf + for i in range(n - 1, -1, -1): + t = sum(d <= distanceThreshold for d in g[i]) + if t < cnt: + cnt, ans = t, i + return ans diff --git a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution2.ts b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution2.ts new file mode 100644 index 0000000000000..20028a2e9c42e --- /dev/null +++ b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution2.ts @@ -0,0 +1,25 @@ +function findTheCity(n: number, edges: number[][], distanceThreshold: number): number { + const g: number[][] = Array.from({ length: n }, () => Array(n).fill(Infinity)); + for (const [f, t, w] of edges) { + g[f][t] = g[t][f] = w; + } + for (let k = 0; k < n; ++k) { + g[k][k] = 0; + for (let i = 0; i < n; ++i) { + for (let j = 0; j < n; ++j) { + g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); + } + } + } + + let ans = n, + cnt = n + 1; + for (let i = n - 1; i >= 0; --i) { + const t = g[i].filter(x => x <= distanceThreshold).length; + if (t < cnt) { + cnt = t; + ans = i; + } + } + return ans; +} diff --git a/solution/1300-1399/1337.The K Weakest Rows in a Matrix/Solution.cpp b/solution/1300-1399/1337.The K Weakest Rows in a Matrix/Solution.cpp index 3364d07cdf923..0caf59667b237 100644 --- a/solution/1300-1399/1337.The K Weakest Rows in a Matrix/Solution.cpp +++ b/solution/1300-1399/1337.The K Weakest Rows in a Matrix/Solution.cpp @@ -26,4 +26,4 @@ class Solution { } return res; } -}; +}; \ No newline at end of file diff --git a/solution/1300-1399/1337.The K Weakest Rows in a Matrix/Solution.py b/solution/1300-1399/1337.The K Weakest Rows in a Matrix/Solution.py index 015968a3daba7..24ab90c0a5c98 100644 --- a/solution/1300-1399/1337.The K Weakest Rows in a Matrix/Solution.py +++ b/solution/1300-1399/1337.The K Weakest Rows in a Matrix/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: - m, n = len(mat), len(mat[0]) - ans = [n - bisect_right(row[::-1], 0) for row in mat] - idx = list(range(m)) - idx.sort(key=lambda i: ans[i]) - return idx[:k] +class Solution: + def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: + m, n = len(mat), len(mat[0]) + ans = [n - bisect_right(row[::-1], 0) for row in mat] + idx = list(range(m)) + idx.sort(key=lambda i: ans[i]) + return idx[:k] diff --git a/solution/1300-1399/1340.Jump Game V/Solution.cpp b/solution/1300-1399/1340.Jump Game V/Solution.cpp index 7c3d94deb58d5..f97edd4bc034f 100644 --- a/solution/1300-1399/1340.Jump Game V/Solution.cpp +++ b/solution/1300-1399/1340.Jump Game V/Solution.cpp @@ -2,24 +2,31 @@ class Solution { public: int maxJumps(vector& arr, int d) { int n = arr.size(); - vector idx(n); - iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) { return arr[i] < arr[j]; }); - vector f(n, 1); - for (int i : idx) { + int f[n]; + memset(f, 0, sizeof(f)); + function dfs = [&](int i) -> int { + if (f[i]) { + return f[i]; + } + int ans = 1; for (int j = i - 1; j >= 0; --j) { if (i - j > d || arr[j] >= arr[i]) { break; } - f[i] = max(f[i], 1 + f[j]); + ans = max(ans, 1 + dfs(j)); } for (int j = i + 1; j < n; ++j) { if (j - i > d || arr[j] >= arr[i]) { break; } - f[i] = max(f[i], 1 + f[j]); + ans = max(ans, 1 + dfs(j)); } + return f[i] = ans; + }; + int ans = 1; + for (int i = 0; i < n; ++i) { + ans = max(ans, dfs(i)); } - return *max_element(f.begin(), f.end()); + return ans; } }; \ No newline at end of file diff --git a/solution/1300-1399/1340.Jump Game V/Solution.go b/solution/1300-1399/1340.Jump Game V/Solution.go index 997eabf746d80..de318fd5a6ec4 100644 --- a/solution/1300-1399/1340.Jump Game V/Solution.go +++ b/solution/1300-1399/1340.Jump Game V/Solution.go @@ -1,25 +1,29 @@ -func maxJumps(arr []int, d int) int { +func maxJumps(arr []int, d int) (ans int) { n := len(arr) - idx := make([]int, n) f := make([]int, n) - for i := range f { - idx[i] = i - f[i] = 1 - } - sort.Slice(idx, func(i, j int) bool { return arr[idx[i]] < arr[idx[j]] }) - for _, i := range idx { + var dfs func(int) int + dfs = func(i int) int { + if f[i] != 0 { + return f[i] + } + ans := 1 for j := i - 1; j >= 0; j-- { if i-j > d || arr[j] >= arr[i] { break } - f[i] = max(f[i], 1+f[j]) + ans = max(ans, 1+dfs(j)) } for j := i + 1; j < n; j++ { if j-i > d || arr[j] >= arr[i] { break } - f[i] = max(f[i], 1+f[j]) + ans = max(ans, 1+dfs(j)) } + f[i] = ans + return ans + } + for i := 0; i < n; i++ { + ans = max(ans, dfs(i)) } - return slices.Max(f) + return } \ No newline at end of file diff --git a/solution/1300-1399/1340.Jump Game V/Solution.java b/solution/1300-1399/1340.Jump Game V/Solution.java index 7eadbd4bb0a0a..61e9c375df8ab 100644 --- a/solution/1300-1399/1340.Jump Game V/Solution.java +++ b/solution/1300-1399/1340.Jump Game V/Solution.java @@ -1,29 +1,38 @@ class Solution { + private int n; + private int d; + private int[] arr; + private Integer[] f; + public int maxJumps(int[] arr, int d) { - int n = arr.length; - Integer[] idx = new Integer[n]; + n = arr.length; + this.d = d; + this.arr = arr; + f = new Integer[n]; + int ans = 1; for (int i = 0; i < n; ++i) { - idx[i] = i; + ans = Math.max(ans, dfs(i)); } - Arrays.sort(idx, (i, j) -> arr[i] - arr[j]); - int[] f = new int[n]; - Arrays.fill(f, 1); - int ans = 0; - for (int i : idx) { - for (int j = i - 1; j >= 0; --j) { - if (i - j > d || arr[j] >= arr[i]) { - break; - } - f[i] = Math.max(f[i], 1 + f[j]); + return ans; + } + + private int dfs(int i) { + if (f[i] != null) { + return f[i]; + } + int ans = 1; + for (int j = i - 1; j >= 0; --j) { + if (i - j > d || arr[j] >= arr[i]) { + break; } - for (int j = i + 1; j < n; ++j) { - if (j - i > d || arr[j] >= arr[i]) { - break; - } - f[i] = Math.max(f[i], 1 + f[j]); + ans = Math.max(ans, 1 + dfs(j)); + } + for (int j = i + 1; j < n; ++j) { + if (j - i > d || arr[j] >= arr[i]) { + break; } - ans = Math.max(ans, f[i]); + ans = Math.max(ans, 1 + dfs(j)); } - return ans; + return f[i] = ans; } } \ No newline at end of file diff --git a/solution/1300-1399/1340.Jump Game V/Solution.py b/solution/1300-1399/1340.Jump Game V/Solution.py index d9cf96bc19559..61db55067b4ec 100644 --- a/solution/1300-1399/1340.Jump Game V/Solution.py +++ b/solution/1300-1399/1340.Jump Game V/Solution.py @@ -1,14 +1,17 @@ class Solution: def maxJumps(self, arr: List[int], d: int) -> int: - n = len(arr) - f = [1] * n - for x, i in sorted(zip(arr, range(n))): + @cache + def dfs(i): + ans = 1 for j in range(i - 1, -1, -1): - if i - j > d or arr[j] >= x: + if i - j > d or arr[j] >= arr[i]: break - f[i] = max(f[i], 1 + f[j]) + ans = max(ans, 1 + dfs(j)) for j in range(i + 1, n): - if j - i > d or arr[j] >= x: + if j - i > d or arr[j] >= arr[i]: break - f[i] = max(f[i], 1 + f[j]) - return max(f) + ans = max(ans, 1 + dfs(j)) + return ans + + n = len(arr) + return max(dfs(i) for i in range(n)) diff --git a/solution/1300-1399/1340.Jump Game V/Solution2.cpp b/solution/1300-1399/1340.Jump Game V/Solution2.cpp new file mode 100644 index 0000000000000..7c3d94deb58d5 --- /dev/null +++ b/solution/1300-1399/1340.Jump Game V/Solution2.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int maxJumps(vector& arr, int d) { + int n = arr.size(); + vector idx(n); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { return arr[i] < arr[j]; }); + vector f(n, 1); + for (int i : idx) { + for (int j = i - 1; j >= 0; --j) { + if (i - j > d || arr[j] >= arr[i]) { + break; + } + f[i] = max(f[i], 1 + f[j]); + } + for (int j = i + 1; j < n; ++j) { + if (j - i > d || arr[j] >= arr[i]) { + break; + } + f[i] = max(f[i], 1 + f[j]); + } + } + return *max_element(f.begin(), f.end()); + } +}; \ No newline at end of file diff --git a/solution/1300-1399/1340.Jump Game V/Solution2.go b/solution/1300-1399/1340.Jump Game V/Solution2.go new file mode 100644 index 0000000000000..997eabf746d80 --- /dev/null +++ b/solution/1300-1399/1340.Jump Game V/Solution2.go @@ -0,0 +1,25 @@ +func maxJumps(arr []int, d int) int { + n := len(arr) + idx := make([]int, n) + f := make([]int, n) + for i := range f { + idx[i] = i + f[i] = 1 + } + sort.Slice(idx, func(i, j int) bool { return arr[idx[i]] < arr[idx[j]] }) + for _, i := range idx { + for j := i - 1; j >= 0; j-- { + if i-j > d || arr[j] >= arr[i] { + break + } + f[i] = max(f[i], 1+f[j]) + } + for j := i + 1; j < n; j++ { + if j-i > d || arr[j] >= arr[i] { + break + } + f[i] = max(f[i], 1+f[j]) + } + } + return slices.Max(f) +} \ No newline at end of file diff --git a/solution/1300-1399/1340.Jump Game V/Solution2.java b/solution/1300-1399/1340.Jump Game V/Solution2.java new file mode 100644 index 0000000000000..7eadbd4bb0a0a --- /dev/null +++ b/solution/1300-1399/1340.Jump Game V/Solution2.java @@ -0,0 +1,29 @@ +class Solution { + public int maxJumps(int[] arr, int d) { + int n = arr.length; + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; ++i) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> arr[i] - arr[j]); + int[] f = new int[n]; + Arrays.fill(f, 1); + int ans = 0; + for (int i : idx) { + for (int j = i - 1; j >= 0; --j) { + if (i - j > d || arr[j] >= arr[i]) { + break; + } + f[i] = Math.max(f[i], 1 + f[j]); + } + for (int j = i + 1; j < n; ++j) { + if (j - i > d || arr[j] >= arr[i]) { + break; + } + f[i] = Math.max(f[i], 1 + f[j]); + } + ans = Math.max(ans, f[i]); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1300-1399/1340.Jump Game V/Solution2.py b/solution/1300-1399/1340.Jump Game V/Solution2.py new file mode 100644 index 0000000000000..d9cf96bc19559 --- /dev/null +++ b/solution/1300-1399/1340.Jump Game V/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def maxJumps(self, arr: List[int], d: int) -> int: + n = len(arr) + f = [1] * n + for x, i in sorted(zip(arr, range(n))): + for j in range(i - 1, -1, -1): + if i - j > d or arr[j] >= x: + break + f[i] = max(f[i], 1 + f[j]) + for j in range(i + 1, n): + if j - i > d or arr[j] >= x: + break + f[i] = max(f[i], 1 + f[j]) + return max(f) diff --git a/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution.java b/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution.java index 0cec56c1b2571..87436e08b8495 100644 --- a/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution.java +++ b/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution.java @@ -1,4 +1,5 @@ class Solution { + public int numberOfSteps(int num) { int ans = 0; while (num != 0) { diff --git a/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution2.cpp b/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution2.cpp new file mode 100644 index 0000000000000..92ccc422aee98 --- /dev/null +++ b/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution2.cpp @@ -0,0 +1,7 @@ +class Solution { +public: + int numberOfSteps(int num) { + if (num == 0) return 0; + return 1 + (num & 1 ? numberOfSteps(num - 1) : numberOfSteps(num >> 1)); + } +}; \ No newline at end of file diff --git a/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution2.go b/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution2.go new file mode 100644 index 0000000000000..1049c54a7ee97 --- /dev/null +++ b/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution2.go @@ -0,0 +1,9 @@ +func numberOfSteps(num int) int { + if num == 0 { + return 0 + } + if (num & 1) == 0 { + return 1 + numberOfSteps(num>>1) + } + return 1 + numberOfSteps(num-1) +} \ No newline at end of file diff --git a/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution2.java b/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution2.java new file mode 100644 index 0000000000000..317450c1b5ee7 --- /dev/null +++ b/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution2.java @@ -0,0 +1,9 @@ +class Solution { + + public int numberOfSteps(int num) { + if (num == 0) { + return 0; + } + return 1 + numberOfSteps((num & 1) == 0 ? num >> 1 : num - 1); + } +} \ No newline at end of file diff --git a/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution2.py b/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution2.py new file mode 100644 index 0000000000000..7be25490023c1 --- /dev/null +++ b/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def numberOfSteps(self, num: int) -> int: + if num == 0: + return 0 + return 1 + ( + self.numberOfSteps(num // 2) + if num % 2 == 0 + else self.numberOfSteps(num - 1) + ) diff --git a/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution2.rs b/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution2.rs new file mode 100644 index 0000000000000..8b3f9cad20d18 --- /dev/null +++ b/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution2.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn number_of_steps(mut num: i32) -> i32 { + if num == 0 { + 0 + } else if num % 2 == 0 { + 1 + Solution::number_of_steps(num >> 1) + } else { + 1 + Solution::number_of_steps(num - 1) + } + } +} diff --git a/solution/1300-1399/1344.Angle Between Hands of a Clock/Solution.cpp b/solution/1300-1399/1344.Angle Between Hands of a Clock/Solution.cpp index 75d6b0733bcdf..9a182891a6b4c 100644 --- a/solution/1300-1399/1344.Angle Between Hands of a Clock/Solution.cpp +++ b/solution/1300-1399/1344.Angle Between Hands of a Clock/Solution.cpp @@ -1,9 +1,9 @@ -class Solution { -public: - double angleClock(int hour, int minutes) { - double h = 30 * hour + 0.5 * minutes; - double m = 6 * minutes; - double diff = abs(h - m); - return min(diff, 360 - diff); - } +class Solution { +public: + double angleClock(int hour, int minutes) { + double h = 30 * hour + 0.5 * minutes; + double m = 6 * minutes; + double diff = abs(h - m); + return min(diff, 360 - diff); + } }; \ No newline at end of file diff --git a/solution/1300-1399/1344.Angle Between Hands of a Clock/Solution.java b/solution/1300-1399/1344.Angle Between Hands of a Clock/Solution.java index 47df9da33fc49..1cad3fdd81335 100644 --- a/solution/1300-1399/1344.Angle Between Hands of a Clock/Solution.java +++ b/solution/1300-1399/1344.Angle Between Hands of a Clock/Solution.java @@ -1,8 +1,8 @@ -class Solution { - public double angleClock(int hour, int minutes) { - double h = 30 * hour + 0.5 * minutes; - double m = 6 * minutes; - double diff = Math.abs(h - m); - return Math.min(diff, 360 - diff); - } +class Solution { + public double angleClock(int hour, int minutes) { + double h = 30 * hour + 0.5 * minutes; + double m = 6 * minutes; + double diff = Math.abs(h - m); + return Math.min(diff, 360 - diff); + } } \ No newline at end of file diff --git a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.cpp b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.cpp index 4a369b948dd41..7dd0d22ff81f4 100644 --- a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.cpp +++ b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.cpp @@ -1,12 +1,12 @@ -class Solution { -public: - bool checkIfExist(vector& arr) { - unordered_map m; - int n = arr.size(); - for (int i = 0; i < n; ++i) m[arr[i]] = i; - for (int i = 0; i < n; ++i) - if (m.count(arr[i] * 2) && m[arr[i] * 2] != i) - return true; - return false; - } +class Solution { +public: + bool checkIfExist(vector& arr) { + unordered_map m; + int n = arr.size(); + for (int i = 0; i < n; ++i) m[arr[i]] = i; + for (int i = 0; i < n; ++i) + if (m.count(arr[i] * 2) && m[arr[i] * 2] != i) + return true; + return false; + } }; \ No newline at end of file diff --git a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.java b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.java index aef020c0e6056..aea6b9b0474c0 100644 --- a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.java +++ b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public boolean checkIfExist(int[] arr) { - Map m = new HashMap<>(); - int n = arr.length; - for (int i = 0; i < n; ++i) { - m.put(arr[i], i); - } - for (int i = 0; i < n; ++i) { - if (m.containsKey(arr[i] << 1) && m.get(arr[i] << 1) != i) { - return true; - } - } - return false; - } +class Solution { + public boolean checkIfExist(int[] arr) { + Map m = new HashMap<>(); + int n = arr.length; + for (int i = 0; i < n; ++i) { + m.put(arr[i], i); + } + for (int i = 0; i < n; ++i) { + if (m.containsKey(arr[i] << 1) && m.get(arr[i] << 1) != i) { + return true; + } + } + return false; + } } \ No newline at end of file diff --git a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.php b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.php index a698850189089..369acca9efdf0 100644 --- a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.php +++ b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.php @@ -14,4 +14,4 @@ function checkIfExist($arr) { } return false; } -} \ No newline at end of file +} diff --git a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.py b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.py index 8770be85309d8..eb09884e959bd 100644 --- a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.py +++ b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.py @@ -1,4 +1,4 @@ -class Solution: - def checkIfExist(self, arr: List[int]) -> bool: - m = {v: i for i, v in enumerate(arr)} - return any(v << 1 in m and m[v << 1] != i for i, v in enumerate(arr)) +class Solution: + def checkIfExist(self, arr: List[int]) -> bool: + m = {v: i for i, v in enumerate(arr)} + return any(v << 1 in m and m[v << 1] != i for i, v in enumerate(arr)) diff --git a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.rs b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.rs index baed199d57ef1..3a9aef2c3a9e3 100644 --- a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.rs +++ b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution.rs @@ -1,28 +1,13 @@ -use std::cmp::Ordering; +use std::collections::HashMap; impl Solution { - pub fn check_if_exist(mut arr: Vec) -> bool { - arr.sort(); - let n = arr.len(); - for i in 0..n { - let target = arr[i] * 2; - let mut left = 0; - let mut right = n; - while left < right { - let mid = left + (right - left) / 2; - match arr[mid].cmp(&target) { - Ordering::Less => { - left = mid + 1; - } - Ordering::Greater => { - right = mid; - } - Ordering::Equal => { - if mid == i { - break; - } - return true; - } - } + pub fn check_if_exist(arr: Vec) -> bool { + let mut map = HashMap::new(); + for (i, v) in arr.iter().enumerate() { + map.insert(v, i); + } + for (i, v) in arr.iter().enumerate() { + if map.contains_key(&(v * 2)) && map[&(v * 2)] != i { + return true; } } false diff --git a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.cpp b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.cpp new file mode 100644 index 0000000000000..15af83adc1144 --- /dev/null +++ b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + bool checkIfExist(vector& arr) { + unordered_set s; + for (int& v : arr) { + if (s.count(v * 2) || (v % 2 == 0 && s.count(v / 2))) { + return true; + } + s.insert(v); + } + return false; + } +}; \ No newline at end of file diff --git a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.go b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.go new file mode 100644 index 0000000000000..b728be64838a0 --- /dev/null +++ b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.go @@ -0,0 +1,10 @@ +func checkIfExist(arr []int) bool { + s := map[int]bool{} + for _, v := range arr { + if s[v*2] || (v%2 == 0 && s[v/2]) { + return true + } + s[v] = true + } + return false +} \ No newline at end of file diff --git a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.java b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.java new file mode 100644 index 0000000000000..b812b2ce9bcc9 --- /dev/null +++ b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.java @@ -0,0 +1,12 @@ +class Solution { + public boolean checkIfExist(int[] arr) { + Set s = new HashSet<>(); + for (int v : arr) { + if (s.contains(v * 2) || (v % 2 == 0 && s.contains(v / 2))) { + return true; + } + s.add(v); + } + return false; + } +} \ No newline at end of file diff --git a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.js b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.js new file mode 100644 index 0000000000000..58964a99a2a9f --- /dev/null +++ b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.js @@ -0,0 +1,35 @@ +/** + * @param {number[]} arr + * @return {boolean} + */ +var checkIfExist = function (arr) { + let cnt = 0; + for (const v of arr) { + if (v == 0) { + ++cnt; + if (cnt > 1) { + return true; + } + } + } + const n = arr.length; + arr.sort((a, b) => a - b); + for (const v of arr) { + if (v != 0) { + let left = 0, + right = n; + while (left < right) { + const mid = (left + right) >> 1; + if (arr[mid] >= v * 2) { + right = mid; + } else { + left = mid + 1; + } + } + if (left != n && arr[left] == v * 2) { + return true; + } + } + } + return false; +}; diff --git a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.py b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.py new file mode 100644 index 0000000000000..815f8a94231cb --- /dev/null +++ b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def checkIfExist(self, arr: List[int]) -> bool: + s = set() + for v in arr: + if v * 2 in s or (v % 2 == 0 and v // 2 in s): + return True + s.add(v) + return False diff --git a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.rs b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.rs new file mode 100644 index 0000000000000..baed199d57ef1 --- /dev/null +++ b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.rs @@ -0,0 +1,30 @@ +use std::cmp::Ordering; +impl Solution { + pub fn check_if_exist(mut arr: Vec) -> bool { + arr.sort(); + let n = arr.len(); + for i in 0..n { + let target = arr[i] * 2; + let mut left = 0; + let mut right = n; + while left < right { + let mid = left + (right - left) / 2; + match arr[mid].cmp(&target) { + Ordering::Less => { + left = mid + 1; + } + Ordering::Greater => { + right = mid; + } + Ordering::Equal => { + if mid == i { + break; + } + return true; + } + } + } + } + false + } +} diff --git a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.ts b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.ts new file mode 100644 index 0000000000000..709120eaba0e7 --- /dev/null +++ b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution2.ts @@ -0,0 +1,31 @@ +function checkIfExist(arr: number[]): boolean { + let cnt = 0; + for (const v of arr) { + if (v == 0) { + ++cnt; + if (cnt > 1) { + return true; + } + } + } + const n = arr.length; + arr.sort((a, b) => a - b); + for (const v of arr) { + if (v != 0) { + let left = 0, + right = n; + while (left < right) { + const mid = (left + right) >> 1; + if (arr[mid] >= v * 2) { + right = mid; + } else { + left = mid + 1; + } + } + if (left != n && arr[left] == v * 2) { + return true; + } + } + } + return false; +} diff --git a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution3.cpp b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution3.cpp new file mode 100644 index 0000000000000..962b0965822d9 --- /dev/null +++ b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution3.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool checkIfExist(vector& arr) { + int cnt = 0; + for (int& v : arr) + if (v == 0) ++cnt; + if (cnt > 1) return true; + sort(arr.begin(), arr.end()); + int n = arr.size(); + for (int& v : arr) { + if (v == 0) continue; + int idx = lower_bound(arr.begin(), arr.end(), v * 2) - arr.begin(); + if (idx != n && arr[idx] == v * 2) return true; + } + return false; + } +}; \ No newline at end of file diff --git a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution3.go b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution3.go new file mode 100644 index 0000000000000..ea2b70c7bef65 --- /dev/null +++ b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution3.go @@ -0,0 +1,30 @@ +func checkIfExist(arr []int) bool { + cnt := 0 + for _, v := range arr { + if v == 0 { + cnt++ + if cnt > 1 { + return true + } + } + } + sort.Ints(arr) + n := len(arr) + for _, v := range arr { + if v != 0 { + left, right := 0, n + for left < right { + mid := (left + right) >> 1 + if arr[mid] >= v*2 { + right = mid + } else { + left = mid + 1 + } + } + if right != n && arr[left] == v*2 { + return true + } + } + } + return false +} \ No newline at end of file diff --git a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution3.java b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution3.java new file mode 100644 index 0000000000000..c059a6bc7f361 --- /dev/null +++ b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution3.java @@ -0,0 +1,23 @@ +class Solution { + public boolean checkIfExist(int[] arr) { + int cnt = 0; + for (int v : arr) { + if (v == 0) { + ++cnt; + if (cnt > 1) { + return true; + } + } + } + Arrays.sort(arr); + for (int v : arr) { + if (v != 0) { + int idx = Arrays.binarySearch(arr, v * 2); + if (idx >= 0) { + return true; + } + } + } + return false; + } +} \ No newline at end of file diff --git a/solution/1300-1399/1346.Check If N and Its Double Exist/Solution3.py b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution3.py new file mode 100644 index 0000000000000..4249762188514 --- /dev/null +++ b/solution/1300-1399/1346.Check If N and Its Double Exist/Solution3.py @@ -0,0 +1,11 @@ +class Solution: + def checkIfExist(self, arr: List[int]) -> bool: + if arr.count(0) > 1: + return True + arr.sort() + n = len(arr) + for v in arr: + idx = bisect_left(arr, v * 2) + if v != 0 and idx != n and arr[idx] == v * 2: + return True + return False diff --git a/solution/1300-1399/1350.Students With Invalid Departments/Solution.sql b/solution/1300-1399/1350.Students With Invalid Departments/Solution.sql index f51003ad5a39b..8d1f500bbfc4b 100644 --- a/solution/1300-1399/1350.Students With Invalid Departments/Solution.sql +++ b/solution/1300-1399/1350.Students With Invalid Departments/Solution.sql @@ -1,6 +1,4 @@ # Write your MySQL query statement below -SELECT s.id, s.name -FROM - Students AS s - LEFT JOIN Departments AS d ON s.department_id = d.id -WHERE d.id IS NULL; +SELECT id, name +FROM Students +WHERE department_id NOT IN (SELECT id FROM Departments); diff --git a/solution/1300-1399/1350.Students With Invalid Departments/Solution2.sql b/solution/1300-1399/1350.Students With Invalid Departments/Solution2.sql new file mode 100644 index 0000000000000..f51003ad5a39b --- /dev/null +++ b/solution/1300-1399/1350.Students With Invalid Departments/Solution2.sql @@ -0,0 +1,6 @@ +# Write your MySQL query statement below +SELECT s.id, s.name +FROM + Students AS s + LEFT JOIN Departments AS d ON s.department_id = d.id +WHERE d.id IS NULL; diff --git a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution.cpp b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution.cpp index be894f7d055bf..c003c82defea0 100644 --- a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution.cpp +++ b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - int countNegatives(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - int ans = 0; - for (int i = m - 1, j = 0; i >= 0 && j < n;) { - if (grid[i][j] < 0) { - ans += n - j; - --i; - } else - ++j; - } - return ans; - } +class Solution { +public: + int countNegatives(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int ans = 0; + for (int i = m - 1, j = 0; i >= 0 && j < n;) { + if (grid[i][j] < 0) { + ans += n - j; + --i; + } else + ++j; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution.java b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution.java index a07806104039c..9465f18ff4ee5 100644 --- a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution.java +++ b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public int countNegatives(int[][] grid) { - int m = grid.length, n = grid[0].length; - int ans = 0; - for (int i = m - 1, j = 0; i >= 0 && j < n;) { - if (grid[i][j] < 0) { - ans += n - j; - --i; - } else { - ++j; - } - } - return ans; - } +class Solution { + public int countNegatives(int[][] grid) { + int m = grid.length, n = grid[0].length; + int ans = 0; + for (int i = m - 1, j = 0; i >= 0 && j < n;) { + if (grid[i][j] < 0) { + ans += n - j; + --i; + } else { + ++j; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution.py b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution.py index 33f854abe2546..853c1b39f9349 100644 --- a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution.py +++ b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def countNegatives(self, grid: List[List[int]]) -> int: - m, n = len(grid), len(grid[0]) - i, j = m - 1, 0 - ans = 0 - while i >= 0 and j < n: - if grid[i][j] < 0: - ans += n - j - i -= 1 - else: - j += 1 - return ans +class Solution: + def countNegatives(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + i, j = m - 1, 0 + ans = 0 + while i >= 0 and j < n: + if grid[i][j] < 0: + ans += n - j + i -= 1 + else: + j += 1 + return ans diff --git a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution.rs b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution.rs index c687451684f19..c455ad3435151 100644 --- a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution.rs +++ b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution.rs @@ -1,18 +1,20 @@ impl Solution { pub fn count_negatives(grid: Vec>) -> i32 { - let m = grid.len(); let n = grid[0].len(); - let mut i = m; - let mut j = 0; - let mut res = 0; - while i > 0 && j < n { - if grid[i - 1][j] >= 0 { - j += 1; - } else { - res += n - j; - i -= 1; - } - } - res as i32 + grid.into_iter() + .map(|nums| { + let mut left = 0; + let mut right = n; + while left < right { + let mid = left + (right - left) / 2; + if nums[mid] >= 0 { + left = mid + 1; + } else { + right = mid; + } + } + (n - left) as i32 + }) + .sum() } } diff --git a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.cpp b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.cpp new file mode 100644 index 0000000000000..28a23c2dbafa5 --- /dev/null +++ b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + int countNegatives(vector>& grid) { + int ans = 0; + for (auto& row : grid) { + ans += lower_bound(row.rbegin(), row.rend(), 0) - row.rbegin(); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.go b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.go new file mode 100644 index 0000000000000..d88ea489fefa6 --- /dev/null +++ b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.go @@ -0,0 +1,16 @@ +func countNegatives(grid [][]int) int { + ans, n := 0, len(grid[0]) + for _, row := range grid { + left, right := 0, n + for left < right { + mid := (left + right) >> 1 + if row[mid] < 0 { + right = mid + } else { + left = mid + 1 + } + } + ans += n - left + } + return ans +} \ No newline at end of file diff --git a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.java b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.java new file mode 100644 index 0000000000000..b92871f5d9ea2 --- /dev/null +++ b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.java @@ -0,0 +1,19 @@ +class Solution { + public int countNegatives(int[][] grid) { + int ans = 0; + int n = grid[0].length; + for (int[] row : grid) { + int left = 0, right = n; + while (left < right) { + int mid = (left + right) >> 1; + if (row[mid] < 0) { + right = mid; + } else { + left = mid + 1; + } + } + ans += n - left; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.js b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.js new file mode 100644 index 0000000000000..f231c992c8232 --- /dev/null +++ b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.js @@ -0,0 +1,22 @@ +/** + * @param {number[][]} grid + * @return {number} + */ +var countNegatives = function (grid) { + const n = grid[0].length; + let ans = 0; + for (let row of grid) { + let left = 0, + right = n; + while (left < right) { + const mid = (left + right) >> 1; + if (row[mid] < 0) { + right = mid; + } else { + left = mid + 1; + } + } + ans += n - left; + } + return ans; +}; diff --git a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.py b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.py new file mode 100644 index 0000000000000..58ba0cf131469 --- /dev/null +++ b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.py @@ -0,0 +1,3 @@ +class Solution: + def countNegatives(self, grid: List[List[int]]) -> int: + return sum(bisect_left(row[::-1], 0) for row in grid) diff --git a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.rs b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.rs new file mode 100644 index 0000000000000..c687451684f19 --- /dev/null +++ b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn count_negatives(grid: Vec>) -> i32 { + let m = grid.len(); + let n = grid[0].len(); + let mut i = m; + let mut j = 0; + let mut res = 0; + while i > 0 && j < n { + if grid[i - 1][j] >= 0 { + j += 1; + } else { + res += n - j; + i -= 1; + } + } + res as i32 + } +} diff --git a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.ts b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.ts new file mode 100644 index 0000000000000..4283282012004 --- /dev/null +++ b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/Solution2.ts @@ -0,0 +1,18 @@ +function countNegatives(grid: number[][]): number { + const n = grid[0].length; + let ans = 0; + for (let row of grid) { + let left = 0, + right = n; + while (left < right) { + const mid = (left + right) >> 1; + if (row[mid] < 0) { + right = mid; + } else { + left = mid + 1; + } + } + ans += n - left; + } + return ans; +} diff --git a/solution/1300-1399/1354.Construct Target Array With Multiple Sums/Solution.cpp b/solution/1300-1399/1354.Construct Target Array With Multiple Sums/Solution.cpp index a86a02d47b8c3..9ed63cbc64951 100644 --- a/solution/1300-1399/1354.Construct Target Array With Multiple Sums/Solution.cpp +++ b/solution/1300-1399/1354.Construct Target Array With Multiple Sums/Solution.cpp @@ -1,26 +1,26 @@ -class Solution { -public: - bool isPossible(vector& target) { - priority_queue pq; - long long s = 0; - for (int i = 0; i < target.size(); i++) { - s += target[i]; - pq.push(target[i]); - } - while (pq.top() != 1) { - int mx = pq.top(); - pq.pop(); - long long t = s - mx; - if (t < 1 || mx - t < 1) { - return false; - } - int x = mx % t; - if (x == 0) { - x = t; - } - pq.push(x); - s = s - mx + x; - } - return true; - } +class Solution { +public: + bool isPossible(vector& target) { + priority_queue pq; + long long s = 0; + for (int i = 0; i < target.size(); i++) { + s += target[i]; + pq.push(target[i]); + } + while (pq.top() != 1) { + int mx = pq.top(); + pq.pop(); + long long t = s - mx; + if (t < 1 || mx - t < 1) { + return false; + } + int x = mx % t; + if (x == 0) { + x = t; + } + pq.push(x); + s = s - mx + x; + } + return true; + } }; \ No newline at end of file diff --git a/solution/1300-1399/1354.Construct Target Array With Multiple Sums/Solution.java b/solution/1300-1399/1354.Construct Target Array With Multiple Sums/Solution.java index 7ffe7d5f2a5d3..bb4a7d401c072 100644 --- a/solution/1300-1399/1354.Construct Target Array With Multiple Sums/Solution.java +++ b/solution/1300-1399/1354.Construct Target Array With Multiple Sums/Solution.java @@ -1,24 +1,24 @@ -class Solution { - public boolean isPossible(int[] target) { - PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder()); - long s = 0; - for (int x : target) { - s += x; - pq.offer((long) x); - } - while (pq.peek() > 1) { - long mx = pq.poll(); - long t = s - mx; - if (t == 0 || mx - t < 1) { - return false; - } - long x = mx % t; - if (x == 0) { - x = t; - } - pq.offer(x); - s = s - mx + x; - } - return true; - } +class Solution { + public boolean isPossible(int[] target) { + PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder()); + long s = 0; + for (int x : target) { + s += x; + pq.offer((long) x); + } + while (pq.peek() > 1) { + long mx = pq.poll(); + long t = s - mx; + if (t == 0 || mx - t < 1) { + return false; + } + long x = mx % t; + if (x == 0) { + x = t; + } + pq.offer(x); + s = s - mx + x; + } + return true; + } } \ No newline at end of file diff --git a/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution.c b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution.c index dee2dd119e7a4..68b6407887e1b 100644 --- a/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution.c +++ b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution.c @@ -24,4 +24,4 @@ int* sortByBits(int* arr, int arrSize, int* returnSize) { qsort(arr, arrSize, sizeof(int), cmp); *returnSize = arrSize; return arr; -} +} \ No newline at end of file diff --git a/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution.py b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution.py index c6fc82635084d..3c67c4b642f71 100644 --- a/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution.py +++ b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution.py @@ -1,3 +1,3 @@ -class Solution: - def sortByBits(self, arr: List[int]) -> List[int]: - return sorted(arr, key=lambda x: (x.bit_count(), x)) +class Solution: + def sortByBits(self, arr: List[int]) -> List[int]: + return sorted(arr, key=lambda x: (x.bit_count(), x)) diff --git a/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution2.cpp b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution2.cpp new file mode 100644 index 0000000000000..2e13579a02557 --- /dev/null +++ b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution2.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + vector sortByBits(vector& arr) { + sort(arr.begin(), arr.end(), [&](auto& a, auto& b) -> bool { + int x = __builtin_popcount(a), y = __builtin_popcount(b); + return x < y || (x == y && a < b); + }); + return arr; + } +}; \ No newline at end of file diff --git a/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution2.go b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution2.go new file mode 100644 index 0000000000000..2edf89bed2455 --- /dev/null +++ b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution2.go @@ -0,0 +1,7 @@ +func sortByBits(arr []int) []int { + sort.Slice(arr, func(i, j int) bool { + a, b := bits.OnesCount(uint(arr[i])), bits.OnesCount(uint(arr[j])) + return a < b || (a == b && arr[i] < arr[j]) + }) + return arr +} \ No newline at end of file diff --git a/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution2.java b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution2.java new file mode 100644 index 0000000000000..7172ad148871f --- /dev/null +++ b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution2.java @@ -0,0 +1,17 @@ +class Solution { + public int[] sortByBits(int[] arr) { + int n = arr.length; + Integer[] t = new Integer[n]; + for (int i = 0; i < n; ++i) { + t[i] = arr[i]; + } + Arrays.sort(t, (a, b) -> { + int x = Integer.bitCount(a), y = Integer.bitCount(b); + return x == y ? a - b : x - y; + }); + for (int i = 0; i < n; ++i) { + arr[i] = t[i]; + } + return arr; + } +} \ No newline at end of file diff --git a/solution/1300-1399/1360.Number of Days Between Two Dates/Solution.java b/solution/1300-1399/1360.Number of Days Between Two Dates/Solution.java index 77712085103c2..8b700295946a6 100644 --- a/solution/1300-1399/1360.Number of Days Between Two Dates/Solution.java +++ b/solution/1300-1399/1360.Number of Days Between Two Dates/Solution.java @@ -1,30 +1,30 @@ -class Solution { - public int daysBetweenDates(String date1, String date2) { - return Math.abs(calcDays(date1) - calcDays(date2)); - } - - private boolean isLeapYear(int year) { - return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); - } - - private int daysInMonth(int year, int month) { - int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; - days[1] += isLeapYear(year) ? 1 : 0; - return days[month - 1]; - } - - private int calcDays(String date) { - int year = Integer.parseInt(date.substring(0, 4)); - int month = Integer.parseInt(date.substring(5, 7)); - int day = Integer.parseInt(date.substring(8)); - int days = 0; - for (int y = 1971; y < year; ++y) { - days += isLeapYear(y) ? 366 : 365; - } - for (int m = 1; m < month; ++m) { - days += daysInMonth(year, m); - } - days += day; - return days; - } +class Solution { + public int daysBetweenDates(String date1, String date2) { + return Math.abs(calcDays(date1) - calcDays(date2)); + } + + private boolean isLeapYear(int year) { + return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); + } + + private int daysInMonth(int year, int month) { + int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + days[1] += isLeapYear(year) ? 1 : 0; + return days[month - 1]; + } + + private int calcDays(String date) { + int year = Integer.parseInt(date.substring(0, 4)); + int month = Integer.parseInt(date.substring(5, 7)); + int day = Integer.parseInt(date.substring(8)); + int days = 0; + for (int y = 1971; y < year; ++y) { + days += isLeapYear(y) ? 366 : 365; + } + for (int m = 1; m < month; ++m) { + days += daysInMonth(year, m); + } + days += day; + return days; + } } \ No newline at end of file diff --git a/solution/1300-1399/1360.Number of Days Between Two Dates/Solution.py b/solution/1300-1399/1360.Number of Days Between Two Dates/Solution.py index 1b7a4e2f48e69..225b4c218a24b 100644 --- a/solution/1300-1399/1360.Number of Days Between Two Dates/Solution.py +++ b/solution/1300-1399/1360.Number of Days Between Two Dates/Solution.py @@ -1,33 +1,33 @@ -class Solution: - def daysBetweenDates(self, date1: str, date2: str) -> int: - def isLeapYear(year: int) -> bool: - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) - - def daysInMonth(year: int, month: int) -> int: - days = [ - 31, - 28 + int(isLeapYear(year)), - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31, - ] - return days[month - 1] - - def calcDays(date: str) -> int: - year, month, day = map(int, date.split("-")) - days = 0 - for y in range(1971, year): - days += 365 + int(isLeapYear(y)) - for m in range(1, month): - days += daysInMonth(year, m) - days += day - return days - - return abs(calcDays(date1) - calcDays(date2)) +class Solution: + def daysBetweenDates(self, date1: str, date2: str) -> int: + def isLeapYear(year: int) -> bool: + return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) + + def daysInMonth(year: int, month: int) -> int: + days = [ + 31, + 28 + int(isLeapYear(year)), + 31, + 30, + 31, + 30, + 31, + 31, + 30, + 31, + 30, + 31, + ] + return days[month - 1] + + def calcDays(date: str) -> int: + year, month, day = map(int, date.split("-")) + days = 0 + for y in range(1971, year): + days += 365 + int(isLeapYear(y)) + for m in range(1, month): + days += daysInMonth(year, m) + days += day + return days + + return abs(calcDays(date1) - calcDays(date2)) diff --git a/solution/1300-1399/1363.Largest Multiple of Three/Solution.cpp b/solution/1300-1399/1363.Largest Multiple of Three/Solution.cpp index dc9b2505edf0b..94b2307ffb3c2 100644 --- a/solution/1300-1399/1363.Largest Multiple of Three/Solution.cpp +++ b/solution/1300-1399/1363.Largest Multiple of Three/Solution.cpp @@ -1,31 +1,31 @@ -class Solution { -public: - string largestMultipleOfThree(vector& digits) { - sort(digits.begin(), digits.end()); - int n = digits.size(); - int f[n + 1][3]; - memset(f, -0x3f, sizeof(f)); - f[0][0] = 0; - for (int i = 1; i <= n; ++i) { - for (int j = 0; j < 3; ++j) { - f[i][j] = max(f[i - 1][j], f[i - 1][(j - digits[i - 1] % 3 + 3) % 3] + 1); - } - } - if (f[n][0] <= 0) { - return ""; - } - string ans; - for (int i = n, j = 0; i; --i) { - int k = (j - digits[i - 1] % 3 + 3) % 3; - if (f[i - 1][k] + 1 == f[i][j]) { - ans += digits[i - 1] + '0'; - j = k; - } - } - int i = 0; - while (i < ans.size() - 1 && ans[i] == '0') { - ++i; - } - return ans.substr(i); - } +class Solution { +public: + string largestMultipleOfThree(vector& digits) { + sort(digits.begin(), digits.end()); + int n = digits.size(); + int f[n + 1][3]; + memset(f, -0x3f, sizeof(f)); + f[0][0] = 0; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < 3; ++j) { + f[i][j] = max(f[i - 1][j], f[i - 1][(j - digits[i - 1] % 3 + 3) % 3] + 1); + } + } + if (f[n][0] <= 0) { + return ""; + } + string ans; + for (int i = n, j = 0; i; --i) { + int k = (j - digits[i - 1] % 3 + 3) % 3; + if (f[i - 1][k] + 1 == f[i][j]) { + ans += digits[i - 1] + '0'; + j = k; + } + } + int i = 0; + while (i < ans.size() - 1 && ans[i] == '0') { + ++i; + } + return ans.substr(i); + } }; \ No newline at end of file diff --git a/solution/1300-1399/1363.Largest Multiple of Three/Solution.java b/solution/1300-1399/1363.Largest Multiple of Three/Solution.java index 835c154768344..8b6df40240123 100644 --- a/solution/1300-1399/1363.Largest Multiple of Three/Solution.java +++ b/solution/1300-1399/1363.Largest Multiple of Three/Solution.java @@ -1,33 +1,33 @@ -class Solution { - public String largestMultipleOfThree(int[] digits) { - Arrays.sort(digits); - int n = digits.length; - int[][] f = new int[n + 1][3]; - final int inf = 1 << 30; - for (var g : f) { - Arrays.fill(g, -inf); - } - f[0][0] = 0; - for (int i = 1; i <= n; ++i) { - for (int j = 0; j < 3; ++j) { - f[i][j] = Math.max(f[i - 1][j], f[i - 1][(j - digits[i - 1] % 3 + 3) % 3] + 1); - } - } - if (f[n][0] <= 0) { - return ""; - } - StringBuilder sb = new StringBuilder(); - for (int i = n, j = 0; i > 0; --i) { - int k = (j - digits[i - 1] % 3 + 3) % 3; - if (f[i - 1][k] + 1 == f[i][j]) { - sb.append(digits[i - 1]); - j = k; - } - } - int i = 0; - while (i < sb.length() - 1 && sb.charAt(i) == '0') { - ++i; - } - return sb.substring(i); - } +class Solution { + public String largestMultipleOfThree(int[] digits) { + Arrays.sort(digits); + int n = digits.length; + int[][] f = new int[n + 1][3]; + final int inf = 1 << 30; + for (var g : f) { + Arrays.fill(g, -inf); + } + f[0][0] = 0; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < 3; ++j) { + f[i][j] = Math.max(f[i - 1][j], f[i - 1][(j - digits[i - 1] % 3 + 3) % 3] + 1); + } + } + if (f[n][0] <= 0) { + return ""; + } + StringBuilder sb = new StringBuilder(); + for (int i = n, j = 0; i > 0; --i) { + int k = (j - digits[i - 1] % 3 + 3) % 3; + if (f[i - 1][k] + 1 == f[i][j]) { + sb.append(digits[i - 1]); + j = k; + } + } + int i = 0; + while (i < sb.length() - 1 && sb.charAt(i) == '0') { + ++i; + } + return sb.substring(i); + } } \ No newline at end of file diff --git a/solution/1300-1399/1363.Largest Multiple of Three/Solution.py b/solution/1300-1399/1363.Largest Multiple of Three/Solution.py index 982e03a768d62..fd2a93925ee4d 100644 --- a/solution/1300-1399/1363.Largest Multiple of Three/Solution.py +++ b/solution/1300-1399/1363.Largest Multiple of Three/Solution.py @@ -1,22 +1,22 @@ -class Solution: - def largestMultipleOfThree(self, digits: List[int]) -> str: - digits.sort() - n = len(digits) - f = [[-inf] * 3 for _ in range(n + 1)] - f[0][0] = 0 - for i, x in enumerate(digits, 1): - for j in range(3): - f[i][j] = max(f[i - 1][j], f[i - 1][(j - x % 3 + 3) % 3] + 1) - if f[n][0] <= 0: - return "" - arr = [] - j = 0 - for i in range(n, 0, -1): - k = (j - digits[i - 1] % 3 + 3) % 3 - if f[i - 1][k] + 1 == f[i][j]: - arr.append(digits[i - 1]) - j = k - i = 0 - while i < len(arr) - 1 and arr[i] == 0: - i += 1 - return "".join(map(str, arr[i:])) +class Solution: + def largestMultipleOfThree(self, digits: List[int]) -> str: + digits.sort() + n = len(digits) + f = [[-inf] * 3 for _ in range(n + 1)] + f[0][0] = 0 + for i, x in enumerate(digits, 1): + for j in range(3): + f[i][j] = max(f[i - 1][j], f[i - 1][(j - x % 3 + 3) % 3] + 1) + if f[n][0] <= 0: + return "" + arr = [] + j = 0 + for i in range(n, 0, -1): + k = (j - digits[i - 1] % 3 + 3) % 3 + if f[i - 1][k] + 1 == f[i][j]: + arr.append(digits[i - 1]) + j = k + i = 0 + while i < len(arr) - 1 and arr[i] == 0: + i += 1 + return "".join(map(str, arr[i:])) diff --git a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.cpp b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.cpp index 6875381798593..0daeb30ddd396 100644 --- a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.cpp +++ b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.cpp @@ -1,17 +1,11 @@ class Solution { public: vector smallerNumbersThanCurrent(vector& nums) { - int cnt[102]{}; - for (int& x : nums) { - ++cnt[x + 1]; + vector arr = nums; + sort(arr.begin(), arr.end()); + for (int i = 0; i < nums.size(); ++i) { + nums[i] = lower_bound(arr.begin(), arr.end(), nums[i]) - arr.begin(); } - for (int i = 1; i < 102; ++i) { - cnt[i] += cnt[i - 1]; - } - vector ans; - for (int& x : nums) { - ans.push_back(cnt[x]); - } - return ans; + return nums; } }; \ No newline at end of file diff --git a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.go b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.go index 164bf413613db..884c8945321e4 100644 --- a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.go +++ b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.go @@ -1,13 +1,9 @@ func smallerNumbersThanCurrent(nums []int) (ans []int) { - cnt := [102]int{} - for _, x := range nums { - cnt[x+1]++ + arr := make([]int, len(nums)) + copy(arr, nums) + sort.Ints(arr) + for i, x := range nums { + nums[i] = sort.SearchInts(arr, x) } - for i := 1; i < len(cnt); i++ { - cnt[i] += cnt[i-1] - } - for _, x := range nums { - ans = append(ans, cnt[x]) - } - return + return nums } \ No newline at end of file diff --git a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.java b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.java index e73f8b3787542..d1500d1d1c330 100644 --- a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.java +++ b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.java @@ -1,17 +1,23 @@ class Solution { public int[] smallerNumbersThanCurrent(int[] nums) { - int[] cnt = new int[102]; - for (int x : nums) { - ++cnt[x + 1]; + int[] arr = nums.clone(); + Arrays.sort(arr); + for (int i = 0; i < nums.length; ++i) { + nums[i] = search(arr, nums[i]); } - for (int i = 1; i < cnt.length; ++i) { - cnt[i] += cnt[i - 1]; - } - int n = nums.length; - int[] ans = new int[n]; - for (int i = 0; i < n; ++i) { - ans[i] = cnt[nums[i]]; + return nums; + } + + private int search(int[] nums, int x) { + int l = 0, r = nums.length; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } } - return ans; + return l; } } \ No newline at end of file diff --git a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.py b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.py index 955140729406e..f33503419a8c1 100644 --- a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.py +++ b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.py @@ -1,7 +1,4 @@ class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: - cnt = [0] * 102 - for x in nums: - cnt[x + 1] += 1 - s = list(accumulate(cnt)) - return [s[x] for x in nums] + arr = sorted(nums) + return [bisect_left(arr, x) for x in nums] diff --git a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.ts b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.ts index 9d7524420c51f..e0f14daa8a05e 100644 --- a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.ts +++ b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.ts @@ -1,15 +1,20 @@ function smallerNumbersThanCurrent(nums: number[]): number[] { - const cnt: number[] = new Array(102).fill(0); - for (const x of nums) { - ++cnt[x + 1]; + const search = (nums: number[], x: number) => { + let l = 0, + r = nums.length; + while (l < r) { + const mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + const arr = nums.slice().sort((a, b) => a - b); + for (let i = 0; i < nums.length; ++i) { + nums[i] = search(arr, nums[i]); } - for (let i = 1; i < cnt.length; ++i) { - cnt[i] += cnt[i - 1]; - } - const n = nums.length; - const ans: number[] = new Array(n); - for (let i = 0; i < n; ++i) { - ans[i] = cnt[nums[i]]; - } - return ans; + return nums; } diff --git a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution2.cpp b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution2.cpp new file mode 100644 index 0000000000000..6875381798593 --- /dev/null +++ b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector smallerNumbersThanCurrent(vector& nums) { + int cnt[102]{}; + for (int& x : nums) { + ++cnt[x + 1]; + } + for (int i = 1; i < 102; ++i) { + cnt[i] += cnt[i - 1]; + } + vector ans; + for (int& x : nums) { + ans.push_back(cnt[x]); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution2.go b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution2.go new file mode 100644 index 0000000000000..164bf413613db --- /dev/null +++ b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution2.go @@ -0,0 +1,13 @@ +func smallerNumbersThanCurrent(nums []int) (ans []int) { + cnt := [102]int{} + for _, x := range nums { + cnt[x+1]++ + } + for i := 1; i < len(cnt); i++ { + cnt[i] += cnt[i-1] + } + for _, x := range nums { + ans = append(ans, cnt[x]) + } + return +} \ No newline at end of file diff --git a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution2.java b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution2.java new file mode 100644 index 0000000000000..e73f8b3787542 --- /dev/null +++ b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution2.java @@ -0,0 +1,17 @@ +class Solution { + public int[] smallerNumbersThanCurrent(int[] nums) { + int[] cnt = new int[102]; + for (int x : nums) { + ++cnt[x + 1]; + } + for (int i = 1; i < cnt.length; ++i) { + cnt[i] += cnt[i - 1]; + } + int n = nums.length; + int[] ans = new int[n]; + for (int i = 0; i < n; ++i) { + ans[i] = cnt[nums[i]]; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution2.py b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution2.py new file mode 100644 index 0000000000000..955140729406e --- /dev/null +++ b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: + cnt = [0] * 102 + for x in nums: + cnt[x + 1] += 1 + s = list(accumulate(cnt)) + return [s[x] for x in nums] diff --git a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution2.ts b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution2.ts new file mode 100644 index 0000000000000..9d7524420c51f --- /dev/null +++ b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution2.ts @@ -0,0 +1,15 @@ +function smallerNumbersThanCurrent(nums: number[]): number[] { + const cnt: number[] = new Array(102).fill(0); + for (const x of nums) { + ++cnt[x + 1]; + } + for (let i = 1; i < cnt.length; ++i) { + cnt[i] += cnt[i - 1]; + } + const n = nums.length; + const ans: number[] = new Array(n); + for (let i = 0; i < n; ++i) { + ans[i] = cnt[nums[i]]; + } + return ans; +} diff --git a/solution/1300-1399/1370.Increasing Decreasing String/Solution.cpp b/solution/1300-1399/1370.Increasing Decreasing String/Solution.cpp index 34bd0da7d47d3..0a40b65804288 100644 --- a/solution/1300-1399/1370.Increasing Decreasing String/Solution.cpp +++ b/solution/1300-1399/1370.Increasing Decreasing String/Solution.cpp @@ -1,25 +1,25 @@ -class Solution { -public: - string sortString(string s) { - int cnt[26]{}; - for (char& c : s) { - ++cnt[c - 'a']; - } - string ans; - while (ans.size() < s.size()) { - for (int i = 0; i < 26; ++i) { - if (cnt[i]) { - ans += i + 'a'; - --cnt[i]; - } - } - for (int i = 25; i >= 0; --i) { - if (cnt[i]) { - ans += i + 'a'; - --cnt[i]; - } - } - } - return ans; - } +class Solution { +public: + string sortString(string s) { + int cnt[26]{}; + for (char& c : s) { + ++cnt[c - 'a']; + } + string ans; + while (ans.size() < s.size()) { + for (int i = 0; i < 26; ++i) { + if (cnt[i]) { + ans += i + 'a'; + --cnt[i]; + } + } + for (int i = 25; i >= 0; --i) { + if (cnt[i]) { + ans += i + 'a'; + --cnt[i]; + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1300-1399/1370.Increasing Decreasing String/Solution.java b/solution/1300-1399/1370.Increasing Decreasing String/Solution.java index 69ae9a5d3f997..e65fbfd3d9c3f 100644 --- a/solution/1300-1399/1370.Increasing Decreasing String/Solution.java +++ b/solution/1300-1399/1370.Increasing Decreasing String/Solution.java @@ -1,25 +1,25 @@ -class Solution { - public String sortString(String s) { - int[] cnt = new int[26]; - int n = s.length(); - for (int i = 0; i < n; ++i) { - cnt[s.charAt(i) - 'a']++; - } - StringBuilder sb = new StringBuilder(); - while (sb.length() < n) { - for (int i = 0; i < 26; ++i) { - if (cnt[i] > 0) { - sb.append((char) ('a' + i)); - --cnt[i]; - } - } - for (int i = 25; i >= 0; --i) { - if (cnt[i] > 0) { - sb.append((char) ('a' + i)); - --cnt[i]; - } - } - } - return sb.toString(); - } +class Solution { + public String sortString(String s) { + int[] cnt = new int[26]; + int n = s.length(); + for (int i = 0; i < n; ++i) { + cnt[s.charAt(i) - 'a']++; + } + StringBuilder sb = new StringBuilder(); + while (sb.length() < n) { + for (int i = 0; i < 26; ++i) { + if (cnt[i] > 0) { + sb.append((char) ('a' + i)); + --cnt[i]; + } + } + for (int i = 25; i >= 0; --i) { + if (cnt[i] > 0) { + sb.append((char) ('a' + i)); + --cnt[i]; + } + } + } + return sb.toString(); + } } \ No newline at end of file diff --git a/solution/1300-1399/1370.Increasing Decreasing String/Solution.py b/solution/1300-1399/1370.Increasing Decreasing String/Solution.py index 4dcfd5a8cd25d..432cd1e6d17f0 100644 --- a/solution/1300-1399/1370.Increasing Decreasing String/Solution.py +++ b/solution/1300-1399/1370.Increasing Decreasing String/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def sortString(self, s: str) -> str: - cnt = Counter(s) - cs = ascii_lowercase + ascii_lowercase[::-1] - ans = [] - while len(ans) < len(s): - for c in cs: - if cnt[c]: - ans.append(c) - cnt[c] -= 1 - return "".join(ans) +class Solution: + def sortString(self, s: str) -> str: + cnt = Counter(s) + cs = ascii_lowercase + ascii_lowercase[::-1] + ans = [] + while len(ans) < len(s): + for c in cs: + if cnt[c]: + ans.append(c) + cnt[c] -= 1 + return "".join(ans) diff --git a/solution/1300-1399/1371.Find the Longest Substring Containing Vowels in Even Counts/Solution.java b/solution/1300-1399/1371.Find the Longest Substring Containing Vowels in Even Counts/Solution.java index f23dbc89cb958..91ef6044f43c5 100644 --- a/solution/1300-1399/1371.Find the Longest Substring Containing Vowels in Even Counts/Solution.java +++ b/solution/1300-1399/1371.Find the Longest Substring Containing Vowels in Even Counts/Solution.java @@ -1,4 +1,5 @@ class Solution { + public int findTheLongestSubstring(String s) { int[] pos = new int[32]; Arrays.fill(pos, Integer.MAX_VALUE); diff --git a/solution/1300-1399/1376.Time Needed to Inform All Employees/Solution.cs b/solution/1300-1399/1376.Time Needed to Inform All Employees/Solution.cs index 3f716054c1fef..3ddf67254cef1 100644 --- a/solution/1300-1399/1376.Time Needed to Inform All Employees/Solution.cs +++ b/solution/1300-1399/1376.Time Needed to Inform All Employees/Solution.cs @@ -23,4 +23,4 @@ private int dfs(int i) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/1300-1399/1377.Frog Position After T Seconds/Solution.cs b/solution/1300-1399/1377.Frog Position After T Seconds/Solution.cs index f99bbb12f06b8..babeef1ff0d4a 100644 --- a/solution/1300-1399/1377.Frog Position After T Seconds/Solution.cs +++ b/solution/1300-1399/1377.Frog Position After T Seconds/Solution.cs @@ -30,4 +30,4 @@ public double FrogPosition(int n, int[][] edges, int t, int target) { } return 0; } -} \ No newline at end of file +} diff --git a/solution/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/Solution.cs b/solution/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/Solution.cs index 3b327ac107812..a2014f88112c9 100644 --- a/solution/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/Solution.cs +++ b/solution/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/Solution.cs @@ -13,7 +13,7 @@ public class Solution { public TreeNode GetTargetCopy(TreeNode original, TreeNode cloned, TreeNode target) { this.target = target; - return dfs(original, cloned); + return dfs(original, cloned); } private TreeNode dfs(TreeNode original, TreeNode cloned) { @@ -26,4 +26,4 @@ private TreeNode dfs(TreeNode original, TreeNode cloned) { TreeNode left = dfs(original.left, cloned.left); return left == null ? dfs(original.right, cloned.right) : left; } -} \ No newline at end of file +} diff --git a/solution/1300-1399/1380.Lucky Numbers in a Matrix/Solution.py b/solution/1300-1399/1380.Lucky Numbers in a Matrix/Solution.py index f32161b4a8d89..2fd6b26b7d760 100644 --- a/solution/1300-1399/1380.Lucky Numbers in a Matrix/Solution.py +++ b/solution/1300-1399/1380.Lucky Numbers in a Matrix/Solution.py @@ -1,5 +1,5 @@ class Solution: def luckyNumbers(self, matrix: List[List[int]]) -> List[int]: - rows = min(row for row in matrix) - cols = max(col for col in zip(*matrix)) + rows = {min(row) for row in matrix} + cols = {max(col) for col in zip(*matrix)} return list(rows & cols) diff --git a/solution/1300-1399/1382.Balance a Binary Search Tree/Solution.cpp b/solution/1300-1399/1382.Balance a Binary Search Tree/Solution.cpp index 6d2d61a2cb2a9..9273bdf3982d8 100644 --- a/solution/1300-1399/1382.Balance a Binary Search Tree/Solution.cpp +++ b/solution/1300-1399/1382.Balance a Binary Search Tree/Solution.cpp @@ -1,40 +1,40 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* balanceBST(TreeNode* root) { - dfs(root); - return build(0, nums.size() - 1); - } - -private: - vector nums; - - void dfs(TreeNode* root) { - if (!root) { - return; - } - dfs(root->left); - nums.push_back(root->val); - dfs(root->right); - } - - TreeNode* build(int i, int j) { - if (i > j) { - return nullptr; - } - int mid = (i + j) >> 1; - TreeNode* left = build(i, mid - 1); - TreeNode* right = build(mid + 1, j); - return new TreeNode(nums[mid], left, right); - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* balanceBST(TreeNode* root) { + dfs(root); + return build(0, nums.size() - 1); + } + +private: + vector nums; + + void dfs(TreeNode* root) { + if (!root) { + return; + } + dfs(root->left); + nums.push_back(root->val); + dfs(root->right); + } + + TreeNode* build(int i, int j) { + if (i > j) { + return nullptr; + } + int mid = (i + j) >> 1; + TreeNode* left = build(i, mid - 1); + TreeNode* right = build(mid + 1, j); + return new TreeNode(nums[mid], left, right); + } }; \ No newline at end of file diff --git a/solution/1300-1399/1382.Balance a Binary Search Tree/Solution.java b/solution/1300-1399/1382.Balance a Binary Search Tree/Solution.java index 5fb0b84cec138..f729b3e626af3 100644 --- a/solution/1300-1399/1382.Balance a Binary Search Tree/Solution.java +++ b/solution/1300-1399/1382.Balance a Binary Search Tree/Solution.java @@ -1,42 +1,42 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private List nums = new ArrayList<>(); - - public TreeNode balanceBST(TreeNode root) { - dfs(root); - return build(0, nums.size() - 1); - } - - private void dfs(TreeNode root) { - if (root == null) { - return; - } - dfs(root.left); - nums.add(root.val); - dfs(root.right); - } - - private TreeNode build(int i, int j) { - if (i > j) { - return null; - } - int mid = (i + j) >> 1; - TreeNode left = build(i, mid - 1); - TreeNode right = build(mid + 1, j); - return new TreeNode(nums.get(mid), left, right); - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private List nums = new ArrayList<>(); + + public TreeNode balanceBST(TreeNode root) { + dfs(root); + return build(0, nums.size() - 1); + } + + private void dfs(TreeNode root) { + if (root == null) { + return; + } + dfs(root.left); + nums.add(root.val); + dfs(root.right); + } + + private TreeNode build(int i, int j) { + if (i > j) { + return null; + } + int mid = (i + j) >> 1; + TreeNode left = build(i, mid - 1); + TreeNode right = build(mid + 1, j); + return new TreeNode(nums.get(mid), left, right); + } } \ No newline at end of file diff --git a/solution/1300-1399/1382.Balance a Binary Search Tree/Solution.py b/solution/1300-1399/1382.Balance a Binary Search Tree/Solution.py index ba1684165f078..079e9d80504f9 100644 --- a/solution/1300-1399/1382.Balance a Binary Search Tree/Solution.py +++ b/solution/1300-1399/1382.Balance a Binary Search Tree/Solution.py @@ -1,26 +1,26 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def balanceBST(self, root: TreeNode) -> TreeNode: - def dfs(root: TreeNode): - if root is None: - return - dfs(root.left) - nums.append(root.val) - dfs(root.right) - - def build(i: int, j: int) -> TreeNode: - if i > j: - return None - mid = (i + j) >> 1 - left = build(i, mid - 1) - right = build(mid + 1, j) - return TreeNode(nums[mid], left, right) - - nums = [] - dfs(root) - return build(0, len(nums) - 1) +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def balanceBST(self, root: TreeNode) -> TreeNode: + def dfs(root: TreeNode): + if root is None: + return + dfs(root.left) + nums.append(root.val) + dfs(root.right) + + def build(i: int, j: int) -> TreeNode: + if i > j: + return None + mid = (i + j) >> 1 + left = build(i, mid - 1) + right = build(mid + 1, j) + return TreeNode(nums[mid], left, right) + + nums = [] + dfs(root) + return build(0, len(nums) - 1) diff --git a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.cpp b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.cpp index 264c9d3ee9498..e443ae16c3b8d 100644 --- a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.cpp +++ b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - int findTheDistanceValue(vector& arr1, vector& arr2, int d) { - auto check = [&](int a) -> bool { - auto it = lower_bound(arr2.begin(), arr2.end(), a - d); - return it == arr2.end() || *it > a + d; - }; - sort(arr2.begin(), arr2.end()); - int ans = 0; - for (int& a : arr1) { - ans += check(a); - } - return ans; - } +class Solution { +public: + int findTheDistanceValue(vector& arr1, vector& arr2, int d) { + auto check = [&](int a) -> bool { + auto it = lower_bound(arr2.begin(), arr2.end(), a - d); + return it == arr2.end() || *it > a + d; + }; + sort(arr2.begin(), arr2.end()); + int ans = 0; + for (int& a : arr1) { + ans += check(a); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.java b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.java index 27ef2a4b25922..b04604fd6f020 100644 --- a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.java +++ b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.java @@ -1,25 +1,25 @@ -class Solution { - public int findTheDistanceValue(int[] arr1, int[] arr2, int d) { - Arrays.sort(arr2); - int ans = 0; - for (int a : arr1) { - if (check(arr2, a, d)) { - ++ans; - } - } - return ans; - } - - private boolean check(int[] arr, int a, int d) { - int l = 0, r = arr.length; - while (l < r) { - int mid = (l + r) >> 1; - if (arr[mid] >= a - d) { - r = mid; - } else { - l = mid + 1; - } - } - return l >= arr.length || arr[l] > a + d; - } +class Solution { + public int findTheDistanceValue(int[] arr1, int[] arr2, int d) { + Arrays.sort(arr2); + int ans = 0; + for (int a : arr1) { + if (check(arr2, a, d)) { + ++ans; + } + } + return ans; + } + + private boolean check(int[] arr, int a, int d) { + int l = 0, r = arr.length; + while (l < r) { + int mid = (l + r) >> 1; + if (arr[mid] >= a - d) { + r = mid; + } else { + l = mid + 1; + } + } + return l >= arr.length || arr[l] > a + d; + } } \ No newline at end of file diff --git a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.py b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.py index 32e643b578858..8e8dccc768186 100644 --- a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.py +++ b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.py @@ -1,8 +1,8 @@ -class Solution: - def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int: - def check(a: int) -> bool: - i = bisect_left(arr2, a - d) - return i == len(arr2) or arr2[i] > a + d - - arr2.sort() - return sum(check(a) for a in arr1) +class Solution: + def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int: + def check(a: int) -> bool: + i = bisect_left(arr2, a - d) + return i == len(arr2) or arr2[i] > a + d + + arr2.sort() + return sum(check(a) for a in arr1) diff --git a/solution/1300-1399/1387.Sort Integers by The Power Value/Solution.cpp b/solution/1300-1399/1387.Sort Integers by The Power Value/Solution.cpp index 53b8fd00681ab..da114480fb32e 100644 --- a/solution/1300-1399/1387.Sort Integers by The Power Value/Solution.cpp +++ b/solution/1300-1399/1387.Sort Integers by The Power Value/Solution.cpp @@ -1,29 +1,29 @@ -class Solution { -public: - int getKth(int lo, int hi, int k) { - auto f = [](int x) { - int ans = 0; - for (; x != 1; ++ans) { - if (x % 2 == 0) { - x /= 2; - } else { - x = 3 * x + 1; - } - } - return ans; - }; - vector nums; - for (int i = lo; i <= hi; ++i) { - nums.push_back(i); - } - sort(nums.begin(), nums.end(), [&](int x, int y) { - int fx = f(x), fy = f(y); - if (fx != fy) { - return fx < fy; - } else { - return x < y; - } - }); - return nums[k - 1]; - } +class Solution { +public: + int getKth(int lo, int hi, int k) { + auto f = [](int x) { + int ans = 0; + for (; x != 1; ++ans) { + if (x % 2 == 0) { + x /= 2; + } else { + x = 3 * x + 1; + } + } + return ans; + }; + vector nums; + for (int i = lo; i <= hi; ++i) { + nums.push_back(i); + } + sort(nums.begin(), nums.end(), [&](int x, int y) { + int fx = f(x), fy = f(y); + if (fx != fy) { + return fx < fy; + } else { + return x < y; + } + }); + return nums[k - 1]; + } }; \ No newline at end of file diff --git a/solution/1300-1399/1387.Sort Integers by The Power Value/Solution.java b/solution/1300-1399/1387.Sort Integers by The Power Value/Solution.java index e60dd7e11fd66..150285066a5cd 100644 --- a/solution/1300-1399/1387.Sort Integers by The Power Value/Solution.java +++ b/solution/1300-1399/1387.Sort Integers by The Power Value/Solution.java @@ -1,25 +1,25 @@ -class Solution { - public int getKth(int lo, int hi, int k) { - Integer[] nums = new Integer[hi - lo + 1]; - for (int i = lo; i <= hi; ++i) { - nums[i - lo] = i; - } - Arrays.sort(nums, (a, b) -> { - int fa = f(a), fb = f(b); - return fa == fb ? a - b : fa - fb; - }); - return nums[k - 1]; - } - - private int f(int x) { - int ans = 0; - for (; x != 1; ++ans) { - if (x % 2 == 0) { - x /= 2; - } else { - x = x * 3 + 1; - } - } - return ans; - } +class Solution { + public int getKth(int lo, int hi, int k) { + Integer[] nums = new Integer[hi - lo + 1]; + for (int i = lo; i <= hi; ++i) { + nums[i - lo] = i; + } + Arrays.sort(nums, (a, b) -> { + int fa = f(a), fb = f(b); + return fa == fb ? a - b : fa - fb; + }); + return nums[k - 1]; + } + + private int f(int x) { + int ans = 0; + for (; x != 1; ++ans) { + if (x % 2 == 0) { + x /= 2; + } else { + x = x * 3 + 1; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1300-1399/1387.Sort Integers by The Power Value/Solution.py b/solution/1300-1399/1387.Sort Integers by The Power Value/Solution.py index 9575b94e7d68f..8fc9b6512916b 100644 --- a/solution/1300-1399/1387.Sort Integers by The Power Value/Solution.py +++ b/solution/1300-1399/1387.Sort Integers by The Power Value/Solution.py @@ -1,15 +1,15 @@ -@cache -def f(x: int) -> int: - ans = 0 - while x != 1: - if x % 2 == 0: - x //= 2 - else: - x = 3 * x + 1 - ans += 1 - return ans - - -class Solution: - def getKth(self, lo: int, hi: int, k: int) -> int: - return sorted(range(lo, hi + 1), key=f)[k - 1] +@cache +def f(x: int) -> int: + ans = 0 + while x != 1: + if x % 2 == 0: + x //= 2 + else: + x = 3 * x + 1 + ans += 1 + return ans + + +class Solution: + def getKth(self, lo: int, hi: int, k: int) -> int: + return sorted(range(lo, hi + 1), key=f)[k - 1] diff --git a/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.php b/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.php index 9a710ec61f34d..978bf0079a7ce 100644 --- a/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.php +++ b/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.php @@ -16,4 +16,4 @@ function findLucky($arr) { } return $max; } -} \ No newline at end of file +} diff --git a/solution/1300-1399/1395.Count Number of Teams/Solution.cpp b/solution/1300-1399/1395.Count Number of Teams/Solution.cpp index 2931e1e769b22..07f2ff1216e0a 100644 --- a/solution/1300-1399/1395.Count Number of Teams/Solution.cpp +++ b/solution/1300-1399/1395.Count Number of Teams/Solution.cpp @@ -1,51 +1,20 @@ -class BinaryIndexedTree { -public: - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += x & -x; - } - } - - int query(int x) { - int s = 0; - while (x) { - s += c[x]; - x -= x & -x; - } - return s; - } - -private: - int n; - vector c; -}; - class Solution { public: int numTeams(vector& rating) { - vector nums = rating; - sort(nums.begin(), nums.end()); - nums.erase(unique(nums.begin(), nums.end()), nums.end()); - int m = nums.size(); - BinaryIndexedTree tree1(m); - BinaryIndexedTree tree2(m); - for (int& v : rating) { - int x = lower_bound(nums.begin(), nums.end(), v) - nums.begin() + 1; - tree2.update(x, 1); - } - int ans = 0; int n = rating.size(); + int ans = 0; for (int i = 0; i < n; ++i) { - int x = lower_bound(nums.begin(), nums.end(), rating[i]) - nums.begin() + 1; - tree1.update(x, 1); - tree2.update(x, -1); - int l = tree1.query(x - 1); - int r = n - i - 1 - tree2.query(x); + int l = 0, r = 0; + for (int j = 0; j < i; ++j) { + if (rating[j] < rating[i]) { + ++l; + } + } + for (int j = i + 1; j < n; ++j) { + if (rating[j] > rating[i]) { + ++r; + } + } ans += l * r; ans += (i - l) * (n - i - 1 - r); } diff --git a/solution/1300-1399/1395.Count Number of Teams/Solution.go b/solution/1300-1399/1395.Count Number of Teams/Solution.go index 1a142d63d097b..2bcd056716102 100644 --- a/solution/1300-1399/1395.Count Number of Teams/Solution.go +++ b/solution/1300-1399/1395.Count Number of Teams/Solution.go @@ -1,53 +1,17 @@ -type BinaryIndexedTree struct { - n int - c []int -} - -func newBinaryIndexedTree(n int) *BinaryIndexedTree { - c := make([]int, n+1) - return &BinaryIndexedTree{n, c} -} - -func (this *BinaryIndexedTree) update(x, delta int) { - for x <= this.n { - this.c[x] += delta - x += x & -x - } -} - -func (this *BinaryIndexedTree) query(x int) int { - s := 0 - for x > 0 { - s += this.c[x] - x -= x & -x - } - return s -} - func numTeams(rating []int) (ans int) { - nums := make([]int, len(rating)) - copy(nums, rating) - sort.Ints(nums) - m := 0 - for i, x := range nums { - if i == 0 || x != nums[i-1] { - nums[m] = x - m++ - } - } - nums = nums[:m] - tree1 := newBinaryIndexedTree(m) - tree2 := newBinaryIndexedTree(m) - for _, x := range rating { - tree2.update(sort.SearchInts(nums, x)+1, 1) - } n := len(rating) - for i, v := range rating { - x := sort.SearchInts(nums, v) + 1 - tree1.update(x, 1) - tree2.update(x, -1) - l := tree1.query(x - 1) - r := n - i - 1 - tree2.query(x) + for i, b := range rating { + l, r := 0, 0 + for _, a := range rating[:i] { + if a < b { + l++ + } + } + for _, c := range rating[i+1:] { + if c < b { + r++ + } + } ans += l * r ans += (i - l) * (n - i - 1 - r) } diff --git a/solution/1300-1399/1395.Count Number of Teams/Solution.java b/solution/1300-1399/1395.Count Number of Teams/Solution.java index 110608e71628b..97066853a0111 100644 --- a/solution/1300-1399/1395.Count Number of Teams/Solution.java +++ b/solution/1300-1399/1395.Count Number of Teams/Solution.java @@ -1,70 +1,22 @@ -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - this.c = new int[n + 1]; - } - - public void update(int x, int v) { - while (x <= n) { - c[x] += v; - x += x & -x; - } - } - - public int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= x & -x; - } - return s; - } -} - class Solution { public int numTeams(int[] rating) { int n = rating.length; - int[] nums = rating.clone(); - Arrays.sort(nums); - int m = 0; - for (int i = 0; i < n; ++i) { - if (i == 0 || nums[i] != nums[i - 1]) { - nums[m++] = nums[i]; - } - } - BinaryIndexedTree tree1 = new BinaryIndexedTree(m); - BinaryIndexedTree tree2 = new BinaryIndexedTree(m); - for (int v : rating) { - int x = search(nums, v); - tree2.update(x, 1); - } - int ans = 0; for (int i = 0; i < n; ++i) { - int x = search(nums, rating[i]); - tree1.update(x, 1); - tree2.update(x, -1); - int l = tree1.query(x - 1); - int r = n - i - 1 - tree2.query(x); + int l = 0, r = 0; + for (int j = 0; j < i; ++j) { + if (rating[j] < rating[i]) { + ++l; + } + } + for (int j = i + 1; j < n; ++j) { + if (rating[j] > rating[i]) { + ++r; + } + } ans += l * r; ans += (i - l) * (n - i - 1 - r); } return ans; } - - private int search(int[] nums, int x) { - int l = 0, r = nums.length; - while (l < r) { - int mid = (l + r) >> 1; - if (nums[mid] >= x) { - r = mid; - } else { - l = mid + 1; - } - } - return l + 1; - } } \ No newline at end of file diff --git a/solution/1300-1399/1395.Count Number of Teams/Solution.py b/solution/1300-1399/1395.Count Number of Teams/Solution.py index afec5cca654ec..74a693c3e611a 100644 --- a/solution/1300-1399/1395.Count Number of Teams/Solution.py +++ b/solution/1300-1399/1395.Count Number of Teams/Solution.py @@ -1,38 +1,9 @@ -class BinaryIndexedTree: - def __init__(self, n: int): - self.n = n - self.c = [0] * (n + 1) - - def update(self, x: int, v: int): - while x <= self.n: - self.c[x] += v - x += x & -x - - def query(self, x: int) -> int: - s = 0 - while x: - s += self.c[x] - x -= x & -x - return s - - class Solution: def numTeams(self, rating: List[int]) -> int: - nums = sorted(set(rating)) - m = len(nums) - tree1 = BinaryIndexedTree(m) - tree2 = BinaryIndexedTree(m) - for v in rating: - x = bisect_left(nums, v) + 1 - tree2.update(x, 1) - n = len(rating) - ans = 0 - for i, v in enumerate(rating): - x = bisect_left(nums, v) + 1 - tree1.update(x, 1) - tree2.update(x, -1) - l = tree1.query(x - 1) - r = n - i - 1 - tree2.query(x) + ans, n = 0, len(rating) + for i, b in enumerate(rating): + l = sum(a < b for a in rating[:i]) + r = sum(c > b for c in rating[i + 1 :]) ans += l * r ans += (i - l) * (n - i - 1 - r) return ans diff --git a/solution/1300-1399/1395.Count Number of Teams/Solution.ts b/solution/1300-1399/1395.Count Number of Teams/Solution.ts index c257355c284cc..6ea38daa111d0 100644 --- a/solution/1300-1399/1395.Count Number of Teams/Solution.ts +++ b/solution/1300-1399/1395.Count Number of Teams/Solution.ts @@ -1,65 +1,19 @@ -class BinaryIndexedTree { - private n: number; - private c: number[]; - - constructor(n: number) { - this.n = n; - this.c = new Array(n + 1).fill(0); - } - - public update(x: number, v: number): void { - while (x <= this.n) { - this.c[x] += v; - x += x & -x; - } - } - - public query(x: number): number { - let s = 0; - while (x > 0) { - s += this.c[x]; - x -= x & -x; - } - return s; - } -} - function numTeams(rating: number[]): number { - let nums = [...rating]; - nums.sort((a, b) => a - b); + let ans = 0; const n = rating.length; - let m = 0; for (let i = 0; i < n; ++i) { - if (i === 0 || nums[i] !== nums[i - 1]) { - nums[m++] = nums[i]; - } - } - nums = nums.slice(0, m); - const search = (x: number): number => { let l = 0; - let r = m; - while (l < r) { - const mid = (l + r) >> 1; - if (nums[mid] >= x) { - r = mid; - } else { - l = mid + 1; + let r = 0; + for (let j = 0; j < i; ++j) { + if (rating[j] < rating[i]) { + ++l; + } + } + for (let j = i + 1; j < n; ++j) { + if (rating[j] > rating[i]) { + ++r; } } - return l + 1; - }; - let ans = 0; - const tree1 = new BinaryIndexedTree(m); - const tree2 = new BinaryIndexedTree(m); - for (const x of rating) { - tree2.update(search(x), 1); - } - for (let i = 0; i < n; ++i) { - const x = search(rating[i]); - tree1.update(x, 1); - tree2.update(x, -1); - const l = tree1.query(x - 1); - const r = n - i - 1 - tree2.query(x); ans += l * r; ans += (i - l) * (n - i - 1 - r); } diff --git a/solution/1300-1399/1395.Count Number of Teams/Solution2.cpp b/solution/1300-1399/1395.Count Number of Teams/Solution2.cpp new file mode 100644 index 0000000000000..2931e1e769b22 --- /dev/null +++ b/solution/1300-1399/1395.Count Number of Teams/Solution2.cpp @@ -0,0 +1,54 @@ +class BinaryIndexedTree { +public: + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + int query(int x) { + int s = 0; + while (x) { + s += c[x]; + x -= x & -x; + } + return s; + } + +private: + int n; + vector c; +}; + +class Solution { +public: + int numTeams(vector& rating) { + vector nums = rating; + sort(nums.begin(), nums.end()); + nums.erase(unique(nums.begin(), nums.end()), nums.end()); + int m = nums.size(); + BinaryIndexedTree tree1(m); + BinaryIndexedTree tree2(m); + for (int& v : rating) { + int x = lower_bound(nums.begin(), nums.end(), v) - nums.begin() + 1; + tree2.update(x, 1); + } + int ans = 0; + int n = rating.size(); + for (int i = 0; i < n; ++i) { + int x = lower_bound(nums.begin(), nums.end(), rating[i]) - nums.begin() + 1; + tree1.update(x, 1); + tree2.update(x, -1); + int l = tree1.query(x - 1); + int r = n - i - 1 - tree2.query(x); + ans += l * r; + ans += (i - l) * (n - i - 1 - r); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1300-1399/1395.Count Number of Teams/Solution2.go b/solution/1300-1399/1395.Count Number of Teams/Solution2.go new file mode 100644 index 0000000000000..1a142d63d097b --- /dev/null +++ b/solution/1300-1399/1395.Count Number of Teams/Solution2.go @@ -0,0 +1,55 @@ +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) update(x, delta int) { + for x <= this.n { + this.c[x] += delta + x += x & -x + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= x & -x + } + return s +} + +func numTeams(rating []int) (ans int) { + nums := make([]int, len(rating)) + copy(nums, rating) + sort.Ints(nums) + m := 0 + for i, x := range nums { + if i == 0 || x != nums[i-1] { + nums[m] = x + m++ + } + } + nums = nums[:m] + tree1 := newBinaryIndexedTree(m) + tree2 := newBinaryIndexedTree(m) + for _, x := range rating { + tree2.update(sort.SearchInts(nums, x)+1, 1) + } + n := len(rating) + for i, v := range rating { + x := sort.SearchInts(nums, v) + 1 + tree1.update(x, 1) + tree2.update(x, -1) + l := tree1.query(x - 1) + r := n - i - 1 - tree2.query(x) + ans += l * r + ans += (i - l) * (n - i - 1 - r) + } + return +} \ No newline at end of file diff --git a/solution/1300-1399/1395.Count Number of Teams/Solution2.java b/solution/1300-1399/1395.Count Number of Teams/Solution2.java new file mode 100644 index 0000000000000..110608e71628b --- /dev/null +++ b/solution/1300-1399/1395.Count Number of Teams/Solution2.java @@ -0,0 +1,70 @@ +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + this.c = new int[n + 1]; + } + + public void update(int x, int v) { + while (x <= n) { + c[x] += v; + x += x & -x; + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +} + +class Solution { + public int numTeams(int[] rating) { + int n = rating.length; + int[] nums = rating.clone(); + Arrays.sort(nums); + int m = 0; + for (int i = 0; i < n; ++i) { + if (i == 0 || nums[i] != nums[i - 1]) { + nums[m++] = nums[i]; + } + } + BinaryIndexedTree tree1 = new BinaryIndexedTree(m); + BinaryIndexedTree tree2 = new BinaryIndexedTree(m); + for (int v : rating) { + int x = search(nums, v); + tree2.update(x, 1); + } + + int ans = 0; + for (int i = 0; i < n; ++i) { + int x = search(nums, rating[i]); + tree1.update(x, 1); + tree2.update(x, -1); + int l = tree1.query(x - 1); + int r = n - i - 1 - tree2.query(x); + ans += l * r; + ans += (i - l) * (n - i - 1 - r); + } + return ans; + } + + private int search(int[] nums, int x) { + int l = 0, r = nums.length; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l + 1; + } +} \ No newline at end of file diff --git a/solution/1300-1399/1395.Count Number of Teams/Solution2.py b/solution/1300-1399/1395.Count Number of Teams/Solution2.py new file mode 100644 index 0000000000000..afec5cca654ec --- /dev/null +++ b/solution/1300-1399/1395.Count Number of Teams/Solution2.py @@ -0,0 +1,38 @@ +class BinaryIndexedTree: + def __init__(self, n: int): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x: int, v: int): + while x <= self.n: + self.c[x] += v + x += x & -x + + def query(self, x: int) -> int: + s = 0 + while x: + s += self.c[x] + x -= x & -x + return s + + +class Solution: + def numTeams(self, rating: List[int]) -> int: + nums = sorted(set(rating)) + m = len(nums) + tree1 = BinaryIndexedTree(m) + tree2 = BinaryIndexedTree(m) + for v in rating: + x = bisect_left(nums, v) + 1 + tree2.update(x, 1) + n = len(rating) + ans = 0 + for i, v in enumerate(rating): + x = bisect_left(nums, v) + 1 + tree1.update(x, 1) + tree2.update(x, -1) + l = tree1.query(x - 1) + r = n - i - 1 - tree2.query(x) + ans += l * r + ans += (i - l) * (n - i - 1 - r) + return ans diff --git a/solution/1300-1399/1395.Count Number of Teams/Solution2.ts b/solution/1300-1399/1395.Count Number of Teams/Solution2.ts new file mode 100644 index 0000000000000..c257355c284cc --- /dev/null +++ b/solution/1300-1399/1395.Count Number of Teams/Solution2.ts @@ -0,0 +1,67 @@ +class BinaryIndexedTree { + private n: number; + private c: number[]; + + constructor(n: number) { + this.n = n; + this.c = new Array(n + 1).fill(0); + } + + public update(x: number, v: number): void { + while (x <= this.n) { + this.c[x] += v; + x += x & -x; + } + } + + public query(x: number): number { + let s = 0; + while (x > 0) { + s += this.c[x]; + x -= x & -x; + } + return s; + } +} + +function numTeams(rating: number[]): number { + let nums = [...rating]; + nums.sort((a, b) => a - b); + const n = rating.length; + let m = 0; + for (let i = 0; i < n; ++i) { + if (i === 0 || nums[i] !== nums[i - 1]) { + nums[m++] = nums[i]; + } + } + nums = nums.slice(0, m); + const search = (x: number): number => { + let l = 0; + let r = m; + while (l < r) { + const mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l + 1; + }; + let ans = 0; + const tree1 = new BinaryIndexedTree(m); + const tree2 = new BinaryIndexedTree(m); + for (const x of rating) { + tree2.update(search(x), 1); + } + for (let i = 0; i < n; ++i) { + const x = search(rating[i]); + tree1.update(x, 1); + tree2.update(x, -1); + const l = tree1.query(x - 1); + const r = n - i - 1 - tree2.query(x); + ans += l * r; + ans += (i - l) * (n - i - 1 - r); + } + return ans; +} diff --git a/solution/1400-1499/1405.Longest Happy String/Solution.cpp b/solution/1400-1499/1405.Longest Happy String/Solution.cpp index a515ff8dbd250..26d34a579508d 100644 --- a/solution/1400-1499/1405.Longest Happy String/Solution.cpp +++ b/solution/1400-1499/1405.Longest Happy String/Solution.cpp @@ -33,4 +33,4 @@ class Solution { return ans; } -}; +}; \ No newline at end of file diff --git a/solution/1400-1499/1405.Longest Happy String/Solution.java b/solution/1400-1499/1405.Longest Happy String/Solution.java index cb6e1f5487183..17d094bb47276 100644 --- a/solution/1400-1499/1405.Longest Happy String/Solution.java +++ b/solution/1400-1499/1405.Longest Happy String/Solution.java @@ -37,4 +37,4 @@ public String longestDiverseString(int a, int b, int c) { return sb.toString(); } -} +} \ No newline at end of file diff --git a/solution/1400-1499/1408.String Matching in an Array/Solution.java b/solution/1400-1499/1408.String Matching in an Array/Solution.java index 5a3442b43d22b..83ca91ed3ba65 100644 --- a/solution/1400-1499/1408.String Matching in an Array/Solution.java +++ b/solution/1400-1499/1408.String Matching in an Array/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public List stringMatching(String[] words) { - List ans = new ArrayList<>(); - int n = words.length; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (i != j && words[j].contains(words[i])) { - ans.add(words[i]); - break; - } - } - } - return ans; - } +class Solution { + public List stringMatching(String[] words) { + List ans = new ArrayList<>(); + int n = words.length; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (i != j && words[j].contains(words[i])) { + ans.add(words[i]); + break; + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1400-1499/1408.String Matching in an Array/Solution.py b/solution/1400-1499/1408.String Matching in an Array/Solution.py index 2e440b5759f7a..08231a47cb278 100644 --- a/solution/1400-1499/1408.String Matching in an Array/Solution.py +++ b/solution/1400-1499/1408.String Matching in an Array/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def stringMatching(self, words: List[str]) -> List[str]: - ans = [] - for i, s in enumerate(words): - if any(i != j and s in t for j, t in enumerate(words)): - ans.append(s) - return ans +class Solution: + def stringMatching(self, words: List[str]) -> List[str]: + ans = [] + for i, s in enumerate(words): + if any(i != j and s in t for j, t in enumerate(words)): + ans.append(s) + return ans diff --git a/solution/1400-1499/1409.Queries on a Permutation With Key/Solution2.cpp b/solution/1400-1499/1409.Queries on a Permutation With Key/Solution2.cpp new file mode 100644 index 0000000000000..01fe6f9cd6e34 --- /dev/null +++ b/solution/1400-1499/1409.Queries on a Permutation With Key/Solution2.cpp @@ -0,0 +1,52 @@ +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + int lowbit(int x) { + return x & -x; + } +}; + +class Solution { +public: + vector processQueries(vector& queries, int m) { + int n = queries.size(); + vector pos(m + 1); + BinaryIndexedTree* tree = new BinaryIndexedTree(m + n); + for (int i = 1; i <= m; ++i) { + pos[i] = n + i; + tree->update(n + i, 1); + } + vector ans; + for (int i = 0; i < n; ++i) { + int v = queries[i]; + int j = pos[v]; + tree->update(j, -1); + ans.push_back(tree->query(j)); + pos[v] = n - i; + tree->update(n - i, 1); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1400-1499/1409.Queries on a Permutation With Key/Solution2.go b/solution/1400-1499/1409.Queries on a Permutation With Key/Solution2.go new file mode 100644 index 0000000000000..3818a3a70e25a --- /dev/null +++ b/solution/1400-1499/1409.Queries on a Permutation With Key/Solution2.go @@ -0,0 +1,48 @@ +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) lowbit(x int) int { + return x & -x +} + +func (this *BinaryIndexedTree) update(x, delta int) { + for x <= this.n { + this.c[x] += delta + x += this.lowbit(x) + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= this.lowbit(x) + } + return s +} + +func processQueries(queries []int, m int) []int { + n := len(queries) + pos := make([]int, m+1) + tree := newBinaryIndexedTree(m + n) + for i := 1; i <= m; i++ { + pos[i] = n + i + tree.update(n+i, 1) + } + ans := []int{} + for i, v := range queries { + j := pos[v] + tree.update(j, -1) + ans = append(ans, tree.query(j)) + pos[v] = n - i + tree.update(n-i, 1) + } + return ans +} \ No newline at end of file diff --git a/solution/1400-1499/1409.Queries on a Permutation With Key/Solution2.java b/solution/1400-1499/1409.Queries on a Permutation With Key/Solution2.java new file mode 100644 index 0000000000000..132838b386e35 --- /dev/null +++ b/solution/1400-1499/1409.Queries on a Permutation With Key/Solution2.java @@ -0,0 +1,52 @@ +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + public static int lowbit(int x) { + return x & -x; + } +} + +class Solution { + public int[] processQueries(int[] queries, int m) { + int n = queries.length; + BinaryIndexedTree tree = new BinaryIndexedTree(m + n); + int[] pos = new int[m + 1]; + for (int i = 1; i <= m; ++i) { + pos[i] = n + i; + tree.update(n + i, 1); + } + int[] ans = new int[n]; + int k = 0; + for (int i = 0; i < n; ++i) { + int v = queries[i]; + int j = pos[v]; + tree.update(j, -1); + ans[k++] = tree.query(j); + pos[v] = n - i; + tree.update(n - i, 1); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1400-1499/1409.Queries on a Permutation With Key/Solution2.py b/solution/1400-1499/1409.Queries on a Permutation With Key/Solution2.py new file mode 100644 index 0000000000000..7936f2b5ad357 --- /dev/null +++ b/solution/1400-1499/1409.Queries on a Permutation With Key/Solution2.py @@ -0,0 +1,39 @@ +class BinaryIndexedTree: + def __init__(self, n): + self.n = n + self.c = [0] * (n + 1) + + @staticmethod + def lowbit(x): + return x & -x + + def update(self, x, delta): + while x <= self.n: + self.c[x] += delta + x += BinaryIndexedTree.lowbit(x) + + def query(self, x): + s = 0 + while x > 0: + s += self.c[x] + x -= BinaryIndexedTree.lowbit(x) + return s + + +class Solution: + def processQueries(self, queries: List[int], m: int) -> List[int]: + n = len(queries) + pos = [0] * (m + 1) + tree = BinaryIndexedTree(m + n) + for i in range(1, m + 1): + pos[i] = n + i + tree.update(n + i, 1) + + ans = [] + for i, v in enumerate(queries): + j = pos[v] + tree.update(j, -1) + ans.append(tree.query(j)) + pos[v] = n - i + tree.update(n - i, 1) + return ans diff --git a/solution/1400-1499/1410.HTML Entity Parser/Solution.cpp b/solution/1400-1499/1410.HTML Entity Parser/Solution.cpp index 6bcfda15178fb..2b14ee6debcb8 100644 --- a/solution/1400-1499/1410.HTML Entity Parser/Solution.cpp +++ b/solution/1400-1499/1410.HTML Entity Parser/Solution.cpp @@ -1,32 +1,32 @@ -class Solution { -public: - string entityParser(string text) { - unordered_map d = { - {""", "\""}, - {"'", "'"}, - {"&", "&"}, - {">", ">"}, - {"<", "<"}, - {"⁄", "/"}, - }; - string ans = ""; - int i = 0, n = text.size(); - while (i < n) { - bool found = false; - for (int l = 1; l < 8; ++l) { - int j = i + l; - if (j <= n) { - string t = text.substr(i, l); - if (d.count(t)) { - ans += d[t]; - i = j; - found = true; - break; - } - } - } - if (!found) ans += text[i++]; - } - return ans; - } +class Solution { +public: + string entityParser(string text) { + unordered_map d = { + {""", "\""}, + {"'", "'"}, + {"&", "&"}, + {">", ">"}, + {"<", "<"}, + {"⁄", "/"}, + }; + string ans = ""; + int i = 0, n = text.size(); + while (i < n) { + bool found = false; + for (int l = 1; l < 8; ++l) { + int j = i + l; + if (j <= n) { + string t = text.substr(i, l); + if (d.count(t)) { + ans += d[t]; + i = j; + found = true; + break; + } + } + } + if (!found) ans += text[i++]; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1400-1499/1410.HTML Entity Parser/Solution.java b/solution/1400-1499/1410.HTML Entity Parser/Solution.java index a81697386f84b..bafbb948cf317 100644 --- a/solution/1400-1499/1410.HTML Entity Parser/Solution.java +++ b/solution/1400-1499/1410.HTML Entity Parser/Solution.java @@ -11,7 +11,7 @@ public String entityParser(String text) { int i = 0; int n = text.length(); while (i < n) { - boolean find = false; + boolean found = false; for (int l = 1; l < 8; ++l) { int j = i + l; if (j <= n) { @@ -19,12 +19,12 @@ public String entityParser(String text) { if (d.containsKey(t)) { ans.append(d.get(t)); i = j; - find = true; + found = true; break; } } } - if (!find) { + if (!found) { ans.append(text.charAt(i++)); } } diff --git a/solution/1400-1499/1410.HTML Entity Parser/Solution.ts b/solution/1400-1499/1410.HTML Entity Parser/Solution.ts index 7fb46770b455a..145369b61e48f 100644 --- a/solution/1400-1499/1410.HTML Entity Parser/Solution.ts +++ b/solution/1400-1499/1410.HTML Entity Parser/Solution.ts @@ -1,5 +1,5 @@ function entityParser(text: string): string { - const d: { [key: string]: string } = { + const d: Record = { '"': '"', ''': "'", '&': '&', @@ -8,6 +8,29 @@ function entityParser(text: string): string { '⁄': '/', }; - const pattern = new RegExp(Object.keys(d).join('|'), 'g'); - return text.replace(pattern, match => d[match]); + let ans: string = ''; + let i: number = 0; + const n: number = text.length; + + while (i < n) { + let found: boolean = false; + for (let l: number = 1; l < 8; ++l) { + const j: number = i + l; + if (j <= n) { + const t: string = text.substring(i, j); + if (d.hasOwnProperty(t)) { + ans += d[t]; + i = j; + found = true; + break; + } + } + } + + if (!found) { + ans += text[i++]; + } + } + + return ans; } diff --git a/solution/1400-1499/1410.HTML Entity Parser/Solution2.ts b/solution/1400-1499/1410.HTML Entity Parser/Solution2.ts new file mode 100644 index 0000000000000..7fb46770b455a --- /dev/null +++ b/solution/1400-1499/1410.HTML Entity Parser/Solution2.ts @@ -0,0 +1,13 @@ +function entityParser(text: string): string { + const d: { [key: string]: string } = { + '"': '"', + ''': "'", + '&': '&', + '>': '>', + '<': '<', + '⁄': '/', + }; + + const pattern = new RegExp(Object.keys(d).join('|'), 'g'); + return text.replace(pattern, match => d[match]); +} diff --git "a/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/Solution2.cpp" "b/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/Solution2.cpp" new file mode 100644 index 0000000000000..b0f45f61c6948 --- /dev/null +++ "b/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/Solution2.cpp" @@ -0,0 +1,60 @@ +class Solution { +public: + int numOfWays(int n) { + int m = 27; + + auto f1 = [&](int x) { + int last = -1; + for (int i = 0; i < 3; ++i) { + if (x % 3 == last) { + return false; + } + last = x % 3; + x /= 3; + } + return true; + }; + auto f2 = [&](int x, int y) { + for (int i = 0; i < 3; ++i) { + if (x % 3 == y % 3) { + return false; + } + x /= 3; + y /= 3; + } + return true; + }; + + const int mod = 1e9 + 7; + unordered_set valid; + vector f(m); + for (int i = 0; i < m; ++i) { + if (f1(i)) { + valid.insert(i); + f[i] = 1; + } + } + unordered_map> d; + for (int i : valid) { + for (int j : valid) { + if (f2(i, j)) { + d[i].push_back(j); + } + } + } + for (int k = 1; k < n; ++k) { + vector g(m); + for (int i : valid) { + for (int j : d[i]) { + g[j] = (g[j] + f[i]) % mod; + } + } + f = move(g); + } + int ans = 0; + for (int x : f) { + ans = (ans + x) % mod; + } + return ans; + } +}; \ No newline at end of file diff --git "a/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/Solution2.go" "b/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/Solution2.go" new file mode 100644 index 0000000000000..b5e2802c72d5b --- /dev/null +++ "b/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/Solution2.go" @@ -0,0 +1,54 @@ +func numOfWays(n int) (ans int) { + f1 := func(x int) bool { + last := -1 + for i := 0; i < 3; i++ { + if x%3 == last { + return false + } + last = x % 3 + x /= 3 + } + return true + } + f2 := func(x, y int) bool { + for i := 0; i < 3; i++ { + if x%3 == y%3 { + return false + } + x /= 3 + y /= 3 + } + return true + } + m := 27 + valid := map[int]bool{} + f := make([]int, m) + for i := 0; i < m; i++ { + if f1(i) { + valid[i] = true + f[i] = 1 + } + } + d := map[int][]int{} + for i := range valid { + for j := range valid { + if f2(i, j) { + d[i] = append(d[i], j) + } + } + } + const mod int = 1e9 + 7 + for k := 1; k < n; k++ { + g := make([]int, m) + for i := range valid { + for _, j := range d[i] { + g[i] = (g[i] + f[j]) % mod + } + } + f = g + } + for _, x := range f { + ans = (ans + x) % mod + } + return +} \ No newline at end of file diff --git "a/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/Solution2.java" "b/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/Solution2.java" new file mode 100644 index 0000000000000..c0aa981f6b70b --- /dev/null +++ "b/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/Solution2.java" @@ -0,0 +1,59 @@ +class Solution { + public int numOfWays(int n) { + final int mod = (int) 1e9 + 7; + int m = 27; + Set valid = new HashSet<>(); + int[] f = new int[m]; + for (int i = 0; i < m; ++i) { + if (f1(i)) { + valid.add(i); + f[i] = 1; + } + } + Map> d = new HashMap<>(); + for (int i : valid) { + for (int j : valid) { + if (f2(i, j)) { + d.computeIfAbsent(i, k -> new ArrayList<>()).add(j); + } + } + } + for (int k = 1; k < n; ++k) { + int[] g = new int[m]; + for (int i : valid) { + for (int j : d.getOrDefault(i, List.of())) { + g[j] = (g[j] + f[i]) % mod; + } + } + f = g; + } + int ans = 0; + for (int x : f) { + ans = (ans + x) % mod; + } + return ans; + } + + private boolean f1(int x) { + int last = -1; + for (int i = 0; i < 3; ++i) { + if (x % 3 == last) { + return false; + } + last = x % 3; + x /= 3; + } + return true; + } + + private boolean f2(int x, int y) { + for (int i = 0; i < 3; ++i) { + if (x % 3 == y % 3) { + return false; + } + x /= 3; + y /= 3; + } + return true; + } +} \ No newline at end of file diff --git "a/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/Solution2.py" "b/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/Solution2.py" new file mode 100644 index 0000000000000..92a28c4a5707f --- /dev/null +++ "b/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/Solution2.py" @@ -0,0 +1,35 @@ +class Solution: + def numOfWays(self, n: int) -> int: + def f1(x: int) -> bool: + last = -1 + for _ in range(3): + if x % 3 == last: + return False + last = x % 3 + x //= 3 + return True + + def f2(x: int, y: int) -> bool: + for _ in range(3): + if x % 3 == y % 3: + return False + x //= 3 + y //= 3 + return True + + mod = 10**9 + 7 + m = 27 + valid = {i for i in range(m) if f1(i)} + d = defaultdict(list) + for i in valid: + for j in valid: + if f2(i, j): + d[i].append(j) + f = [int(i in valid) for i in range(m)] + for _ in range(n - 1): + g = [0] * m + for i in valid: + for j in d[i]: + g[j] = (g[j] + f[i]) % mod + f = g + return sum(f) % mod diff --git "a/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/Solution2.ts" "b/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/Solution2.ts" new file mode 100644 index 0000000000000..786fa632b5e99 --- /dev/null +++ "b/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/Solution2.ts" @@ -0,0 +1,55 @@ +function numOfWays(n: number): number { + const f1 = (x: number): boolean => { + let last = -1; + for (let i = 0; i < 3; ++i) { + if (x % 3 === last) { + return false; + } + last = x % 3; + x = Math.floor(x / 3); + } + return true; + }; + const f2 = (x: number, y: number): boolean => { + for (let i = 0; i < 3; ++i) { + if (x % 3 === y % 3) { + return false; + } + x = Math.floor(x / 3); + y = Math.floor(y / 3); + } + return true; + }; + const m = 27; + const valid = new Set(); + const f: number[] = Array(m).fill(0); + for (let i = 0; i < m; ++i) { + if (f1(i)) { + valid.add(i); + f[i] = 1; + } + } + const d: Map = new Map(); + for (const i of valid) { + for (const j of valid) { + if (f2(i, j)) { + d.set(i, (d.get(i) || []).concat(j)); + } + } + } + const mod = 10 ** 9 + 7; + for (let k = 1; k < n; ++k) { + const g: number[] = Array(m).fill(0); + for (const i of valid) { + for (const j of d.get(i) || []) { + g[i] = (g[i] + f[j]) % mod; + } + } + f.splice(0, f.length, ...g); + } + let ans = 0; + for (const x of f) { + ans = (ans + x) % mod; + } + return ans; +} diff --git a/solution/1400-1499/1413.Minimum Value to Get Positive Step by Step Sum/Solution2.py b/solution/1400-1499/1413.Minimum Value to Get Positive Step by Step Sum/Solution2.py new file mode 100644 index 0000000000000..3f1e937e767a8 --- /dev/null +++ b/solution/1400-1499/1413.Minimum Value to Get Positive Step by Step Sum/Solution2.py @@ -0,0 +1,4 @@ +class Solution: + def minStartValue(self, nums: List[int]) -> int: + s = list(accumulate(nums)) + return 1 if min(s) >= 0 else abs(min(s)) + 1 diff --git a/solution/1400-1499/1414.Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/Solution.java b/solution/1400-1499/1414.Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/Solution.java index ece69fa3dc52d..dfc3b8ae6d741 100644 --- a/solution/1400-1499/1414.Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/Solution.java +++ b/solution/1400-1499/1414.Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/Solution.java @@ -1,4 +1,5 @@ class Solution { + public int findMinFibonacciNumbers(int k) { if (k < 2) { return k; diff --git a/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution.cpp b/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution.cpp index 3109efd6356e9..f78ec22439dcc 100644 --- a/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution.cpp +++ b/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution.cpp @@ -1,12 +1,15 @@ class Solution { public: int maxScore(string s) { - int t = 0; - if (s[0] == '0') ++t; - for (int i = 1; i < s.size(); ++i) t += s[i] == '1'; - int ans = t; - for (int i = 1; i < s.size() - 1; ++i) { - t += s[i] == '0' ? 1 : -1; + int ans = 0; + for (int i = 1, n = s.size(); i < n; ++i) { + int t = 0; + for (int j = 0; j < i; ++j) { + t += s[j] == '0'; + } + for (int j = i; j < n; ++j) { + t += s[j] == '1'; + } ans = max(ans, t); } return ans; diff --git a/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution.go b/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution.go index 26aad8e48a855..901ebc0bb8520 100644 --- a/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution.go +++ b/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution.go @@ -1,20 +1,16 @@ func maxScore(s string) int { - t := 0 - if s[0] == '0' { - t++ - } - n := len(s) - for i := 1; i < n; i++ { - if s[i] == '1' { - t++ + ans := 0 + for i, n := 1, len(s); i < n; i++ { + t := 0 + for j := 0; j < i; j++ { + if s[j] == '0' { + t++ + } } - } - ans := t - for i := 1; i < n-1; i++ { - if s[i] == '0' { - t++ - } else { - t-- + for j := i; j < n; j++ { + if s[j] == '1' { + t++ + } } ans = max(ans, t) } diff --git a/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution.java b/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution.java index 2af2f65f0d499..e3dad9d463fe2 100644 --- a/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution.java +++ b/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution.java @@ -1,17 +1,18 @@ class Solution { public int maxScore(String s) { - int t = 0; - if (s.charAt(0) == '0') { - t++; - } + int ans = 0; for (int i = 1; i < s.length(); ++i) { - if (s.charAt(i) == '1') { - t++; + int t = 0; + for (int j = 0; j < i; ++j) { + if (s.charAt(j) == '0') { + ++t; + } + } + for (int j = i; j < s.length(); ++j) { + if (s.charAt(j) == '1') { + ++t; + } } - } - int ans = t; - for (int i = 1; i < s.length() - 1; ++i) { - t += s.charAt(i) == '0' ? 1 : -1; ans = Math.max(ans, t); } return ans; diff --git a/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution.py b/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution.py index 04eb3724a077c..ab07d81eec3ef 100644 --- a/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution.py +++ b/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution.py @@ -1,7 +1,3 @@ class Solution: def maxScore(self, s: str) -> int: - ans = t = (s[0] == '0') + s[1:].count('1') - for i in range(1, len(s) - 1): - t += 1 if s[i] == '0' else -1 - ans = max(ans, t) - return ans + return max(s[:i].count('0') + s[i:].count('1') for i in range(1, len(s))) diff --git a/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution2.cpp b/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution2.cpp new file mode 100644 index 0000000000000..3109efd6356e9 --- /dev/null +++ b/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int maxScore(string s) { + int t = 0; + if (s[0] == '0') ++t; + for (int i = 1; i < s.size(); ++i) t += s[i] == '1'; + int ans = t; + for (int i = 1; i < s.size() - 1; ++i) { + t += s[i] == '0' ? 1 : -1; + ans = max(ans, t); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution2.go b/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution2.go new file mode 100644 index 0000000000000..26aad8e48a855 --- /dev/null +++ b/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution2.go @@ -0,0 +1,22 @@ +func maxScore(s string) int { + t := 0 + if s[0] == '0' { + t++ + } + n := len(s) + for i := 1; i < n; i++ { + if s[i] == '1' { + t++ + } + } + ans := t + for i := 1; i < n-1; i++ { + if s[i] == '0' { + t++ + } else { + t-- + } + ans = max(ans, t) + } + return ans +} \ No newline at end of file diff --git a/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution2.java b/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution2.java new file mode 100644 index 0000000000000..2af2f65f0d499 --- /dev/null +++ b/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution2.java @@ -0,0 +1,19 @@ +class Solution { + public int maxScore(String s) { + int t = 0; + if (s.charAt(0) == '0') { + t++; + } + for (int i = 1; i < s.length(); ++i) { + if (s.charAt(i) == '1') { + t++; + } + } + int ans = t; + for (int i = 1; i < s.length() - 1; ++i) { + t += s.charAt(i) == '0' ? 1 : -1; + ans = Math.max(ans, t); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution2.py b/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution2.py new file mode 100644 index 0000000000000..04eb3724a077c --- /dev/null +++ b/solution/1400-1499/1422.Maximum Score After Splitting a String/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def maxScore(self, s: str) -> int: + ans = t = (s[0] == '0') + s[1:].count('1') + for i in range(1, len(s) - 1): + t += 1 if s[i] == '0' else -1 + ans = max(ans, t) + return ans diff --git a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.cpp b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.cpp index ee700dace24d8..378b2983f1bb5 100644 --- a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.cpp +++ b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.cpp @@ -1,13 +1,13 @@ -class Solution { -public: - int maxScore(vector& cardPoints, int k) { - int n = cardPoints.size(); - int s = accumulate(cardPoints.end() - k, cardPoints.end(), 0); - int ans = s; - for (int i = 0; i < k; ++i) { - s += cardPoints[i] - cardPoints[n - k + i]; - ans = max(ans, s); - } - return ans; - } +class Solution { +public: + int maxScore(vector& cardPoints, int k) { + int n = cardPoints.size(); + int s = accumulate(cardPoints.end() - k, cardPoints.end(), 0); + int ans = s; + for (int i = 0; i < k; ++i) { + s += cardPoints[i] - cardPoints[n - k + i]; + ans = max(ans, s); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.cs b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.cs index fcc263877bbae..e9ba12e25e480 100644 --- a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.cs +++ b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.cs @@ -1,12 +1,12 @@ -public class Solution { - public int MaxScore(int[] cardPoints, int k) { - int n = cardPoints.Length; - int s = cardPoints[^k..].Sum(); - int ans = s; - for (int i = 0; i < k; ++i) { - s += cardPoints[i] - cardPoints[n - k + i]; - ans = Math.Max(ans, s); - } - return ans; - } -} \ No newline at end of file +public class Solution { + public int MaxScore(int[] cardPoints, int k) { + int n = cardPoints.Length; + int s = cardPoints[^k..].Sum(); + int ans = s; + for (int i = 0; i < k; ++i) { + s += cardPoints[i] - cardPoints[n - k + i]; + ans = Math.Max(ans, s); + } + return ans; + } +} diff --git a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.java b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.java index 8fa5e9535071c..3984b676bb2bd 100644 --- a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.java +++ b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.java @@ -1,14 +1,14 @@ -class Solution { - public int maxScore(int[] cardPoints, int k) { - int s = 0, n = cardPoints.length; - for (int i = n - k; i < n; ++i) { - s += cardPoints[i]; - } - int ans = s; - for (int i = 0; i < k; ++i) { - s += cardPoints[i] - cardPoints[n - k + i]; - ans = Math.max(ans, s); - } - return ans; - } +class Solution { + public int maxScore(int[] cardPoints, int k) { + int s = 0, n = cardPoints.length; + for (int i = n - k; i < n; ++i) { + s += cardPoints[i]; + } + int ans = s; + for (int i = 0; i < k; ++i) { + s += cardPoints[i] - cardPoints[n - k + i]; + ans = Math.max(ans, s); + } + return ans; + } } \ No newline at end of file diff --git a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.kt b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.kt index b0a4c26bc531d..c7b05588a5ba8 100644 --- a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.kt +++ b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.kt @@ -1,12 +1,12 @@ -class Solution { - fun maxScore(cardPoints: IntArray, k: Int): Int { - val n = cardPoints.size - var s = cardPoints.sliceArray(n - k until n).sum() - var ans = s - for (i in 0 until k) { - s += cardPoints[i] - cardPoints[n - k + i] - ans = maxOf(ans, s) - } - return ans - } -} \ No newline at end of file +class Solution { + fun maxScore(cardPoints: IntArray, k: Int): Int { + val n = cardPoints.size + var s = cardPoints.sliceArray(n - k until n).sum() + var ans = s + for (i in 0 until k) { + s += cardPoints[i] - cardPoints[n - k + i] + ans = maxOf(ans, s) + } + return ans + } +} diff --git a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.php b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.php index 51235fb0ac772..d624e3958a82e 100644 --- a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.php +++ b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.php @@ -14,4 +14,4 @@ function maxScore($cardPoints, $k) { } return $ans; } -} \ No newline at end of file +} diff --git a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.py b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.py index f40cab157e12f..ae66619885814 100644 --- a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.py +++ b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def maxScore(self, cardPoints: List[int], k: int) -> int: - ans = s = sum(cardPoints[-k:]) - for i, x in enumerate(cardPoints[:k]): - s += x - cardPoints[-k + i] - ans = max(ans, s) - return ans +class Solution: + def maxScore(self, cardPoints: List[int], k: int) -> int: + ans = s = sum(cardPoints[-k:]) + for i, x in enumerate(cardPoints[:k]): + s += x - cardPoints[-k + i] + ans = max(ans, s) + return ans diff --git a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.rb b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.rb index 6e058bc599fcc..055c1d348954d 100644 --- a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.rb +++ b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.rb @@ -1,13 +1,13 @@ -# @param {Integer[]} card_points -# @param {Integer} k -# @return {Integer} -def max_score(card_points, k) - n = card_points.length - s = card_points[-k..].sum - ans = s - k.times do |i| - s += card_points[i] - card_points[n - k + i] - ans = [ans, s].max - end - ans -end \ No newline at end of file +# @param {Integer[]} card_points +# @param {Integer} k +# @return {Integer} +def max_score(card_points, k) + n = card_points.length + s = card_points[-k..].sum + ans = s + k.times do |i| + s += card_points[i] - card_points[n - k + i] + ans = [ans, s].max + end + ans +end diff --git a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.scala b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.scala index 2b6f7f22f1306..1ee7c162da531 100644 --- a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.scala +++ b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.scala @@ -1,12 +1,12 @@ -object Solution { - def maxScore(cardPoints: Array[Int], k: Int): Int = { - val n = cardPoints.length - var s = cardPoints.takeRight(k).sum - var ans = s - for (i <- 0 until k) { - s += cardPoints(i) - cardPoints(n - k + i) - ans = ans.max(s) - } - ans - } -} \ No newline at end of file +object Solution { + def maxScore(cardPoints: Array[Int], k: Int): Int = { + val n = cardPoints.length + var s = cardPoints.takeRight(k).sum + var ans = s + for (i <- 0 until k) { + s += cardPoints(i) - cardPoints(n - k + i) + ans = ans.max(s) + } + ans + } +} diff --git a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.swift b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.swift index c1a1449af04ae..f64a5ef59a13e 100644 --- a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.swift +++ b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/Solution.swift @@ -1,12 +1,12 @@ -class Solution { - func maxScore(_ cardPoints: [Int], _ k: Int) -> Int { - let n = cardPoints.count - var s = cardPoints.suffix(k).reduce(0, +) - var ans = s - for i in 0.. Int { + let n = cardPoints.count + var s = cardPoints.suffix(k).reduce(0, +) + var ans = s + for i in 0..& arr) { - int cnt[1001]{}; - for (int x : arr) { - ++cnt[x]; - } - int ans = 0; - for (int x = 0; x < 1000; ++x) { - if (cnt[x + 1]) { - ans += cnt[x]; - } - } - return ans; - } +class Solution { +public: + int countElements(vector& arr) { + int cnt[1001]{}; + for (int x : arr) { + ++cnt[x]; + } + int ans = 0; + for (int x = 0; x < 1000; ++x) { + if (cnt[x + 1]) { + ans += cnt[x]; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1400-1499/1426.Counting Elements/Solution.java b/solution/1400-1499/1426.Counting Elements/Solution.java index afe2f735ec494..45f1aaf81d6da 100644 --- a/solution/1400-1499/1426.Counting Elements/Solution.java +++ b/solution/1400-1499/1426.Counting Elements/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public int countElements(int[] arr) { - int[] cnt = new int[1002]; - for (int x : arr) { - ++cnt[x]; - } - int ans = 0; - for (int x = 0; x < 1001; ++x) { - if (cnt[x + 1] > 0) { - ans += cnt[x]; - } - } - return ans; - } +class Solution { + public int countElements(int[] arr) { + int[] cnt = new int[1001]; + for (int x : arr) { + ++cnt[x]; + } + int ans = 0; + for (int x = 0; x < 1000; ++x) { + if (cnt[x + 1] > 0) { + ans += cnt[x]; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1400-1499/1426.Counting Elements/Solution.php b/solution/1400-1499/1426.Counting Elements/Solution.php index be3606aa2e746..4a6acb5779b33 100644 --- a/solution/1400-1499/1426.Counting Elements/Solution.php +++ b/solution/1400-1499/1426.Counting Elements/Solution.php @@ -13,4 +13,4 @@ function countElements($arr) { } return $ans; } -} \ No newline at end of file +} diff --git a/solution/1400-1499/1426.Counting Elements/Solution.py b/solution/1400-1499/1426.Counting Elements/Solution.py index d703f8e623863..feb831a6cac01 100644 --- a/solution/1400-1499/1426.Counting Elements/Solution.py +++ b/solution/1400-1499/1426.Counting Elements/Solution.py @@ -1,4 +1,4 @@ -class Solution: - def countElements(self, arr: List[int]) -> int: - cnt = Counter(arr) - return sum(v for x, v in cnt.items() if cnt[x + 1]) +class Solution: + def countElements(self, arr: List[int]) -> int: + cnt = Counter(arr) + return sum(v for x, v in cnt.items() if cnt[x + 1]) diff --git a/solution/1400-1499/1427.Perform String Shifts/Solution.java b/solution/1400-1499/1427.Perform String Shifts/Solution.java index d7ffd1e9a332c..d9cf09329e0cc 100644 --- a/solution/1400-1499/1427.Perform String Shifts/Solution.java +++ b/solution/1400-1499/1427.Perform String Shifts/Solution.java @@ -1,14 +1,14 @@ -class Solution { - public String stringShift(String s, int[][] shift) { - int x = 0; - for (var e : shift) { - if (e[0] == 0) { - e[1] *= -1; - } - x += e[1]; - } - int n = s.length(); - x = (x % n + n) % n; - return s.substring(n - x) + s.substring(0, n - x); - } +class Solution { + public String stringShift(String s, int[][] shift) { + int x = 0; + for (var e : shift) { + if (e[0] == 0) { + e[1] *= -1; + } + x += e[1]; + } + int n = s.length(); + x = (x % n + n) % n; + return s.substring(n - x) + s.substring(0, n - x); + } } \ No newline at end of file diff --git a/solution/1400-1499/1427.Perform String Shifts/Solution.py b/solution/1400-1499/1427.Perform String Shifts/Solution.py index d274495f65eb3..2c61fe7f1cf5d 100644 --- a/solution/1400-1499/1427.Perform String Shifts/Solution.py +++ b/solution/1400-1499/1427.Perform String Shifts/Solution.py @@ -1,5 +1,5 @@ -class Solution: - def stringShift(self, s: str, shift: List[List[int]]) -> str: - x = sum((b if a else -b) for a, b in shift) - x %= len(s) - return s[-x:] + s[:-x] +class Solution: + def stringShift(self, s: str, shift: List[List[int]]) -> str: + x = sum((b if a else -b) for a, b in shift) + x %= len(s) + return s[-x:] + s[:-x] diff --git a/solution/1400-1499/1428.Leftmost Column with at Least a One/Solution.cpp b/solution/1400-1499/1428.Leftmost Column with at Least a One/Solution.cpp index 1725dceff57dc..202cf3f82930f 100644 --- a/solution/1400-1499/1428.Leftmost Column with at Least a One/Solution.cpp +++ b/solution/1400-1499/1428.Leftmost Column with at Least a One/Solution.cpp @@ -1,31 +1,31 @@ -/** - * // This is the BinaryMatrix's API interface. - * // You should not implement it, or speculate about its implementation - * class BinaryMatrix { - * public: - * int get(int row, int col); - * vector dimensions(); - * }; - */ - -class Solution { -public: - int leftMostColumnWithOne(BinaryMatrix& binaryMatrix) { - auto e = binaryMatrix.dimensions(); - int m = e[0], n = e[1]; - int ans = n; - for (int i = 0; i < m; ++i) { - int l = 0, r = n; - while (l < r) { - int mid = (l + r) >> 1; - if (binaryMatrix.get(i, mid)) { - r = mid; - } else { - l = mid + 1; - } - } - ans = min(ans, l); - } - return ans >= n ? -1 : ans; - } +/** + * // This is the BinaryMatrix's API interface. + * // You should not implement it, or speculate about its implementation + * class BinaryMatrix { + * public: + * int get(int row, int col); + * vector dimensions(); + * }; + */ + +class Solution { +public: + int leftMostColumnWithOne(BinaryMatrix& binaryMatrix) { + auto e = binaryMatrix.dimensions(); + int m = e[0], n = e[1]; + int ans = n; + for (int i = 0; i < m; ++i) { + int l = 0, r = n; + while (l < r) { + int mid = (l + r) >> 1; + if (binaryMatrix.get(i, mid)) { + r = mid; + } else { + l = mid + 1; + } + } + ans = min(ans, l); + } + return ans >= n ? -1 : ans; + } }; \ No newline at end of file diff --git a/solution/1400-1499/1428.Leftmost Column with at Least a One/Solution.cs b/solution/1400-1499/1428.Leftmost Column with at Least a One/Solution.cs index 51ce96c39375d..8479556f52ed0 100644 --- a/solution/1400-1499/1428.Leftmost Column with at Least a One/Solution.cs +++ b/solution/1400-1499/1428.Leftmost Column with at Least a One/Solution.cs @@ -1,29 +1,29 @@ -/** - * // This is BinaryMatrix's API interface. - * // You should not implement it, or speculate about its implementation - * class BinaryMatrix { - * public int Get(int row, int col) {} - * public IList Dimensions() {} - * } - */ - -class Solution { - public int LeftMostColumnWithOne(BinaryMatrix binaryMatrix) { - var e = binaryMatrix.Dimensions(); - int m = e[0], n = e[1]; - int ans = n; - for (int i = 0; i < m; ++i) { - int l = 0, r = n; - while (l < r) { - int mid = (l + r) >> 1; - if (binaryMatrix.Get(i, mid) == 1) { - r = mid; - } else { - l = mid + 1; - } - } - ans = Math.Min(ans, l); - } - return ans >= n ? -1 : ans; - } -} \ No newline at end of file +/** + * // This is BinaryMatrix's API interface. + * // You should not implement it, or speculate about its implementation + * class BinaryMatrix { + * public int Get(int row, int col) {} + * public IList Dimensions() {} + * } + */ + +class Solution { + public int LeftMostColumnWithOne(BinaryMatrix binaryMatrix) { + var e = binaryMatrix.Dimensions(); + int m = e[0], n = e[1]; + int ans = n; + for (int i = 0; i < m; ++i) { + int l = 0, r = n; + while (l < r) { + int mid = (l + r) >> 1; + if (binaryMatrix.Get(i, mid) == 1) { + r = mid; + } else { + l = mid + 1; + } + } + ans = Math.Min(ans, l); + } + return ans >= n ? -1 : ans; + } +} diff --git a/solution/1400-1499/1428.Leftmost Column with at Least a One/Solution.java b/solution/1400-1499/1428.Leftmost Column with at Least a One/Solution.java index 812806f5916a4..13de1dd186c45 100644 --- a/solution/1400-1499/1428.Leftmost Column with at Least a One/Solution.java +++ b/solution/1400-1499/1428.Leftmost Column with at Least a One/Solution.java @@ -1,29 +1,29 @@ -/** - * // This is the BinaryMatrix's API interface. - * // You should not implement it, or speculate about its implementation - * interface BinaryMatrix { - * public int get(int row, int col) {} - * public List dimensions {} - * }; - */ - -class Solution { - public int leftMostColumnWithOne(BinaryMatrix binaryMatrix) { - List e = binaryMatrix.dimensions(); - int m = e.get(0), n = e.get(1); - int ans = n; - for (int i = 0; i < m; ++i) { - int l = 0, r = n; - while (l < r) { - int mid = (l + r) >> 1; - if (binaryMatrix.get(i, mid) == 1) { - r = mid; - } else { - l = mid + 1; - } - } - ans = Math.min(ans, l); - } - return ans >= n ? -1 : ans; - } +/** + * // This is the BinaryMatrix's API interface. + * // You should not implement it, or speculate about its implementation + * interface BinaryMatrix { + * public int get(int row, int col) {} + * public List dimensions {} + * }; + */ + +class Solution { + public int leftMostColumnWithOne(BinaryMatrix binaryMatrix) { + List e = binaryMatrix.dimensions(); + int m = e.get(0), n = e.get(1); + int ans = n; + for (int i = 0; i < m; ++i) { + int l = 0, r = n; + while (l < r) { + int mid = (l + r) >> 1; + if (binaryMatrix.get(i, mid) == 1) { + r = mid; + } else { + l = mid + 1; + } + } + ans = Math.min(ans, l); + } + return ans >= n ? -1 : ans; + } } \ No newline at end of file diff --git a/solution/1400-1499/1428.Leftmost Column with at Least a One/Solution.py b/solution/1400-1499/1428.Leftmost Column with at Least a One/Solution.py index 50d0d102db641..338efdc41666c 100644 --- a/solution/1400-1499/1428.Leftmost Column with at Least a One/Solution.py +++ b/solution/1400-1499/1428.Leftmost Column with at Least a One/Solution.py @@ -1,17 +1,17 @@ -# """ -# This is BinaryMatrix's API interface. -# You should not implement it, or speculate about its implementation -# """ -# class BinaryMatrix(object): -# def get(self, row: int, col: int) -> int: -# def dimensions(self) -> list[]: - - -class Solution: - def leftMostColumnWithOne(self, binaryMatrix: "BinaryMatrix") -> int: - m, n = binaryMatrix.dimensions() - ans = n - for i in range(m): - j = bisect_left(range(n), 1, key=lambda k: binaryMatrix.get(i, k)) - ans = min(ans, j) - return -1 if ans >= n else ans +# """ +# This is BinaryMatrix's API interface. +# You should not implement it, or speculate about its implementation +# """ +# class BinaryMatrix(object): +# def get(self, row: int, col: int) -> int: +# def dimensions(self) -> list[]: + + +class Solution: + def leftMostColumnWithOne(self, binaryMatrix: "BinaryMatrix") -> int: + m, n = binaryMatrix.dimensions() + ans = n + for i in range(m): + j = bisect_left(range(n), 1, key=lambda k: binaryMatrix.get(i, k)) + ans = min(ans, j) + return -1 if ans >= n else ans diff --git a/solution/1400-1499/1429.First Unique Number/Solution.java b/solution/1400-1499/1429.First Unique Number/Solution.java index 25b32c977b81c..a9312923a6f2f 100644 --- a/solution/1400-1499/1429.First Unique Number/Solution.java +++ b/solution/1400-1499/1429.First Unique Number/Solution.java @@ -1,24 +1,29 @@ class FirstUnique { private Map cnt = new HashMap<>(); - private Deque q = new ArrayDeque<>(); + private Set unique = new LinkedHashSet<>(); public FirstUnique(int[] nums) { for (int v : nums) { cnt.put(v, cnt.getOrDefault(v, 0) + 1); - q.offer(v); + } + for (int v : nums) { + if (cnt.get(v) == 1) { + unique.add(v); + } } } public int showFirstUnique() { - while (!q.isEmpty() && cnt.get(q.peekFirst()) != 1) { - q.poll(); - } - return q.isEmpty() ? -1 : q.peekFirst(); + return unique.isEmpty() ? -1 : unique.iterator().next(); } public void add(int value) { cnt.put(value, cnt.getOrDefault(value, 0) + 1); - q.offer(value); + if (cnt.get(value) == 1) { + unique.add(value); + } else { + unique.remove(value); + } } } diff --git a/solution/1400-1499/1429.First Unique Number/Solution.py b/solution/1400-1499/1429.First Unique Number/Solution.py index fb7abd69e821a..dbd5d9adddc32 100644 --- a/solution/1400-1499/1429.First Unique Number/Solution.py +++ b/solution/1400-1499/1429.First Unique Number/Solution.py @@ -1,16 +1,17 @@ class FirstUnique: def __init__(self, nums: List[int]): self.cnt = Counter(nums) - self.q = deque(nums) + self.unique = OrderedDict({v: 1 for v in nums if self.cnt[v] == 1}) def showFirstUnique(self) -> int: - while self.q and self.cnt[self.q[0]] != 1: - self.q.popleft() - return -1 if not self.q else self.q[0] + return -1 if not self.unique else next(v for v in self.unique.keys()) def add(self, value: int) -> None: self.cnt[value] += 1 - self.q.append(value) + if self.cnt[value] == 1: + self.unique[value] = 1 + elif value in self.unique: + self.unique.pop(value) # Your FirstUnique object will be instantiated and called as such: diff --git a/solution/1400-1499/1429.First Unique Number/Solution2.java b/solution/1400-1499/1429.First Unique Number/Solution2.java new file mode 100644 index 0000000000000..25b32c977b81c --- /dev/null +++ b/solution/1400-1499/1429.First Unique Number/Solution2.java @@ -0,0 +1,30 @@ +class FirstUnique { + private Map cnt = new HashMap<>(); + private Deque q = new ArrayDeque<>(); + + public FirstUnique(int[] nums) { + for (int v : nums) { + cnt.put(v, cnt.getOrDefault(v, 0) + 1); + q.offer(v); + } + } + + public int showFirstUnique() { + while (!q.isEmpty() && cnt.get(q.peekFirst()) != 1) { + q.poll(); + } + return q.isEmpty() ? -1 : q.peekFirst(); + } + + public void add(int value) { + cnt.put(value, cnt.getOrDefault(value, 0) + 1); + q.offer(value); + } +} + +/** + * Your FirstUnique object will be instantiated and called as such: + * FirstUnique obj = new FirstUnique(nums); + * int param_1 = obj.showFirstUnique(); + * obj.add(value); + */ \ No newline at end of file diff --git a/solution/1400-1499/1429.First Unique Number/Solution2.py b/solution/1400-1499/1429.First Unique Number/Solution2.py new file mode 100644 index 0000000000000..fb7abd69e821a --- /dev/null +++ b/solution/1400-1499/1429.First Unique Number/Solution2.py @@ -0,0 +1,19 @@ +class FirstUnique: + def __init__(self, nums: List[int]): + self.cnt = Counter(nums) + self.q = deque(nums) + + def showFirstUnique(self) -> int: + while self.q and self.cnt[self.q[0]] != 1: + self.q.popleft() + return -1 if not self.q else self.q[0] + + def add(self, value: int) -> None: + self.cnt[value] += 1 + self.q.append(value) + + +# Your FirstUnique object will be instantiated and called as such: +# obj = FirstUnique(nums) +# param_1 = obj.showFirstUnique() +# obj.add(value) diff --git a/solution/1400-1499/1431.Kids With the Greatest Number of Candies/Solution.c b/solution/1400-1499/1431.Kids With the Greatest Number of Candies/Solution.c index 356e0a4853956..2aca52ca8f043 100644 --- a/solution/1400-1499/1431.Kids With the Greatest Number of Candies/Solution.c +++ b/solution/1400-1499/1431.Kids With the Greatest Number of Candies/Solution.c @@ -13,4 +13,4 @@ bool* kidsWithCandies(int* candies, int candiesSize, int extraCandies, int* retu } *returnSize = candiesSize; return ans; -} +} \ No newline at end of file diff --git a/solution/1400-1499/1431.Kids With the Greatest Number of Candies/Solution.java b/solution/1400-1499/1431.Kids With the Greatest Number of Candies/Solution.java index 99e8ccf90c81a..35e0d83c70ecb 100644 --- a/solution/1400-1499/1431.Kids With the Greatest Number of Candies/Solution.java +++ b/solution/1400-1499/1431.Kids With the Greatest Number of Candies/Solution.java @@ -1,10 +1,13 @@ class Solution { - public : vector kidsWithCandies(vector& candies, int extraCandies) { - int mx = *max_element(candies.begin(), candies.end()); - vector res; + public List kidsWithCandies(int[] candies, int extraCandies) { + int mx = 0; for (int candy : candies) { - res.push_back(candy + extraCandies >= mx); + mx = Math.max(mx, candy); + } + List res = new ArrayList<>(); + for (int candy : candies) { + res.add(candy + extraCandies >= mx); } return res; } -}; \ No newline at end of file +} \ No newline at end of file diff --git a/solution/1400-1499/1431.Kids With the Greatest Number of Candies/Solution.php b/solution/1400-1499/1431.Kids With the Greatest Number of Candies/Solution.php index 65b023ddb2927..46adedfd5c67a 100644 --- a/solution/1400-1499/1431.Kids With the Greatest Number of Candies/Solution.php +++ b/solution/1400-1499/1431.Kids With the Greatest Number of Candies/Solution.php @@ -12,4 +12,4 @@ function kidsWithCandies($candies, $extraCandies) { } return $rs; } -} \ No newline at end of file +} diff --git a/solution/1400-1499/1436.Destination City/Solution.c b/solution/1400-1499/1436.Destination City/Solution.c index 83fc5cb140f69..598c5adf07974 100644 --- a/solution/1400-1499/1436.Destination City/Solution.c +++ b/solution/1400-1499/1436.Destination City/Solution.c @@ -12,4 +12,4 @@ char* destCity(char*** paths, int pathsSize, int* pathsColSize) { } } return NULL; -} +} \ No newline at end of file diff --git a/solution/1400-1499/1441.Build an Array With Stack Operations/Solution.c b/solution/1400-1499/1441.Build an Array With Stack Operations/Solution.c index 8738d0c5500e9..67fefa2b67519 100644 --- a/solution/1400-1499/1441.Build an Array With Stack Operations/Solution.c +++ b/solution/1400-1499/1441.Build an Array With Stack Operations/Solution.c @@ -17,4 +17,4 @@ char** buildArray(int* target, int targetSize, int n, int* returnSize) { } *returnSize = i; return res; -} +} \ No newline at end of file diff --git a/solution/1400-1499/1446.Consecutive Characters/Solution.cpp b/solution/1400-1499/1446.Consecutive Characters/Solution.cpp index 69ecaeeb3c438..163d17779aa76 100644 --- a/solution/1400-1499/1446.Consecutive Characters/Solution.cpp +++ b/solution/1400-1499/1446.Consecutive Characters/Solution.cpp @@ -1,14 +1,14 @@ -class Solution { -public: - int maxPower(string s) { - int ans = 1, t = 1; - for (int i = 1; i < s.size(); ++i) { - if (s[i] == s[i - 1]) { - ans = max(ans, ++t); - } else { - t = 1; - } - } - return ans; - } +class Solution { +public: + int maxPower(string s) { + int ans = 1, t = 1; + for (int i = 1; i < s.size(); ++i) { + if (s[i] == s[i - 1]) { + ans = max(ans, ++t); + } else { + t = 1; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1400-1499/1446.Consecutive Characters/Solution.java b/solution/1400-1499/1446.Consecutive Characters/Solution.java index e23b514be4545..1b0214274c7ee 100644 --- a/solution/1400-1499/1446.Consecutive Characters/Solution.java +++ b/solution/1400-1499/1446.Consecutive Characters/Solution.java @@ -1,13 +1,13 @@ -class Solution { - public int maxPower(String s) { - int ans = 1, t = 1; - for (int i = 1; i < s.length(); ++i) { - if (s.charAt(i) == s.charAt(i - 1)) { - ans = Math.max(ans, ++t); - } else { - t = 1; - } - } - return ans; - } +class Solution { + public int maxPower(String s) { + int ans = 1, t = 1; + for (int i = 1; i < s.length(); ++i) { + if (s.charAt(i) == s.charAt(i - 1)) { + ans = Math.max(ans, ++t); + } else { + t = 1; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1400-1499/1446.Consecutive Characters/Solution.py b/solution/1400-1499/1446.Consecutive Characters/Solution.py index 649a036822ab3..79b7fb3be597b 100644 --- a/solution/1400-1499/1446.Consecutive Characters/Solution.py +++ b/solution/1400-1499/1446.Consecutive Characters/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def maxPower(self, s: str) -> int: - ans = t = 1 - for a, b in pairwise(s): - if a == b: - t += 1 - ans = max(ans, t) - else: - t = 1 - return ans +class Solution: + def maxPower(self, s: str) -> int: + ans = t = 1 + for a, b in pairwise(s): + if a == b: + t += 1 + ans = max(ans, t) + else: + t = 1 + return ans diff --git a/solution/1400-1499/1447.Simplified Fractions/Solution.cpp b/solution/1400-1499/1447.Simplified Fractions/Solution.cpp index 083771e216ac7..393ca3aff2dc8 100644 --- a/solution/1400-1499/1447.Simplified Fractions/Solution.cpp +++ b/solution/1400-1499/1447.Simplified Fractions/Solution.cpp @@ -1,14 +1,14 @@ -class Solution { -public: - vector simplifiedFractions(int n) { - vector ans; - for (int i = 1; i < n; ++i) { - for (int j = i + 1; j < n + 1; ++j) { - if (__gcd(i, j) == 1) { - ans.push_back(to_string(i) + "/" + to_string(j)); - } - } - } - return ans; - } +class Solution { +public: + vector simplifiedFractions(int n) { + vector ans; + for (int i = 1; i < n; ++i) { + for (int j = i + 1; j < n + 1; ++j) { + if (__gcd(i, j) == 1) { + ans.push_back(to_string(i) + "/" + to_string(j)); + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1400-1499/1448.Count Good Nodes in Binary Tree/Solution.cpp b/solution/1400-1499/1448.Count Good Nodes in Binary Tree/Solution.cpp index 2110ac9335a39..abf94921663e1 100644 --- a/solution/1400-1499/1448.Count Good Nodes in Binary Tree/Solution.cpp +++ b/solution/1400-1499/1448.Count Good Nodes in Binary Tree/Solution.cpp @@ -1,30 +1,30 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int goodNodes(TreeNode* root) { - int ans = 0; - function dfs = [&](TreeNode* root, int mx) { - if (!root) { - return; - } - if (mx <= root->val) { - ++ans; - mx = root->val; - } - dfs(root->left, mx); - dfs(root->right, mx); - }; - dfs(root, -1e6); - return ans; - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int goodNodes(TreeNode* root) { + int ans = 0; + function dfs = [&](TreeNode* root, int mx) { + if (!root) { + return; + } + if (mx <= root->val) { + ++ans; + mx = root->val; + } + dfs(root->left, mx); + dfs(root->right, mx); + }; + dfs(root, -1e6); + return ans; + } }; \ No newline at end of file diff --git a/solution/1400-1499/1448.Count Good Nodes in Binary Tree/Solution.java b/solution/1400-1499/1448.Count Good Nodes in Binary Tree/Solution.java index e70023d239d18..9aa786ab23c7f 100644 --- a/solution/1400-1499/1448.Count Good Nodes in Binary Tree/Solution.java +++ b/solution/1400-1499/1448.Count Good Nodes in Binary Tree/Solution.java @@ -1,35 +1,35 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private int ans = 0; - - public int goodNodes(TreeNode root) { - dfs(root, -100000); - return ans; - } - - private void dfs(TreeNode root, int mx) { - if (root == null) { - return; - } - if (mx <= root.val) { - ++ans; - mx = root.val; - } - dfs(root.left, mx); - dfs(root.right, mx); - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int ans = 0; + + public int goodNodes(TreeNode root) { + dfs(root, -100000); + return ans; + } + + private void dfs(TreeNode root, int mx) { + if (root == null) { + return; + } + if (mx <= root.val) { + ++ans; + mx = root.val; + } + dfs(root.left, mx); + dfs(root.right, mx); + } } \ No newline at end of file diff --git a/solution/1400-1499/1448.Count Good Nodes in Binary Tree/Solution.py b/solution/1400-1499/1448.Count Good Nodes in Binary Tree/Solution.py index 15b1c56e8160c..9ef81b8a5ed7d 100644 --- a/solution/1400-1499/1448.Count Good Nodes in Binary Tree/Solution.py +++ b/solution/1400-1499/1448.Count Good Nodes in Binary Tree/Solution.py @@ -1,21 +1,21 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def goodNodes(self, root: TreeNode) -> int: - def dfs(root: TreeNode, mx: int): - if root is None: - return - nonlocal ans - if mx <= root.val: - ans += 1 - mx = root.val - dfs(root.left, mx) - dfs(root.right, mx) - - ans = 0 - dfs(root, -1000000) - return ans +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def goodNodes(self, root: TreeNode) -> int: + def dfs(root: TreeNode, mx: int): + if root is None: + return + nonlocal ans + if mx <= root.val: + ans += 1 + mx = root.val + dfs(root.left, mx) + dfs(root.right, mx) + + ans = 0 + dfs(root, -1000000) + return ans diff --git a/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/Solution.cpp b/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/Solution.cpp index 8345037eea55d..697c09a56e7cc 100644 --- a/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/Solution.cpp +++ b/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/Solution.cpp @@ -1,34 +1,34 @@ -class Solution { -public: - string largestNumber(vector& cost, int target) { - const int inf = 1 << 30; - vector> f(10, vector(target + 1, -inf)); - vector> g(10, vector(target + 1)); - f[0][0] = 0; - for (int i = 1; i <= 9; ++i) { - int c = cost[i - 1]; - for (int j = 0; j <= target; ++j) { - if (j < c || f[i][j - c] + 1 < f[i - 1][j]) { - f[i][j] = f[i - 1][j]; - g[i][j] = j; - } else { - f[i][j] = f[i][j - c] + 1; - g[i][j] = j - c; - } - } - } - if (f[9][target] < 0) { - return "0"; - } - string ans; - for (int i = 9, j = target; i;) { - if (g[i][j] == j) { - --i; - } else { - ans += '0' + i; - j = g[i][j]; - } - } - return ans; - } +class Solution { +public: + string largestNumber(vector& cost, int target) { + const int inf = 1 << 30; + vector> f(10, vector(target + 1, -inf)); + vector> g(10, vector(target + 1)); + f[0][0] = 0; + for (int i = 1; i <= 9; ++i) { + int c = cost[i - 1]; + for (int j = 0; j <= target; ++j) { + if (j < c || f[i][j - c] + 1 < f[i - 1][j]) { + f[i][j] = f[i - 1][j]; + g[i][j] = j; + } else { + f[i][j] = f[i][j - c] + 1; + g[i][j] = j - c; + } + } + } + if (f[9][target] < 0) { + return "0"; + } + string ans; + for (int i = 9, j = target; i;) { + if (g[i][j] == j) { + --i; + } else { + ans += '0' + i; + j = g[i][j]; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/Solution.java b/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/Solution.java index 65cb2460ae6ee..99ebf9059661c 100644 --- a/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/Solution.java +++ b/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/Solution.java @@ -1,36 +1,36 @@ -class Solution { - public String largestNumber(int[] cost, int target) { - final int inf = 1 << 30; - int[][] f = new int[10][target + 1]; - int[][] g = new int[10][target + 1]; - for (var e : f) { - Arrays.fill(e, -inf); - } - f[0][0] = 0; - for (int i = 1; i <= 9; ++i) { - int c = cost[i - 1]; - for (int j = 0; j <= target; ++j) { - if (j < c || f[i][j - c] + 1 < f[i - 1][j]) { - f[i][j] = f[i - 1][j]; - g[i][j] = j; - } else { - f[i][j] = f[i][j - c] + 1; - g[i][j] = j - c; - } - } - } - if (f[9][target] < 0) { - return "0"; - } - StringBuilder sb = new StringBuilder(); - for (int i = 9, j = target; i > 0;) { - if (j == g[i][j]) { - --i; - } else { - sb.append(i); - j = g[i][j]; - } - } - return sb.toString(); - } +class Solution { + public String largestNumber(int[] cost, int target) { + final int inf = 1 << 30; + int[][] f = new int[10][target + 1]; + int[][] g = new int[10][target + 1]; + for (var e : f) { + Arrays.fill(e, -inf); + } + f[0][0] = 0; + for (int i = 1; i <= 9; ++i) { + int c = cost[i - 1]; + for (int j = 0; j <= target; ++j) { + if (j < c || f[i][j - c] + 1 < f[i - 1][j]) { + f[i][j] = f[i - 1][j]; + g[i][j] = j; + } else { + f[i][j] = f[i][j - c] + 1; + g[i][j] = j - c; + } + } + } + if (f[9][target] < 0) { + return "0"; + } + StringBuilder sb = new StringBuilder(); + for (int i = 9, j = target; i > 0;) { + if (j == g[i][j]) { + --i; + } else { + sb.append(i); + j = g[i][j]; + } + } + return sb.toString(); + } } \ No newline at end of file diff --git a/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/Solution.py b/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/Solution.py index 7a075ecc9a1d3..e324b2e320bfe 100644 --- a/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/Solution.py +++ b/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/Solution.py @@ -1,24 +1,24 @@ -class Solution: - def largestNumber(self, cost: List[int], target: int) -> str: - f = [[-inf] * (target + 1) for _ in range(10)] - f[0][0] = 0 - g = [[0] * (target + 1) for _ in range(10)] - for i, c in enumerate(cost, 1): - for j in range(target + 1): - if j < c or f[i][j - c] + 1 < f[i - 1][j]: - f[i][j] = f[i - 1][j] - g[i][j] = j - else: - f[i][j] = f[i][j - c] + 1 - g[i][j] = j - c - if f[9][target] < 0: - return "0" - ans = [] - i, j = 9, target - while i: - if j == g[i][j]: - i -= 1 - else: - ans.append(str(i)) - j = g[i][j] - return "".join(ans) +class Solution: + def largestNumber(self, cost: List[int], target: int) -> str: + f = [[-inf] * (target + 1) for _ in range(10)] + f[0][0] = 0 + g = [[0] * (target + 1) for _ in range(10)] + for i, c in enumerate(cost, 1): + for j in range(target + 1): + if j < c or f[i][j - c] + 1 < f[i - 1][j]: + f[i][j] = f[i - 1][j] + g[i][j] = j + else: + f[i][j] = f[i][j - c] + 1 + g[i][j] = j - c + if f[9][target] < 0: + return "0" + ans = [] + i, j = 9, target + while i: + if j == g[i][j]: + i -= 1 + else: + ans.append(str(i)) + j = g[i][j] + return "".join(ans) diff --git a/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/Solution.c b/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/Solution.c index 3219430e2af49..2dd59ef5a3103 100644 --- a/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/Solution.c +++ b/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/Solution.c @@ -6,4 +6,4 @@ int busyStudent(int* startTime, int startTimeSize, int* endTime, int endTimeSize } } return res; -} +} \ No newline at end of file diff --git a/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/Solution2.cpp b/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/Solution2.cpp new file mode 100644 index 0000000000000..c9e276a0733ee --- /dev/null +++ b/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int busyStudent(vector& startTime, vector& endTime, int queryTime) { + vector c(1010); + for (int i = 0; i < startTime.size(); ++i) { + c[startTime[i]]++; + c[endTime[i] + 1]--; + } + int ans = 0; + for (int i = 0; i <= queryTime; ++i) { + ans += c[i]; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/Solution2.go b/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/Solution2.go new file mode 100644 index 0000000000000..3cb84a13f9147 --- /dev/null +++ b/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/Solution2.go @@ -0,0 +1,13 @@ +func busyStudent(startTime []int, endTime []int, queryTime int) int { + c := make([]int, 1010) + for i, a := range startTime { + b := endTime[i] + c[a]++ + c[b+1]-- + } + ans := 0 + for i := 0; i <= queryTime; i++ { + ans += c[i] + } + return ans +} \ No newline at end of file diff --git a/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/Solution2.java b/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/Solution2.java new file mode 100644 index 0000000000000..f2c779d094def --- /dev/null +++ b/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public int busyStudent(int[] startTime, int[] endTime, int queryTime) { + int[] c = new int[1010]; + for (int i = 0; i < startTime.length; ++i) { + c[startTime[i]]++; + c[endTime[i] + 1]--; + } + int ans = 0; + for (int i = 0; i <= queryTime; ++i) { + ans += c[i]; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/Solution2.py b/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/Solution2.py new file mode 100644 index 0000000000000..aa441bc60d933 --- /dev/null +++ b/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def busyStudent( + self, startTime: List[int], endTime: List[int], queryTime: int + ) -> int: + c = [0] * 1010 + for a, b in zip(startTime, endTime): + c[a] += 1 + c[b + 1] -= 1 + return sum(c[: queryTime + 1]) diff --git a/solution/1400-1499/1451.Rearrange Words in a Sentence/Solution.php b/solution/1400-1499/1451.Rearrange Words in a Sentence/Solution.php index 0592b22af353b..6106131ad4384 100644 --- a/solution/1400-1499/1451.Rearrange Words in a Sentence/Solution.php +++ b/solution/1400-1499/1451.Rearrange Words in a Sentence/Solution.php @@ -17,4 +17,4 @@ function arrangeWords($text) { } return ucfirst(implode(' ', $rs)); } -} \ No newline at end of file +} diff --git a/solution/1400-1499/1454.Active Users/Solution.sql b/solution/1400-1499/1454.Active Users/Solution.sql index 5da5fda07fa8b..719eff9fce0c8 100644 --- a/solution/1400-1499/1454.Active Users/Solution.sql +++ b/solution/1400-1499/1454.Active Users/Solution.sql @@ -1,13 +1,13 @@ # Write your MySQL query statement below -WITH t AS +WITH t AS (SELECT *, SUM(id) over(partition by id ORDER BY login_date range interval 4 day preceding)/id cnt - FROM + FROM (SELECT DISTINCT * FROM Accounts JOIN Logins using(id) ) tt ) SELECT DISTINCT id, name FROM t -WHERE cnt=5; \ No newline at end of file +WHERE cnt=5; diff --git a/solution/1400-1499/1455.Check If a Word Occurs As a Prefix of Any Word in a Sentence/Solution.php b/solution/1400-1499/1455.Check If a Word Occurs As a Prefix of Any Word in a Sentence/Solution.php index 10701dbba59cc..2025bc4f30248 100644 --- a/solution/1400-1499/1455.Check If a Word Occurs As a Prefix of Any Word in a Sentence/Solution.php +++ b/solution/1400-1499/1455.Check If a Word Occurs As a Prefix of Any Word in a Sentence/Solution.php @@ -13,4 +13,4 @@ function isPrefixOfWord($sentence, $searchWord) { } return -1; } -} \ No newline at end of file +} diff --git a/solution/1400-1499/1456.Maximum Number of Vowels in a Substring of Given Length/Solution.php b/solution/1400-1499/1456.Maximum Number of Vowels in a Substring of Given Length/Solution.php index ecdea8ddedb6e..2daa08c28da11 100644 --- a/solution/1400-1499/1456.Maximum Number of Vowels in a Substring of Given Length/Solution.php +++ b/solution/1400-1499/1456.Maximum Number of Vowels in a Substring of Given Length/Solution.php @@ -27,4 +27,4 @@ function maxVowels($s, $k) { } return $rs; } -} \ No newline at end of file +} diff --git a/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/Solution.cpp b/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/Solution.cpp index 7b6fdc9893a48..80553afd222a0 100644 --- a/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/Solution.cpp +++ b/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/Solution.cpp @@ -1,27 +1,27 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int pseudoPalindromicPaths(TreeNode* root) { - function dfs = [&](TreeNode* root, int mask) { - if (!root) { - return 0; - } - mask ^= 1 << root->val; - if (!root->left && !root->right) { - return (mask & (mask - 1)) == 0 ? 1 : 0; - } - return dfs(root->left, mask) + dfs(root->right, mask); - }; - return dfs(root, 0); - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int pseudoPalindromicPaths(TreeNode* root) { + function dfs = [&](TreeNode* root, int mask) { + if (!root) { + return 0; + } + mask ^= 1 << root->val; + if (!root->left && !root->right) { + return (mask & (mask - 1)) == 0 ? 1 : 0; + } + return dfs(root->left, mask) + dfs(root->right, mask); + }; + return dfs(root, 0); + } }; \ No newline at end of file diff --git a/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/Solution.java b/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/Solution.java index 165c0f8b9e91d..1b26a13650779 100644 --- a/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/Solution.java +++ b/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/Solution.java @@ -1,31 +1,31 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public int pseudoPalindromicPaths(TreeNode root) { - return dfs(root, 0); - } - - private int dfs(TreeNode root, int mask) { - if (root == null) { - return 0; - } - mask ^= 1 << root.val; - if (root.left == null && root.right == null) { - return (mask & (mask - 1)) == 0 ? 1 : 0; - } - return dfs(root.left, mask) + dfs(root.right, mask); - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int pseudoPalindromicPaths(TreeNode root) { + return dfs(root, 0); + } + + private int dfs(TreeNode root, int mask) { + if (root == null) { + return 0; + } + mask ^= 1 << root.val; + if (root.left == null && root.right == null) { + return (mask & (mask - 1)) == 0 ? 1 : 0; + } + return dfs(root.left, mask) + dfs(root.right, mask); + } } \ No newline at end of file diff --git a/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/Solution.py b/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/Solution.py index d007071e0fedf..fba5b4a247677 100644 --- a/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/Solution.py +++ b/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/Solution.py @@ -1,17 +1,17 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def pseudoPalindromicPaths(self, root: Optional[TreeNode]) -> int: - def dfs(root: Optional[TreeNode], mask: int): - if root is None: - return 0 - mask ^= 1 << root.val - if root.left is None and root.right is None: - return int((mask & (mask - 1)) == 0) - return dfs(root.left, mask) + dfs(root.right, mask) - - return dfs(root, 0) +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def pseudoPalindromicPaths(self, root: Optional[TreeNode]) -> int: + def dfs(root: Optional[TreeNode], mask: int): + if root is None: + return 0 + mask ^= 1 << root.val + if root.left is None and root.right is None: + return int((mask & (mask - 1)) == 0) + return dfs(root.left, mask) + dfs(root.right, mask) + + return dfs(root, 0) diff --git a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution.c b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution.c index 0528bf1dede6d..92f1ed12e9b35 100644 --- a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution.c +++ b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution.c @@ -10,4 +10,4 @@ bool canBeEqual(int* target, int targetSize, int* arr, int arrSize) { } } return true; -} +} \ No newline at end of file diff --git a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution.php b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution.php index 4a0fe1062ff83..64a0af9960efd 100644 --- a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution.php +++ b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution.php @@ -9,4 +9,4 @@ function canBeEqual($target, $arr) { sort($arr); return $target === $arr; } -} \ No newline at end of file +} diff --git a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution.rs b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution.rs index adc78ade998e3..cb695a5cb1e78 100644 --- a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution.rs +++ b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution.rs @@ -1,11 +1,7 @@ impl Solution { pub fn can_be_equal(mut target: Vec, mut arr: Vec) -> bool { - let n = target.len(); - let mut count = [0; 1001]; - for i in 0..n { - count[target[i] as usize] += 1; - count[arr[i] as usize] -= 1; - } - count.iter().all(|v| *v == 0) + target.sort(); + arr.sort(); + target == arr } } diff --git a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution.ts b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution.ts index 2d322489c82fe..5fad452af809f 100644 --- a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution.ts +++ b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution.ts @@ -1,9 +1,11 @@ function canBeEqual(target: number[], arr: number[]): boolean { - const n = target.length; - const count = new Array(1001).fill(0); + target.sort((a, b) => a - b); + arr.sort((a, b) => a - b); + const n = arr.length; for (let i = 0; i < n; i++) { - count[target[i]]++; - count[arr[i]]--; + if (target[i] !== arr[i]) { + return false; + } } - return count.every(v => v === 0); + return true; } diff --git a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution2.cpp b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution2.cpp new file mode 100644 index 0000000000000..fbe654c934f9d --- /dev/null +++ b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution2.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + bool canBeEqual(vector& target, vector& arr) { + vector cnt1(1001); + vector cnt2(1001); + for (int& v : target) ++cnt1[v]; + for (int& v : arr) ++cnt2[v]; + return cnt1 == cnt2; + } +}; \ No newline at end of file diff --git a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution2.go b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution2.go new file mode 100644 index 0000000000000..8d2f7d61fbfe4 --- /dev/null +++ b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution2.go @@ -0,0 +1,16 @@ +func canBeEqual(target []int, arr []int) bool { + cnt1 := make([]int, 1001) + cnt2 := make([]int, 1001) + for _, v := range target { + cnt1[v]++ + } + for _, v := range arr { + cnt2[v]++ + } + for i, v := range cnt1 { + if v != cnt2[i] { + return false + } + } + return true +} \ No newline at end of file diff --git a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution2.java b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution2.java new file mode 100644 index 0000000000000..efd5229689724 --- /dev/null +++ b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution2.java @@ -0,0 +1,13 @@ +class Solution { + public boolean canBeEqual(int[] target, int[] arr) { + int[] cnt1 = new int[1001]; + int[] cnt2 = new int[1001]; + for (int v : target) { + ++cnt1[v]; + } + for (int v : arr) { + ++cnt2[v]; + } + return Arrays.equals(cnt1, cnt2); + } +} \ No newline at end of file diff --git a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution2.py b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution2.py new file mode 100644 index 0000000000000..3e54e682e504a --- /dev/null +++ b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution2.py @@ -0,0 +1,3 @@ +class Solution: + def canBeEqual(self, target: List[int], arr: List[int]) -> bool: + return Counter(target) == Counter(arr) diff --git a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution2.rs b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution2.rs new file mode 100644 index 0000000000000..adc78ade998e3 --- /dev/null +++ b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution2.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn can_be_equal(mut target: Vec, mut arr: Vec) -> bool { + let n = target.len(); + let mut count = [0; 1001]; + for i in 0..n { + count[target[i] as usize] += 1; + count[arr[i] as usize] -= 1; + } + count.iter().all(|v| *v == 0) + } +} diff --git a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution2.ts b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution2.ts new file mode 100644 index 0000000000000..2d322489c82fe --- /dev/null +++ b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution2.ts @@ -0,0 +1,9 @@ +function canBeEqual(target: number[], arr: number[]): boolean { + const n = target.length; + const count = new Array(1001).fill(0); + for (let i = 0; i < n; i++) { + count[target[i]]++; + count[arr[i]]--; + } + return count.every(v => v === 0); +} diff --git a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution3.cpp b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution3.cpp new file mode 100644 index 0000000000000..d10a84ff2022a --- /dev/null +++ b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution3.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + bool canBeEqual(vector& target, vector& arr) { + vector cnt(1001); + for (int& v : target) ++cnt[v]; + for (int& v : arr) + if (--cnt[v] < 0) return false; + return true; + } +}; \ No newline at end of file diff --git a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution3.go b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution3.go new file mode 100644 index 0000000000000..92f6979489c67 --- /dev/null +++ b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution3.go @@ -0,0 +1,13 @@ +func canBeEqual(target []int, arr []int) bool { + cnt := make([]int, 1001) + for _, v := range target { + cnt[v]++ + } + for _, v := range arr { + cnt[v]-- + if cnt[v] < 0 { + return false + } + } + return true +} \ No newline at end of file diff --git a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution3.java b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution3.java new file mode 100644 index 0000000000000..71adc1ef4f400 --- /dev/null +++ b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution3.java @@ -0,0 +1,14 @@ +class Solution { + public boolean canBeEqual(int[] target, int[] arr) { + int[] cnt = new int[1001]; + for (int v : target) { + ++cnt[v]; + } + for (int v : arr) { + if (--cnt[v] < 0) { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution3.py b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution3.py new file mode 100644 index 0000000000000..4349ca9e910ce --- /dev/null +++ b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution3.py @@ -0,0 +1,7 @@ +class Solution: + def canBeEqual(self, target: List[int], arr: List[int]) -> bool: + cnt = [0] * 1001 + for a, b in zip(target, arr): + cnt[a] += 1 + cnt[b] -= 1 + return all(v == 0 for v in cnt) diff --git a/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/Solution.cpp b/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/Solution.cpp index fa82b12a07c58..4018b4114dfef 100644 --- a/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/Solution.cpp +++ b/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/Solution.cpp @@ -1,19 +1,10 @@ class Solution { public: bool hasAllCodes(string s, int k) { - int n = s.size(); - if (n - k + 1 < (1 << k)) return false; - vector vis(1 << k); - int num = stoi(s.substr(0, k), nullptr, 2); - vis[num] = true; - for (int i = k; i < n; ++i) { - int a = (s[i - k] - '0') << (k - 1); - int b = s[i] - '0'; - num = (num - a) << 1 | b; - vis[num] = true; + unordered_set ss; + for (int i = 0; i + k <= s.size(); ++i) { + ss.insert(move(s.substr(i, k))); } - for (bool v : vis) - if (!v) return false; - return true; + return ss.size() == 1 << k; } }; \ No newline at end of file diff --git a/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/Solution.go b/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/Solution.go index ba3f68b1fe399..2852e51db7b2a 100644 --- a/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/Solution.go +++ b/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/Solution.go @@ -1,23 +1,7 @@ func hasAllCodes(s string, k int) bool { - n := len(s) - if n-k+1 < (1 << k) { - return false + ss := map[string]bool{} + for i := 0; i+k <= len(s); i++ { + ss[s[i:i+k]] = true } - vis := make([]bool, 1< ss = new HashSet<>(); + for (int i = 0; i < s.length() - k + 1; ++i) { + ss.add(s.substring(i, i + k)); } - boolean[] vis = new boolean[1 << k]; - int num = Integer.parseInt(s.substring(0, k), 2); - vis[num] = true; - for (int i = k; i < n; ++i) { - int a = (s.charAt(i - k) - '0') << (k - 1); - int b = s.charAt(i) - '0'; - num = (num - a) << 1 | b; - vis[num] = true; - } - for (boolean v : vis) { - if (!v) { - return false; - } - } - return true; + return ss.size() == 1 << k; } } \ No newline at end of file diff --git a/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/Solution2.cpp b/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/Solution2.cpp new file mode 100644 index 0000000000000..fa82b12a07c58 --- /dev/null +++ b/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + bool hasAllCodes(string s, int k) { + int n = s.size(); + if (n - k + 1 < (1 << k)) return false; + vector vis(1 << k); + int num = stoi(s.substr(0, k), nullptr, 2); + vis[num] = true; + for (int i = k; i < n; ++i) { + int a = (s[i - k] - '0') << (k - 1); + int b = s[i] - '0'; + num = (num - a) << 1 | b; + vis[num] = true; + } + for (bool v : vis) + if (!v) return false; + return true; + } +}; \ No newline at end of file diff --git a/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/Solution2.go b/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/Solution2.go new file mode 100644 index 0000000000000..ba3f68b1fe399 --- /dev/null +++ b/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/Solution2.go @@ -0,0 +1,23 @@ +func hasAllCodes(s string, k int) bool { + n := len(s) + if n-k+1 < (1 << k) { + return false + } + vis := make([]bool, 1< bool: + if len(s) - k + 1 < (1 << k): + return False + vis = [False] * (1 << k) + num = int(s[:k], 2) + vis[num] = True + for i in range(k, len(s)): + a = (ord(s[i - k]) - ord('0')) << (k - 1) + b = ord(s[i]) - ord('0') + num = ((num - a) << 1) + b + vis[num] = True + return all(v for v in vis) diff --git a/solution/1400-1499/1462.Course Schedule IV/Solution.cpp b/solution/1400-1499/1462.Course Schedule IV/Solution.cpp index bad2f96485c14..a852d3b536cb2 100644 --- a/solution/1400-1499/1462.Course Schedule IV/Solution.cpp +++ b/solution/1400-1499/1462.Course Schedule IV/Solution.cpp @@ -1,37 +1,22 @@ -class Solution { -public: - vector checkIfPrerequisite(int n, vector>& prerequisites, vector>& queries) { - bool f[n][n]; - memset(f, false, sizeof(f)); - vector g[n]; - vector indeg(n); - for (auto& p : prerequisites) { - g[p[0]].push_back(p[1]); - ++indeg[p[1]]; - } - queue q; - for (int i = 0; i < n; ++i) { - if (indeg[i] == 0) { - q.push(i); - } - } - while (!q.empty()) { - int i = q.front(); - q.pop(); - for (int j : g[i]) { - f[i][j] = true; - for (int h = 0; h < n; ++h) { - f[h][j] |= f[h][i]; - } - if (--indeg[j] == 0) { - q.push(j); - } - } - } - vector ans; - for (auto& qry : queries) { - ans.push_back(f[qry[0]][qry[1]]); - } - return ans; - } +class Solution { +public: + vector checkIfPrerequisite(int n, vector>& prerequisites, vector>& queries) { + bool f[n][n]; + memset(f, false, sizeof(f)); + for (auto& p : prerequisites) { + f[p[0]][p[1]] = true; + } + for (int k = 0; k < n; ++k) { + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + f[i][j] |= (f[i][k] && f[k][j]); + } + } + } + vector ans; + for (auto& q : queries) { + ans.push_back(f[q[0]][q[1]]); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1400-1499/1462.Course Schedule IV/Solution.go b/solution/1400-1499/1462.Course Schedule IV/Solution.go index 53b3f8f7929b9..44145d799fb0e 100644 --- a/solution/1400-1499/1462.Course Schedule IV/Solution.go +++ b/solution/1400-1499/1462.Course Schedule IV/Solution.go @@ -3,30 +3,13 @@ func checkIfPrerequisite(n int, prerequisites [][]int, queries [][]int) (ans []b for i := range f { f[i] = make([]bool, n) } - g := make([][]int, n) - indeg := make([]int, n) for _, p := range prerequisites { - a, b := p[0], p[1] - g[a] = append(g[a], b) - indeg[b]++ + f[p[0]][p[1]] = true } - q := []int{} - for i, x := range indeg { - if x == 0 { - q = append(q, i) - } - } - for len(q) > 0 { - i := q[0] - q = q[1:] - for _, j := range g[i] { - f[i][j] = true - for h := 0; h < n; h++ { - f[h][j] = f[h][j] || f[h][i] - } - indeg[j]-- - if indeg[j] == 0 { - q = append(q, j) + for k := 0; k < n; k++ { + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + f[i][j] = f[i][j] || (f[i][k] && f[k][j]) } } } diff --git a/solution/1400-1499/1462.Course Schedule IV/Solution.java b/solution/1400-1499/1462.Course Schedule IV/Solution.java index e22837bc760e5..93fedf59d910c 100644 --- a/solution/1400-1499/1462.Course Schedule IV/Solution.java +++ b/solution/1400-1499/1462.Course Schedule IV/Solution.java @@ -1,35 +1,20 @@ -class Solution { - public List checkIfPrerequisite(int n, int[][] prerequisites, int[][] queries) { - boolean[][] f = new boolean[n][n]; - List[] g = new List[n]; - int[] indeg = new int[n]; - Arrays.setAll(g, i -> new ArrayList<>()); - for (var p : prerequisites) { - g[p[0]].add(p[1]); - ++indeg[p[1]]; - } - Deque q = new ArrayDeque<>(); - for (int i = 0; i < n; ++i) { - if (indeg[i] == 0) { - q.offer(i); - } - } - while (!q.isEmpty()) { - int i = q.poll(); - for (int j : g[i]) { - f[i][j] = true; - for (int h = 0; h < n; ++h) { - f[h][j] |= f[h][i]; - } - if (--indeg[j] == 0) { - q.offer(j); - } - } - } - List ans = new ArrayList<>(); - for (var qry : queries) { - ans.add(f[qry[0]][qry[1]]); - } - return ans; - } +class Solution { + public List checkIfPrerequisite(int n, int[][] prerequisites, int[][] queries) { + boolean[][] f = new boolean[n][n]; + for (var p : prerequisites) { + f[p[0]][p[1]] = true; + } + for (int k = 0; k < n; ++k) { + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + f[i][j] |= f[i][k] && f[k][j]; + } + } + } + List ans = new ArrayList<>(); + for (var q : queries) { + ans.add(f[q[0]][q[1]]); + } + return ans; + } } \ No newline at end of file diff --git a/solution/1400-1499/1462.Course Schedule IV/Solution.py b/solution/1400-1499/1462.Course Schedule IV/Solution.py index 13949d15d5447..3a156287a0973 100644 --- a/solution/1400-1499/1462.Course Schedule IV/Solution.py +++ b/solution/1400-1499/1462.Course Schedule IV/Solution.py @@ -1,21 +1,13 @@ -class Solution: - def checkIfPrerequisite( - self, n: int, prerequisites: List[List[int]], queries: List[List[int]] - ) -> List[bool]: - f = [[False] * n for _ in range(n)] - g = [[] for _ in range(n)] - indeg = [0] * n - for a, b in prerequisites: - g[a].append(b) - indeg[b] += 1 - q = deque(i for i, x in enumerate(indeg) if x == 0) - while q: - i = q.popleft() - for j in g[i]: - f[i][j] = True - for h in range(n): - f[h][j] = f[h][j] or f[h][i] - indeg[j] -= 1 - if indeg[j] == 0: - q.append(j) - return [f[a][b] for a, b in queries] +class Solution: + def checkIfPrerequisite( + self, n: int, prerequisites: List[List[int]], queries: List[List[int]] + ) -> List[bool]: + f = [[False] * n for _ in range(n)] + for a, b in prerequisites: + f[a][b] = True + for k in range(n): + for i in range(n): + for j in range(n): + if f[i][k] and f[k][j]: + f[i][j] = True + return [f[a][b] for a, b in queries] diff --git a/solution/1400-1499/1462.Course Schedule IV/Solution.ts b/solution/1400-1499/1462.Course Schedule IV/Solution.ts index 31e41346b04a3..dc2c74858d868 100644 --- a/solution/1400-1499/1462.Course Schedule IV/Solution.ts +++ b/solution/1400-1499/1462.Course Schedule IV/Solution.ts @@ -1,26 +1,10 @@ function checkIfPrerequisite(n: number, prerequisites: number[][], queries: number[][]): boolean[] { const f = Array.from({ length: n }, () => Array(n).fill(false)); - const g: number[][] = Array.from({ length: n }, () => []); - const indeg: number[] = Array(n).fill(0); - for (const [a, b] of prerequisites) { - g[a].push(b); - ++indeg[b]; - } - const q: number[] = []; - for (let i = 0; i < n; ++i) { - if (indeg[i] === 0) { - q.push(i); - } - } - while (q.length) { - const i = q.shift()!; - for (const j of g[i]) { - f[i][j] = true; - for (let h = 0; h < n; ++h) { - f[h][j] ||= f[h][i]; - } - if (--indeg[j] === 0) { - q.push(j); + prerequisites.forEach(([a, b]) => (f[a][b] = true)); + for (let k = 0; k < n; ++k) { + for (let i = 0; i < n; ++i) { + for (let j = 0; j < n; ++j) { + f[i][j] ||= f[i][k] && f[k][j]; } } } diff --git a/solution/1400-1499/1462.Course Schedule IV/Solution2.cpp b/solution/1400-1499/1462.Course Schedule IV/Solution2.cpp new file mode 100644 index 0000000000000..d7f4a575db69d --- /dev/null +++ b/solution/1400-1499/1462.Course Schedule IV/Solution2.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + vector checkIfPrerequisite(int n, vector>& prerequisites, vector>& queries) { + bool f[n][n]; + memset(f, false, sizeof(f)); + vector g[n]; + vector indeg(n); + for (auto& p : prerequisites) { + g[p[0]].push_back(p[1]); + ++indeg[p[1]]; + } + queue q; + for (int i = 0; i < n; ++i) { + if (indeg[i] == 0) { + q.push(i); + } + } + while (!q.empty()) { + int i = q.front(); + q.pop(); + for (int j : g[i]) { + f[i][j] = true; + for (int h = 0; h < n; ++h) { + f[h][j] |= f[h][i]; + } + if (--indeg[j] == 0) { + q.push(j); + } + } + } + vector ans; + for (auto& qry : queries) { + ans.push_back(f[qry[0]][qry[1]]); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1400-1499/1462.Course Schedule IV/Solution2.go b/solution/1400-1499/1462.Course Schedule IV/Solution2.go new file mode 100644 index 0000000000000..53b3f8f7929b9 --- /dev/null +++ b/solution/1400-1499/1462.Course Schedule IV/Solution2.go @@ -0,0 +1,37 @@ +func checkIfPrerequisite(n int, prerequisites [][]int, queries [][]int) (ans []bool) { + f := make([][]bool, n) + for i := range f { + f[i] = make([]bool, n) + } + g := make([][]int, n) + indeg := make([]int, n) + for _, p := range prerequisites { + a, b := p[0], p[1] + g[a] = append(g[a], b) + indeg[b]++ + } + q := []int{} + for i, x := range indeg { + if x == 0 { + q = append(q, i) + } + } + for len(q) > 0 { + i := q[0] + q = q[1:] + for _, j := range g[i] { + f[i][j] = true + for h := 0; h < n; h++ { + f[h][j] = f[h][j] || f[h][i] + } + indeg[j]-- + if indeg[j] == 0 { + q = append(q, j) + } + } + } + for _, q := range queries { + ans = append(ans, f[q[0]][q[1]]) + } + return +} \ No newline at end of file diff --git a/solution/1400-1499/1462.Course Schedule IV/Solution2.java b/solution/1400-1499/1462.Course Schedule IV/Solution2.java new file mode 100644 index 0000000000000..01170318d6071 --- /dev/null +++ b/solution/1400-1499/1462.Course Schedule IV/Solution2.java @@ -0,0 +1,35 @@ +class Solution { + public List checkIfPrerequisite(int n, int[][] prerequisites, int[][] queries) { + boolean[][] f = new boolean[n][n]; + List[] g = new List[n]; + int[] indeg = new int[n]; + Arrays.setAll(g, i -> new ArrayList<>()); + for (var p : prerequisites) { + g[p[0]].add(p[1]); + ++indeg[p[1]]; + } + Deque q = new ArrayDeque<>(); + for (int i = 0; i < n; ++i) { + if (indeg[i] == 0) { + q.offer(i); + } + } + while (!q.isEmpty()) { + int i = q.poll(); + for (int j : g[i]) { + f[i][j] = true; + for (int h = 0; h < n; ++h) { + f[h][j] |= f[h][i]; + } + if (--indeg[j] == 0) { + q.offer(j); + } + } + } + List ans = new ArrayList<>(); + for (var qry : queries) { + ans.add(f[qry[0]][qry[1]]); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1400-1499/1462.Course Schedule IV/Solution2.py b/solution/1400-1499/1462.Course Schedule IV/Solution2.py new file mode 100644 index 0000000000000..f8bbc94633e98 --- /dev/null +++ b/solution/1400-1499/1462.Course Schedule IV/Solution2.py @@ -0,0 +1,21 @@ +class Solution: + def checkIfPrerequisite( + self, n: int, prerequisites: List[List[int]], queries: List[List[int]] + ) -> List[bool]: + f = [[False] * n for _ in range(n)] + g = [[] for _ in range(n)] + indeg = [0] * n + for a, b in prerequisites: + g[a].append(b) + indeg[b] += 1 + q = deque(i for i, x in enumerate(indeg) if x == 0) + while q: + i = q.popleft() + for j in g[i]: + f[i][j] = True + for h in range(n): + f[h][j] = f[h][j] or f[h][i] + indeg[j] -= 1 + if indeg[j] == 0: + q.append(j) + return [f[a][b] for a, b in queries] diff --git a/solution/1400-1499/1462.Course Schedule IV/Solution2.ts b/solution/1400-1499/1462.Course Schedule IV/Solution2.ts new file mode 100644 index 0000000000000..31e41346b04a3 --- /dev/null +++ b/solution/1400-1499/1462.Course Schedule IV/Solution2.ts @@ -0,0 +1,28 @@ +function checkIfPrerequisite(n: number, prerequisites: number[][], queries: number[][]): boolean[] { + const f = Array.from({ length: n }, () => Array(n).fill(false)); + const g: number[][] = Array.from({ length: n }, () => []); + const indeg: number[] = Array(n).fill(0); + for (const [a, b] of prerequisites) { + g[a].push(b); + ++indeg[b]; + } + const q: number[] = []; + for (let i = 0; i < n; ++i) { + if (indeg[i] === 0) { + q.push(i); + } + } + while (q.length) { + const i = q.shift()!; + for (const j of g[i]) { + f[i][j] = true; + for (let h = 0; h < n; ++h) { + f[h][j] ||= f[h][i]; + } + if (--indeg[j] === 0) { + q.push(j); + } + } + } + return queries.map(([a, b]) => f[a][b]); +} diff --git a/solution/1400-1499/1463.Cherry Pickup II/Solution.cpp b/solution/1400-1499/1463.Cherry Pickup II/Solution.cpp index 381765fbda3fa..1cd85a90b792d 100644 --- a/solution/1400-1499/1463.Cherry Pickup II/Solution.cpp +++ b/solution/1400-1499/1463.Cherry Pickup II/Solution.cpp @@ -1,31 +1,30 @@ -class Solution { -public: - int cherryPickup(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - vector> f(n, vector(n, -1)); - vector> g(n, vector(n, -1)); - f[0][n - 1] = grid[0][0] + grid[0][n - 1]; - for (int i = 1; i < m; ++i) { - for (int j1 = 0; j1 < n; ++j1) { - for (int j2 = 0; j2 < n; ++j2) { - int x = grid[i][j1] + (j1 == j2 ? 0 : grid[i][j2]); - for (int y1 = j1 - 1; y1 <= j1 + 1; ++y1) { - for (int y2 = j2 - 1; y2 <= j2 + 1; ++y2) { - if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[y1][y2] != -1) { - g[j1][j2] = max(g[j1][j2], f[y1][y2] + x); - } - } - } - } - } - swap(f, g); - } - int ans = 0; - for (int j1 = 0; j1 < n; ++j1) { - for (int j2 = 0; j2 < n; ++j2) { - ans = max(ans, f[j1][j2]); - } - } - return ans; - } +class Solution { +public: + int cherryPickup(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int f[m][n][n]; + memset(f, -1, sizeof(f)); + f[0][0][n - 1] = grid[0][0] + grid[0][n - 1]; + for (int i = 1; i < m; ++i) { + for (int j1 = 0; j1 < n; ++j1) { + for (int j2 = 0; j2 < n; ++j2) { + int x = grid[i][j1] + (j1 == j2 ? 0 : grid[i][j2]); + for (int y1 = j1 - 1; y1 <= j1 + 1; ++y1) { + for (int y2 = j2 - 1; y2 <= j2 + 1; ++y2) { + if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[i - 1][y1][y2] != -1) { + f[i][j1][j2] = max(f[i][j1][j2], f[i - 1][y1][y2] + x); + } + } + } + } + } + } + int ans = 0; + for (int j1 = 0; j1 < n; ++j1) { + for (int j2 = 0; j2 < n; ++j2) { + ans = max(ans, f[m - 1][j1][j2]); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1400-1499/1463.Cherry Pickup II/Solution.go b/solution/1400-1499/1463.Cherry Pickup II/Solution.go index f0d29d1fffb48..b373190afd69a 100644 --- a/solution/1400-1499/1463.Cherry Pickup II/Solution.go +++ b/solution/1400-1499/1463.Cherry Pickup II/Solution.go @@ -1,16 +1,16 @@ func cherryPickup(grid [][]int) int { m, n := len(grid), len(grid[0]) - f := make([][]int, n) - g := make([][]int, n) + f := make([][][]int, m) for i := range f { - f[i] = make([]int, n) - g[i] = make([]int, n) + f[i] = make([][]int, n) for j := range f[i] { - f[i][j] = -1 - g[i][j] = -1 + f[i][j] = make([]int, n) + for k := range f[i][j] { + f[i][j][k] = -1 + } } } - f[0][n-1] = grid[0][0] + grid[0][n-1] + f[0][0][n-1] = grid[0][0] + grid[0][n-1] for i := 1; i < m; i++ { for j1 := 0; j1 < n; j1++ { for j2 := 0; j2 < n; j2++ { @@ -20,19 +20,18 @@ func cherryPickup(grid [][]int) int { } for y1 := j1 - 1; y1 <= j1+1; y1++ { for y2 := j2 - 1; y2 <= j2+1; y2++ { - if y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[y1][y2] != -1 { - g[j1][j2] = max(g[j1][j2], f[y1][y2]+x) + if y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[i-1][y1][y2] != -1 { + f[i][j1][j2] = max(f[i][j1][j2], f[i-1][y1][y2]+x) } } } } } - f, g = g, f } ans := 0 for j1 := 0; j1 < n; j1++ { for j2 := 0; j2 < n; j2++ { - ans = max(ans, f[j1][j2]) + ans = max(ans, f[m-1][j1][j2]) } } return ans diff --git a/solution/1400-1499/1463.Cherry Pickup II/Solution.java b/solution/1400-1499/1463.Cherry Pickup II/Solution.java index a4f4bd56dae2e..3ee3cbc78e9c1 100644 --- a/solution/1400-1499/1463.Cherry Pickup II/Solution.java +++ b/solution/1400-1499/1463.Cherry Pickup II/Solution.java @@ -1,36 +1,33 @@ -class Solution { - public int cherryPickup(int[][] grid) { - int m = grid.length, n = grid[0].length; - int[][] f = new int[n][n]; - int[][] g = new int[n][n]; - for (int i = 0; i < n; ++i) { - Arrays.fill(f[i], -1); - Arrays.fill(g[i], -1); - } - f[0][n - 1] = grid[0][0] + grid[0][n - 1]; - for (int i = 1; i < m; ++i) { - for (int j1 = 0; j1 < n; ++j1) { - for (int j2 = 0; j2 < n; ++j2) { - int x = grid[i][j1] + (j1 == j2 ? 0 : grid[i][j2]); - for (int y1 = j1 - 1; y1 <= j1 + 1; ++y1) { - for (int y2 = j2 - 1; y2 <= j2 + 1; ++y2) { - if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[y1][y2] != -1) { - g[j1][j2] = Math.max(g[j1][j2], f[y1][y2] + x); - } - } - } - } - } - int[][] t = f; - f = g; - g = t; - } - int ans = 0; - for (int j1 = 0; j1 < n; ++j1) { - for (int j2 = 0; j2 < n; ++j2) { - ans = Math.max(ans, f[j1][j2]); - } - } - return ans; - } +class Solution { + public int cherryPickup(int[][] grid) { + int m = grid.length, n = grid[0].length; + int[][][] f = new int[m][n][n]; + for (var g : f) { + for (var h : g) { + Arrays.fill(h, -1); + } + } + f[0][0][n - 1] = grid[0][0] + grid[0][n - 1]; + for (int i = 1; i < m; ++i) { + for (int j1 = 0; j1 < n; ++j1) { + for (int j2 = 0; j2 < n; ++j2) { + int x = grid[i][j1] + (j1 == j2 ? 0 : grid[i][j2]); + for (int y1 = j1 - 1; y1 <= j1 + 1; ++y1) { + for (int y2 = j2 - 1; y2 <= j2 + 1; ++y2) { + if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[i - 1][y1][y2] != -1) { + f[i][j1][j2] = Math.max(f[i][j1][j2], f[i - 1][y1][y2] + x); + } + } + } + } + } + } + int ans = 0; + for (int j1 = 0; j1 < n; ++j1) { + for (int j2 = 0; j2 < n; ++j2) { + ans = Math.max(ans, f[m - 1][j1][j2]); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1400-1499/1463.Cherry Pickup II/Solution.py b/solution/1400-1499/1463.Cherry Pickup II/Solution.py index 9a50f4e4e1ea2..a78cfcc6889f3 100644 --- a/solution/1400-1499/1463.Cherry Pickup II/Solution.py +++ b/solution/1400-1499/1463.Cherry Pickup II/Solution.py @@ -1,16 +1,14 @@ -class Solution: - def cherryPickup(self, grid: List[List[int]]) -> int: - m, n = len(grid), len(grid[0]) - f = [[-1] * n for _ in range(n)] - g = [[-1] * n for _ in range(n)] - f[0][n - 1] = grid[0][0] + grid[0][n - 1] - for i in range(1, m): - for j1 in range(n): - for j2 in range(n): - x = grid[i][j1] + (0 if j1 == j2 else grid[i][j2]) - for y1 in range(j1 - 1, j1 + 2): - for y2 in range(j2 - 1, j2 + 2): - if 0 <= y1 < n and 0 <= y2 < n and f[y1][y2] != -1: - g[j1][j2] = max(g[j1][j2], f[y1][y2] + x) - f, g = g, f - return max(f[j1][j2] for j1, j2 in product(range(n), range(n))) +class Solution: + def cherryPickup(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + f = [[[-1] * n for _ in range(n)] for _ in range(m)] + f[0][0][n - 1] = grid[0][0] + grid[0][n - 1] + for i in range(1, m): + for j1 in range(n): + for j2 in range(n): + x = grid[i][j1] + (0 if j1 == j2 else grid[i][j2]) + for y1 in range(j1 - 1, j1 + 2): + for y2 in range(j2 - 1, j2 + 2): + if 0 <= y1 < n and 0 <= y2 < n and f[i - 1][y1][y2] != -1: + f[i][j1][j2] = max(f[i][j1][j2], f[i - 1][y1][y2] + x) + return max(f[-1][j1][j2] for j1, j2 in product(range(n), range(n))) diff --git a/solution/1400-1499/1463.Cherry Pickup II/Solution.ts b/solution/1400-1499/1463.Cherry Pickup II/Solution.ts index b523176718041..446efa119723e 100644 --- a/solution/1400-1499/1463.Cherry Pickup II/Solution.ts +++ b/solution/1400-1499/1463.Cherry Pickup II/Solution.ts @@ -1,28 +1,28 @@ function cherryPickup(grid: number[][]): number { const m = grid.length; const n = grid[0].length; - let f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(-1)); - let g: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(-1)); - f[0][n - 1] = grid[0][0] + grid[0][n - 1]; + const f: number[][][] = new Array(m) + .fill(0) + .map(() => new Array(n).fill(0).map(() => new Array(n).fill(-1))); + f[0][0][n - 1] = grid[0][0] + grid[0][n - 1]; for (let i = 1; i < m; ++i) { for (let j1 = 0; j1 < n; ++j1) { for (let j2 = 0; j2 < n; ++j2) { const x = grid[i][j1] + (j1 === j2 ? 0 : grid[i][j2]); for (let y1 = j1 - 1; y1 <= j1 + 1; ++y1) { for (let y2 = j2 - 1; y2 <= j2 + 1; ++y2) { - if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[y1][y2] !== -1) { - g[j1][j2] = Math.max(g[j1][j2], f[y1][y2] + x); + if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[i - 1][y1][y2] !== -1) { + f[i][j1][j2] = Math.max(f[i][j1][j2], f[i - 1][y1][y2] + x); } } } } } - [f, g] = [g, f]; } let ans = 0; for (let j1 = 0; j1 < n; ++j1) { for (let j2 = 0; j2 < n; ++j2) { - ans = Math.max(ans, f[j1][j2]); + ans = Math.max(ans, f[m - 1][j1][j2]); } } return ans; diff --git a/solution/1400-1499/1463.Cherry Pickup II/Solution2.cpp b/solution/1400-1499/1463.Cherry Pickup II/Solution2.cpp new file mode 100644 index 0000000000000..019e5f9e6b4d3 --- /dev/null +++ b/solution/1400-1499/1463.Cherry Pickup II/Solution2.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int cherryPickup(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + vector> f(n, vector(n, -1)); + vector> g(n, vector(n, -1)); + f[0][n - 1] = grid[0][0] + grid[0][n - 1]; + for (int i = 1; i < m; ++i) { + for (int j1 = 0; j1 < n; ++j1) { + for (int j2 = 0; j2 < n; ++j2) { + int x = grid[i][j1] + (j1 == j2 ? 0 : grid[i][j2]); + for (int y1 = j1 - 1; y1 <= j1 + 1; ++y1) { + for (int y2 = j2 - 1; y2 <= j2 + 1; ++y2) { + if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[y1][y2] != -1) { + g[j1][j2] = max(g[j1][j2], f[y1][y2] + x); + } + } + } + } + } + swap(f, g); + } + int ans = 0; + for (int j1 = 0; j1 < n; ++j1) { + for (int j2 = 0; j2 < n; ++j2) { + ans = max(ans, f[j1][j2]); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1400-1499/1463.Cherry Pickup II/Solution2.go b/solution/1400-1499/1463.Cherry Pickup II/Solution2.go new file mode 100644 index 0000000000000..f0d29d1fffb48 --- /dev/null +++ b/solution/1400-1499/1463.Cherry Pickup II/Solution2.go @@ -0,0 +1,39 @@ +func cherryPickup(grid [][]int) int { + m, n := len(grid), len(grid[0]) + f := make([][]int, n) + g := make([][]int, n) + for i := range f { + f[i] = make([]int, n) + g[i] = make([]int, n) + for j := range f[i] { + f[i][j] = -1 + g[i][j] = -1 + } + } + f[0][n-1] = grid[0][0] + grid[0][n-1] + for i := 1; i < m; i++ { + for j1 := 0; j1 < n; j1++ { + for j2 := 0; j2 < n; j2++ { + x := grid[i][j1] + if j1 != j2 { + x += grid[i][j2] + } + for y1 := j1 - 1; y1 <= j1+1; y1++ { + for y2 := j2 - 1; y2 <= j2+1; y2++ { + if y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[y1][y2] != -1 { + g[j1][j2] = max(g[j1][j2], f[y1][y2]+x) + } + } + } + } + } + f, g = g, f + } + ans := 0 + for j1 := 0; j1 < n; j1++ { + for j2 := 0; j2 < n; j2++ { + ans = max(ans, f[j1][j2]) + } + } + return ans +} \ No newline at end of file diff --git a/solution/1400-1499/1463.Cherry Pickup II/Solution2.java b/solution/1400-1499/1463.Cherry Pickup II/Solution2.java new file mode 100644 index 0000000000000..d3354acaea32f --- /dev/null +++ b/solution/1400-1499/1463.Cherry Pickup II/Solution2.java @@ -0,0 +1,36 @@ +class Solution { + public int cherryPickup(int[][] grid) { + int m = grid.length, n = grid[0].length; + int[][] f = new int[n][n]; + int[][] g = new int[n][n]; + for (int i = 0; i < n; ++i) { + Arrays.fill(f[i], -1); + Arrays.fill(g[i], -1); + } + f[0][n - 1] = grid[0][0] + grid[0][n - 1]; + for (int i = 1; i < m; ++i) { + for (int j1 = 0; j1 < n; ++j1) { + for (int j2 = 0; j2 < n; ++j2) { + int x = grid[i][j1] + (j1 == j2 ? 0 : grid[i][j2]); + for (int y1 = j1 - 1; y1 <= j1 + 1; ++y1) { + for (int y2 = j2 - 1; y2 <= j2 + 1; ++y2) { + if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[y1][y2] != -1) { + g[j1][j2] = Math.max(g[j1][j2], f[y1][y2] + x); + } + } + } + } + } + int[][] t = f; + f = g; + g = t; + } + int ans = 0; + for (int j1 = 0; j1 < n; ++j1) { + for (int j2 = 0; j2 < n; ++j2) { + ans = Math.max(ans, f[j1][j2]); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1400-1499/1463.Cherry Pickup II/Solution2.py b/solution/1400-1499/1463.Cherry Pickup II/Solution2.py new file mode 100644 index 0000000000000..2c901ef44f17f --- /dev/null +++ b/solution/1400-1499/1463.Cherry Pickup II/Solution2.py @@ -0,0 +1,16 @@ +class Solution: + def cherryPickup(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + f = [[-1] * n for _ in range(n)] + g = [[-1] * n for _ in range(n)] + f[0][n - 1] = grid[0][0] + grid[0][n - 1] + for i in range(1, m): + for j1 in range(n): + for j2 in range(n): + x = grid[i][j1] + (0 if j1 == j2 else grid[i][j2]) + for y1 in range(j1 - 1, j1 + 2): + for y2 in range(j2 - 1, j2 + 2): + if 0 <= y1 < n and 0 <= y2 < n and f[y1][y2] != -1: + g[j1][j2] = max(g[j1][j2], f[y1][y2] + x) + f, g = g, f + return max(f[j1][j2] for j1, j2 in product(range(n), range(n))) diff --git a/solution/1400-1499/1463.Cherry Pickup II/Solution2.ts b/solution/1400-1499/1463.Cherry Pickup II/Solution2.ts new file mode 100644 index 0000000000000..b523176718041 --- /dev/null +++ b/solution/1400-1499/1463.Cherry Pickup II/Solution2.ts @@ -0,0 +1,29 @@ +function cherryPickup(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + let f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(-1)); + let g: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(-1)); + f[0][n - 1] = grid[0][0] + grid[0][n - 1]; + for (let i = 1; i < m; ++i) { + for (let j1 = 0; j1 < n; ++j1) { + for (let j2 = 0; j2 < n; ++j2) { + const x = grid[i][j1] + (j1 === j2 ? 0 : grid[i][j2]); + for (let y1 = j1 - 1; y1 <= j1 + 1; ++y1) { + for (let y2 = j2 - 1; y2 <= j2 + 1; ++y2) { + if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[y1][y2] !== -1) { + g[j1][j2] = Math.max(g[j1][j2], f[y1][y2] + x); + } + } + } + } + } + [f, g] = [g, f]; + } + let ans = 0; + for (let j1 = 0; j1 < n; ++j1) { + for (let j2 = 0; j2 < n; ++j2) { + ans = Math.max(ans, f[j1][j2]); + } + } + return ans; +} diff --git a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.c b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.c index c0a18f49d9c97..86f86385ab676 100644 --- a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.c +++ b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.c @@ -11,4 +11,4 @@ int maxProduct(int* nums, int numsSize) { } } return (max - 1) * (submax - 1); -} +} \ No newline at end of file diff --git a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.cpp b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.cpp index 40fa5b3794eee..e99efbc3587fd 100644 --- a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.cpp +++ b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.cpp @@ -1,15 +1,13 @@ class Solution { public: int maxProduct(vector& nums) { - int a = 0, b = 0; - for (int v : nums) { - if (v > a) { - b = a; - a = v; - } else if (v > b) { - b = v; + int ans = 0; + int n = nums.size(); + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + ans = max(ans, (nums[i] - 1) * (nums[j] - 1)); } } - return (a - 1) * (b - 1); + return ans; } }; \ No newline at end of file diff --git a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.go b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.go index 3497cbcdbbdf2..a13de93be24de 100644 --- a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.go +++ b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.go @@ -1,11 +1,12 @@ func maxProduct(nums []int) int { - a, b := 0, 0 - for _, v := range nums { - if v > a { - b, a = a, v - } else if v > b { - b = v + ans := 0 + for i, a := range nums { + for _, b := range nums[i+1:] { + t := (a - 1) * (b - 1) + if ans < t { + ans = t + } } } - return (a - 1) * (b - 1) + return ans } \ No newline at end of file diff --git a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.java b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.java index 9205d19b78bfd..9b8a4a8f8c6e1 100644 --- a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.java +++ b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.java @@ -1,14 +1,12 @@ class Solution { public int maxProduct(int[] nums) { - int a = 0, b = 0; - for (int v : nums) { - if (v > a) { - b = a; - a = v; - } else if (v > b) { - b = v; + int ans = 0; + int n = nums.length; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + ans = Math.max(ans, (nums[i] - 1) * (nums[j] - 1)); } } - return (a - 1) * (b - 1); + return ans; } } \ No newline at end of file diff --git a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.php b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.php index 84b4000023e29..338cb5a4e184d 100644 --- a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.php +++ b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.php @@ -16,4 +16,4 @@ function maxProduct($nums) { } return ($max - 1) * ($submax - 1); } -} \ No newline at end of file +} diff --git a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.py b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.py index 642a01b3af403..271ce51d48c80 100644 --- a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.py +++ b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.py @@ -1,9 +1,7 @@ class Solution: def maxProduct(self, nums: List[int]) -> int: - a = b = 0 - for v in nums: - if v > a: - a, b = v, a - elif v > b: - b = v - return (a - 1) * (b - 1) + ans = 0 + for i, a in enumerate(nums): + for b in nums[i + 1 :]: + ans = max(ans, (a - 1) * (b - 1)) + return ans diff --git a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.ts b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.ts index f59646a4760b2..919df3b7c47c6 100644 --- a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.ts +++ b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.ts @@ -1,13 +1,13 @@ function maxProduct(nums: number[]): number { - let max = 0; - let submax = 0; - for (const num of nums) { - if (num > max) { - submax = max; - max = num; - } else if (num > submax) { - submax = num; + const n = nums.length; + for (let i = 0; i < 2; i++) { + let maxIdx = i; + for (let j = i + 1; j < n; j++) { + if (nums[j] > nums[maxIdx]) { + maxIdx = j; + } } + [nums[i], nums[maxIdx]] = [nums[maxIdx], nums[i]]; } - return (max - 1) * (submax - 1); + return (nums[0] - 1) * (nums[1] - 1); } diff --git a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution2.cpp b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution2.cpp new file mode 100644 index 0000000000000..3d9162847fd02 --- /dev/null +++ b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution2.cpp @@ -0,0 +1,7 @@ +class Solution { +public: + int maxProduct(vector& nums) { + sort(nums.rbegin(), nums.rend()); + return (nums[0] - 1) * (nums[1] - 1); + } +}; \ No newline at end of file diff --git a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution2.go b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution2.go new file mode 100644 index 0000000000000..0e134c9835a1a --- /dev/null +++ b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution2.go @@ -0,0 +1,5 @@ +func maxProduct(nums []int) int { + sort.Ints(nums) + n := len(nums) + return (nums[n-1] - 1) * (nums[n-2] - 1) +} \ No newline at end of file diff --git a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution2.java b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution2.java new file mode 100644 index 0000000000000..5376d66dcfa08 --- /dev/null +++ b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution2.java @@ -0,0 +1,7 @@ +class Solution { + public int maxProduct(int[] nums) { + Arrays.sort(nums); + int n = nums.length; + return (nums[n - 1] - 1) * (nums[n - 2] - 1); + } +} \ No newline at end of file diff --git a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution2.py b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution2.py new file mode 100644 index 0000000000000..c2ac512b47fdc --- /dev/null +++ b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution2.py @@ -0,0 +1,4 @@ +class Solution: + def maxProduct(self, nums: List[int]) -> int: + nums.sort() + return (nums[-1] - 1) * (nums[-2] - 1) diff --git a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution2.ts b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution2.ts new file mode 100644 index 0000000000000..f59646a4760b2 --- /dev/null +++ b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution2.ts @@ -0,0 +1,13 @@ +function maxProduct(nums: number[]): number { + let max = 0; + let submax = 0; + for (const num of nums) { + if (num > max) { + submax = max; + max = num; + } else if (num > submax) { + submax = num; + } + } + return (max - 1) * (submax - 1); +} diff --git a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution3.cpp b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution3.cpp new file mode 100644 index 0000000000000..40fa5b3794eee --- /dev/null +++ b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution3.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int maxProduct(vector& nums) { + int a = 0, b = 0; + for (int v : nums) { + if (v > a) { + b = a; + a = v; + } else if (v > b) { + b = v; + } + } + return (a - 1) * (b - 1); + } +}; \ No newline at end of file diff --git a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution3.go b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution3.go new file mode 100644 index 0000000000000..3497cbcdbbdf2 --- /dev/null +++ b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution3.go @@ -0,0 +1,11 @@ +func maxProduct(nums []int) int { + a, b := 0, 0 + for _, v := range nums { + if v > a { + b, a = a, v + } else if v > b { + b = v + } + } + return (a - 1) * (b - 1) +} \ No newline at end of file diff --git a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution3.java b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution3.java new file mode 100644 index 0000000000000..9205d19b78bfd --- /dev/null +++ b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution3.java @@ -0,0 +1,14 @@ +class Solution { + public int maxProduct(int[] nums) { + int a = 0, b = 0; + for (int v : nums) { + if (v > a) { + b = a; + a = v; + } else if (v > b) { + b = v; + } + } + return (a - 1) * (b - 1); + } +} \ No newline at end of file diff --git a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution3.py b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution3.py new file mode 100644 index 0000000000000..642a01b3af403 --- /dev/null +++ b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution3.py @@ -0,0 +1,9 @@ +class Solution: + def maxProduct(self, nums: List[int]) -> int: + a = b = 0 + for v in nums: + if v > a: + a, b = v, a + elif v > b: + b = v + return (a - 1) * (b - 1) diff --git a/solution/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/Solution.cpp b/solution/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/Solution.cpp index 5a56dc123bbf2..b80f1afff0a91 100644 --- a/solution/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/Solution.cpp +++ b/solution/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - int maxArea(int h, int w, vector& horizontalCuts, vector& verticalCuts) { - horizontalCuts.push_back(0); - horizontalCuts.push_back(h); - verticalCuts.push_back(0); - verticalCuts.push_back(w); - sort(horizontalCuts.begin(), horizontalCuts.end()); - sort(verticalCuts.begin(), verticalCuts.end()); - int x = 0, y = 0; - for (int i = 1; i < horizontalCuts.size(); ++i) { - x = max(x, horizontalCuts[i] - horizontalCuts[i - 1]); - } - for (int i = 1; i < verticalCuts.size(); ++i) { - y = max(y, verticalCuts[i] - verticalCuts[i - 1]); - } - const int mod = 1e9 + 7; - return (1ll * x * y) % mod; - } +class Solution { +public: + int maxArea(int h, int w, vector& horizontalCuts, vector& verticalCuts) { + horizontalCuts.push_back(0); + horizontalCuts.push_back(h); + verticalCuts.push_back(0); + verticalCuts.push_back(w); + sort(horizontalCuts.begin(), horizontalCuts.end()); + sort(verticalCuts.begin(), verticalCuts.end()); + int x = 0, y = 0; + for (int i = 1; i < horizontalCuts.size(); ++i) { + x = max(x, horizontalCuts[i] - horizontalCuts[i - 1]); + } + for (int i = 1; i < verticalCuts.size(); ++i) { + y = max(y, verticalCuts[i] - verticalCuts[i - 1]); + } + const int mod = 1e9 + 7; + return (1ll * x * y) % mod; + } }; \ No newline at end of file diff --git a/solution/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/Solution.java b/solution/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/Solution.java index ab1a5ea3ae124..11320bf2fb9e3 100644 --- a/solution/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/Solution.java +++ b/solution/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/Solution.java @@ -1,18 +1,18 @@ -class Solution { - public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) { - final int mod = (int) 1e9 + 7; - Arrays.sort(horizontalCuts); - Arrays.sort(verticalCuts); - int m = horizontalCuts.length; - int n = verticalCuts.length; - long x = Math.max(horizontalCuts[0], h - horizontalCuts[m - 1]); - long y = Math.max(verticalCuts[0], w - verticalCuts[n - 1]); - for (int i = 1; i < m; ++i) { - x = Math.max(x, horizontalCuts[i] - horizontalCuts[i - 1]); - } - for (int i = 1; i < n; ++i) { - y = Math.max(y, verticalCuts[i] - verticalCuts[i - 1]); - } - return (int) ((x * y) % mod); - } +class Solution { + public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) { + final int mod = (int) 1e9 + 7; + Arrays.sort(horizontalCuts); + Arrays.sort(verticalCuts); + int m = horizontalCuts.length; + int n = verticalCuts.length; + long x = Math.max(horizontalCuts[0], h - horizontalCuts[m - 1]); + long y = Math.max(verticalCuts[0], w - verticalCuts[n - 1]); + for (int i = 1; i < m; ++i) { + x = Math.max(x, horizontalCuts[i] - horizontalCuts[i - 1]); + } + for (int i = 1; i < n; ++i) { + y = Math.max(y, verticalCuts[i] - verticalCuts[i - 1]); + } + return (int) ((x * y) % mod); + } } \ No newline at end of file diff --git a/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/Solution.cpp b/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/Solution.cpp index c1ac286b2ccf9..d7323009d1525 100644 --- a/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/Solution.cpp +++ b/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - int minReorder(int n, vector>& connections) { - vector> g[n]; - for (auto& e : connections) { - int a = e[0], b = e[1]; - g[a].emplace_back(b, 1); - g[b].emplace_back(a, 0); - } - function dfs = [&](int a, int fa) { - int ans = 0; - for (auto& [b, c] : g[a]) { - if (b != fa) { - ans += c + dfs(b, a); - } - } - return ans; - }; - return dfs(0, -1); - } +class Solution { +public: + int minReorder(int n, vector>& connections) { + vector> g[n]; + for (auto& e : connections) { + int a = e[0], b = e[1]; + g[a].emplace_back(b, 1); + g[b].emplace_back(a, 0); + } + function dfs = [&](int a, int fa) { + int ans = 0; + for (auto& [b, c] : g[a]) { + if (b != fa) { + ans += c + dfs(b, a); + } + } + return ans; + }; + return dfs(0, -1); + } }; \ No newline at end of file diff --git a/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/Solution.java b/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/Solution.java index 0ef19041a7dc9..4c1a95b7da1ea 100644 --- a/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/Solution.java +++ b/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/Solution.java @@ -1,25 +1,25 @@ -class Solution { - private List[] g; - - public int minReorder(int n, int[][] connections) { - g = new List[n]; - Arrays.setAll(g, k -> new ArrayList<>()); - for (var e : connections) { - int a = e[0], b = e[1]; - g[a].add(new int[] {b, 1}); - g[b].add(new int[] {a, 0}); - } - return dfs(0, -1); - } - - private int dfs(int a, int fa) { - int ans = 0; - for (var e : g[a]) { - int b = e[0], c = e[1]; - if (b != fa) { - ans += c + dfs(b, a); - } - } - return ans; - } +class Solution { + private List[] g; + + public int minReorder(int n, int[][] connections) { + g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (var e : connections) { + int a = e[0], b = e[1]; + g[a].add(new int[] {b, 1}); + g[b].add(new int[] {a, 0}); + } + return dfs(0, -1); + } + + private int dfs(int a, int fa) { + int ans = 0; + for (var e : g[a]) { + int b = e[0], c = e[1]; + if (b != fa) { + ans += c + dfs(b, a); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/Solution.py b/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/Solution.py index 49271fb166ff5..fe8dcc8ba385c 100644 --- a/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/Solution.py +++ b/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def minReorder(self, n: int, connections: List[List[int]]) -> int: - def dfs(a: int, fa: int) -> int: - return sum(c + dfs(b, a) for b, c in g[a] if b != fa) - - g = [[] for _ in range(n)] - for a, b in connections: - g[a].append((b, 1)) - g[b].append((a, 0)) - return dfs(0, -1) +class Solution: + def minReorder(self, n: int, connections: List[List[int]]) -> int: + def dfs(a: int, fa: int) -> int: + return sum(c + dfs(b, a) for b, c in g[a] if b != fa) + + g = [[] for _ in range(n)] + for a, b in connections: + g[a].append((b, 1)) + g[b].append((a, 0)) + return dfs(0, -1) diff --git a/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/Solution.cpp b/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/Solution.cpp index 2d8b1521be19c..9211f5a840ea8 100644 --- a/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/Solution.cpp +++ b/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/Solution.cpp @@ -1,37 +1,37 @@ -class Solution { -public: - double getProbability(vector& balls) { - int n = accumulate(balls.begin(), balls.end(), 0) / 2; - int mx = *max_element(balls.begin(), balls.end()); - int m = max(mx, n << 1); - long long c[m + 1][m + 1]; - memset(c, 0, sizeof(c)); - for (int i = 0; i <= m; ++i) { - c[i][0] = 1; - for (int j = 1; j <= i; ++j) { - c[i][j] = c[i - 1][j - 1] + c[i - 1][j]; - } - } - int k = balls.size(); - long long f[k][n + 1][k << 1 | 1]; - memset(f, -1, sizeof(f)); - function dfs = [&](int i, int j, int diff) -> long long { - if (i >= k) { - return j == 0 && diff == k ? 1 : 0; - } - if (j < 0) { - return 0; - } - if (f[i][j][diff] != -1) { - return f[i][j][diff]; - } - long long ans = 0; - for (int x = 0; x <= balls[i]; ++x) { - int y = x == balls[i] ? 1 : (x == 0 ? -1 : 0); - ans += dfs(i + 1, j - x, diff + y) * c[balls[i]][x]; - } - return f[i][j][diff] = ans; - }; - return dfs(0, n, k) * 1.0 / c[n << 1][n]; - } +class Solution { +public: + double getProbability(vector& balls) { + int n = accumulate(balls.begin(), balls.end(), 0) / 2; + int mx = *max_element(balls.begin(), balls.end()); + int m = max(mx, n << 1); + long long c[m + 1][m + 1]; + memset(c, 0, sizeof(c)); + for (int i = 0; i <= m; ++i) { + c[i][0] = 1; + for (int j = 1; j <= i; ++j) { + c[i][j] = c[i - 1][j - 1] + c[i - 1][j]; + } + } + int k = balls.size(); + long long f[k][n + 1][k << 1 | 1]; + memset(f, -1, sizeof(f)); + function dfs = [&](int i, int j, int diff) -> long long { + if (i >= k) { + return j == 0 && diff == k ? 1 : 0; + } + if (j < 0) { + return 0; + } + if (f[i][j][diff] != -1) { + return f[i][j][diff]; + } + long long ans = 0; + for (int x = 0; x <= balls[i]; ++x) { + int y = x == balls[i] ? 1 : (x == 0 ? -1 : 0); + ans += dfs(i + 1, j - x, diff + y) * c[balls[i]][x]; + } + return f[i][j][diff] = ans; + }; + return dfs(0, n, k) * 1.0 / c[n << 1][n]; + } }; \ No newline at end of file diff --git a/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/Solution.java b/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/Solution.java index aa87f18fe6c50..57d556cfb5d52 100644 --- a/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/Solution.java +++ b/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/Solution.java @@ -1,45 +1,45 @@ -class Solution { - private int n; - private long[][] c; - private int[] balls; - private Map, Long> f = new HashMap<>(); - - public double getProbability(int[] balls) { - int mx = 0; - for (int x : balls) { - n += x; - mx = Math.max(mx, x); - } - n >>= 1; - this.balls = balls; - int m = Math.max(mx, n << 1); - c = new long[m + 1][m + 1]; - for (int i = 0; i <= m; ++i) { - c[i][0] = 1; - for (int j = 1; j <= i; ++j) { - c[i][j] = c[i - 1][j - 1] + c[i - 1][j]; - } - } - return dfs(0, n, 0) * 1.0 / c[n << 1][n]; - } - - private long dfs(int i, int j, int diff) { - if (i >= balls.length) { - return j == 0 && diff == 0 ? 1 : 0; - } - if (j < 0) { - return 0; - } - List key = List.of(i, j, diff); - if (f.containsKey(key)) { - return f.get(key); - } - long ans = 0; - for (int x = 0; x <= balls[i]; ++x) { - int y = x == balls[i] ? 1 : (x == 0 ? -1 : 0); - ans += dfs(i + 1, j - x, diff + y) * c[balls[i]][x]; - } - f.put(key, ans); - return ans; - } +class Solution { + private int n; + private long[][] c; + private int[] balls; + private Map, Long> f = new HashMap<>(); + + public double getProbability(int[] balls) { + int mx = 0; + for (int x : balls) { + n += x; + mx = Math.max(mx, x); + } + n >>= 1; + this.balls = balls; + int m = Math.max(mx, n << 1); + c = new long[m + 1][m + 1]; + for (int i = 0; i <= m; ++i) { + c[i][0] = 1; + for (int j = 1; j <= i; ++j) { + c[i][j] = c[i - 1][j - 1] + c[i - 1][j]; + } + } + return dfs(0, n, 0) * 1.0 / c[n << 1][n]; + } + + private long dfs(int i, int j, int diff) { + if (i >= balls.length) { + return j == 0 && diff == 0 ? 1 : 0; + } + if (j < 0) { + return 0; + } + List key = List.of(i, j, diff); + if (f.containsKey(key)) { + return f.get(key); + } + long ans = 0; + for (int x = 0; x <= balls[i]; ++x) { + int y = x == balls[i] ? 1 : (x == 0 ? -1 : 0); + ans += dfs(i + 1, j - x, diff + y) * c[balls[i]][x]; + } + f.put(key, ans); + return ans; + } } \ No newline at end of file diff --git a/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/Solution.py b/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/Solution.py index 7823b20b32d02..63a29da813004 100644 --- a/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/Solution.py +++ b/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/Solution.py @@ -1,17 +1,17 @@ -class Solution: - def getProbability(self, balls: List[int]) -> float: - @cache - def dfs(i: int, j: int, diff: int) -> float: - if i >= k: - return 1 if j == 0 and diff == 0 else 0 - if j < 0: - return 0 - ans = 0 - for x in range(balls[i] + 1): - y = 1 if x == balls[i] else (-1 if x == 0 else 0) - ans += dfs(i + 1, j - x, diff + y) * comb(balls[i], x) - return ans - - n = sum(balls) >> 1 - k = len(balls) - return dfs(0, n, 0) / comb(n << 1, n) +class Solution: + def getProbability(self, balls: List[int]) -> float: + @cache + def dfs(i: int, j: int, diff: int) -> float: + if i >= k: + return 1 if j == 0 and diff == 0 else 0 + if j < 0: + return 0 + ans = 0 + for x in range(balls[i] + 1): + y = 1 if x == balls[i] else (-1 if x == 0 else 0) + ans += dfs(i + 1, j - x, diff + y) * comb(balls[i], x) + return ans + + n = sum(balls) >> 1 + k = len(balls) + return dfs(0, n, 0) / comb(n << 1, n) diff --git a/solution/1400-1499/1470.Shuffle the Array/Solution.c b/solution/1400-1499/1470.Shuffle the Array/Solution.c index f20b3e686fd02..348c1b1be4cc0 100644 --- a/solution/1400-1499/1470.Shuffle the Array/Solution.c +++ b/solution/1400-1499/1470.Shuffle the Array/Solution.c @@ -9,4 +9,4 @@ int* shuffle(int* nums, int numsSize, int n, int* returnSize) { } *returnSize = n * 2; return res; -} +} \ No newline at end of file diff --git a/solution/1400-1499/1470.Shuffle the Array/Solution2.py b/solution/1400-1499/1470.Shuffle the Array/Solution2.py new file mode 100644 index 0000000000000..ae53df289da3e --- /dev/null +++ b/solution/1400-1499/1470.Shuffle the Array/Solution2.py @@ -0,0 +1,4 @@ +class Solution: + def shuffle(self, nums: List[int], n: int) -> List[int]: + nums[::2], nums[1::2] = nums[:n], nums[n:] + return nums diff --git a/solution/1400-1499/1470.Shuffle the Array/Solution2.rs b/solution/1400-1499/1470.Shuffle the Array/Solution2.rs new file mode 100644 index 0000000000000..7a07624809757 --- /dev/null +++ b/solution/1400-1499/1470.Shuffle the Array/Solution2.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn shuffle(mut nums: Vec, n: i32) -> Vec { + let n = n as usize; + for i in 0..n * 2 { + let mut j = i; + while nums[i] > 0 { + j = if j < n { 2 * j } else { 2 * (j - n) + 1 }; + nums.swap(i, j); + nums[j] *= -1; + } + } + for i in 0..n * 2 { + nums[i] *= -1; + } + nums + } +} diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.cpp b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.cpp index c3ffc6b6269e6..a27c24247cb10 100644 --- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.cpp +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.cpp @@ -1,14 +1,16 @@ class Solution { public: vector finalPrices(vector& prices) { - stack stk; - vector ans = prices; - for (int i = 0; i < prices.size(); ++i) { - while (!stk.empty() && prices[stk.top()] >= prices[i]) { - ans[stk.top()] -= prices[i]; - stk.pop(); + int n = prices.size(); + vector ans(n); + for (int i = 0; i < n; ++i) { + ans[i] = prices[i]; + for (int j = i + 1; j < n; ++j) { + if (prices[j] <= prices[i]) { + ans[i] -= prices[j]; + break; + } } - stk.push(i); } return ans; } diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.go b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.go index 45a1268ec3f07..6d9911f2dd0e4 100644 --- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.go +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.go @@ -1,14 +1,14 @@ func finalPrices(prices []int) []int { - var stk []int n := len(prices) ans := make([]int, n) for i, v := range prices { ans[i] = v - for len(stk) > 0 && prices[stk[len(stk)-1]] >= v { - ans[stk[len(stk)-1]] -= v - stk = stk[:len(stk)-1] + for j := i + 1; j < n; j++ { + if prices[j] <= v { + ans[i] -= prices[j] + break + } } - stk = append(stk, i) } return ans } \ No newline at end of file diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.java b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.java index d921c3896b78b..1f9c12d04cea6 100644 --- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.java +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.java @@ -1,14 +1,15 @@ class Solution { public int[] finalPrices(int[] prices) { - Deque stk = new ArrayDeque<>(); int n = prices.length; int[] ans = new int[n]; for (int i = 0; i < n; ++i) { ans[i] = prices[i]; - while (!stk.isEmpty() && prices[stk.peek()] >= prices[i]) { - ans[stk.pop()] -= prices[i]; + for (int j = i + 1; j < n; ++j) { + if (prices[j] <= prices[i]) { + ans[i] -= prices[j]; + break; + } } - stk.push(i); } return ans; } diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.php b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.php index 02932132d6895..3347b98a08557 100644 --- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.php +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.php @@ -14,4 +14,4 @@ function finalPrices($prices) { } return $prices; } -} \ No newline at end of file +} diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.py b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.py index 5b205f2d148c3..7942f1115c027 100644 --- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.py +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.py @@ -1,9 +1,10 @@ class Solution: def finalPrices(self, prices: List[int]) -> List[int]: - stk = [] - ans = prices[:] + ans = [] for i, v in enumerate(prices): - while stk and prices[stk[-1]] >= v: - ans[stk.pop()] -= v - stk.append(i) + ans.append(v) + for j in range(i + 1, len(prices)): + if prices[j] <= v: + ans[-1] -= prices[j] + break return ans diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.ts b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.ts index b580bca0a5f7b..dfaead9442012 100644 --- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.ts +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.ts @@ -1,14 +1,14 @@ function finalPrices(prices: number[]): number[] { const n = prices.length; - const res = new Array(n); - const stack = []; - for (let i = n - 1; i >= 0; i--) { - const price = prices[i]; - while (stack.length !== 0 && stack[stack.length - 1] > price) { - stack.pop(); + const ans = new Array(n); + for (let i = 0; i < n; ++i) { + ans[i] = prices[i]; + for (let j = i + 1; j < n; ++j) { + if (prices[j] <= prices[i]) { + ans[i] -= prices[j]; + break; + } } - res[i] = price - (stack[stack.length - 1] ?? 0); - stack.push(price); } - return res; + return ans; } diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.cpp b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.cpp new file mode 100644 index 0000000000000..c3ffc6b6269e6 --- /dev/null +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + vector finalPrices(vector& prices) { + stack stk; + vector ans = prices; + for (int i = 0; i < prices.size(); ++i) { + while (!stk.empty() && prices[stk.top()] >= prices[i]) { + ans[stk.top()] -= prices[i]; + stk.pop(); + } + stk.push(i); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.go b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.go new file mode 100644 index 0000000000000..45a1268ec3f07 --- /dev/null +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.go @@ -0,0 +1,14 @@ +func finalPrices(prices []int) []int { + var stk []int + n := len(prices) + ans := make([]int, n) + for i, v := range prices { + ans[i] = v + for len(stk) > 0 && prices[stk[len(stk)-1]] >= v { + ans[stk[len(stk)-1]] -= v + stk = stk[:len(stk)-1] + } + stk = append(stk, i) + } + return ans +} \ No newline at end of file diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.java b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.java new file mode 100644 index 0000000000000..d921c3896b78b --- /dev/null +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public int[] finalPrices(int[] prices) { + Deque stk = new ArrayDeque<>(); + int n = prices.length; + int[] ans = new int[n]; + for (int i = 0; i < n; ++i) { + ans[i] = prices[i]; + while (!stk.isEmpty() && prices[stk.peek()] >= prices[i]) { + ans[stk.pop()] -= prices[i]; + } + stk.push(i); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.py b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.py new file mode 100644 index 0000000000000..5b205f2d148c3 --- /dev/null +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def finalPrices(self, prices: List[int]) -> List[int]: + stk = [] + ans = prices[:] + for i, v in enumerate(prices): + while stk and prices[stk[-1]] >= v: + ans[stk.pop()] -= v + stk.append(i) + return ans diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.ts b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.ts new file mode 100644 index 0000000000000..8f59cd019eae0 --- /dev/null +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.ts @@ -0,0 +1,13 @@ +function finalPrices(prices: number[]): number[] { + const n = prices.length; + const stk = []; + const ans = new Array(n); + for (let i = 0; i < n; ++i) { + ans[i] = prices[i]; + while (stk.length && prices[stk[stk.length - 1]] >= prices[i]) { + ans[stk.pop()] -= prices[i]; + } + stk.push(i); + } + return ans; +} diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.cpp b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.cpp new file mode 100644 index 0000000000000..31676616def76 --- /dev/null +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + vector finalPrices(vector& prices) { + stack stk; + int n = prices.size(); + vector ans(n); + for (int i = n - 1; i >= 0; --i) { + ans[i] = prices[i]; + while (!stk.empty() && prices[stk.top()] > prices[i]) { + stk.pop(); + } + if (!stk.empty()) { + ans[i] -= prices[stk.top()]; + } + stk.push(i); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.go b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.go new file mode 100644 index 0000000000000..0e2ed7f1c6429 --- /dev/null +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.go @@ -0,0 +1,16 @@ +func finalPrices(prices []int) []int { + stk := []int{} + n := len(prices) + ans := make([]int, n) + for i := n - 1; i >= 0; i-- { + ans[i] = prices[i] + for len(stk) > 0 && prices[stk[len(stk)-1]] > prices[i] { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + ans[i] -= prices[stk[len(stk)-1]] + } + stk = append(stk, i) + } + return ans +} \ No newline at end of file diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.java b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.java new file mode 100644 index 0000000000000..bbba5ea49ba52 --- /dev/null +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.java @@ -0,0 +1,18 @@ +class Solution { + public int[] finalPrices(int[] prices) { + Deque stk = new ArrayDeque<>(); + int n = prices.length; + int[] ans = new int[n]; + for (int i = n - 1; i >= 0; --i) { + ans[i] = prices[i]; + while (!stk.isEmpty() && prices[stk.peek()] > prices[i]) { + stk.pop(); + } + if (!stk.isEmpty()) { + ans[i] -= prices[stk.peek()]; + } + stk.push(i); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.py b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.py new file mode 100644 index 0000000000000..4de446e25eb2d --- /dev/null +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.py @@ -0,0 +1,11 @@ +class Solution: + def finalPrices(self, prices: List[int]) -> List[int]: + stk = [] + ans = prices[:] + for i in range(len(prices) - 1, -1, -1): + while stk and prices[stk[-1]] > prices[i]: + stk.pop() + if stk: + ans[i] -= prices[stk[-1]] + stk.append(i) + return ans diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.ts b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.ts new file mode 100644 index 0000000000000..a784c3155edea --- /dev/null +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.ts @@ -0,0 +1,14 @@ +function finalPrices(prices: number[]): number[] { + const n = prices.length; + const stack = []; + const res = new Array(n); + for (let i = n - 1; i >= 0; i--) { + const price = prices[i]; + while (stack.length !== 0 && stack[stack.length - 1] > price) { + stack.pop(); + } + res[i] = price - (stack[stack.length - 1] ?? 0); + stack.push(price); + } + return res; +} diff --git a/solution/1400-1499/1480.Running Sum of 1d Array/Solution.cs b/solution/1400-1499/1480.Running Sum of 1d Array/Solution.cs new file mode 100644 index 0000000000000..bee633b1ad7c4 --- /dev/null +++ b/solution/1400-1499/1480.Running Sum of 1d Array/Solution.cs @@ -0,0 +1,8 @@ +public class Solution { + public int[] RunningSum(int[] nums) { + for (int i = 1; i < nums.Length; ++i) { + nums[i] += nums[i - 1]; + } + return nums; + } +} diff --git a/solution/1400-1499/1480.Running Sum of 1d Array/Solution.php b/solution/1400-1499/1480.Running Sum of 1d Array/Solution.php index 87ebd8d6fef64..21a154217cb88 100644 --- a/solution/1400-1499/1480.Running Sum of 1d Array/Solution.php +++ b/solution/1400-1499/1480.Running Sum of 1d Array/Solution.php @@ -9,4 +9,4 @@ function runningSum($nums) { } return $nums; } -} \ No newline at end of file +} diff --git a/solution/1400-1499/1482.Minimum Number of Days to Make m Bouquets/Solution.java b/solution/1400-1499/1482.Minimum Number of Days to Make m Bouquets/Solution.java index d2f02c8b49384..ea962af7212e6 100644 --- a/solution/1400-1499/1482.Minimum Number of Days to Make m Bouquets/Solution.java +++ b/solution/1400-1499/1482.Minimum Number of Days to Make m Bouquets/Solution.java @@ -31,4 +31,4 @@ private boolean check(int[] bloomDay, int m, int k, int day) { } return cnt >= m; } -} +} \ No newline at end of file diff --git a/solution/1400-1499/1484.Group Sold Products By The Date/Solution.sql b/solution/1400-1499/1484.Group Sold Products By The Date/Solution.sql index 38bb614659f29..eb6d680c40df1 100644 --- a/solution/1400-1499/1484.Group Sold Products By The Date/Solution.sql +++ b/solution/1400-1499/1484.Group Sold Products By The Date/Solution.sql @@ -1,7 +1,7 @@ SELECT sell_date, COUNT(DISTINCT product) AS num_sold, - GROUP_CONCAT(DISTINCT product ORDER BY product) AS products + GROUP_CONCAT(DISTINCT product) AS products FROM Activities GROUP BY sell_date ORDER BY sell_date; diff --git a/solution/1400-1499/1486.XOR Operation in an Array/Solution2.py b/solution/1400-1499/1486.XOR Operation in an Array/Solution2.py new file mode 100644 index 0000000000000..297463abee32f --- /dev/null +++ b/solution/1400-1499/1486.XOR Operation in an Array/Solution2.py @@ -0,0 +1,3 @@ +class Solution: + def xorOperation(self, n: int, start: int) -> int: + return reduce(xor, ((start + 2 * i) for i in range(n))) diff --git a/solution/1400-1499/1488.Avoid Flood in The City/Solution.py b/solution/1400-1499/1488.Avoid Flood in The City/Solution.py index 6cd34b2e447e9..bc77246f2cf8d 100644 --- a/solution/1400-1499/1488.Avoid Flood in The City/Solution.py +++ b/solution/1400-1499/1488.Avoid Flood in The City/Solution.py @@ -1,22 +1,22 @@ -from sortedcontainers import SortedList - - -class Solution: - def avoidFlood(self, rains: List[int]) -> List[int]: - n = len(rains) - ans = [-1] * n - sunny = SortedList() - rainy = {} - for i, v in enumerate(rains): - if v: - if v in rainy: - idx = sunny.bisect_right(rainy[v]) - if idx == len(sunny): - return [] - ans[sunny[idx]] = v - sunny.discard(sunny[idx]) - rainy[v] = i - else: - sunny.add(i) - ans[i] = 1 - return ans +from sortedcontainers import SortedList + + +class Solution: + def avoidFlood(self, rains: List[int]) -> List[int]: + n = len(rains) + ans = [-1] * n + sunny = SortedList() + rainy = {} + for i, v in enumerate(rains): + if v: + if v in rainy: + idx = sunny.bisect_right(rainy[v]) + if idx == len(sunny): + return [] + ans[sunny[idx]] = v + sunny.discard(sunny[idx]) + rainy[v] = i + else: + sunny.add(i) + ans[i] = 1 + return ans diff --git a/solution/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/Solution.c b/solution/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/Solution.c index dcda365bd51d5..9fe88f9a2775a 100644 --- a/solution/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/Solution.c +++ b/solution/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/Solution.c @@ -11,4 +11,4 @@ double average(int* salary, int salarySize) { mi = min(mi, salary[i]); } return (sum - mi - ma) * 1.0 / (salarySize - 2); -} +} \ No newline at end of file diff --git a/solution/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/Solution.php b/solution/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/Solution.php index 535d3cb31b3a4..03814563c48b5 100644 --- a/solution/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/Solution.php +++ b/solution/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/Solution.php @@ -13,4 +13,4 @@ function average($salary) { } return ($sum - $max - $min) / (count($salary) - 2); } -} \ No newline at end of file +} diff --git a/solution/1400-1499/1492.The kth Factor of n/Solution.go b/solution/1400-1499/1492.The kth Factor of n/Solution.go index bed12591e0345..f1cb5a4238a88 100644 --- a/solution/1400-1499/1492.The kth Factor of n/Solution.go +++ b/solution/1400-1499/1492.The kth Factor of n/Solution.go @@ -1,6 +1,5 @@ func kthFactor(n int, k int) int { - i := 1 - for ; i < n/i; i++ { + for i := 1; i <= n; i++ { if n%i == 0 { k-- if k == 0 { @@ -8,16 +7,5 @@ func kthFactor(n int, k int) int { } } } - if i*i != n { - i-- - } - for ; i > 0; i-- { - if n%(n/i) == 0 { - k-- - if k == 0 { - return n / i - } - } - } return -1 } \ No newline at end of file diff --git a/solution/1400-1499/1492.The kth Factor of n/Solution.java b/solution/1400-1499/1492.The kth Factor of n/Solution.java index 2d7fd5a0cb64c..a02e5406c39ee 100644 --- a/solution/1400-1499/1492.The kth Factor of n/Solution.java +++ b/solution/1400-1499/1492.The kth Factor of n/Solution.java @@ -1,19 +1,10 @@ class Solution { public int kthFactor(int n, int k) { - int i = 1; - for (; i < n / i; ++i) { + for (int i = 1; i <= n; ++i) { if (n % i == 0 && (--k == 0)) { return i; } } - if (i * i != n) { - --i; - } - for (; i > 0; --i) { - if (n % (n / i) == 0 && (--k == 0)) { - return n / i; - } - } return -1; } } \ No newline at end of file diff --git a/solution/1400-1499/1492.The kth Factor of n/Solution.py b/solution/1400-1499/1492.The kth Factor of n/Solution.py index f8666b201495f..09acba357d10c 100644 --- a/solution/1400-1499/1492.The kth Factor of n/Solution.py +++ b/solution/1400-1499/1492.The kth Factor of n/Solution.py @@ -1,18 +1,8 @@ class Solution: def kthFactor(self, n: int, k: int) -> int: - i = 1 - while i * i < n: + for i in range(1, n + 1): if n % i == 0: k -= 1 if k == 0: return i - i += 1 - if i * i != n: - i -= 1 - while i: - if (n % (n // i)) == 0: - k -= 1 - if k == 0: - return n // i - i -= 1 return -1 diff --git a/solution/1400-1499/1492.The kth Factor of n/Solution2.go b/solution/1400-1499/1492.The kth Factor of n/Solution2.go new file mode 100644 index 0000000000000..bed12591e0345 --- /dev/null +++ b/solution/1400-1499/1492.The kth Factor of n/Solution2.go @@ -0,0 +1,23 @@ +func kthFactor(n int, k int) int { + i := 1 + for ; i < n/i; i++ { + if n%i == 0 { + k-- + if k == 0 { + return i + } + } + } + if i*i != n { + i-- + } + for ; i > 0; i-- { + if n%(n/i) == 0 { + k-- + if k == 0 { + return n / i + } + } + } + return -1 +} \ No newline at end of file diff --git a/solution/1400-1499/1492.The kth Factor of n/Solution2.java b/solution/1400-1499/1492.The kth Factor of n/Solution2.java new file mode 100644 index 0000000000000..2d7fd5a0cb64c --- /dev/null +++ b/solution/1400-1499/1492.The kth Factor of n/Solution2.java @@ -0,0 +1,19 @@ +class Solution { + public int kthFactor(int n, int k) { + int i = 1; + for (; i < n / i; ++i) { + if (n % i == 0 && (--k == 0)) { + return i; + } + } + if (i * i != n) { + --i; + } + for (; i > 0; --i) { + if (n % (n / i) == 0 && (--k == 0)) { + return n / i; + } + } + return -1; + } +} \ No newline at end of file diff --git a/solution/1400-1499/1492.The kth Factor of n/Solution2.py b/solution/1400-1499/1492.The kth Factor of n/Solution2.py new file mode 100644 index 0000000000000..f8666b201495f --- /dev/null +++ b/solution/1400-1499/1492.The kth Factor of n/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def kthFactor(self, n: int, k: int) -> int: + i = 1 + while i * i < n: + if n % i == 0: + k -= 1 + if k == 0: + return i + i += 1 + if i * i != n: + i -= 1 + while i: + if (n % (n // i)) == 0: + k -= 1 + if k == 0: + return n // i + i -= 1 + return -1 diff --git a/solution/1400-1499/1494.Parallel Courses II/Solution.cpp b/solution/1400-1499/1494.Parallel Courses II/Solution.cpp index 045b91fd13280..6a8e0f37d9f68 100644 --- a/solution/1400-1499/1494.Parallel Courses II/Solution.cpp +++ b/solution/1400-1499/1494.Parallel Courses II/Solution.cpp @@ -1,42 +1,42 @@ -class Solution { -public: - int minNumberOfSemesters(int n, vector>& relations, int k) { - vector d(n + 1); - for (auto& e : relations) { - d[e[1]] |= 1 << e[0]; - } - queue> q; - q.push({0, 0}); - unordered_set vis{{0}}; - while (!q.empty()) { - auto [cur, t] = q.front(); - q.pop(); - if (cur == (1 << (n + 1)) - 2) { - return t; - } - int nxt = 0; - for (int i = 1; i <= n; ++i) { - if ((cur & d[i]) == d[i]) { - nxt |= 1 << i; - } - } - nxt ^= cur; - if (__builtin_popcount(nxt) <= k) { - if (!vis.count(nxt | cur)) { - vis.insert(nxt | cur); - q.push({nxt | cur, t + 1}); - } - } else { - int x = nxt; - while (nxt) { - if (__builtin_popcount(nxt) == k && !vis.count(nxt | cur)) { - vis.insert(nxt | cur); - q.push({nxt | cur, t + 1}); - } - nxt = (nxt - 1) & x; - } - } - } - return 0; - } +class Solution { +public: + int minNumberOfSemesters(int n, vector>& relations, int k) { + vector d(n + 1); + for (auto& e : relations) { + d[e[1]] |= 1 << e[0]; + } + queue> q; + q.push({0, 0}); + unordered_set vis{{0}}; + while (!q.empty()) { + auto [cur, t] = q.front(); + q.pop(); + if (cur == (1 << (n + 1)) - 2) { + return t; + } + int nxt = 0; + for (int i = 1; i <= n; ++i) { + if ((cur & d[i]) == d[i]) { + nxt |= 1 << i; + } + } + nxt ^= cur; + if (__builtin_popcount(nxt) <= k) { + if (!vis.count(nxt | cur)) { + vis.insert(nxt | cur); + q.push({nxt | cur, t + 1}); + } + } else { + int x = nxt; + while (nxt) { + if (__builtin_popcount(nxt) == k && !vis.count(nxt | cur)) { + vis.insert(nxt | cur); + q.push({nxt | cur, t + 1}); + } + nxt = (nxt - 1) & x; + } + } + } + return 0; + } }; \ No newline at end of file diff --git a/solution/1400-1499/1499.Max Value of Equation/Solution.cpp b/solution/1400-1499/1499.Max Value of Equation/Solution.cpp index 8c51b81e68951..025283866ea2c 100644 --- a/solution/1400-1499/1499.Max Value of Equation/Solution.cpp +++ b/solution/1400-1499/1499.Max Value of Equation/Solution.cpp @@ -1,21 +1,18 @@ -class Solution { -public: - int findMaxValueOfEquation(vector>& points, int k) { - int ans = -(1 << 30); - deque> q; - for (auto& p : points) { - int x = p[0], y = p[1]; - while (!q.empty() && x - q.front().first > k) { - q.pop_front(); - } - if (!q.empty()) { - ans = max(ans, x + y + q.front().second - q.front().first); - } - while (!q.empty() && y - x >= q.back().second - q.back().first) { - q.pop_back(); - } - q.emplace_back(x, y); - } - return ans; - } +class Solution { +public: + int findMaxValueOfEquation(vector>& points, int k) { + int ans = -(1 << 30); + priority_queue> pq; + for (auto& p : points) { + int x = p[0], y = p[1]; + while (pq.size() && x - pq.top().second > k) { + pq.pop(); + } + if (pq.size()) { + ans = max(ans, x + y + pq.top().first); + } + pq.emplace(y - x, x); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1400-1499/1499.Max Value of Equation/Solution.go b/solution/1400-1499/1499.Max Value of Equation/Solution.go index 13318001dc699..8b6e9f4cdcad6 100644 --- a/solution/1400-1499/1499.Max Value of Equation/Solution.go +++ b/solution/1400-1499/1499.Max Value of Equation/Solution.go @@ -1,18 +1,28 @@ func findMaxValueOfEquation(points [][]int, k int) int { ans := -(1 << 30) - q := [][2]int{} + hp := hp{} for _, p := range points { x, y := p[0], p[1] - for len(q) > 0 && x-q[0][0] > k { - q = q[1:] + for hp.Len() > 0 && x-hp[0].x > k { + heap.Pop(&hp) } - if len(q) > 0 { - ans = max(ans, x+y+q[0][1]-q[0][0]) + if hp.Len() > 0 { + ans = max(ans, x+y+hp[0].v) } - for len(q) > 0 && y-x >= q[len(q)-1][1]-q[len(q)-1][0] { - q = q[:len(q)-1] - } - q = append(q, [2]int{x, y}) + heap.Push(&hp, pair{y - x, x}) } return ans -} \ No newline at end of file +} + +type pair struct{ v, x int } + +type hp []pair + +func (h hp) Len() int { return len(h) } +func (h hp) Less(i, j int) bool { + a, b := h[i], h[j] + return a.v > b.v +} +func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } +func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } \ No newline at end of file diff --git a/solution/1400-1499/1499.Max Value of Equation/Solution.java b/solution/1400-1499/1499.Max Value of Equation/Solution.java index 38297e3c2dc86..5739c2e5c7107 100644 --- a/solution/1400-1499/1499.Max Value of Equation/Solution.java +++ b/solution/1400-1499/1499.Max Value of Equation/Solution.java @@ -1,20 +1,17 @@ -class Solution { - public int findMaxValueOfEquation(int[][] points, int k) { - int ans = -(1 << 30); - Deque q = new ArrayDeque<>(); - for (var p : points) { - int x = p[0], y = p[1]; - while (!q.isEmpty() && x - q.peekFirst()[0] > k) { - q.pollFirst(); - } - if (!q.isEmpty()) { - ans = Math.max(ans, x + y + q.peekFirst()[1] - q.peekFirst()[0]); - } - while (!q.isEmpty() && y - x >= q.peekLast()[1] - q.peekLast()[0]) { - q.pollLast(); - } - q.offerLast(p); - } - return ans; - } +class Solution { + public int findMaxValueOfEquation(int[][] points, int k) { + int ans = -(1 << 30); + PriorityQueue pq = new PriorityQueue<>((a, b) -> b[0] - a[0]); + for (var p : points) { + int x = p[0], y = p[1]; + while (!pq.isEmpty() && x - pq.peek()[1] > k) { + pq.poll(); + } + if (!pq.isEmpty()) { + ans = Math.max(ans, x + y + pq.peek()[0]); + } + pq.offer(new int[] {y - x, x}); + } + return ans; + } } \ No newline at end of file diff --git a/solution/1400-1499/1499.Max Value of Equation/Solution.py b/solution/1400-1499/1499.Max Value of Equation/Solution.py index a353053c9529f..cc5acfb1b69e6 100644 --- a/solution/1400-1499/1499.Max Value of Equation/Solution.py +++ b/solution/1400-1499/1499.Max Value of Equation/Solution.py @@ -1,13 +1,11 @@ -class Solution: - def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int: - ans = -inf - q = deque() - for x, y in points: - while q and x - q[0][0] > k: - q.popleft() - if q: - ans = max(ans, x + y + q[0][1] - q[0][0]) - while q and y - x >= q[-1][1] - q[-1][0]: - q.pop() - q.append((x, y)) - return ans +class Solution: + def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int: + ans = -inf + pq = [] + for x, y in points: + while pq and x - pq[0][1] > k: + heappop(pq) + if pq: + ans = max(ans, x + y - pq[0][0]) + heappush(pq, (x - y, x)) + return ans diff --git a/solution/1400-1499/1499.Max Value of Equation/Solution.ts b/solution/1400-1499/1499.Max Value of Equation/Solution.ts index 854fd92b5bbb8..d5108d5a8a4db 100644 --- a/solution/1400-1499/1499.Max Value of Equation/Solution.ts +++ b/solution/1400-1499/1499.Max Value of Equation/Solution.ts @@ -1,17 +1,80 @@ function findMaxValueOfEquation(points: number[][], k: number): number { let ans = -(1 << 30); - const q: number[][] = []; + const pq = new Heap<[number, number]>((a, b) => b[0] - a[0]); for (const [x, y] of points) { - while (q.length > 0 && x - q[0][0] > k) { - q.shift(); + while (pq.size() && x - pq.top()[1] > k) { + pq.pop(); } - if (q.length > 0) { - ans = Math.max(ans, x + y + q[0][1] - q[0][0]); + if (pq.size()) { + ans = Math.max(ans, x + y + pq.top()[0]); } - while (q.length > 0 && y - x > q[q.length - 1][1] - q[q.length - 1][0]) { - q.pop(); - } - q.push([x, y]); + pq.push([y - x, x]); } return ans; } + +type Compare = (lhs: T, rhs: T) => number; + +class Heap { + data: Array; + lt: (i: number, j: number) => boolean; + constructor(); + constructor(data: T[]); + constructor(compare: Compare); + constructor(data: T[], compare: Compare); + constructor(data: T[] | Compare, compare?: (lhs: T, rhs: T) => number); + constructor( + data: T[] | Compare = [], + compare: Compare = (lhs: T, rhs: T) => (lhs < rhs ? -1 : lhs > rhs ? 1 : 0), + ) { + if (typeof data === 'function') { + compare = data; + data = []; + } + this.data = [null, ...data]; + this.lt = (i, j) => compare(this.data[i]!, this.data[j]!) < 0; + for (let i = this.size(); i > 0; i--) this.heapify(i); + } + + size(): number { + return this.data.length - 1; + } + + push(v: T): void { + this.data.push(v); + let i = this.size(); + while (i >> 1 !== 0 && this.lt(i, i >> 1)) this.swap(i, (i >>= 1)); + } + + pop(): T { + this.swap(1, this.size()); + const top = this.data.pop(); + this.heapify(1); + return top!; + } + + top(): T { + return this.data[1]!; + } + heapify(i: number): void { + while (true) { + let min = i; + const [l, r, n] = [i * 2, i * 2 + 1, this.data.length]; + if (l < n && this.lt(l, min)) min = l; + if (r < n && this.lt(r, min)) min = r; + if (min !== i) { + this.swap(i, min); + i = min; + } else break; + } + } + + clear(): void { + this.data = [null]; + } + + private swap(i: number, j: number): void { + const d = this.data; + [d[i], d[j]] = [d[j], d[i]]; + } +} diff --git a/solution/1400-1499/1499.Max Value of Equation/Solution2.cpp b/solution/1400-1499/1499.Max Value of Equation/Solution2.cpp new file mode 100644 index 0000000000000..1339c8ce9e003 --- /dev/null +++ b/solution/1400-1499/1499.Max Value of Equation/Solution2.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int findMaxValueOfEquation(vector>& points, int k) { + int ans = -(1 << 30); + deque> q; + for (auto& p : points) { + int x = p[0], y = p[1]; + while (!q.empty() && x - q.front().first > k) { + q.pop_front(); + } + if (!q.empty()) { + ans = max(ans, x + y + q.front().second - q.front().first); + } + while (!q.empty() && y - x >= q.back().second - q.back().first) { + q.pop_back(); + } + q.emplace_back(x, y); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1400-1499/1499.Max Value of Equation/Solution2.go b/solution/1400-1499/1499.Max Value of Equation/Solution2.go new file mode 100644 index 0000000000000..13318001dc699 --- /dev/null +++ b/solution/1400-1499/1499.Max Value of Equation/Solution2.go @@ -0,0 +1,18 @@ +func findMaxValueOfEquation(points [][]int, k int) int { + ans := -(1 << 30) + q := [][2]int{} + for _, p := range points { + x, y := p[0], p[1] + for len(q) > 0 && x-q[0][0] > k { + q = q[1:] + } + if len(q) > 0 { + ans = max(ans, x+y+q[0][1]-q[0][0]) + } + for len(q) > 0 && y-x >= q[len(q)-1][1]-q[len(q)-1][0] { + q = q[:len(q)-1] + } + q = append(q, [2]int{x, y}) + } + return ans +} \ No newline at end of file diff --git a/solution/1400-1499/1499.Max Value of Equation/Solution2.java b/solution/1400-1499/1499.Max Value of Equation/Solution2.java new file mode 100644 index 0000000000000..77101afa2fe1d --- /dev/null +++ b/solution/1400-1499/1499.Max Value of Equation/Solution2.java @@ -0,0 +1,20 @@ +class Solution { + public int findMaxValueOfEquation(int[][] points, int k) { + int ans = -(1 << 30); + Deque q = new ArrayDeque<>(); + for (var p : points) { + int x = p[0], y = p[1]; + while (!q.isEmpty() && x - q.peekFirst()[0] > k) { + q.pollFirst(); + } + if (!q.isEmpty()) { + ans = Math.max(ans, x + y + q.peekFirst()[1] - q.peekFirst()[0]); + } + while (!q.isEmpty() && y - x >= q.peekLast()[1] - q.peekLast()[0]) { + q.pollLast(); + } + q.offerLast(p); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1400-1499/1499.Max Value of Equation/Solution2.py b/solution/1400-1499/1499.Max Value of Equation/Solution2.py new file mode 100644 index 0000000000000..03c6b4b565c9b --- /dev/null +++ b/solution/1400-1499/1499.Max Value of Equation/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int: + ans = -inf + q = deque() + for x, y in points: + while q and x - q[0][0] > k: + q.popleft() + if q: + ans = max(ans, x + y + q[0][1] - q[0][0]) + while q and y - x >= q[-1][1] - q[-1][0]: + q.pop() + q.append((x, y)) + return ans diff --git a/solution/1400-1499/1499.Max Value of Equation/Solution2.ts b/solution/1400-1499/1499.Max Value of Equation/Solution2.ts new file mode 100644 index 0000000000000..854fd92b5bbb8 --- /dev/null +++ b/solution/1400-1499/1499.Max Value of Equation/Solution2.ts @@ -0,0 +1,17 @@ +function findMaxValueOfEquation(points: number[][], k: number): number { + let ans = -(1 << 30); + const q: number[][] = []; + for (const [x, y] of points) { + while (q.length > 0 && x - q[0][0] > k) { + q.shift(); + } + if (q.length > 0) { + ans = Math.max(ans, x + y + q[0][1] - q[0][0]); + } + while (q.length > 0 && y - x > q[q.length - 1][1] - q[q.length - 1][0]) { + q.pop(); + } + q.push([x, y]); + } + return ans; +} diff --git a/solution/1500-1599/1501.Countries You Can Safely Invest In/Solution.sql b/solution/1500-1599/1501.Countries You Can Safely Invest In/Solution.sql index 32d57e1223b29..ea1810b63d204 100644 --- a/solution/1500-1599/1501.Countries You Can Safely Invest In/Solution.sql +++ b/solution/1500-1599/1501.Countries You Can Safely Invest In/Solution.sql @@ -1,13 +1,12 @@ # Write your MySQL query statement below -WITH - T AS ( +SELECT country +FROM + ( SELECT c.name AS country, AVG(duration) AS duration FROM Person JOIN Calls ON id IN (caller_id, callee_id) JOIN Country AS c ON LEFT(phone_number, 3) = country_code GROUP BY 1 - ) -SELECT country -FROM T + ) AS t WHERE duration > (SELECT AVG(duration) FROM Calls); diff --git a/solution/1500-1599/1501.Countries You Can Safely Invest In/Solution2.sql b/solution/1500-1599/1501.Countries You Can Safely Invest In/Solution2.sql new file mode 100644 index 0000000000000..32d57e1223b29 --- /dev/null +++ b/solution/1500-1599/1501.Countries You Can Safely Invest In/Solution2.sql @@ -0,0 +1,13 @@ +# Write your MySQL query statement below +WITH + T AS ( + SELECT c.name AS country, AVG(duration) AS duration + FROM + Person + JOIN Calls ON id IN (caller_id, callee_id) + JOIN Country AS c ON LEFT(phone_number, 3) = country_code + GROUP BY 1 + ) +SELECT country +FROM T +WHERE duration > (SELECT AVG(duration) FROM Calls); diff --git a/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution.c b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution.c index c10393b20d0b5..393dbf94bdc73 100644 --- a/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution.c +++ b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution.c @@ -10,4 +10,4 @@ bool canMakeArithmeticProgression(int* arr, int arrSize) { } } return 1; -} +} \ No newline at end of file diff --git a/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution2.cpp b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution2.cpp new file mode 100644 index 0000000000000..d6c691b5df4be --- /dev/null +++ b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution2.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + bool canMakeArithmeticProgression(vector& arr) { + auto [a, b] = minmax_element(arr.begin(), arr.end()); + int n = arr.size(); + if ((*b - *a) % (n - 1) != 0) { + return false; + } + int d = (*b - *a) / (n - 1); + unordered_set s(arr.begin(), arr.end()); + for (int i = 0; i < n; ++i) { + if (!s.count(*a + d * i)) { + return false; + } + } + return true; + } +}; \ No newline at end of file diff --git a/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution2.go b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution2.go new file mode 100644 index 0000000000000..d82d9d4b8ddb8 --- /dev/null +++ b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution2.go @@ -0,0 +1,18 @@ +func canMakeArithmeticProgression(arr []int) bool { + a, b := slices.Min(arr), slices.Max(arr) + n := len(arr) + if (b-a)%(n-1) != 0 { + return false + } + d := (b - a) / (n - 1) + s := map[int]bool{} + for _, x := range arr { + s[x] = true + } + for i := 0; i < n; i++ { + if !s[a+i*d] { + return false + } + } + return true +} \ No newline at end of file diff --git a/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution2.java b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution2.java new file mode 100644 index 0000000000000..fa1f2b3b236cc --- /dev/null +++ b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution2.java @@ -0,0 +1,22 @@ +class Solution { + public boolean canMakeArithmeticProgression(int[] arr) { + int n = arr.length; + int a = arr[0], b = arr[0]; + Set s = new HashSet<>(); + for (int x : arr) { + a = Math.min(a, x); + b = Math.max(b, x); + s.add(x); + } + if ((b - a) % (n - 1) != 0) { + return false; + } + int d = (b - a) / (n - 1); + for (int i = 0; i < n; ++i) { + if (!s.contains(a + d * i)) { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution2.py b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution2.py new file mode 100644 index 0000000000000..8b67053bf061e --- /dev/null +++ b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def canMakeArithmeticProgression(self, arr: List[int]) -> bool: + a = min(arr) + b = max(arr) + n = len(arr) + if (b - a) % (n - 1): + return False + d = (b - a) // (n - 1) + s = set(arr) + return all(a + d * i in s for i in range(n)) diff --git a/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution2.rs b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution2.rs new file mode 100644 index 0000000000000..6704507d29594 --- /dev/null +++ b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution2.rs @@ -0,0 +1,29 @@ +use std::collections::HashMap; +impl Solution { + pub fn can_make_arithmetic_progression(arr: Vec) -> bool { + let n = arr.len() as i32; + let mut min = i32::MAX; + let mut max = i32::MIN; + let mut map = HashMap::new(); + for &num in arr.iter() { + *map.entry(num).or_insert(0) += 1; + min = min.min(num); + max = max.max(num); + } + if min == max { + return true; + } + if (max - min) % (n - 1) != 0 { + return false; + } + let diff = (max - min) / (n - 1); + let mut k = min; + while k <= max { + if *map.get(&k).unwrap_or(&0) != 1 { + return false; + } + k += diff; + } + true + } +} diff --git a/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution2.ts b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution2.ts new file mode 100644 index 0000000000000..4770f4be6460f --- /dev/null +++ b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution2.ts @@ -0,0 +1,24 @@ +function canMakeArithmeticProgression(arr: number[]): boolean { + const n = arr.length; + const map = new Map(); + let min = Infinity; + let max = -Infinity; + for (const num of arr) { + map.set(num, (map.get(num) ?? 0) + 1); + min = Math.min(min, num); + max = Math.max(max, num); + } + if (max === min) { + return true; + } + if ((max - min) % (arr.length - 1)) { + return false; + } + const diff = (max - min) / (arr.length - 1); + for (let i = min; i <= max; i += diff) { + if (map.get(i) !== 1) { + return false; + } + } + return true; +} diff --git a/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/Solution.cpp b/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/Solution.cpp index 1cd43e674e756..1dd77cd2eab3e 100644 --- a/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/Solution.cpp +++ b/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/Solution.cpp @@ -1,57 +1,57 @@ -class BinaryIndexedTree { -public: - int n; - vector c; - - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); - } - } - - int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } - - int lowbit(int x) { - return x & -x; - } -}; - -class Solution { -public: - string minInteger(string num, int k) { - vector> pos(10); - int n = num.size(); - for (int i = 0; i < n; ++i) pos[num[i] - '0'].push(i + 1); - BinaryIndexedTree* tree = new BinaryIndexedTree(n); - string ans = ""; - for (int i = 1; i <= n; ++i) { - for (int v = 0; v < 10; ++v) { - auto& q = pos[v]; - if (!q.empty()) { - int j = q.front(); - int dist = tree->query(n) - tree->query(j) + j - i; - if (dist <= k) { - k -= dist; - q.pop(); - ans += (v + '0'); - tree->update(j, 1); - break; - } - } - } - } - return ans; - } +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + int lowbit(int x) { + return x & -x; + } +}; + +class Solution { +public: + string minInteger(string num, int k) { + vector> pos(10); + int n = num.size(); + for (int i = 0; i < n; ++i) pos[num[i] - '0'].push(i + 1); + BinaryIndexedTree* tree = new BinaryIndexedTree(n); + string ans = ""; + for (int i = 1; i <= n; ++i) { + for (int v = 0; v < 10; ++v) { + auto& q = pos[v]; + if (!q.empty()) { + int j = q.front(); + int dist = tree->query(n) - tree->query(j) + j - i; + if (dist <= k) { + k -= dist; + q.pop(); + ans += (v + '0'); + tree->update(j, 1); + break; + } + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/Solution.java b/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/Solution.java index c237d21971630..668383c8b255d 100644 --- a/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/Solution.java +++ b/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/Solution.java @@ -1,61 +1,61 @@ -class Solution { - public String minInteger(String num, int k) { - Queue[] pos = new Queue[10]; - for (int i = 0; i < 10; ++i) { - pos[i] = new ArrayDeque<>(); - } - int n = num.length(); - for (int i = 0; i < n; ++i) { - pos[num.charAt(i) - '0'].offer(i + 1); - } - StringBuilder ans = new StringBuilder(); - BinaryIndexedTree tree = new BinaryIndexedTree(n); - for (int i = 1; i <= n; ++i) { - for (int v = 0; v < 10; ++v) { - if (!pos[v].isEmpty()) { - Queue q = pos[v]; - int j = q.peek(); - int dist = tree.query(n) - tree.query(j) + j - i; - if (dist <= k) { - k -= dist; - q.poll(); - ans.append(v); - tree.update(j, 1); - break; - } - } - } - } - return ans.toString(); - } -} - -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); - } - } - - public int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } - - public static int lowbit(int x) { - return x & -x; - } +class Solution { + public String minInteger(String num, int k) { + Queue[] pos = new Queue[10]; + for (int i = 0; i < 10; ++i) { + pos[i] = new ArrayDeque<>(); + } + int n = num.length(); + for (int i = 0; i < n; ++i) { + pos[num.charAt(i) - '0'].offer(i + 1); + } + StringBuilder ans = new StringBuilder(); + BinaryIndexedTree tree = new BinaryIndexedTree(n); + for (int i = 1; i <= n; ++i) { + for (int v = 0; v < 10; ++v) { + if (!pos[v].isEmpty()) { + Queue q = pos[v]; + int j = q.peek(); + int dist = tree.query(n) - tree.query(j) + j - i; + if (dist <= k) { + k -= dist; + q.poll(); + ans.append(v); + tree.update(j, 1); + break; + } + } + } + } + return ans.toString(); + } +} + +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + public static int lowbit(int x) { + return x & -x; + } } \ No newline at end of file diff --git a/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/Solution.py b/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/Solution.py index 6ac5d815f3867..9a93fb6311016 100644 --- a/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/Solution.py +++ b/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/Solution.py @@ -1,43 +1,43 @@ -class BinaryIndexedTree: - def __init__(self, n): - self.n = n - self.c = [0] * (n + 1) - - @staticmethod - def lowbit(x): - return x & -x - - def update(self, x, delta): - while x <= self.n: - self.c[x] += delta - x += BinaryIndexedTree.lowbit(x) - - def query(self, x): - s = 0 - while x: - s += self.c[x] - x -= BinaryIndexedTree.lowbit(x) - return s - - -class Solution: - def minInteger(self, num: str, k: int) -> str: - pos = defaultdict(deque) - for i, v in enumerate(num, 1): - pos[int(v)].append(i) - ans = [] - n = len(num) - tree = BinaryIndexedTree(n) - for i in range(1, n + 1): - for v in range(10): - q = pos[v] - if q: - j = q[0] - dist = tree.query(n) - tree.query(j) + j - i - if dist <= k: - k -= dist - q.popleft() - ans.append(str(v)) - tree.update(j, 1) - break - return ''.join(ans) +class BinaryIndexedTree: + def __init__(self, n): + self.n = n + self.c = [0] * (n + 1) + + @staticmethod + def lowbit(x): + return x & -x + + def update(self, x, delta): + while x <= self.n: + self.c[x] += delta + x += BinaryIndexedTree.lowbit(x) + + def query(self, x): + s = 0 + while x: + s += self.c[x] + x -= BinaryIndexedTree.lowbit(x) + return s + + +class Solution: + def minInteger(self, num: str, k: int) -> str: + pos = defaultdict(deque) + for i, v in enumerate(num, 1): + pos[int(v)].append(i) + ans = [] + n = len(num) + tree = BinaryIndexedTree(n) + for i in range(1, n + 1): + for v in range(10): + q = pos[v] + if q: + j = q[0] + dist = tree.query(n) - tree.query(j) + j - i + if dist <= k: + k -= dist + q.popleft() + ans.append(str(v)) + tree.update(j, 1) + break + return ''.join(ans) diff --git a/solution/1500-1599/1507.Reformat Date/Solution.php b/solution/1500-1599/1507.Reformat Date/Solution.php index 6041e22d3d687..882cfcbce69f1 100644 --- a/solution/1500-1599/1507.Reformat Date/Solution.php +++ b/solution/1500-1599/1507.Reformat Date/Solution.php @@ -27,4 +27,4 @@ function reformatDate($date) { } return $year . '-' . $month . '-' . $day; } -} \ No newline at end of file +} diff --git a/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/Solution.cpp b/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/Solution.cpp index f4003ec9b8900..8f29be25250b5 100644 --- a/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/Solution.cpp +++ b/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - int rangeSum(vector& nums, int n, int left, int right) { - int arr[n * (n + 1) / 2]; - for (int i = 0, k = 0; i < n; ++i) { - int s = 0; - for (int j = i; j < n; ++j) { - s += nums[j]; - arr[k++] = s; - } - } - sort(arr, arr + n * (n + 1) / 2); - int ans = 0; - const int mod = 1e9 + 7; - for (int i = left - 1; i < right; ++i) { - ans = (ans + arr[i]) % mod; - } - return ans; - } +class Solution { +public: + int rangeSum(vector& nums, int n, int left, int right) { + int arr[n * (n + 1) / 2]; + for (int i = 0, k = 0; i < n; ++i) { + int s = 0; + for (int j = i; j < n; ++j) { + s += nums[j]; + arr[k++] = s; + } + } + sort(arr, arr + n * (n + 1) / 2); + int ans = 0; + const int mod = 1e9 + 7; + for (int i = left - 1; i < right; ++i) { + ans = (ans + arr[i]) % mod; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/Solution.java b/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/Solution.java index a3fb13196a4fd..602ae79da6ac0 100644 --- a/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/Solution.java +++ b/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/Solution.java @@ -1,19 +1,19 @@ -class Solution { - public int rangeSum(int[] nums, int n, int left, int right) { - int[] arr = new int[n * (n + 1) / 2]; - for (int i = 0, k = 0; i < n; ++i) { - int s = 0; - for (int j = i; j < n; ++j) { - s += nums[j]; - arr[k++] = s; - } - } - Arrays.sort(arr); - int ans = 0; - final int mod = (int) 1e9 + 7; - for (int i = left - 1; i < right; ++i) { - ans = (ans + arr[i]) % mod; - } - return ans; - } +class Solution { + public int rangeSum(int[] nums, int n, int left, int right) { + int[] arr = new int[n * (n + 1) / 2]; + for (int i = 0, k = 0; i < n; ++i) { + int s = 0; + for (int j = i; j < n; ++j) { + s += nums[j]; + arr[k++] = s; + } + } + Arrays.sort(arr); + int ans = 0; + final int mod = (int) 1e9 + 7; + for (int i = left - 1; i < right; ++i) { + ans = (ans + arr[i]) % mod; + } + return ans; + } } \ No newline at end of file diff --git a/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/Solution.py b/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/Solution.py index c95457d3091a3..04b5b64578f18 100644 --- a/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/Solution.py +++ b/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int: - arr = [] - for i in range(n): - s = 0 - for j in range(i, n): - s += nums[j] - arr.append(s) - arr.sort() - mod = 10**9 + 7 - return sum(arr[left - 1 : right]) % mod +class Solution: + def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int: + arr = [] + for i in range(n): + s = 0 + for j in range(i, n): + s += nums[j] + arr.append(s) + arr.sort() + mod = 10**9 + 7 + return sum(arr[left - 1 : right]) % mod diff --git a/solution/1500-1599/1510.Stone Game IV/Solution.ts b/solution/1500-1599/1510.Stone Game IV/Solution.ts index 70cdee92f1bcd..fdb8e4f7a6114 100644 --- a/solution/1500-1599/1510.Stone Game IV/Solution.ts +++ b/solution/1500-1599/1510.Stone Game IV/Solution.ts @@ -1,12 +1,20 @@ function winnerSquareGame(n: number): boolean { - const f: boolean[] = new Array(n + 1).fill(false); - for (let i = 1; i <= n; ++i) { + const f: number[] = new Array(n + 1).fill(0); + const dfs = (i: number): boolean => { + if (i <= 0) { + return false; + } + if (f[i] !== 0) { + return f[i] === 1; + } for (let j = 1; j * j <= i; ++j) { - if (!f[i - j * j]) { - f[i] = true; - break; + if (!dfs(i - j * j)) { + f[i] = 1; + return true; } } - } - return f[n]; + f[i] = -1; + return false; + }; + return dfs(n); } diff --git a/solution/1500-1599/1510.Stone Game IV/Solution2.cpp b/solution/1500-1599/1510.Stone Game IV/Solution2.cpp new file mode 100644 index 0000000000000..5751f3e28f120 --- /dev/null +++ b/solution/1500-1599/1510.Stone Game IV/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + bool winnerSquareGame(int n) { + bool f[n + 1]; + memset(f, false, sizeof(f)); + for (int i = 1; i <= n; ++i) { + for (int j = 1; j <= i / j; ++j) { + if (!f[i - j * j]) { + f[i] = true; + break; + } + } + } + return f[n]; + } +}; \ No newline at end of file diff --git a/solution/1500-1599/1510.Stone Game IV/Solution2.go b/solution/1500-1599/1510.Stone Game IV/Solution2.go new file mode 100644 index 0000000000000..137376e6332a5 --- /dev/null +++ b/solution/1500-1599/1510.Stone Game IV/Solution2.go @@ -0,0 +1,12 @@ +func winnerSquareGame(n int) bool { + f := make([]bool, n+1) + for i := 1; i <= n; i++ { + for j := 1; j <= i/j; j++ { + if !f[i-j*j] { + f[i] = true + break + } + } + } + return f[n] +} \ No newline at end of file diff --git a/solution/1500-1599/1510.Stone Game IV/Solution2.java b/solution/1500-1599/1510.Stone Game IV/Solution2.java new file mode 100644 index 0000000000000..0e9ab63a14778 --- /dev/null +++ b/solution/1500-1599/1510.Stone Game IV/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public boolean winnerSquareGame(int n) { + boolean[] f = new boolean[n + 1]; + for (int i = 1; i <= n; ++i) { + for (int j = 1; j <= i / j; ++j) { + if (!f[i - j * j]) { + f[i] = true; + break; + } + } + } + return f[n]; + } +} \ No newline at end of file diff --git a/solution/1500-1599/1510.Stone Game IV/Solution2.py b/solution/1500-1599/1510.Stone Game IV/Solution2.py new file mode 100644 index 0000000000000..7848f6541551d --- /dev/null +++ b/solution/1500-1599/1510.Stone Game IV/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def winnerSquareGame(self, n: int) -> bool: + f = [False] * (n + 1) + for i in range(1, n + 1): + j = 1 + while j <= i // j: + if not f[i - j * j]: + f[i] = True + break + j += 1 + return f[n] diff --git a/solution/1500-1599/1510.Stone Game IV/Solution2.ts b/solution/1500-1599/1510.Stone Game IV/Solution2.ts new file mode 100644 index 0000000000000..70cdee92f1bcd --- /dev/null +++ b/solution/1500-1599/1510.Stone Game IV/Solution2.ts @@ -0,0 +1,12 @@ +function winnerSquareGame(n: number): boolean { + const f: boolean[] = new Array(n + 1).fill(false); + for (let i = 1; i <= n; ++i) { + for (let j = 1; j * j <= i; ++j) { + if (!f[i - j * j]) { + f[i] = true; + break; + } + } + } + return f[n]; +} diff --git a/solution/1500-1599/1512.Number of Good Pairs/Solution.c b/solution/1500-1599/1512.Number of Good Pairs/Solution.c index 48361299bf020..bd0c2c2697be0 100644 --- a/solution/1500-1599/1512.Number of Good Pairs/Solution.c +++ b/solution/1500-1599/1512.Number of Good Pairs/Solution.c @@ -5,4 +5,4 @@ int numIdenticalPairs(int* nums, int numsSize) { ans += cnt[nums[i]]++; } return ans; -} +} \ No newline at end of file diff --git a/solution/1500-1599/1512.Number of Good Pairs/Solution.php b/solution/1500-1599/1512.Number of Good Pairs/Solution.php index a4ee40b356440..9aef1c0565e44 100644 --- a/solution/1500-1599/1512.Number of Good Pairs/Solution.php +++ b/solution/1500-1599/1512.Number of Good Pairs/Solution.php @@ -14,4 +14,4 @@ function numIdenticalPairs($nums) { } return $rs; } -} \ No newline at end of file +} diff --git a/solution/1500-1599/1512.Number of Good Pairs/Solution2.c b/solution/1500-1599/1512.Number of Good Pairs/Solution2.c new file mode 100644 index 0000000000000..a15ad28a7ed56 --- /dev/null +++ b/solution/1500-1599/1512.Number of Good Pairs/Solution2.c @@ -0,0 +1,11 @@ +int numIdenticalPairs(int* nums, int numsSize) { + int cnt[101] = {0}; + for (int i = 0; i < numsSize; i++) { + cnt[nums[i]]++; + } + int ans = 0; + for (int i = 0; i < 101; ++i) { + ans += cnt[i] * (cnt[i] - 1) / 2; + } + return ans; +} \ No newline at end of file diff --git a/solution/1500-1599/1512.Number of Good Pairs/Solution2.cpp b/solution/1500-1599/1512.Number of Good Pairs/Solution2.cpp new file mode 100644 index 0000000000000..eee7d0bca33b1 --- /dev/null +++ b/solution/1500-1599/1512.Number of Good Pairs/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int numIdenticalPairs(vector& nums) { + int cnt[101]{}; + for (int& x : nums) { + ++cnt[x]; + } + int ans = 0; + for (int v : cnt) { + ans += v * (v - 1) / 2; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1500-1599/1512.Number of Good Pairs/Solution2.go b/solution/1500-1599/1512.Number of Good Pairs/Solution2.go new file mode 100644 index 0000000000000..9221177f22a7d --- /dev/null +++ b/solution/1500-1599/1512.Number of Good Pairs/Solution2.go @@ -0,0 +1,10 @@ +func numIdenticalPairs(nums []int) (ans int) { + cnt := [101]int{} + for _, x := range nums { + cnt[x]++ + } + for _, v := range cnt { + ans += v * (v - 1) / 2 + } + return +} \ No newline at end of file diff --git a/solution/1500-1599/1512.Number of Good Pairs/Solution2.java b/solution/1500-1599/1512.Number of Good Pairs/Solution2.java new file mode 100644 index 0000000000000..ded87607f2db9 --- /dev/null +++ b/solution/1500-1599/1512.Number of Good Pairs/Solution2.java @@ -0,0 +1,13 @@ +class Solution { + public int numIdenticalPairs(int[] nums) { + int[] cnt = new int[101]; + for (int x : nums) { + ++cnt[x]; + } + int ans = 0; + for (int v : cnt) { + ans += v * (v - 1) / 2; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1500-1599/1512.Number of Good Pairs/Solution2.py b/solution/1500-1599/1512.Number of Good Pairs/Solution2.py new file mode 100644 index 0000000000000..fd0d38656d18d --- /dev/null +++ b/solution/1500-1599/1512.Number of Good Pairs/Solution2.py @@ -0,0 +1,4 @@ +class Solution: + def numIdenticalPairs(self, nums: List[int]) -> int: + cnt = Counter(nums) + return sum(v * (v - 1) for v in cnt.values()) >> 1 diff --git a/solution/1500-1599/1512.Number of Good Pairs/Solution2.rs b/solution/1500-1599/1512.Number of Good Pairs/Solution2.rs new file mode 100644 index 0000000000000..555ad4f47400f --- /dev/null +++ b/solution/1500-1599/1512.Number of Good Pairs/Solution2.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn num_identical_pairs(nums: Vec) -> i32 { + let mut cnt = [0; 101]; + for &num in nums.iter() { + cnt[num as usize] += 1; + } + let mut ans = 0; + for &v in cnt.iter() { + ans += (v * (v - 1)) / 2; + } + ans + } +} diff --git a/solution/1500-1599/1512.Number of Good Pairs/Solution2.ts b/solution/1500-1599/1512.Number of Good Pairs/Solution2.ts new file mode 100644 index 0000000000000..bf835619d39e1 --- /dev/null +++ b/solution/1500-1599/1512.Number of Good Pairs/Solution2.ts @@ -0,0 +1,11 @@ +function numIdenticalPairs(nums: number[]): number { + const cnt = new Array(101).fill(0); + for (const x of nums) { + ++cnt[x]; + } + let ans = 0; + for (const v of cnt) { + ans += v * (v - 1); + } + return ans >> 1; +} diff --git a/solution/1500-1599/1514.Path with Maximum Probability/Solution.cpp b/solution/1500-1599/1514.Path with Maximum Probability/Solution.cpp index fb0047bfdd733..42180e06f87e2 100644 --- a/solution/1500-1599/1514.Path with Maximum Probability/Solution.cpp +++ b/solution/1500-1599/1514.Path with Maximum Probability/Solution.cpp @@ -1,32 +1,32 @@ -class Solution { -public: - double maxProbability(int n, vector>& edges, vector& succProb, int start, int end) { - vector>> g(n); - for (int i = 0; i < edges.size(); ++i) { - int a = edges[i][0], b = edges[i][1]; - double s = succProb[i]; - g[a].push_back({b, s}); - g[b].push_back({a, s}); - } - vector d(n); - d[start] = 1.0; - queue> q; - q.push({1.0, start}); - while (!q.empty()) { - auto p = q.front(); - q.pop(); - double w = p.first; - int u = p.second; - if (d[u] > w) continue; - for (auto& e : g[u]) { - int v = e.first; - double t = e.second; - if (d[v] < d[u] * t) { - d[v] = d[u] * t; - q.push({d[v], v}); - } - } - } - return d[end]; - } +class Solution { +public: + double maxProbability(int n, vector>& edges, vector& succProb, int start, int end) { + vector>> g(n); + for (int i = 0; i < edges.size(); ++i) { + int a = edges[i][0], b = edges[i][1]; + double s = succProb[i]; + g[a].push_back({b, s}); + g[b].push_back({a, s}); + } + vector d(n); + d[start] = 1.0; + queue> q; + q.push({1.0, start}); + while (!q.empty()) { + auto p = q.front(); + q.pop(); + double w = p.first; + int u = p.second; + if (d[u] > w) continue; + for (auto& e : g[u]) { + int v = e.first; + double t = e.second; + if (d[v] < d[u] * t) { + d[v] = d[u] * t; + q.push({d[v], v}); + } + } + } + return d[end]; + } }; \ No newline at end of file diff --git a/solution/1500-1599/1514.Path with Maximum Probability/Solution.java b/solution/1500-1599/1514.Path with Maximum Probability/Solution.java index 863986d3b588b..2e8d1111abd32 100644 --- a/solution/1500-1599/1514.Path with Maximum Probability/Solution.java +++ b/solution/1500-1599/1514.Path with Maximum Probability/Solution.java @@ -1,32 +1,32 @@ -class Solution { - public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) { - List>[] g = new List[n]; - Arrays.setAll(g, k -> new ArrayList<>()); - for (int i = 0; i < edges.length; ++i) { - int a = edges[i][0], b = edges[i][1]; - double s = succProb[i]; - g[a].add(new Pair<>(b, s)); - g[b].add(new Pair<>(a, s)); - } - PriorityQueue> q - = new PriorityQueue<>(Comparator.comparingDouble(Pair::getKey)); - double[] d = new double[n]; - d[start] = 1.0; - q.offer(new Pair<>(-1.0, start)); - while (!q.isEmpty()) { - Pair p = q.poll(); - double w = p.getKey(); - w *= -1; - int u = p.getValue(); - for (Pair ne : g[u]) { - int v = ne.getKey(); - double t = ne.getValue(); - if (d[v] < d[u] * t) { - d[v] = d[u] * t; - q.offer(new Pair<>(-d[v], v)); - } - } - } - return d[end]; - } +class Solution { + public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) { + List>[] g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (int i = 0; i < edges.length; ++i) { + int a = edges[i][0], b = edges[i][1]; + double s = succProb[i]; + g[a].add(new Pair<>(b, s)); + g[b].add(new Pair<>(a, s)); + } + PriorityQueue> q + = new PriorityQueue<>(Comparator.comparingDouble(Pair::getKey)); + double[] d = new double[n]; + d[start] = 1.0; + q.offer(new Pair<>(-1.0, start)); + while (!q.isEmpty()) { + Pair p = q.poll(); + double w = p.getKey(); + w *= -1; + int u = p.getValue(); + for (Pair ne : g[u]) { + int v = ne.getKey(); + double t = ne.getValue(); + if (d[v] < d[u] * t) { + d[v] = d[u] * t; + q.offer(new Pair<>(-d[v], v)); + } + } + } + return d[end]; + } } \ No newline at end of file diff --git a/solution/1500-1599/1514.Path with Maximum Probability/Solution.py b/solution/1500-1599/1514.Path with Maximum Probability/Solution.py index 69cede6c109fa..83a0d71fddfe4 100644 --- a/solution/1500-1599/1514.Path with Maximum Probability/Solution.py +++ b/solution/1500-1599/1514.Path with Maximum Probability/Solution.py @@ -1,26 +1,26 @@ -class Solution: - def maxProbability( - self, - n: int, - edges: List[List[int]], - succProb: List[float], - start: int, - end: int, - ) -> float: - g = defaultdict(list) - for (a, b), s in zip(edges, succProb): - g[a].append((b, s)) - g[b].append((a, s)) - q = [(-1, start)] - d = [0] * n - d[start] = 1 - while q: - w, u = heappop(q) - w = -w - if d[u] > w: - continue - for v, t in g[u]: - if d[v] < d[u] * t: - d[v] = d[u] * t - heappush(q, (-d[v], v)) - return d[end] +class Solution: + def maxProbability( + self, + n: int, + edges: List[List[int]], + succProb: List[float], + start: int, + end: int, + ) -> float: + g = defaultdict(list) + for (a, b), s in zip(edges, succProb): + g[a].append((b, s)) + g[b].append((a, s)) + q = [(-1, start)] + d = [0] * n + d[start] = 1 + while q: + w, u = heappop(q) + w = -w + if d[u] > w: + continue + for v, t in g[u]: + if d[v] < d[u] * t: + d[v] = d[u] * t + heappush(q, (-d[v], v)) + return d[end] diff --git a/solution/1500-1599/1514.Path with Maximum Probability/Solution2.cpp b/solution/1500-1599/1514.Path with Maximum Probability/Solution2.cpp new file mode 100644 index 0000000000000..0dde5981953d1 --- /dev/null +++ b/solution/1500-1599/1514.Path with Maximum Probability/Solution2.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + double maxProbability(int n, vector>& edges, vector& succProb, int start, int end) { + vector>> g(n); + for (int i = 0; i < edges.size(); ++i) { + int a = edges[i][0], b = edges[i][1]; + double s = succProb[i]; + g[a].push_back({b, s}); + g[b].push_back({a, s}); + } + vector d(n); + vector vis(n); + d[start] = 1.0; + queue q{{start}}; + vis[start] = true; + while (!q.empty()) { + int i = q.front(); + q.pop(); + vis[i] = false; + for (auto& ne : g[i]) { + int j = ne.first; + double s = ne.second; + if (d[j] < d[i] * s) { + d[j] = d[i] * s; + if (!vis[j]) { + q.push(j); + vis[j] = true; + } + } + } + } + return d[end]; + } +}; \ No newline at end of file diff --git a/solution/1500-1599/1514.Path with Maximum Probability/Solution2.java b/solution/1500-1599/1514.Path with Maximum Probability/Solution2.java new file mode 100644 index 0000000000000..57209b5876d90 --- /dev/null +++ b/solution/1500-1599/1514.Path with Maximum Probability/Solution2.java @@ -0,0 +1,34 @@ +class Solution { + public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) { + List>[] g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (int i = 0; i < edges.length; ++i) { + int a = edges[i][0], b = edges[i][1]; + double s = succProb[i]; + g[a].add(new Pair<>(b, s)); + g[b].add(new Pair<>(a, s)); + } + double[] d = new double[n]; + d[start] = 1.0; + boolean[] vis = new boolean[n]; + Deque q = new ArrayDeque<>(); + q.offer(start); + vis[start] = true; + while (!q.isEmpty()) { + int i = q.poll(); + vis[i] = false; + for (Pair ne : g[i]) { + int j = ne.getKey(); + double s = ne.getValue(); + if (d[j] < d[i] * s) { + d[j] = d[i] * s; + if (!vis[j]) { + q.offer(j); + vis[j] = true; + } + } + } + } + return d[end]; + } +} \ No newline at end of file diff --git a/solution/1500-1599/1514.Path with Maximum Probability/Solution2.py b/solution/1500-1599/1514.Path with Maximum Probability/Solution2.py new file mode 100644 index 0000000000000..1e7d863d8221c --- /dev/null +++ b/solution/1500-1599/1514.Path with Maximum Probability/Solution2.py @@ -0,0 +1,28 @@ +class Solution: + def maxProbability( + self, + n: int, + edges: List[List[int]], + succProb: List[float], + start: int, + end: int, + ) -> float: + g = defaultdict(list) + for (a, b), s in zip(edges, succProb): + g[a].append((b, s)) + g[b].append((a, s)) + d = [0] * n + vis = [False] * n + d[start] = 1 + q = deque([start]) + vis[start] = True + while q: + i = q.popleft() + vis[i] = False + for j, s in g[i]: + if d[j] < d[i] * s: + d[j] = d[i] * s + if not vis[j]: + q.append(j) + vis[j] = True + return d[end] diff --git a/solution/1500-1599/1515.Best Position for a Service Centre/Solution.cpp b/solution/1500-1599/1515.Best Position for a Service Centre/Solution.cpp index 2808b6ad2bec7..9c28dd7c45b2f 100644 --- a/solution/1500-1599/1515.Best Position for a Service Centre/Solution.cpp +++ b/solution/1500-1599/1515.Best Position for a Service Centre/Solution.cpp @@ -1,34 +1,34 @@ -class Solution { -public: - double getMinDistSum(vector>& positions) { - int n = positions.size(); - double x = 0, y = 0; - for (auto& p : positions) { - x += p[0]; - y += p[1]; - } - x /= n; - y /= n; - double decay = 0.999; - double eps = 1e-6; - double alpha = 0.5; - while (true) { - double gradX = 0, gradY = 0; - double dist = 0; - for (auto& p : positions) { - double a = x - p[0], b = y - p[1]; - double c = sqrt(a * a + b * b); - gradX += a / (c + 1e-8); - gradY += b / (c + 1e-8); - dist += c; - } - double dx = gradX * alpha, dy = gradY * alpha; - if (abs(dx) <= eps && abs(dy) <= eps) { - return dist; - } - x -= dx; - y -= dy; - alpha *= decay; - } - } +class Solution { +public: + double getMinDistSum(vector>& positions) { + int n = positions.size(); + double x = 0, y = 0; + for (auto& p : positions) { + x += p[0]; + y += p[1]; + } + x /= n; + y /= n; + double decay = 0.999; + double eps = 1e-6; + double alpha = 0.5; + while (true) { + double gradX = 0, gradY = 0; + double dist = 0; + for (auto& p : positions) { + double a = x - p[0], b = y - p[1]; + double c = sqrt(a * a + b * b); + gradX += a / (c + 1e-8); + gradY += b / (c + 1e-8); + dist += c; + } + double dx = gradX * alpha, dy = gradY * alpha; + if (abs(dx) <= eps && abs(dy) <= eps) { + return dist; + } + x -= dx; + y -= dy; + alpha *= decay; + } + } }; \ No newline at end of file diff --git a/solution/1500-1599/1515.Best Position for a Service Centre/Solution.java b/solution/1500-1599/1515.Best Position for a Service Centre/Solution.java index 7737b24503500..2b20751fec366 100644 --- a/solution/1500-1599/1515.Best Position for a Service Centre/Solution.java +++ b/solution/1500-1599/1515.Best Position for a Service Centre/Solution.java @@ -1,33 +1,33 @@ -class Solution { - public double getMinDistSum(int[][] positions) { - int n = positions.length; - double x = 0, y = 0; - for (int[] p : positions) { - x += p[0]; - y += p[1]; - } - x /= n; - y /= n; - double decay = 0.999; - double eps = 1e-6; - double alpha = 0.5; - while (true) { - double gradX = 0, gradY = 0; - double dist = 0; - for (int[] p : positions) { - double a = x - p[0], b = y - p[1]; - double c = Math.sqrt(a * a + b * b); - gradX += a / (c + 1e-8); - gradY += b / (c + 1e-8); - dist += c; - } - double dx = gradX * alpha, dy = gradY * alpha; - if (Math.abs(dx) <= eps && Math.abs(dy) <= eps) { - return dist; - } - x -= dx; - y -= dy; - alpha *= decay; - } - } +class Solution { + public double getMinDistSum(int[][] positions) { + int n = positions.length; + double x = 0, y = 0; + for (int[] p : positions) { + x += p[0]; + y += p[1]; + } + x /= n; + y /= n; + double decay = 0.999; + double eps = 1e-6; + double alpha = 0.5; + while (true) { + double gradX = 0, gradY = 0; + double dist = 0; + for (int[] p : positions) { + double a = x - p[0], b = y - p[1]; + double c = Math.sqrt(a * a + b * b); + gradX += a / (c + 1e-8); + gradY += b / (c + 1e-8); + dist += c; + } + double dx = gradX * alpha, dy = gradY * alpha; + if (Math.abs(dx) <= eps && Math.abs(dy) <= eps) { + return dist; + } + x -= dx; + y -= dy; + alpha *= decay; + } + } } \ No newline at end of file diff --git a/solution/1500-1599/1515.Best Position for a Service Centre/Solution.py b/solution/1500-1599/1515.Best Position for a Service Centre/Solution.py index 0e08883f511ad..51cf303f16d59 100644 --- a/solution/1500-1599/1515.Best Position for a Service Centre/Solution.py +++ b/solution/1500-1599/1515.Best Position for a Service Centre/Solution.py @@ -1,28 +1,28 @@ -class Solution: - def getMinDistSum(self, positions: List[List[int]]) -> float: - n = len(positions) - x = y = 0 - for x1, y1 in positions: - x += x1 - y += y1 - x, y = x / n, y / n - decay = 0.999 - eps = 1e-6 - alpha = 0.5 - while 1: - grad_x = grad_y = 0 - dist = 0 - for x1, y1 in positions: - a = x - x1 - b = y - y1 - c = sqrt(a * a + b * b) - grad_x += a / (c + 1e-8) - grad_y += b / (c + 1e-8) - dist += c - dx = grad_x * alpha - dy = grad_y * alpha - x -= dx - y -= dy - alpha *= decay - if abs(dx) <= eps and abs(dy) <= eps: - return dist +class Solution: + def getMinDistSum(self, positions: List[List[int]]) -> float: + n = len(positions) + x = y = 0 + for x1, y1 in positions: + x += x1 + y += y1 + x, y = x / n, y / n + decay = 0.999 + eps = 1e-6 + alpha = 0.5 + while 1: + grad_x = grad_y = 0 + dist = 0 + for x1, y1 in positions: + a = x - x1 + b = y - y1 + c = sqrt(a * a + b * b) + grad_x += a / (c + 1e-8) + grad_y += b / (c + 1e-8) + dist += c + dx = grad_x * alpha + dy = grad_y * alpha + x -= dx + y -= dy + alpha *= decay + if abs(dx) <= eps and abs(dy) <= eps: + return dist diff --git a/solution/1500-1599/1518.Water Bottles/Solution.cpp b/solution/1500-1599/1518.Water Bottles/Solution.cpp index c507ac0b6f88d..ba14588b4f22a 100644 --- a/solution/1500-1599/1518.Water Bottles/Solution.cpp +++ b/solution/1500-1599/1518.Water Bottles/Solution.cpp @@ -1,10 +1,10 @@ -class Solution { -public: - int numWaterBottles(int numBottles, int numExchange) { - int ans = numBottles; - for (; numBottles >= numExchange; ++ans) { - numBottles -= (numExchange - 1); - } - return ans; - } +class Solution { +public: + int numWaterBottles(int numBottles, int numExchange) { + int ans = numBottles; + for (; numBottles >= numExchange; ++ans) { + numBottles -= (numExchange - 1); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1500-1599/1518.Water Bottles/Solution.java b/solution/1500-1599/1518.Water Bottles/Solution.java index f0af87acfe923..8dc2a961ca44c 100644 --- a/solution/1500-1599/1518.Water Bottles/Solution.java +++ b/solution/1500-1599/1518.Water Bottles/Solution.java @@ -1,9 +1,9 @@ -class Solution { - public int numWaterBottles(int numBottles, int numExchange) { - int ans = numBottles; - for (; numBottles >= numExchange; ++ans) { - numBottles -= (numExchange - 1); - } - return ans; - } +class Solution { + public int numWaterBottles(int numBottles, int numExchange) { + int ans = numBottles; + for (; numBottles >= numExchange; ++ans) { + numBottles -= (numExchange - 1); + } + return ans; + } } \ No newline at end of file diff --git a/solution/1500-1599/1518.Water Bottles/Solution.php b/solution/1500-1599/1518.Water Bottles/Solution.php index f94f316647fbd..1d2070c6be2df 100644 --- a/solution/1500-1599/1518.Water Bottles/Solution.php +++ b/solution/1500-1599/1518.Water Bottles/Solution.php @@ -12,4 +12,4 @@ function numWaterBottles($numBottles, $numExchange) { } return $ans; } -} \ No newline at end of file +} diff --git a/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/Solution.cpp b/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/Solution.cpp index c7e41dd141bf2..0e9bef2c9b6aa 100644 --- a/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/Solution.cpp +++ b/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - int closestToTarget(vector& arr, int target) { - int ans = abs(arr[0] - target); - unordered_set pre; - pre.insert(arr[0]); - for (int x : arr) { - unordered_set cur; - cur.insert(x); - for (int y : pre) { - cur.insert(x & y); - } - for (int y : cur) { - ans = min(ans, abs(y - target)); - } - pre = move(cur); - } - return ans; - } +class Solution { +public: + int closestToTarget(vector& arr, int target) { + int ans = abs(arr[0] - target); + unordered_set pre; + pre.insert(arr[0]); + for (int x : arr) { + unordered_set cur; + cur.insert(x); + for (int y : pre) { + cur.insert(x & y); + } + for (int y : cur) { + ans = min(ans, abs(y - target)); + } + pre = move(cur); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/Solution.java b/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/Solution.java index 31682567f1e3a..d1ec9e366239b 100644 --- a/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/Solution.java +++ b/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/Solution.java @@ -1,19 +1,19 @@ -class Solution { - public int closestToTarget(int[] arr, int target) { - int ans = Math.abs(arr[0] - target); - Set pre = new HashSet<>(); - pre.add(arr[0]); - for (int x : arr) { - Set cur = new HashSet<>(); - for (int y : pre) { - cur.add(x & y); - } - cur.add(x); - for (int y : cur) { - ans = Math.min(ans, Math.abs(y - target)); - } - pre = cur; - } - return ans; - } +class Solution { + public int closestToTarget(int[] arr, int target) { + int ans = Math.abs(arr[0] - target); + Set pre = new HashSet<>(); + pre.add(arr[0]); + for (int x : arr) { + Set cur = new HashSet<>(); + for (int y : pre) { + cur.add(x & y); + } + cur.add(x); + for (int y : cur) { + ans = Math.min(ans, Math.abs(y - target)); + } + pre = cur; + } + return ans; + } } \ No newline at end of file diff --git a/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/Solution.py b/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/Solution.py index 85c7316c936aa..e7180289c7026 100644 --- a/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/Solution.py +++ b/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/Solution.py @@ -1,8 +1,8 @@ -class Solution: - def closestToTarget(self, arr: List[int], target: int) -> int: - ans = abs(arr[0] - target) - s = {arr[0]} - for x in arr: - s = {x & y for y in s} | {x} - ans = min(ans, min(abs(y - target) for y in s)) - return ans +class Solution: + def closestToTarget(self, arr: List[int], target: int) -> int: + ans = abs(arr[0] - target) + s = {arr[0]} + for x in arr: + s = {x & y for y in s} | {x} + ans = min(ans, min(abs(y - target) for y in s)) + return ans diff --git a/solution/1500-1599/1522.Diameter of N-Ary Tree/Solution2.cpp b/solution/1500-1599/1522.Diameter of N-Ary Tree/Solution2.cpp new file mode 100644 index 0000000000000..5e8beaa0f3dc0 --- /dev/null +++ b/solution/1500-1599/1522.Diameter of N-Ary Tree/Solution2.cpp @@ -0,0 +1,58 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { +public: + unordered_map> g; + unordered_set vis; + Node* next; + int ans; + + int diameter(Node* root) { + build(root); + next = root; + ans = 0; + dfs(next, 0); + vis.clear(); + dfs(next, 0); + return ans; + } + + void dfs(Node* u, int t) { + if (vis.count(u)) return; + vis.insert(u); + if (ans < t) { + ans = t; + next = u; + } + if (g.count(u)) + for (Node* v : g[u]) + dfs(v, t + 1); + } + + void build(Node* root) { + if (!root) return; + for (Node* child : root->children) { + g[root].insert(child); + g[child].insert(root); + build(child); + } + } +}; \ No newline at end of file diff --git a/solution/1500-1599/1522.Diameter of N-Ary Tree/Solution2.go b/solution/1500-1599/1522.Diameter of N-Ary Tree/Solution2.go new file mode 100644 index 0000000000000..9e00862ca77c2 --- /dev/null +++ b/solution/1500-1599/1522.Diameter of N-Ary Tree/Solution2.go @@ -0,0 +1,46 @@ +/** + * Definition for a Node. + * type Node struct { + * Val int + * Children []*Node + * } + */ + +func diameter(root *Node) int { + g := make(map[*Node][]*Node) + vis := make(map[*Node]bool) + next := root + ans := 0 + var build func(root *Node) + build = func(root *Node) { + if root == nil { + return + } + for _, child := range root.Children { + g[root] = append(g[root], child) + g[child] = append(g[child], root) + build(child) + } + } + build(root) + var dfs func(u *Node, t int) + dfs = func(u *Node, t int) { + if vis[u] { + return + } + vis[u] = true + if t > ans { + ans = t + next = u + } + if vs, ok := g[u]; ok { + for _, v := range vs { + dfs(v, t+1) + } + } + } + dfs(next, 0) + vis = make(map[*Node]bool) + dfs(next, 0) + return ans +} \ No newline at end of file diff --git a/solution/1500-1599/1522.Diameter of N-Ary Tree/Solution2.java b/solution/1500-1599/1522.Diameter of N-Ary Tree/Solution2.java new file mode 100644 index 0000000000000..9430fdf30753d --- /dev/null +++ b/solution/1500-1599/1522.Diameter of N-Ary Tree/Solution2.java @@ -0,0 +1,68 @@ +/* +// Definition for a Node. +class Node { + public int val; + public List children; + + + public Node() { + children = new ArrayList(); + } + + public Node(int _val) { + val = _val; + children = new ArrayList(); + } + + public Node(int _val,ArrayList _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { + private Map> g; + private Set vis; + private Node next; + private int ans; + + public int diameter(Node root) { + g = new HashMap<>(); + build(root); + vis = new HashSet<>(); + next = root; + ans = 0; + dfs(next, 0); + vis.clear(); + dfs(next, 0); + return ans; + } + + private void dfs(Node u, int t) { + if (vis.contains(u)) { + return; + } + vis.add(u); + if (t > ans) { + ans = t; + next = u; + } + if (g.containsKey(u)) { + for (Node v : g.get(u)) { + dfs(v, t + 1); + } + } + } + + private void build(Node root) { + if (root == null) { + return; + } + for (Node child : root.children) { + g.computeIfAbsent(root, k -> new HashSet<>()).add(child); + g.computeIfAbsent(child, k -> new HashSet<>()).add(root); + build(child); + } + } +} \ No newline at end of file diff --git a/solution/1500-1599/1522.Diameter of N-Ary Tree/Solution2.py b/solution/1500-1599/1522.Diameter of N-Ary Tree/Solution2.py new file mode 100644 index 0000000000000..bcfa1f4fc9f42 --- /dev/null +++ b/solution/1500-1599/1522.Diameter of N-Ary Tree/Solution2.py @@ -0,0 +1,45 @@ +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children if children is not None else [] +""" + + +class Solution: + def diameter(self, root: 'Node') -> int: + """ + :type root: 'Node' + :rtype: int + """ + + def build(root): + nonlocal d + if root is None: + return + for child in root.children: + d[root].add(child) + d[child].add(root) + build(child) + + def dfs(u, t): + nonlocal ans, vis, d, next + if u in vis: + return + vis.add(u) + for v in d[u]: + dfs(v, t + 1) + if ans < t: + ans = t + next = u + + d = defaultdict(set) + vis = set() + build(root) + ans = 0 + next = None + dfs(root, 0) + vis.clear() + dfs(next, 0) + return ans diff --git a/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/Solution.c b/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/Solution.c index 7c2326e80aebe..64debe075b34f 100644 --- a/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/Solution.c +++ b/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/Solution.c @@ -1,3 +1,3 @@ int countOdds(int low, int high) { return ((high + 1) >> 1) - (low >> 1); -} +} \ No newline at end of file diff --git a/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/Solution.php b/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/Solution.php index 2a59328f91b58..65bfec1d2e810 100644 --- a/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/Solution.php +++ b/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/Solution.php @@ -7,4 +7,4 @@ class Solution { function countOdds($low, $high) { return ($high + 1 >> 1) - ($low >> 1); } -} \ No newline at end of file +} diff --git a/solution/1500-1599/1531.String Compression II/Solution.java b/solution/1500-1599/1531.String Compression II/Solution.java new file mode 100644 index 0000000000000..1cec95bfceac3 --- /dev/null +++ b/solution/1500-1599/1531.String Compression II/Solution.java @@ -0,0 +1,49 @@ +class Solution { + public int getLengthOfOptimalCompression(String s, int k) { + // dp[i][k] := the length of the optimal compression of s[i..n) with at most + // k deletion + dp = new int[s.length()][k + 1]; + Arrays.stream(dp).forEach(A -> Arrays.fill(A, K_MAX)); + return compression(s, 0, k); + } + + private static final int K_MAX = 101; + private int[][] dp; + + private int compression(final String s, int i, int k) { + if (k < 0) { + return K_MAX; + } + if (i == s.length() || s.length() - i <= k) { + return 0; + } + if (dp[i][k] != K_MAX) { + return dp[i][k]; + } + int maxFreq = 0; + int[] count = new int[128]; + // Make letters in s[i..j] be the same. + // Keep the letter that has the maximum frequency in this range and remove + // the other letters. + for (int j = i; j < s.length(); ++j) { + maxFreq = Math.max(maxFreq, ++count[s.charAt(j)]); + dp[i][k] = Math.min( + dp[i][k], getLength(maxFreq) + compression(s, j + 1, k - (j - i + 1 - maxFreq))); + } + return dp[i][k]; + } + + // Returns the length to compress `maxFreq`. + private int getLength(int maxFreq) { + if (maxFreq == 1) { + return 1; // c + } + if (maxFreq < 10) { + return 2; // [1-9]c + } + if (maxFreq < 100) { + return 3; // [1-9][0-9]c + } + return 4; // [1-9][0-9][0-9]c + } +} \ No newline at end of file diff --git a/solution/1500-1599/1535.Find the Winner of an Array Game/Solution.cpp b/solution/1500-1599/1535.Find the Winner of an Array Game/Solution.cpp index 1d58aa0990445..d14543cd98e2d 100644 --- a/solution/1500-1599/1535.Find the Winner of an Array Game/Solution.cpp +++ b/solution/1500-1599/1535.Find the Winner of an Array Game/Solution.cpp @@ -1,18 +1,18 @@ -class Solution { -public: - int getWinner(vector& arr, int k) { - int mx = arr[0]; - for (int i = 1, cnt = 0; i < arr.size(); ++i) { - if (mx < arr[i]) { - mx = arr[i]; - cnt = 1; - } else { - ++cnt; - } - if (cnt == k) { - break; - } - } - return mx; - } +class Solution { +public: + int getWinner(vector& arr, int k) { + int mx = arr[0]; + for (int i = 1, cnt = 0; i < arr.size(); ++i) { + if (mx < arr[i]) { + mx = arr[i]; + cnt = 1; + } else { + ++cnt; + } + if (cnt == k) { + break; + } + } + return mx; + } }; \ No newline at end of file diff --git a/solution/1500-1599/1535.Find the Winner of an Array Game/Solution.cs b/solution/1500-1599/1535.Find the Winner of an Array Game/Solution.cs new file mode 100644 index 0000000000000..8f495550493d3 --- /dev/null +++ b/solution/1500-1599/1535.Find the Winner of an Array Game/Solution.cs @@ -0,0 +1,17 @@ +public class Solution { + public int GetWinner(int[] arr, int k) { + int maxElement = arr[0], count = 0; + for (int i = 1; i < arr.Length; i++) { + if (maxElement < arr[i]) { + maxElement = arr[i]; + count = 1; + } else { + count++; + } + if (count == k) { + break; + } + } + return maxElement; + } +} diff --git a/solution/1500-1599/1535.Find the Winner of an Array Game/Solution.java b/solution/1500-1599/1535.Find the Winner of an Array Game/Solution.java index afdcff451c17d..612dff455a94b 100644 --- a/solution/1500-1599/1535.Find the Winner of an Array Game/Solution.java +++ b/solution/1500-1599/1535.Find the Winner of an Array Game/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public int getWinner(int[] arr, int k) { - int mx = arr[0]; - for (int i = 1, cnt = 0; i < arr.length; ++i) { - if (mx < arr[i]) { - mx = arr[i]; - cnt = 1; - } else { - ++cnt; - } - if (cnt == k) { - break; - } - } - return mx; - } +class Solution { + public int getWinner(int[] arr, int k) { + int mx = arr[0]; + for (int i = 1, cnt = 0; i < arr.length; ++i) { + if (mx < arr[i]) { + mx = arr[i]; + cnt = 1; + } else { + ++cnt; + } + if (cnt == k) { + break; + } + } + return mx; + } } \ No newline at end of file diff --git a/solution/1500-1599/1535.Find the Winner of an Array Game/Solution.py b/solution/1500-1599/1535.Find the Winner of an Array Game/Solution.py index 9478e249ed90c..fb4c3ada37fd7 100644 --- a/solution/1500-1599/1535.Find the Winner of an Array Game/Solution.py +++ b/solution/1500-1599/1535.Find the Winner of an Array Game/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def getWinner(self, arr: List[int], k: int) -> int: - mx = arr[0] - cnt = 0 - for x in arr[1:]: - if mx < x: - mx = x - cnt = 1 - else: - cnt += 1 - if cnt == k: - break - return mx +class Solution: + def getWinner(self, arr: List[int], k: int) -> int: + mx = arr[0] + cnt = 0 + for x in arr[1:]: + if mx < x: + mx = x + cnt = 1 + else: + cnt += 1 + if cnt == k: + break + return mx diff --git a/solution/1500-1599/1538.Guess the Majority in a Hidden Array/Solution.cpp b/solution/1500-1599/1538.Guess the Majority in a Hidden Array/Solution.cpp index 568044d65840b..c5f2f54a2de89 100644 --- a/solution/1500-1599/1538.Guess the Majority in a Hidden Array/Solution.cpp +++ b/solution/1500-1599/1538.Guess the Majority in a Hidden Array/Solution.cpp @@ -1,57 +1,57 @@ -/** - * // This is the ArrayReader's API interface. - * // You should not implement it, or speculate about its implementation - * class ArrayReader { - * public: - * // Compares 4 different elements in the array - * // return 4 if the values of the 4 elements are the same (0 or 1). - * // return 2 if three elements have a value equal to 0 and one element has value equal to 1 or vice versa. - * // return 0 : if two element have a value equal to 0 and two elements have a value equal to 1. - * int query(int a, int b, int c, int d); - * - * // Returns the length of the array - * int length(); - * }; - */ - -class Solution { -public: - int guessMajority(ArrayReader& reader) { - int n = reader.length(); - int x = reader.query(0, 1, 2, 3); - int a = 1, b = 0; - int k = 0; - for (int i = 4; i < n; ++i) { - if (reader.query(0, 1, 2, i) == x) { - ++a; - } else { - ++b; - k = i; - } - } - - int y = reader.query(0, 1, 2, 4); - if (reader.query(1, 2, 3, 4) == y) { - ++a; - } else { - ++b; - k = 0; - } - if (reader.query(0, 2, 3, 4) == y) { - ++a; - } else { - ++b; - k = 1; - } - if (reader.query(0, 1, 3, 4) == y) { - ++a; - } else { - ++b; - k = 2; - } - if (a == b) { - return -1; - } - return a > b ? 3 : k; - } +/** + * // This is the ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * class ArrayReader { + * public: + * // Compares 4 different elements in the array + * // return 4 if the values of the 4 elements are the same (0 or 1). + * // return 2 if three elements have a value equal to 0 and one element has value equal to 1 or vice versa. + * // return 0 : if two element have a value equal to 0 and two elements have a value equal to 1. + * int query(int a, int b, int c, int d); + * + * // Returns the length of the array + * int length(); + * }; + */ + +class Solution { +public: + int guessMajority(ArrayReader& reader) { + int n = reader.length(); + int x = reader.query(0, 1, 2, 3); + int a = 1, b = 0; + int k = 0; + for (int i = 4; i < n; ++i) { + if (reader.query(0, 1, 2, i) == x) { + ++a; + } else { + ++b; + k = i; + } + } + + int y = reader.query(0, 1, 2, 4); + if (reader.query(1, 2, 3, 4) == y) { + ++a; + } else { + ++b; + k = 0; + } + if (reader.query(0, 2, 3, 4) == y) { + ++a; + } else { + ++b; + k = 1; + } + if (reader.query(0, 1, 3, 4) == y) { + ++a; + } else { + ++b; + k = 2; + } + if (a == b) { + return -1; + } + return a > b ? 3 : k; + } }; \ No newline at end of file diff --git a/solution/1500-1599/1538.Guess the Majority in a Hidden Array/Solution.java b/solution/1500-1599/1538.Guess the Majority in a Hidden Array/Solution.java index 47b6ad0130646..400d6a2983da7 100644 --- a/solution/1500-1599/1538.Guess the Majority in a Hidden Array/Solution.java +++ b/solution/1500-1599/1538.Guess the Majority in a Hidden Array/Solution.java @@ -1,57 +1,57 @@ -/** - * // This is the ArrayReader's API interface. - * // You should not implement it, or speculate about its implementation - * interface ArrayReader { - * public: - * // Compares 4 different elements in the array - * // return 4 if the values of the 4 elements are the same (0 or 1). - * // return 2 if three elements have a value equal to 0 and one element has value equal to 1 or - * vice versa. - * // return 0 : if two element have a value equal to 0 and two elements have a value equal - * to 1. public int query(int a, int b, int c, int d); - * - * // Returns the length of the array - * public int length(); - * }; - */ - -class Solution { - public int guessMajority(ArrayReader reader) { - int n = reader.length(); - int x = reader.query(0, 1, 2, 3); - int a = 1, b = 0; - int k = 0; - for (int i = 4; i < n; ++i) { - if (reader.query(0, 1, 2, i) == x) { - ++a; - } else { - ++b; - k = i; - } - } - - int y = reader.query(0, 1, 2, 4); - if (reader.query(1, 2, 3, 4) == y) { - ++a; - } else { - ++b; - k = 0; - } - if (reader.query(0, 2, 3, 4) == y) { - ++a; - } else { - ++b; - k = 1; - } - if (reader.query(0, 1, 3, 4) == y) { - ++a; - } else { - ++b; - k = 2; - } - if (a == b) { - return -1; - } - return a > b ? 3 : k; - } +/** + * // This is the ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * interface ArrayReader { + * public: + * // Compares 4 different elements in the array + * // return 4 if the values of the 4 elements are the same (0 or 1). + * // return 2 if three elements have a value equal to 0 and one element has value equal to 1 or + * vice versa. + * // return 0 : if two element have a value equal to 0 and two elements have a value equal + * to 1. public int query(int a, int b, int c, int d); + * + * // Returns the length of the array + * public int length(); + * }; + */ + +class Solution { + public int guessMajority(ArrayReader reader) { + int n = reader.length(); + int x = reader.query(0, 1, 2, 3); + int a = 1, b = 0; + int k = 0; + for (int i = 4; i < n; ++i) { + if (reader.query(0, 1, 2, i) == x) { + ++a; + } else { + ++b; + k = i; + } + } + + int y = reader.query(0, 1, 2, 4); + if (reader.query(1, 2, 3, 4) == y) { + ++a; + } else { + ++b; + k = 0; + } + if (reader.query(0, 2, 3, 4) == y) { + ++a; + } else { + ++b; + k = 1; + } + if (reader.query(0, 1, 3, 4) == y) { + ++a; + } else { + ++b; + k = 2; + } + if (a == b) { + return -1; + } + return a > b ? 3 : k; + } } \ No newline at end of file diff --git a/solution/1500-1599/1538.Guess the Majority in a Hidden Array/Solution.py b/solution/1500-1599/1538.Guess the Majority in a Hidden Array/Solution.py index 7a070bf3ff478..435b8c16aa929 100644 --- a/solution/1500-1599/1538.Guess the Majority in a Hidden Array/Solution.py +++ b/solution/1500-1599/1538.Guess the Majority in a Hidden Array/Solution.py @@ -1,49 +1,49 @@ -# """ -# This is the ArrayReader's API interface. -# You should not implement it, or speculate about its implementation -# """ -# class ArrayReader(object): -# # Compares 4 different elements in the array -# # return 4 if the values of the 4 elements are the same (0 or 1). -# # return 2 if three elements have a value equal to 0 and one element has value equal to 1 or vice versa. -# # return 0 : if two element have a value equal to 0 and two elements have a value equal to 1. -# def query(self, a: int, b: int, c: int, d: int) -> int: -# -# # Returns the length of the array -# def length(self) -> int: -# - - -class Solution: - def guessMajority(self, reader: "ArrayReader") -> int: - n = reader.length() - x = reader.query(0, 1, 2, 3) - a, b = 1, 0 - k = 0 - for i in range(4, n): - if reader.query(0, 1, 2, i) == x: - a += 1 - else: - b += 1 - k = i - - y = reader.query(0, 1, 2, 4) - if reader.query(1, 2, 3, 4) == y: - a += 1 - else: - b += 1 - k = 0 - if reader.query(0, 2, 3, 4) == y: - a += 1 - else: - b += 1 - k = 1 - if reader.query(0, 1, 3, 4) == y: - a += 1 - else: - b += 1 - k = 2 - - if a == b: - return -1 - return 3 if a > b else k +# """ +# This is the ArrayReader's API interface. +# You should not implement it, or speculate about its implementation +# """ +# class ArrayReader(object): +# # Compares 4 different elements in the array +# # return 4 if the values of the 4 elements are the same (0 or 1). +# # return 2 if three elements have a value equal to 0 and one element has value equal to 1 or vice versa. +# # return 0 : if two element have a value equal to 0 and two elements have a value equal to 1. +# def query(self, a: int, b: int, c: int, d: int) -> int: +# +# # Returns the length of the array +# def length(self) -> int: +# + + +class Solution: + def guessMajority(self, reader: "ArrayReader") -> int: + n = reader.length() + x = reader.query(0, 1, 2, 3) + a, b = 1, 0 + k = 0 + for i in range(4, n): + if reader.query(0, 1, 2, i) == x: + a += 1 + else: + b += 1 + k = i + + y = reader.query(0, 1, 2, 4) + if reader.query(1, 2, 3, 4) == y: + a += 1 + else: + b += 1 + k = 0 + if reader.query(0, 2, 3, 4) == y: + a += 1 + else: + b += 1 + k = 1 + if reader.query(0, 1, 3, 4) == y: + a += 1 + else: + b += 1 + k = 2 + + if a == b: + return -1 + return 3 if a > b else k diff --git a/solution/1500-1599/1539.Kth Missing Positive Number/Solution.cpp b/solution/1500-1599/1539.Kth Missing Positive Number/Solution.cpp index ed887d321a004..364ddbb115b39 100644 --- a/solution/1500-1599/1539.Kth Missing Positive Number/Solution.cpp +++ b/solution/1500-1599/1539.Kth Missing Positive Number/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - int findKthPositive(vector& arr, int k) { - if (arr[0] > k) return k; - int left = 0, right = arr.size(); - while (left < right) { - int mid = (left + right) >> 1; - if (arr[mid] - mid - 1 >= k) - right = mid; - else - left = mid + 1; - } - return arr[left - 1] + k - (arr[left - 1] - (left - 1) - 1); - } +class Solution { +public: + int findKthPositive(vector& arr, int k) { + if (arr[0] > k) return k; + int left = 0, right = arr.size(); + while (left < right) { + int mid = (left + right) >> 1; + if (arr[mid] - mid - 1 >= k) + right = mid; + else + left = mid + 1; + } + return arr[left - 1] + k - (arr[left - 1] - (left - 1) - 1); + } }; \ No newline at end of file diff --git a/solution/1500-1599/1539.Kth Missing Positive Number/Solution.java b/solution/1500-1599/1539.Kth Missing Positive Number/Solution.java index f8620b7a5d8b7..7bd5e5712c716 100644 --- a/solution/1500-1599/1539.Kth Missing Positive Number/Solution.java +++ b/solution/1500-1599/1539.Kth Missing Positive Number/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public int findKthPositive(int[] arr, int k) { - if (arr[0] > k) { - return k; - } - int left = 0, right = arr.length; - while (left < right) { - int mid = (left + right) >> 1; - if (arr[mid] - mid - 1 >= k) { - right = mid; - } else { - left = mid + 1; - } - } - return arr[left - 1] + k - (arr[left - 1] - (left - 1) - 1); - } +class Solution { + public int findKthPositive(int[] arr, int k) { + if (arr[0] > k) { + return k; + } + int left = 0, right = arr.length; + while (left < right) { + int mid = (left + right) >> 1; + if (arr[mid] - mid - 1 >= k) { + right = mid; + } else { + left = mid + 1; + } + } + return arr[left - 1] + k - (arr[left - 1] - (left - 1) - 1); + } } \ No newline at end of file diff --git a/solution/1500-1599/1539.Kth Missing Positive Number/Solution.py b/solution/1500-1599/1539.Kth Missing Positive Number/Solution.py index 7438e7a7c6d8b..c4c010205ef96 100644 --- a/solution/1500-1599/1539.Kth Missing Positive Number/Solution.py +++ b/solution/1500-1599/1539.Kth Missing Positive Number/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def findKthPositive(self, arr: List[int], k: int) -> int: - if arr[0] > k: - return k - left, right = 0, len(arr) - while left < right: - mid = (left + right) >> 1 - if arr[mid] - mid - 1 >= k: - right = mid - else: - left = mid + 1 - return arr[left - 1] + k - (arr[left - 1] - (left - 1) - 1) +class Solution: + def findKthPositive(self, arr: List[int], k: int) -> int: + if arr[0] > k: + return k + left, right = 0, len(arr) + while left < right: + mid = (left + right) >> 1 + if arr[mid] - mid - 1 >= k: + right = mid + else: + left = mid + 1 + return arr[left - 1] + k - (arr[left - 1] - (left - 1) - 1) diff --git a/solution/1500-1599/1541.Minimum Insertions to Balance a Parentheses String/Solution.py b/solution/1500-1599/1541.Minimum Insertions to Balance a Parentheses String/Solution.py index ad932165f6b0c..30209eba9803c 100644 --- a/solution/1500-1599/1541.Minimum Insertions to Balance a Parentheses String/Solution.py +++ b/solution/1500-1599/1541.Minimum Insertions to Balance a Parentheses String/Solution.py @@ -4,16 +4,22 @@ def minInsertions(self, s: str) -> int: i, n = 0, len(s) while i < n: if s[i] == '(': + # 待匹配的左括号加 1 x += 1 else: if i < n - 1 and s[i + 1] == ')': + # 有连续两个右括号,i 往后移动 i += 1 else: + # 只有一个右括号,插入一个 ans += 1 if x == 0: + # 无待匹配的左括号,插入一个 ans += 1 else: + # 待匹配的左括号减 1 x -= 1 i += 1 + # 遍历结束,仍有待匹配的左括号,说明右括号不足,插入 x << 1 个 ans += x << 1 return ans diff --git a/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/Solution.cpp b/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/Solution.cpp index c9cc15ae97fd2..9e40b26f07960 100644 --- a/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/Solution.cpp +++ b/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/Solution.cpp @@ -1,19 +1,19 @@ -class Solution { -public: - char findKthBit(int n, int k) { - function dfs = [&](int n, int k) { - if (k == 1) { - return 0; - } - if ((k & (k - 1)) == 0) { - return 1; - } - int m = 1 << n; - if (k * 2 < m - 1) { - return dfs(n - 1, k); - } - return dfs(n - 1, m - k) ^ 1; - }; - return '0' + dfs(n, k); - } +class Solution { +public: + char findKthBit(int n, int k) { + function dfs = [&](int n, int k) { + if (k == 1) { + return 0; + } + if ((k & (k - 1)) == 0) { + return 1; + } + int m = 1 << n; + if (k * 2 < m - 1) { + return dfs(n - 1, k); + } + return dfs(n - 1, m - k) ^ 1; + }; + return '0' + dfs(n, k); + } }; \ No newline at end of file diff --git a/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/Solution.java b/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/Solution.java index 3b84fa85d9816..067cc590f2658 100644 --- a/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/Solution.java +++ b/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/Solution.java @@ -1,19 +1,19 @@ -class Solution { - public char findKthBit(int n, int k) { - return (char) ('0' + dfs(n, k)); - } - - private int dfs(int n, int k) { - if (k == 1) { - return 0; - } - if ((k & (k - 1)) == 0) { - return 1; - } - int m = 1 << n; - if (k * 2 < m - 1) { - return dfs(n - 1, k); - } - return dfs(n - 1, m - k) ^ 1; - } +class Solution { + public char findKthBit(int n, int k) { + return (char) ('0' + dfs(n, k)); + } + + private int dfs(int n, int k) { + if (k == 1) { + return 0; + } + if ((k & (k - 1)) == 0) { + return 1; + } + int m = 1 << n; + if (k * 2 < m - 1) { + return dfs(n - 1, k); + } + return dfs(n - 1, m - k) ^ 1; + } } \ No newline at end of file diff --git a/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/Solution.py b/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/Solution.py index 39255d33cc1a4..c49cb07387c6e 100644 --- a/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/Solution.py +++ b/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def findKthBit(self, n: int, k: int) -> str: - def dfs(n: int, k: int) -> int: - if k == 1: - return 0 - if (k & (k - 1)) == 0: - return 1 - m = 1 << n - if k * 2 < m - 1: - return dfs(n - 1, k) - return dfs(n - 1, m - k) ^ 1 - - return str(dfs(n, k)) +class Solution: + def findKthBit(self, n: int, k: int) -> str: + def dfs(n: int, k: int) -> int: + if k == 1: + return 0 + if (k & (k - 1)) == 0: + return 1 + m = 1 << n + if k * 2 < m - 1: + return dfs(n - 1, k) + return dfs(n - 1, m - k) ^ 1 + + return str(dfs(n, k)) diff --git a/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/Solution.cpp b/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/Solution.cpp index 8456f320be078..0b8934b573d8b 100644 --- a/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/Solution.cpp +++ b/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - int maxNonOverlapping(vector& nums, int target) { - int ans = 0, n = nums.size(); - for (int i = 0; i < n; ++i) { - unordered_set vis{{0}}; - int s = 0; - while (i < n) { - s += nums[i]; - if (vis.count(s - target)) { - ++ans; - break; - } - ++i; - vis.insert(s); - } - } - return ans; - } +class Solution { +public: + int maxNonOverlapping(vector& nums, int target) { + int ans = 0, n = nums.size(); + for (int i = 0; i < n; ++i) { + unordered_set vis{{0}}; + int s = 0; + while (i < n) { + s += nums[i]; + if (vis.count(s - target)) { + ++ans; + break; + } + ++i; + vis.insert(s); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/Solution.java b/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/Solution.java index ba02bbaa3c53d..0f2306009aaeb 100644 --- a/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/Solution.java +++ b/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/Solution.java @@ -1,20 +1,20 @@ -class Solution { - public int maxNonOverlapping(int[] nums, int target) { - int ans = 0, n = nums.length; - for (int i = 0; i < n; ++i) { - Set vis = new HashSet<>(); - int s = 0; - vis.add(0); - while (i < n) { - s += nums[i]; - if (vis.contains(s - target)) { - ++ans; - break; - } - ++i; - vis.add(s); - } - } - return ans; - } +class Solution { + public int maxNonOverlapping(int[] nums, int target) { + int ans = 0, n = nums.length; + for (int i = 0; i < n; ++i) { + Set vis = new HashSet<>(); + int s = 0; + vis.add(0); + while (i < n) { + s += nums[i]; + if (vis.contains(s - target)) { + ++ans; + break; + } + ++i; + vis.add(s); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/Solution.py b/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/Solution.py index 8370cab581940..ddc7360a51f71 100644 --- a/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/Solution.py +++ b/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/Solution.py @@ -1,16 +1,16 @@ -class Solution: - def maxNonOverlapping(self, nums: List[int], target: int) -> int: - ans = 0 - i, n = 0, len(nums) - while i < n: - s = 0 - vis = {0} - while i < n: - s += nums[i] - if s - target in vis: - ans += 1 - break - i += 1 - vis.add(s) - i += 1 - return ans +class Solution: + def maxNonOverlapping(self, nums: List[int], target: int) -> int: + ans = 0 + i, n = 0, len(nums) + while i < n: + s = 0 + vis = {0} + while i < n: + s += nums[i] + if s - target in vis: + ans += 1 + break + i += 1 + vis.add(s) + i += 1 + return ans diff --git a/solution/1500-1599/1547.Minimum Cost to Cut a Stick/Solution.ts b/solution/1500-1599/1547.Minimum Cost to Cut a Stick/Solution.ts index 9854b194e4c17..8a9e80c03a793 100644 --- a/solution/1500-1599/1547.Minimum Cost to Cut a Stick/Solution.ts +++ b/solution/1500-1599/1547.Minimum Cost to Cut a Stick/Solution.ts @@ -4,9 +4,8 @@ function minCost(n: number, cuts: number[]): number { cuts.sort((a, b) => a - b); const m = cuts.length; const f: number[][] = new Array(m).fill(0).map(() => new Array(m).fill(0)); - for (let l = 2; l < m; ++l) { - for (let i = 0; i + l < m; ++i) { - const j = i + l; + for (let i = m - 2; i >= 0; --i) { + for (let j = i + 2; j < m; ++j) { f[i][j] = 1 << 30; for (let k = i + 1; k < j; ++k) { f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + cuts[j] - cuts[i]); diff --git a/solution/1500-1599/1547.Minimum Cost to Cut a Stick/Solution2.cpp b/solution/1500-1599/1547.Minimum Cost to Cut a Stick/Solution2.cpp new file mode 100644 index 0000000000000..26c7cf87975cc --- /dev/null +++ b/solution/1500-1599/1547.Minimum Cost to Cut a Stick/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int minCost(int n, vector& cuts) { + cuts.push_back(0); + cuts.push_back(n); + sort(cuts.begin(), cuts.end()); + int m = cuts.size(); + int f[110][110]{}; + for (int i = m - 1; ~i; --i) { + for (int j = i + 2; j < m; ++j) { + f[i][j] = 1 << 30; + for (int k = i + 1; k < j; ++k) { + f[i][j] = min(f[i][j], f[i][k] + f[k][j] + cuts[j] - cuts[i]); + } + } + } + return f[0][m - 1]; + } +}; \ No newline at end of file diff --git a/solution/1500-1599/1547.Minimum Cost to Cut a Stick/Solution2.go b/solution/1500-1599/1547.Minimum Cost to Cut a Stick/Solution2.go new file mode 100644 index 0000000000000..6c15d52836b82 --- /dev/null +++ b/solution/1500-1599/1547.Minimum Cost to Cut a Stick/Solution2.go @@ -0,0 +1,18 @@ +func minCost(n int, cuts []int) int { + cuts = append(cuts, []int{0, n}...) + sort.Ints(cuts) + m := len(cuts) + f := make([][]int, m) + for i := range f { + f[i] = make([]int, m) + } + for i := m - 1; i >= 0; i-- { + for j := i + 2; j < m; j++ { + f[i][j] = 1 << 30 + for k := i + 1; k < j; k++ { + f[i][j] = min(f[i][j], f[i][k]+f[k][j]+cuts[j]-cuts[i]) + } + } + } + return f[0][m-1] +} \ No newline at end of file diff --git a/solution/1500-1599/1547.Minimum Cost to Cut a Stick/Solution2.java b/solution/1500-1599/1547.Minimum Cost to Cut a Stick/Solution2.java new file mode 100644 index 0000000000000..8f1636bf5eed7 --- /dev/null +++ b/solution/1500-1599/1547.Minimum Cost to Cut a Stick/Solution2.java @@ -0,0 +1,22 @@ +class Solution { + public int minCost(int n, int[] cuts) { + List nums = new ArrayList<>(); + for (int x : cuts) { + nums.add(x); + } + nums.add(0); + nums.add(n); + Collections.sort(nums); + int m = nums.size(); + int[][] f = new int[m][m]; + for (int i = m - 1; i >= 0; --i) { + for (int j = i + 2; j < m; ++j) { + f[i][j] = 1 << 30; + for (int k = i + 1; k < j; ++k) { + f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + nums.get(j) - nums.get(i)); + } + } + } + return f[0][m - 1]; + } +} \ No newline at end of file diff --git a/solution/1500-1599/1547.Minimum Cost to Cut a Stick/Solution2.py b/solution/1500-1599/1547.Minimum Cost to Cut a Stick/Solution2.py new file mode 100644 index 0000000000000..4accdcb6ab70b --- /dev/null +++ b/solution/1500-1599/1547.Minimum Cost to Cut a Stick/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def minCost(self, n: int, cuts: List[int]) -> int: + cuts.extend([0, n]) + cuts.sort() + m = len(cuts) + f = [[0] * m for _ in range(m)] + for i in range(m - 1, -1, -1): + for j in range(i + 2, m): + f[i][j] = inf + for k in range(i + 1, j): + f[i][j] = min(f[i][j], f[i][k] + f[k][j] + cuts[j] - cuts[i]) + return f[0][-1] diff --git a/solution/1500-1599/1548.The Most Similar Path in a Graph/Solution.cpp b/solution/1500-1599/1548.The Most Similar Path in a Graph/Solution.cpp index 80dbc3032c1cc..138b3c4336763 100644 --- a/solution/1500-1599/1548.The Most Similar Path in a Graph/Solution.cpp +++ b/solution/1500-1599/1548.The Most Similar Path in a Graph/Solution.cpp @@ -1,44 +1,44 @@ -class Solution { -public: - vector mostSimilar(int n, vector>& roads, vector& names, vector& targetPath) { - vector g[n]; - for (auto& r : roads) { - int a = r[0], b = r[1]; - g[a].push_back(b); - g[b].push_back(a); - } - int m = targetPath.size(); - int f[m][n]; - int pre[m][n]; - memset(f, 0x3f, sizeof(f)); - memset(pre, -1, sizeof(pre)); - for (int j = 0; j < n; ++j) { - f[0][j] = targetPath[0] != names[j]; - } - for (int i = 1; i < m; ++i) { - for (int j = 0; j < n; ++j) { - for (int k : g[j]) { - int t = f[i - 1][k] + (targetPath[i] != names[j]); - if (t < f[i][j]) { - f[i][j] = t; - pre[i][j] = k; - } - } - } - } - int k = 0; - int mi = 1 << 30; - for (int j = 0; j < n; ++j) { - if (f[m - 1][j] < mi) { - mi = f[m - 1][j]; - k = j; - } - } - vector ans(m); - for (int i = m - 1; ~i; --i) { - ans[i] = k; - k = pre[i][k]; - } - return ans; - } +class Solution { +public: + vector mostSimilar(int n, vector>& roads, vector& names, vector& targetPath) { + vector g[n]; + for (auto& r : roads) { + int a = r[0], b = r[1]; + g[a].push_back(b); + g[b].push_back(a); + } + int m = targetPath.size(); + int f[m][n]; + int pre[m][n]; + memset(f, 0x3f, sizeof(f)); + memset(pre, -1, sizeof(pre)); + for (int j = 0; j < n; ++j) { + f[0][j] = targetPath[0] != names[j]; + } + for (int i = 1; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k : g[j]) { + int t = f[i - 1][k] + (targetPath[i] != names[j]); + if (t < f[i][j]) { + f[i][j] = t; + pre[i][j] = k; + } + } + } + } + int k = 0; + int mi = 1 << 30; + for (int j = 0; j < n; ++j) { + if (f[m - 1][j] < mi) { + mi = f[m - 1][j]; + k = j; + } + } + vector ans(m); + for (int i = m - 1; ~i; --i) { + ans[i] = k; + k = pre[i][k]; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1500-1599/1548.The Most Similar Path in a Graph/Solution.java b/solution/1500-1599/1548.The Most Similar Path in a Graph/Solution.java index c92eccf679a40..4788b71d9ac12 100644 --- a/solution/1500-1599/1548.The Most Similar Path in a Graph/Solution.java +++ b/solution/1500-1599/1548.The Most Similar Path in a Graph/Solution.java @@ -1,47 +1,47 @@ -class Solution { - public List mostSimilar(int n, int[][] roads, String[] names, String[] targetPath) { - List[] g = new List[n]; - Arrays.setAll(g, i -> new ArrayList<>()); - for (int[] r : roads) { - int a = r[0], b = r[1]; - g[a].add(b); - g[b].add(a); - } - int m = targetPath.length; - final int inf = 1 << 30; - int[][] f = new int[m][n]; - int[][] pre = new int[m][n]; - for (int i = 0; i < m; i++) { - Arrays.fill(f[i], inf); - Arrays.fill(pre[i], -1); - } - for (int j = 0; j < n; ++j) { - f[0][j] = targetPath[0].equals(names[j]) ? 0 : 1; - } - for (int i = 1; i < m; ++i) { - for (int j = 0; j < n; ++j) { - for (int k : g[j]) { - int t = f[i - 1][k] + (targetPath[i].equals(names[j]) ? 0 : 1); - if (t < f[i][j]) { - f[i][j] = t; - pre[i][j] = k; - } - } - } - } - int mi = inf, k = 0; - for (int j = 0; j < n; ++j) { - if (f[m - 1][j] < mi) { - mi = f[m - 1][j]; - k = j; - } - } - List ans = new ArrayList<>(); - for (int i = m - 1; i >= 0; --i) { - ans.add(k); - k = pre[i][k]; - } - Collections.reverse(ans); - return ans; - } +class Solution { + public List mostSimilar(int n, int[][] roads, String[] names, String[] targetPath) { + List[] g = new List[n]; + Arrays.setAll(g, i -> new ArrayList<>()); + for (int[] r : roads) { + int a = r[0], b = r[1]; + g[a].add(b); + g[b].add(a); + } + int m = targetPath.length; + final int inf = 1 << 30; + int[][] f = new int[m][n]; + int[][] pre = new int[m][n]; + for (int i = 0; i < m; i++) { + Arrays.fill(f[i], inf); + Arrays.fill(pre[i], -1); + } + for (int j = 0; j < n; ++j) { + f[0][j] = targetPath[0].equals(names[j]) ? 0 : 1; + } + for (int i = 1; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k : g[j]) { + int t = f[i - 1][k] + (targetPath[i].equals(names[j]) ? 0 : 1); + if (t < f[i][j]) { + f[i][j] = t; + pre[i][j] = k; + } + } + } + } + int mi = inf, k = 0; + for (int j = 0; j < n; ++j) { + if (f[m - 1][j] < mi) { + mi = f[m - 1][j]; + k = j; + } + } + List ans = new ArrayList<>(); + for (int i = m - 1; i >= 0; --i) { + ans.add(k); + k = pre[i][k]; + } + Collections.reverse(ans); + return ans; + } } \ No newline at end of file diff --git a/solution/1500-1599/1548.The Most Similar Path in a Graph/Solution.py b/solution/1500-1599/1548.The Most Similar Path in a Graph/Solution.py index 20c14753e4a2e..0cdadc564c7c3 100644 --- a/solution/1500-1599/1548.The Most Similar Path in a Graph/Solution.py +++ b/solution/1500-1599/1548.The Most Similar Path in a Graph/Solution.py @@ -1,30 +1,30 @@ -class Solution: - def mostSimilar( - self, n: int, roads: List[List[int]], names: List[str], targetPath: List[str] - ) -> List[int]: - g = [[] for _ in range(n)] - for a, b in roads: - g[a].append(b) - g[b].append(a) - m = len(targetPath) - f = [[inf] * n for _ in range(m)] - pre = [[-1] * n for _ in range(m)] - for j, s in enumerate(names): - f[0][j] = targetPath[0] != s - for i in range(1, m): - for j in range(n): - for k in g[j]: - if (t := f[i - 1][k] + (targetPath[i] != names[j])) < f[i][j]: - f[i][j] = t - pre[i][j] = k - k = 0 - mi = inf - for j in range(n): - if f[-1][j] < mi: - mi = f[-1][j] - k = j - ans = [0] * m - for i in range(m - 1, -1, -1): - ans[i] = k - k = pre[i][k] - return ans +class Solution: + def mostSimilar( + self, n: int, roads: List[List[int]], names: List[str], targetPath: List[str] + ) -> List[int]: + g = [[] for _ in range(n)] + for a, b in roads: + g[a].append(b) + g[b].append(a) + m = len(targetPath) + f = [[inf] * n for _ in range(m)] + pre = [[-1] * n for _ in range(m)] + for j, s in enumerate(names): + f[0][j] = targetPath[0] != s + for i in range(1, m): + for j in range(n): + for k in g[j]: + if (t := f[i - 1][k] + (targetPath[i] != names[j])) < f[i][j]: + f[i][j] = t + pre[i][j] = k + k = 0 + mi = inf + for j in range(n): + if f[-1][j] < mi: + mi = f[-1][j] + k = j + ans = [0] * m + for i in range(m - 1, -1, -1): + ans[i] = k + k = pre[i][k] + return ans diff --git a/solution/1500-1599/1550.Three Consecutive Odds/Solution.py b/solution/1500-1599/1550.Three Consecutive Odds/Solution.py index a0fa200a72249..ee2e71c3c26c7 100644 --- a/solution/1500-1599/1550.Three Consecutive Odds/Solution.py +++ b/solution/1500-1599/1550.Three Consecutive Odds/Solution.py @@ -1,6 +1,11 @@ class Solution: def threeConsecutiveOdds(self, arr: List[int]) -> bool: - for i in range(len(arr) - 2): - if arr[i] % 2 + arr[i + 1] % 2 + arr[i + 2] % 2 == 3: + cnt = 0 + for v in arr: + if v & 1: + cnt += 1 + else: + cnt = 0 + if cnt == 3: return True return False diff --git a/solution/1500-1599/1550.Three Consecutive Odds/Solution2.py b/solution/1500-1599/1550.Three Consecutive Odds/Solution2.py new file mode 100644 index 0000000000000..a0fa200a72249 --- /dev/null +++ b/solution/1500-1599/1550.Three Consecutive Odds/Solution2.py @@ -0,0 +1,6 @@ +class Solution: + def threeConsecutiveOdds(self, arr: List[int]) -> bool: + for i in range(len(arr) - 2): + if arr[i] % 2 + arr[i + 1] % 2 + arr[i + 2] % 2 == 3: + return True + return False diff --git a/solution/1500-1599/1552.Magnetic Force Between Two Balls/Solution.cpp b/solution/1500-1599/1552.Magnetic Force Between Two Balls/Solution.cpp index a12dba095bf27..f4a093bf42fce 100644 --- a/solution/1500-1599/1552.Magnetic Force Between Two Balls/Solution.cpp +++ b/solution/1500-1599/1552.Magnetic Force Between Two Balls/Solution.cpp @@ -1,28 +1,28 @@ -class Solution { -public: - int maxDistance(vector& position, int m) { - sort(position.begin(), position.end()); - int left = 1, right = position[position.size() - 1]; - while (left < right) { - int mid = (left + right + 1) >> 1; - if (check(position, mid, m)) - left = mid; - else - right = mid - 1; - } - return left; - } - - bool check(vector& position, int f, int m) { - int prev = position[0]; - int cnt = 1; - for (int i = 1; i < position.size(); ++i) { - int curr = position[i]; - if (curr - prev >= f) { - prev = curr; - ++cnt; - } - } - return cnt >= m; - } +class Solution { +public: + int maxDistance(vector& position, int m) { + sort(position.begin(), position.end()); + int left = 1, right = position[position.size() - 1]; + while (left < right) { + int mid = (left + right + 1) >> 1; + if (check(position, mid, m)) + left = mid; + else + right = mid - 1; + } + return left; + } + + bool check(vector& position, int f, int m) { + int prev = position[0]; + int cnt = 1; + for (int i = 1; i < position.size(); ++i) { + int curr = position[i]; + if (curr - prev >= f) { + prev = curr; + ++cnt; + } + } + return cnt >= m; + } }; \ No newline at end of file diff --git a/solution/1500-1599/1552.Magnetic Force Between Two Balls/Solution.java b/solution/1500-1599/1552.Magnetic Force Between Two Balls/Solution.java index 39e849786e651..20bb5e01d489d 100644 --- a/solution/1500-1599/1552.Magnetic Force Between Two Balls/Solution.java +++ b/solution/1500-1599/1552.Magnetic Force Between Two Balls/Solution.java @@ -1,28 +1,28 @@ -class Solution { - public int maxDistance(int[] position, int m) { - Arrays.sort(position); - int left = 1, right = position[position.length - 1]; - while (left < right) { - int mid = (left + right + 1) >>> 1; - if (check(position, mid, m)) { - left = mid; - } else { - right = mid - 1; - } - } - return left; - } - - private boolean check(int[] position, int f, int m) { - int prev = position[0]; - int cnt = 1; - for (int i = 1; i < position.length; ++i) { - int curr = position[i]; - if (curr - prev >= f) { - prev = curr; - ++cnt; - } - } - return cnt >= m; - } +class Solution { + public int maxDistance(int[] position, int m) { + Arrays.sort(position); + int left = 1, right = position[position.length - 1]; + while (left < right) { + int mid = (left + right + 1) >>> 1; + if (check(position, mid, m)) { + left = mid; + } else { + right = mid - 1; + } + } + return left; + } + + private boolean check(int[] position, int f, int m) { + int prev = position[0]; + int cnt = 1; + for (int i = 1; i < position.length; ++i) { + int curr = position[i]; + if (curr - prev >= f) { + prev = curr; + ++cnt; + } + } + return cnt >= m; + } } \ No newline at end of file diff --git a/solution/1500-1599/1552.Magnetic Force Between Two Balls/Solution.py b/solution/1500-1599/1552.Magnetic Force Between Two Balls/Solution.py index d6dd8a99296a5..1aef515d52e7f 100644 --- a/solution/1500-1599/1552.Magnetic Force Between Two Balls/Solution.py +++ b/solution/1500-1599/1552.Magnetic Force Between Two Balls/Solution.py @@ -1,21 +1,21 @@ -class Solution: - def maxDistance(self, position: List[int], m: int) -> int: - def check(f): - prev = position[0] - cnt = 1 - for curr in position[1:]: - if curr - prev >= f: - prev = curr - cnt += 1 - return cnt >= m - - position.sort() - left, right = 1, position[-1] - while left < right: - mid = (left + right + 1) >> 1 - - if check(mid): - left = mid - else: - right = mid - 1 - return left +class Solution: + def maxDistance(self, position: List[int], m: int) -> int: + def check(f): + prev = position[0] + cnt = 1 + for curr in position[1:]: + if curr - prev >= f: + prev = curr + cnt += 1 + return cnt >= m + + position.sort() + left, right = 1, position[-1] + while left < right: + mid = (left + right + 1) >> 1 + + if check(mid): + left = mid + else: + right = mid - 1 + return left diff --git a/solution/1500-1599/1561.Maximum Number of Coins You Can Get/Solution.c b/solution/1500-1599/1561.Maximum Number of Coins You Can Get/Solution.c index af50fe2fd20f9..03c4ca746fd4f 100644 --- a/solution/1500-1599/1561.Maximum Number of Coins You Can Get/Solution.c +++ b/solution/1500-1599/1561.Maximum Number of Coins You Can Get/Solution.c @@ -9,4 +9,4 @@ int maxCoins(int* piles, int pilesSize) { ans += piles[pilesSize - 2 * i]; }; return ans; -} +} \ No newline at end of file diff --git a/solution/1500-1599/1561.Maximum Number of Coins You Can Get/Solution.java b/solution/1500-1599/1561.Maximum Number of Coins You Can Get/Solution.java index 88bad0bd291f1..37427886c5322 100644 --- a/solution/1500-1599/1561.Maximum Number of Coins You Can Get/Solution.java +++ b/solution/1500-1599/1561.Maximum Number of Coins You Can Get/Solution.java @@ -1,4 +1,5 @@ class Solution { + public int maxCoins(int[] piles) { Arrays.sort(piles); int ans = 0; diff --git a/solution/1500-1599/1562.Find Latest Group of Size M/Solution.cpp b/solution/1500-1599/1562.Find Latest Group of Size M/Solution.cpp index 31d9a0f6812df..4bfeff8e0df8e 100644 --- a/solution/1500-1599/1562.Find Latest Group of Size M/Solution.cpp +++ b/solution/1500-1599/1562.Find Latest Group of Size M/Solution.cpp @@ -1,16 +1,40 @@ class Solution { public: + vector p; + vector size; + int findLatestStep(vector& arr, int m) { int n = arr.size(); if (m == n) return n; - vector cnt(n + 2); + p.resize(n); + size.assign(n, 1); + for (int i = 0; i < n; ++i) p[i] = i; int ans = -1; + vector vis(n); for (int i = 0; i < n; ++i) { - int v = arr[i]; - int l = cnt[v - 1], r = cnt[v + 1]; - if (l == m || r == m) ans = i; - cnt[v - l] = cnt[v + r] = l + r + 1; + int v = arr[i] - 1; + if (v && vis[v - 1]) { + if (size[find(v - 1)] == m) ans = i; + unite(v, v - 1); + } + if (v < n - 1 && vis[v + 1]) { + if (size[find(v + 1)] == m) ans = i; + unite(v, v + 1); + } + vis[v] = true; } return ans; } + + int find(int x) { + if (p[x] != x) p[x] = find(p[x]); + return p[x]; + } + + void unite(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) return; + p[pa] = pb; + size[pb] += size[pa]; + } }; \ No newline at end of file diff --git a/solution/1500-1599/1562.Find Latest Group of Size M/Solution.go b/solution/1500-1599/1562.Find Latest Group of Size M/Solution.go index d237d3761b927..f21fb218dbc1a 100644 --- a/solution/1500-1599/1562.Find Latest Group of Size M/Solution.go +++ b/solution/1500-1599/1562.Find Latest Group of Size M/Solution.go @@ -3,14 +3,45 @@ func findLatestStep(arr []int, m int) int { if m == n { return n } - cnt := make([]int, n+2) + p := make([]int, n) + size := make([]int, n) + vis := make([]bool, n) + for i := range p { + p[i] = i + size[i] = 1 + } + var find func(int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + union := func(a, b int) { + pa, pb := find(a), find(b) + if pa == pb { + return + } + p[pa] = pb + size[pb] += size[pa] + } + ans := -1 for i, v := range arr { - l, r := cnt[v-1], cnt[v+1] - if l == m || r == m { - ans = i + v-- + if v > 0 && vis[v-1] { + if size[find(v-1)] == m { + ans = i + } + union(v, v-1) + } + if v < n-1 && vis[v+1] { + if size[find(v+1)] == m { + ans = i + } + union(v, v+1) } - cnt[v-l], cnt[v+r] = l+r+1, l+r+1 + vis[v] = true } return ans } \ No newline at end of file diff --git a/solution/1500-1599/1562.Find Latest Group of Size M/Solution.java b/solution/1500-1599/1562.Find Latest Group of Size M/Solution.java index ad4b334667ff3..63a934e48d559 100644 --- a/solution/1500-1599/1562.Find Latest Group of Size M/Solution.java +++ b/solution/1500-1599/1562.Find Latest Group of Size M/Solution.java @@ -1,20 +1,52 @@ class Solution { + private int[] p; + private int[] size; + public int findLatestStep(int[] arr, int m) { int n = arr.length; if (m == n) { return n; } - int[] cnt = new int[n + 2]; + boolean[] vis = new boolean[n]; + p = new int[n]; + size = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + size[i] = 1; + } int ans = -1; for (int i = 0; i < n; ++i) { - int v = arr[i]; - int l = cnt[v - 1], r = cnt[v + 1]; - if (l == m || r == m) { - ans = i; + int v = arr[i] - 1; + if (v > 0 && vis[v - 1]) { + if (size[find(v - 1)] == m) { + ans = i; + } + union(v, v - 1); } - cnt[v - l] = l + r + 1; - cnt[v + r] = l + r + 1; + if (v < n - 1 && vis[v + 1]) { + if (size[find(v + 1)] == m) { + ans = i; + } + union(v, v + 1); + } + vis[v] = true; } return ans; } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + + private void union(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) { + return; + } + p[pa] = pb; + size[pb] += size[pa]; + } } \ No newline at end of file diff --git a/solution/1500-1599/1562.Find Latest Group of Size M/Solution.py b/solution/1500-1599/1562.Find Latest Group of Size M/Solution.py index 6a61291434534..baa3597db0bde 100644 --- a/solution/1500-1599/1562.Find Latest Group of Size M/Solution.py +++ b/solution/1500-1599/1562.Find Latest Group of Size M/Solution.py @@ -1,14 +1,33 @@ class Solution: def findLatestStep(self, arr: List[int], m: int) -> int: + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + def union(a, b): + pa, pb = find(a), find(b) + if pa == pb: + return + p[pa] = pb + size[pb] += size[pa] + n = len(arr) if m == n: return n - cnt = [0] * (n + 2) + vis = [False] * n + p = list(range(n)) + size = [1] * n ans = -1 for i, v in enumerate(arr): v -= 1 - l, r = cnt[v - 1], cnt[v + 1] - if l == m or r == m: - ans = i - cnt[v - l] = cnt[v + r] = l + r + 1 + if v and vis[v - 1]: + if size[find(v - 1)] == m: + ans = i + union(v, v - 1) + if v < n - 1 and vis[v + 1]: + if size[find(v + 1)] == m: + ans = i + union(v, v + 1) + vis[v] = True return ans diff --git a/solution/1500-1599/1562.Find Latest Group of Size M/Solution2.cpp b/solution/1500-1599/1562.Find Latest Group of Size M/Solution2.cpp new file mode 100644 index 0000000000000..31d9a0f6812df --- /dev/null +++ b/solution/1500-1599/1562.Find Latest Group of Size M/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int findLatestStep(vector& arr, int m) { + int n = arr.size(); + if (m == n) return n; + vector cnt(n + 2); + int ans = -1; + for (int i = 0; i < n; ++i) { + int v = arr[i]; + int l = cnt[v - 1], r = cnt[v + 1]; + if (l == m || r == m) ans = i; + cnt[v - l] = cnt[v + r] = l + r + 1; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1500-1599/1562.Find Latest Group of Size M/Solution2.go b/solution/1500-1599/1562.Find Latest Group of Size M/Solution2.go new file mode 100644 index 0000000000000..d237d3761b927 --- /dev/null +++ b/solution/1500-1599/1562.Find Latest Group of Size M/Solution2.go @@ -0,0 +1,16 @@ +func findLatestStep(arr []int, m int) int { + n := len(arr) + if m == n { + return n + } + cnt := make([]int, n+2) + ans := -1 + for i, v := range arr { + l, r := cnt[v-1], cnt[v+1] + if l == m || r == m { + ans = i + } + cnt[v-l], cnt[v+r] = l+r+1, l+r+1 + } + return ans +} \ No newline at end of file diff --git a/solution/1500-1599/1562.Find Latest Group of Size M/Solution2.java b/solution/1500-1599/1562.Find Latest Group of Size M/Solution2.java new file mode 100644 index 0000000000000..ad4b334667ff3 --- /dev/null +++ b/solution/1500-1599/1562.Find Latest Group of Size M/Solution2.java @@ -0,0 +1,20 @@ +class Solution { + public int findLatestStep(int[] arr, int m) { + int n = arr.length; + if (m == n) { + return n; + } + int[] cnt = new int[n + 2]; + int ans = -1; + for (int i = 0; i < n; ++i) { + int v = arr[i]; + int l = cnt[v - 1], r = cnt[v + 1]; + if (l == m || r == m) { + ans = i; + } + cnt[v - l] = l + r + 1; + cnt[v + r] = l + r + 1; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1500-1599/1562.Find Latest Group of Size M/Solution2.py b/solution/1500-1599/1562.Find Latest Group of Size M/Solution2.py new file mode 100644 index 0000000000000..6a61291434534 --- /dev/null +++ b/solution/1500-1599/1562.Find Latest Group of Size M/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def findLatestStep(self, arr: List[int], m: int) -> int: + n = len(arr) + if m == n: + return n + cnt = [0] * (n + 2) + ans = -1 + for i, v in enumerate(arr): + v -= 1 + l, r = cnt[v - 1], cnt[v + 1] + if l == m or r == m: + ans = i + cnt[v - l] = cnt[v + r] = l + r + 1 + return ans diff --git a/solution/1500-1599/1564.Put Boxes Into the Warehouse I/Solution.cpp b/solution/1500-1599/1564.Put Boxes Into the Warehouse I/Solution.cpp index 6fea641a4b04e..9bd1026c5c748 100644 --- a/solution/1500-1599/1564.Put Boxes Into the Warehouse I/Solution.cpp +++ b/solution/1500-1599/1564.Put Boxes Into the Warehouse I/Solution.cpp @@ -1,24 +1,24 @@ -class Solution { -public: - int maxBoxesInWarehouse(vector& boxes, vector& warehouse) { - int n = warehouse.size(); - int left[n]; - left[0] = warehouse[0]; - for (int i = 1; i < n; ++i) { - left[i] = min(left[i - 1], warehouse[i]); - } - sort(boxes.begin(), boxes.end()); - int i = 0, j = n - 1; - while (i < boxes.size()) { - while (j >= 0 && left[j] < boxes[i]) { - --j; - } - if (j < 0) { - break; - } - ++i; - --j; - } - return i; - } +class Solution { +public: + int maxBoxesInWarehouse(vector& boxes, vector& warehouse) { + int n = warehouse.size(); + int left[n]; + left[0] = warehouse[0]; + for (int i = 1; i < n; ++i) { + left[i] = min(left[i - 1], warehouse[i]); + } + sort(boxes.begin(), boxes.end()); + int i = 0, j = n - 1; + while (i < boxes.size()) { + while (j >= 0 && left[j] < boxes[i]) { + --j; + } + if (j < 0) { + break; + } + ++i; + --j; + } + return i; + } }; \ No newline at end of file diff --git a/solution/1500-1599/1564.Put Boxes Into the Warehouse I/Solution.java b/solution/1500-1599/1564.Put Boxes Into the Warehouse I/Solution.java index 8aff34fb1ec5c..495499145a087 100644 --- a/solution/1500-1599/1564.Put Boxes Into the Warehouse I/Solution.java +++ b/solution/1500-1599/1564.Put Boxes Into the Warehouse I/Solution.java @@ -1,23 +1,23 @@ -class Solution { - public int maxBoxesInWarehouse(int[] boxes, int[] warehouse) { - int n = warehouse.length; - int[] left = new int[n]; - left[0] = warehouse[0]; - for (int i = 1; i < n; ++i) { - left[i] = Math.min(left[i - 1], warehouse[i]); - } - Arrays.sort(boxes); - int i = 0, j = n - 1; - while (i < boxes.length) { - while (j >= 0 && left[j] < boxes[i]) { - --j; - } - if (j < 0) { - break; - } - ++i; - --j; - } - return i; - } +class Solution { + public int maxBoxesInWarehouse(int[] boxes, int[] warehouse) { + int n = warehouse.length; + int[] left = new int[n]; + left[0] = warehouse[0]; + for (int i = 1; i < n; ++i) { + left[i] = Math.min(left[i - 1], warehouse[i]); + } + Arrays.sort(boxes); + int i = 0, j = n - 1; + while (i < boxes.length) { + while (j >= 0 && left[j] < boxes[i]) { + --j; + } + if (j < 0) { + break; + } + ++i; + --j; + } + return i; + } } \ No newline at end of file diff --git a/solution/1500-1599/1564.Put Boxes Into the Warehouse I/Solution.py b/solution/1500-1599/1564.Put Boxes Into the Warehouse I/Solution.py index 4ba914ce8debe..8e58fd3e8db2c 100644 --- a/solution/1500-1599/1564.Put Boxes Into the Warehouse I/Solution.py +++ b/solution/1500-1599/1564.Put Boxes Into the Warehouse I/Solution.py @@ -1,15 +1,15 @@ -class Solution: - def maxBoxesInWarehouse(self, boxes: List[int], warehouse: List[int]) -> int: - n = len(warehouse) - left = [warehouse[0]] * n - for i in range(1, n): - left[i] = min(left[i - 1], warehouse[i]) - boxes.sort() - i, j = 0, n - 1 - while i < len(boxes): - while j >= 0 and left[j] < boxes[i]: - j -= 1 - if j < 0: - break - i, j = i + 1, j - 1 - return i +class Solution: + def maxBoxesInWarehouse(self, boxes: List[int], warehouse: List[int]) -> int: + n = len(warehouse) + left = [warehouse[0]] * n + for i in range(1, n): + left[i] = min(left[i - 1], warehouse[i]) + boxes.sort() + i, j = 0, n - 1 + while i < len(boxes): + while j >= 0 and left[j] < boxes[i]: + j -= 1 + if j < 0: + break + i, j = i + 1, j - 1 + return i diff --git a/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/Solution.cpp b/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/Solution.cpp index 25f956dd22998..f50ea39a27057 100644 --- a/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/Solution.cpp +++ b/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/Solution.cpp @@ -1,33 +1,33 @@ -class SparseVector { -public: - unordered_map d; - - SparseVector(vector& nums) { - for (int i = 0; i < nums.size(); ++i) { - if (nums[i]) { - d[i] = nums[i]; - } - } - } - - // Return the dotProduct of two sparse vectors - int dotProduct(SparseVector& vec) { - auto a = d; - auto b = vec.d; - if (a.size() > b.size()) { - swap(a, b); - } - int ans = 0; - for (auto& [i, v] : a) { - if (b.count(i)) { - ans += v * b[i]; - } - } - return ans; - } -}; - -// Your SparseVector object will be instantiated and called as such: -// SparseVector v1(nums1); -// SparseVector v2(nums2); +class SparseVector { +public: + unordered_map d; + + SparseVector(vector& nums) { + for (int i = 0; i < nums.size(); ++i) { + if (nums[i]) { + d[i] = nums[i]; + } + } + } + + // Return the dotProduct of two sparse vectors + int dotProduct(SparseVector& vec) { + auto a = d; + auto b = vec.d; + if (a.size() > b.size()) { + swap(a, b); + } + int ans = 0; + for (auto& [i, v] : a) { + if (b.count(i)) { + ans += v * b[i]; + } + } + return ans; + } +}; + +// Your SparseVector object will be instantiated and called as such: +// SparseVector v1(nums1); +// SparseVector v2(nums2); // int ans = v1.dotProduct(v2); \ No newline at end of file diff --git a/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/Solution.java b/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/Solution.java index ca1116e9e5ff9..5ceaec0ba1550 100644 --- a/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/Solution.java +++ b/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/Solution.java @@ -1,33 +1,33 @@ -class SparseVector { - public Map d = new HashMap<>(128); - - SparseVector(int[] nums) { - for (int i = 0; i < nums.length; ++i) { - if (nums[i] != 0) { - d.put(i, nums[i]); - } - } - } - - // Return the dotProduct of two sparse vectors - public int dotProduct(SparseVector vec) { - var a = d; - var b = vec.d; - if (b.size() < a.size()) { - var t = a; - a = b; - b = t; - } - int ans = 0; - for (var e : a.entrySet()) { - int i = e.getKey(), v = e.getValue(); - ans += v * b.getOrDefault(i, 0); - } - return ans; - } -} - -// Your SparseVector object will be instantiated and called as such: -// SparseVector v1 = new SparseVector(nums1); -// SparseVector v2 = new SparseVector(nums2); +class SparseVector { + public Map d = new HashMap<>(128); + + SparseVector(int[] nums) { + for (int i = 0; i < nums.length; ++i) { + if (nums[i] != 0) { + d.put(i, nums[i]); + } + } + } + + // Return the dotProduct of two sparse vectors + public int dotProduct(SparseVector vec) { + var a = d; + var b = vec.d; + if (b.size() < a.size()) { + var t = a; + a = b; + b = t; + } + int ans = 0; + for (var e : a.entrySet()) { + int i = e.getKey(), v = e.getValue(); + ans += v * b.getOrDefault(i, 0); + } + return ans; + } +} + +// Your SparseVector object will be instantiated and called as such: +// SparseVector v1 = new SparseVector(nums1); +// SparseVector v2 = new SparseVector(nums2); // int ans = v1.dotProduct(v2); \ No newline at end of file diff --git a/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/Solution.py b/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/Solution.py index 42d7430e81e43..6a65f0236f7e4 100644 --- a/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/Solution.py +++ b/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/Solution.py @@ -1,16 +1,16 @@ -class SparseVector: - def __init__(self, nums: List[int]): - self.d = {i: v for i, v in enumerate(nums) if v} - - # Return the dotProduct of two sparse vectors - def dotProduct(self, vec: "SparseVector") -> int: - a, b = self.d, vec.d - if len(b) < len(a): - a, b = b, a - return sum(v * b.get(i, 0) for i, v in a.items()) - - -# Your SparseVector object will be instantiated and called as such: -# v1 = SparseVector(nums1) -# v2 = SparseVector(nums2) -# ans = v1.dotProduct(v2) +class SparseVector: + def __init__(self, nums: List[int]): + self.d = {i: v for i, v in enumerate(nums) if v} + + # Return the dotProduct of two sparse vectors + def dotProduct(self, vec: "SparseVector") -> int: + a, b = self.d, vec.d + if len(b) < len(a): + a, b = b, a + return sum(v * b.get(i, 0) for i, v in a.items()) + + +# Your SparseVector object will be instantiated and called as such: +# v1 = SparseVector(nums1) +# v2 = SparseVector(nums2) +# ans = v1.dotProduct(v2) diff --git a/solution/1500-1599/1572.Matrix Diagonal Sum/Solution.c b/solution/1500-1599/1572.Matrix Diagonal Sum/Solution.c index 6c02325eed294..0e490859aa992 100644 --- a/solution/1500-1599/1572.Matrix Diagonal Sum/Solution.c +++ b/solution/1500-1599/1572.Matrix Diagonal Sum/Solution.c @@ -7,4 +7,4 @@ int diagonalSum(int** mat, int matSize, int* matColSize) { ans -= mat[matSize >> 1][matSize >> 1]; } return ans; -} +} \ No newline at end of file diff --git a/solution/1500-1599/1572.Matrix Diagonal Sum/Solution.ts b/solution/1500-1599/1572.Matrix Diagonal Sum/Solution.ts index e870aa932ff9f..d9f756d4464f2 100644 --- a/solution/1500-1599/1572.Matrix Diagonal Sum/Solution.ts +++ b/solution/1500-1599/1572.Matrix Diagonal Sum/Solution.ts @@ -1,11 +1,9 @@ function diagonalSum(mat: number[][]): number { - const n = mat.length; let ans = 0; - for (let i = 0; i < n; i++) { - ans += mat[i][i] + mat[i][n - 1 - i]; - } - if (n & 1) { - ans -= mat[n >> 1][n >> 1]; + const n = mat.length; + for (let i = 0; i < n; ++i) { + const j = n - i - 1; + ans += mat[i][i] + (i === j ? 0 : mat[i][j]); } return ans; } diff --git a/solution/1500-1599/1572.Matrix Diagonal Sum/Solution2.ts b/solution/1500-1599/1572.Matrix Diagonal Sum/Solution2.ts new file mode 100644 index 0000000000000..e870aa932ff9f --- /dev/null +++ b/solution/1500-1599/1572.Matrix Diagonal Sum/Solution2.ts @@ -0,0 +1,11 @@ +function diagonalSum(mat: number[][]): number { + const n = mat.length; + let ans = 0; + for (let i = 0; i < n; i++) { + ans += mat[i][i] + mat[i][n - 1 - i]; + } + if (n & 1) { + ans -= mat[n >> 1][n >> 1]; + } + return ans; +} diff --git a/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution.cpp b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution.cpp index 2dcbe39cff8ea..17335e0e82356 100644 --- a/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution.cpp +++ b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution.cpp @@ -13,10 +13,8 @@ class Solution { return 0; } int ans = min(n - 1 - i, j); - for (int l = 0, r = j; l <= i; ++l) { - while (r < n && arr[r] < arr[l]) { - ++r; - } + for (int l = 0; l <= i; ++l) { + int r = lower_bound(arr.begin() + j, arr.end(), arr[l]) - arr.begin(); ans = min(ans, r - l - 1); } return ans; diff --git a/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution.go b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution.go index 1289d4591404e..3c8a1cd30d11c 100644 --- a/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution.go +++ b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution.go @@ -11,11 +11,8 @@ func findLengthOfShortestSubarray(arr []int) int { return 0 } ans := min(n-i-1, j) - r := j for l := 0; l <= i; l++ { - for r < n && arr[r] < arr[l] { - r += 1 - } + r := j + sort.SearchInts(arr[j:], arr[l]) ans = min(ans, r-l-1) } return ans diff --git a/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution.java b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution.java index 7fb41378e53a9..3b2a54c44d588 100644 --- a/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution.java +++ b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution.java @@ -12,12 +12,23 @@ public int findLengthOfShortestSubarray(int[] arr) { return 0; } int ans = Math.min(n - i - 1, j); - for (int l = 0, r = j; l <= i; ++l) { - while (r < n && arr[r] < arr[l]) { - ++r; - } + for (int l = 0; l <= i; ++l) { + int r = search(arr, arr[l], j); ans = Math.min(ans, r - l - 1); } return ans; } + + private int search(int[] arr, int x, int left) { + int right = arr.length; + while (left < right) { + int mid = (left + right) >> 1; + if (arr[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } } \ No newline at end of file diff --git a/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution.py b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution.py index d6f78ceec845d..c2307a3765dde 100644 --- a/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution.py +++ b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution.py @@ -9,9 +9,7 @@ def findLengthOfShortestSubarray(self, arr: List[int]) -> int: if i >= j: return 0 ans = min(n - i - 1, j) - r = j for l in range(i + 1): - while r < n and arr[r] < arr[l]: - r += 1 + r = bisect_left(arr, arr[l], lo=j) ans = min(ans, r - l - 1) return ans diff --git a/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution2.cpp b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution2.cpp new file mode 100644 index 0000000000000..2dcbe39cff8ea --- /dev/null +++ b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution2.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int findLengthOfShortestSubarray(vector& arr) { + int n = arr.size(); + int i = 0, j = n - 1; + while (i + 1 < n && arr[i] <= arr[i + 1]) { + ++i; + } + while (j - 1 >= 0 && arr[j - 1] <= arr[j]) { + --j; + } + if (i >= j) { + return 0; + } + int ans = min(n - 1 - i, j); + for (int l = 0, r = j; l <= i; ++l) { + while (r < n && arr[r] < arr[l]) { + ++r; + } + ans = min(ans, r - l - 1); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution2.go b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution2.go new file mode 100644 index 0000000000000..1289d4591404e --- /dev/null +++ b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution2.go @@ -0,0 +1,22 @@ +func findLengthOfShortestSubarray(arr []int) int { + n := len(arr) + i, j := 0, n-1 + for i+1 < n && arr[i] <= arr[i+1] { + i++ + } + for j-1 >= 0 && arr[j-1] <= arr[j] { + j-- + } + if i >= j { + return 0 + } + ans := min(n-i-1, j) + r := j + for l := 0; l <= i; l++ { + for r < n && arr[r] < arr[l] { + r += 1 + } + ans = min(ans, r-l-1) + } + return ans +} \ No newline at end of file diff --git a/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution2.java b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution2.java new file mode 100644 index 0000000000000..7fb41378e53a9 --- /dev/null +++ b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution2.java @@ -0,0 +1,23 @@ +class Solution { + public int findLengthOfShortestSubarray(int[] arr) { + int n = arr.length; + int i = 0, j = n - 1; + while (i + 1 < n && arr[i] <= arr[i + 1]) { + ++i; + } + while (j - 1 >= 0 && arr[j - 1] <= arr[j]) { + --j; + } + if (i >= j) { + return 0; + } + int ans = Math.min(n - i - 1, j); + for (int l = 0, r = j; l <= i; ++l) { + while (r < n && arr[r] < arr[l]) { + ++r; + } + ans = Math.min(ans, r - l - 1); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution2.py b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution2.py new file mode 100644 index 0000000000000..d6f78ceec845d --- /dev/null +++ b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def findLengthOfShortestSubarray(self, arr: List[int]) -> int: + n = len(arr) + i, j = 0, n - 1 + while i + 1 < n and arr[i] <= arr[i + 1]: + i += 1 + while j - 1 >= 0 and arr[j - 1] <= arr[j]: + j -= 1 + if i >= j: + return 0 + ans = min(n - i - 1, j) + r = j + for l in range(i + 1): + while r < n and arr[r] < arr[l]: + r += 1 + ans = min(ans, r - l - 1) + return ans diff --git a/solution/1500-1599/1575.Count All Possible Routes/Solution2.cpp b/solution/1500-1599/1575.Count All Possible Routes/Solution2.cpp new file mode 100644 index 0000000000000..59a71917c6d0e --- /dev/null +++ b/solution/1500-1599/1575.Count All Possible Routes/Solution2.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int countRoutes(vector& locations, int start, int finish, int fuel) { + const int mod = 1e9 + 7; + int n = locations.size(); + int f[n][fuel + 1]; + memset(f, 0, sizeof(f)); + for (int k = 0; k <= fuel; ++k) { + f[finish][k] = 1; + } + for (int k = 0; k <= fuel; ++k) { + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (j != i && abs(locations[i] - locations[j]) <= k) { + f[i][k] = (f[i][k] + f[j][k - abs(locations[i] - locations[j])]) % mod; + } + } + } + } + return f[start][fuel]; + } +}; \ No newline at end of file diff --git a/solution/1500-1599/1575.Count All Possible Routes/Solution2.go b/solution/1500-1599/1575.Count All Possible Routes/Solution2.go new file mode 100644 index 0000000000000..3ba3cd40b9213 --- /dev/null +++ b/solution/1500-1599/1575.Count All Possible Routes/Solution2.go @@ -0,0 +1,28 @@ +func countRoutes(locations []int, start int, finish int, fuel int) int { + n := len(locations) + const mod = 1e9 + 7 + f := make([][]int, n) + for i := range f { + f[i] = make([]int, fuel+1) + } + for k := 0; k <= fuel; k++ { + f[finish][k] = 1 + } + for k := 0; k <= fuel; k++ { + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + if j != i && abs(locations[i]-locations[j]) <= k { + f[i][k] = (f[i][k] + f[j][k-abs(locations[i]-locations[j])]) % mod + } + } + } + } + return f[start][fuel] +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} \ No newline at end of file diff --git a/solution/1500-1599/1575.Count All Possible Routes/Solution2.java b/solution/1500-1599/1575.Count All Possible Routes/Solution2.java new file mode 100644 index 0000000000000..5a4aaf3392328 --- /dev/null +++ b/solution/1500-1599/1575.Count All Possible Routes/Solution2.java @@ -0,0 +1,20 @@ +class Solution { + public int countRoutes(int[] locations, int start, int finish, int fuel) { + final int mod = (int) 1e9 + 7; + int n = locations.length; + int[][] f = new int[n][fuel + 1]; + for (int k = 0; k <= fuel; ++k) { + f[finish][k] = 1; + } + for (int k = 0; k <= fuel; ++k) { + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (j != i && Math.abs(locations[i] - locations[j]) <= k) { + f[i][k] = (f[i][k] + f[j][k - Math.abs(locations[i] - locations[j])]) % mod; + } + } + } + } + return f[start][fuel]; + } +} \ No newline at end of file diff --git a/solution/1500-1599/1575.Count All Possible Routes/Solution2.py b/solution/1500-1599/1575.Count All Possible Routes/Solution2.py new file mode 100644 index 0000000000000..dfa5bf229e901 --- /dev/null +++ b/solution/1500-1599/1575.Count All Possible Routes/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def countRoutes( + self, locations: List[int], start: int, finish: int, fuel: int + ) -> int: + mod = 10**9 + 7 + n = len(locations) + f = [[0] * (fuel + 1) for _ in range(n)] + for k in range(fuel + 1): + f[finish][k] = 1 + for k in range(fuel + 1): + for i in range(n): + for j in range(n): + if j != i and abs(locations[i] - locations[j]) <= k: + f[i][k] = ( + f[i][k] + f[j][k - abs(locations[i] - locations[j])] + ) % mod + return f[start][fuel] diff --git a/solution/1500-1599/1575.Count All Possible Routes/Solution2.ts b/solution/1500-1599/1575.Count All Possible Routes/Solution2.ts new file mode 100644 index 0000000000000..f1b63a69fed89 --- /dev/null +++ b/solution/1500-1599/1575.Count All Possible Routes/Solution2.ts @@ -0,0 +1,18 @@ +function countRoutes(locations: number[], start: number, finish: number, fuel: number): number { + const n = locations.length; + const f = Array.from({ length: n }, () => Array(fuel + 1).fill(0)); + for (let k = 0; k <= fuel; ++k) { + f[finish][k] = 1; + } + const mod = 1e9 + 7; + for (let k = 0; k <= fuel; ++k) { + for (let i = 0; i < n; ++i) { + for (let j = 0; j < n; ++j) { + if (j !== i && Math.abs(locations[i] - locations[j]) <= k) { + f[i][k] = (f[i][k] + f[j][k - Math.abs(locations[i] - locations[j])]) % mod; + } + } + } + } + return f[start][fuel]; +} diff --git a/solution/1500-1599/1581.Customer Who Visited but Did Not Make Any Transactions/Solution.sql b/solution/1500-1599/1581.Customer Who Visited but Did Not Make Any Transactions/Solution.sql index a10764142ed97..c0716dec26880 100644 --- a/solution/1500-1599/1581.Customer Who Visited but Did Not Make Any Transactions/Solution.sql +++ b/solution/1500-1599/1581.Customer Who Visited but Did Not Make Any Transactions/Solution.sql @@ -1,7 +1,5 @@ # Write your MySQL query statement below SELECT customer_id, COUNT(1) AS count_no_trans -FROM - Visits - LEFT JOIN Transactions USING (visit_id) -WHERE amount IS NULL +FROM Visits +WHERE visit_id NOT IN (SELECT visit_id FROM Transactions) GROUP BY 1; diff --git a/solution/1500-1599/1581.Customer Who Visited but Did Not Make Any Transactions/Solution2.sql b/solution/1500-1599/1581.Customer Who Visited but Did Not Make Any Transactions/Solution2.sql new file mode 100644 index 0000000000000..a10764142ed97 --- /dev/null +++ b/solution/1500-1599/1581.Customer Who Visited but Did Not Make Any Transactions/Solution2.sql @@ -0,0 +1,7 @@ +# Write your MySQL query statement below +SELECT customer_id, COUNT(1) AS count_no_trans +FROM + Visits + LEFT JOIN Transactions USING (visit_id) +WHERE amount IS NULL +GROUP BY 1; diff --git a/solution/1500-1599/1582.Special Positions in a Binary Matrix/Solution.c b/solution/1500-1599/1582.Special Positions in a Binary Matrix/Solution.c index 296dbb02ca9e5..8b2a0f1053708 100644 --- a/solution/1500-1599/1582.Special Positions in a Binary Matrix/Solution.c +++ b/solution/1500-1599/1582.Special Positions in a Binary Matrix/Solution.c @@ -24,4 +24,4 @@ int numSpecial(int** mat, int matSize, int* matColSize) { free(rows); free(cols); return res; -} +} \ No newline at end of file diff --git a/solution/1500-1599/1584.Min Cost to Connect All Points/Solution.cpp b/solution/1500-1599/1584.Min Cost to Connect All Points/Solution.cpp index 0bb0330320e72..884972c23b74b 100644 --- a/solution/1500-1599/1584.Min Cost to Connect All Points/Solution.cpp +++ b/solution/1500-1599/1584.Min Cost to Connect All Points/Solution.cpp @@ -1,38 +1,38 @@ -class Solution { -public: - int minCostConnectPoints(vector>& points) { - int n = points.size(); - int g[n][n]; - for (int i = 0; i < n; ++i) { - int x1 = points[i][0], y1 = points[i][1]; - for (int j = i + 1; j < n; ++j) { - int x2 = points[j][0], y2 = points[j][1]; - int t = abs(x1 - x2) + abs(y1 - y2); - g[i][j] = t; - g[j][i] = t; - } - } - int dist[n]; - bool vis[n]; - memset(dist, 0x3f, sizeof(dist)); - memset(vis, false, sizeof(vis)); - dist[0] = 0; - int ans = 0; - for (int i = 0; i < n; ++i) { - int j = -1; - for (int k = 0; k < n; ++k) { - if (!vis[k] && (j == -1 || dist[k] < dist[j])) { - j = k; - } - } - vis[j] = true; - ans += dist[j]; - for (int k = 0; k < n; ++k) { - if (!vis[k]) { - dist[k] = min(dist[k], g[j][k]); - } - } - } - return ans; - } +class Solution { +public: + int minCostConnectPoints(vector>& points) { + int n = points.size(); + int g[n][n]; + for (int i = 0; i < n; ++i) { + int x1 = points[i][0], y1 = points[i][1]; + for (int j = i + 1; j < n; ++j) { + int x2 = points[j][0], y2 = points[j][1]; + int t = abs(x1 - x2) + abs(y1 - y2); + g[i][j] = t; + g[j][i] = t; + } + } + int dist[n]; + bool vis[n]; + memset(dist, 0x3f, sizeof(dist)); + memset(vis, false, sizeof(vis)); + dist[0] = 0; + int ans = 0; + for (int i = 0; i < n; ++i) { + int j = -1; + for (int k = 0; k < n; ++k) { + if (!vis[k] && (j == -1 || dist[k] < dist[j])) { + j = k; + } + } + vis[j] = true; + ans += dist[j]; + for (int k = 0; k < n; ++k) { + if (!vis[k]) { + dist[k] = min(dist[k], g[j][k]); + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1500-1599/1584.Min Cost to Connect All Points/Solution.java b/solution/1500-1599/1584.Min Cost to Connect All Points/Solution.java index 99de8a512e720..4259d6c718e03 100644 --- a/solution/1500-1599/1584.Min Cost to Connect All Points/Solution.java +++ b/solution/1500-1599/1584.Min Cost to Connect All Points/Solution.java @@ -1,37 +1,37 @@ -class Solution { - public int minCostConnectPoints(int[][] points) { - final int inf = 1 << 30; - int n = points.length; - int[][] g = new int[n][n]; - for (int i = 0; i < n; ++i) { - int x1 = points[i][0], y1 = points[i][1]; - for (int j = i + 1; j < n; ++j) { - int x2 = points[j][0], y2 = points[j][1]; - int t = Math.abs(x1 - x2) + Math.abs(y1 - y2); - g[i][j] = t; - g[j][i] = t; - } - } - int[] dist = new int[n]; - boolean[] vis = new boolean[n]; - Arrays.fill(dist, inf); - dist[0] = 0; - int ans = 0; - for (int i = 0; i < n; ++i) { - int j = -1; - for (int k = 0; k < n; ++k) { - if (!vis[k] && (j == -1 || dist[k] < dist[j])) { - j = k; - } - } - vis[j] = true; - ans += dist[j]; - for (int k = 0; k < n; ++k) { - if (!vis[k]) { - dist[k] = Math.min(dist[k], g[j][k]); - } - } - } - return ans; - } +class Solution { + public int minCostConnectPoints(int[][] points) { + final int inf = 1 << 30; + int n = points.length; + int[][] g = new int[n][n]; + for (int i = 0; i < n; ++i) { + int x1 = points[i][0], y1 = points[i][1]; + for (int j = i + 1; j < n; ++j) { + int x2 = points[j][0], y2 = points[j][1]; + int t = Math.abs(x1 - x2) + Math.abs(y1 - y2); + g[i][j] = t; + g[j][i] = t; + } + } + int[] dist = new int[n]; + boolean[] vis = new boolean[n]; + Arrays.fill(dist, inf); + dist[0] = 0; + int ans = 0; + for (int i = 0; i < n; ++i) { + int j = -1; + for (int k = 0; k < n; ++k) { + if (!vis[k] && (j == -1 || dist[k] < dist[j])) { + j = k; + } + } + vis[j] = true; + ans += dist[j]; + for (int k = 0; k < n; ++k) { + if (!vis[k]) { + dist[k] = Math.min(dist[k], g[j][k]); + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1500-1599/1584.Min Cost to Connect All Points/Solution.py b/solution/1500-1599/1584.Min Cost to Connect All Points/Solution.py index a9a19425f00e4..c7ff0e825f3df 100644 --- a/solution/1500-1599/1584.Min Cost to Connect All Points/Solution.py +++ b/solution/1500-1599/1584.Min Cost to Connect All Points/Solution.py @@ -1,24 +1,24 @@ -class Solution: - def minCostConnectPoints(self, points: List[List[int]]) -> int: - n = len(points) - g = [[0] * n for _ in range(n)] - dist = [inf] * n - vis = [False] * n - for i, (x1, y1) in enumerate(points): - for j in range(i + 1, n): - x2, y2 = points[j] - t = abs(x1 - x2) + abs(y1 - y2) - g[i][j] = g[j][i] = t - dist[0] = 0 - ans = 0 - for _ in range(n): - i = -1 - for j in range(n): - if not vis[j] and (i == -1 or dist[j] < dist[i]): - i = j - vis[i] = True - ans += dist[i] - for j in range(n): - if not vis[j]: - dist[j] = min(dist[j], g[i][j]) - return ans +class Solution: + def minCostConnectPoints(self, points: List[List[int]]) -> int: + n = len(points) + g = [[0] * n for _ in range(n)] + dist = [inf] * n + vis = [False] * n + for i, (x1, y1) in enumerate(points): + for j in range(i + 1, n): + x2, y2 = points[j] + t = abs(x1 - x2) + abs(y1 - y2) + g[i][j] = g[j][i] = t + dist[0] = 0 + ans = 0 + for _ in range(n): + i = -1 + for j in range(n): + if not vis[j] and (i == -1 or dist[j] < dist[i]): + i = j + vis[i] = True + ans += dist[i] + for j in range(n): + if not vis[j]: + dist[j] = min(dist[j], g[i][j]) + return ans diff --git a/solution/1500-1599/1584.Min Cost to Connect All Points/Solution2.cpp b/solution/1500-1599/1584.Min Cost to Connect All Points/Solution2.cpp new file mode 100644 index 0000000000000..43314650db204 --- /dev/null +++ b/solution/1500-1599/1584.Min Cost to Connect All Points/Solution2.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + vector p; + + int minCostConnectPoints(vector>& points) { + int n = points.size(); + vector> g; + for (int i = 0; i < n; ++i) { + int x1 = points[i][0], y1 = points[i][1]; + for (int j = i + 1; j < n; ++j) { + int x2 = points[j][0], y2 = points[j][1]; + g.push_back({abs(x1 - x2) + abs(y1 - y2), i, j}); + } + } + sort(g.begin(), g.end()); + p.resize(n); + for (int i = 0; i < n; ++i) p[i] = i; + int ans = 0; + for (auto& e : g) { + int cost = e[0], i = e[1], j = e[2]; + if (find(i) == find(j)) continue; + p[find(i)] = find(j); + ans += cost; + if (--n == 1) return ans; + } + return 0; + } + + int find(int x) { + if (p[x] != x) p[x] = find(p[x]); + return p[x]; + } +}; \ No newline at end of file diff --git a/solution/1500-1599/1584.Min Cost to Connect All Points/Solution2.go b/solution/1500-1599/1584.Min Cost to Connect All Points/Solution2.go new file mode 100644 index 0000000000000..0e4c4c9e4d2a3 --- /dev/null +++ b/solution/1500-1599/1584.Min Cost to Connect All Points/Solution2.go @@ -0,0 +1,46 @@ +func minCostConnectPoints(points [][]int) int { + n := len(points) + var g [][]int + for i, p := range points { + x1, y1 := p[0], p[1] + for j := i + 1; j < n; j++ { + x2, y2 := points[j][0], points[j][1] + g = append(g, []int{abs(x1-x2) + abs(y1-y2), i, j}) + } + } + sort.Slice(g, func(i, j int) bool { + return g[i][0] < g[j][0] + }) + ans := 0 + p := make([]int, n) + for i := range p { + p[i] = i + } + var find func(x int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + for _, e := range g { + cost, i, j := e[0], e[1], e[2] + if find(i) == find(j) { + continue + } + p[find(i)] = find(j) + ans += cost + n-- + if n == 1 { + return ans + } + } + return 0 +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} \ No newline at end of file diff --git a/solution/1500-1599/1584.Min Cost to Connect All Points/Solution2.java b/solution/1500-1599/1584.Min Cost to Connect All Points/Solution2.java new file mode 100644 index 0000000000000..23355aaa89cf8 --- /dev/null +++ b/solution/1500-1599/1584.Min Cost to Connect All Points/Solution2.java @@ -0,0 +1,40 @@ +class Solution { + private int[] p; + + public int minCostConnectPoints(int[][] points) { + int n = points.length; + List g = new ArrayList<>(); + for (int i = 0; i < n; ++i) { + int x1 = points[i][0], y1 = points[i][1]; + for (int j = i + 1; j < n; ++j) { + int x2 = points[j][0], y2 = points[j][1]; + g.add(new int[] {Math.abs(x1 - x2) + Math.abs(y1 - y2), i, j}); + } + } + g.sort(Comparator.comparingInt(a -> a[0])); + p = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + } + int ans = 0; + for (int[] e : g) { + int cost = e[0], i = e[1], j = e[2]; + if (find(i) == find(j)) { + continue; + } + p[find(i)] = find(j); + ans += cost; + if (--n == 1) { + return ans; + } + } + return 0; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} \ No newline at end of file diff --git a/solution/1500-1599/1584.Min Cost to Connect All Points/Solution2.py b/solution/1500-1599/1584.Min Cost to Connect All Points/Solution2.py new file mode 100644 index 0000000000000..7f7913acb8e00 --- /dev/null +++ b/solution/1500-1599/1584.Min Cost to Connect All Points/Solution2.py @@ -0,0 +1,26 @@ +class Solution: + def minCostConnectPoints(self, points: List[List[int]]) -> int: + def find(x: int) -> int: + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + n = len(points) + g = [] + for i, (x1, y1) in enumerate(points): + for j in range(i + 1, n): + x2, y2 = points[j] + t = abs(x1 - x2) + abs(y1 - y2) + g.append((t, i, j)) + p = list(range(n)) + ans = 0 + for cost, i, j in sorted(g): + pa, pb = find(i), find(j) + if pa == pb: + continue + p[pa] = pb + ans += cost + n -= 1 + if n == 1: + break + return ans diff --git a/solution/1500-1599/1586.Binary Search Tree Iterator II/Solution.cpp b/solution/1500-1599/1586.Binary Search Tree Iterator II/Solution.cpp index 02507c9b54768..30f7d9918db8a 100644 --- a/solution/1500-1599/1586.Binary Search Tree Iterator II/Solution.cpp +++ b/solution/1500-1599/1586.Binary Search Tree Iterator II/Solution.cpp @@ -1,57 +1,57 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class BSTIterator { -public: - BSTIterator(TreeNode* root) { - dfs(root); - n = nums.size(); - } - - bool hasNext() { - return i < n - 1; - } - - int next() { - return nums[++i]; - } - - bool hasPrev() { - return i > 0; - } - - int prev() { - return nums[--i]; - } - -private: - vector nums; - int i = -1; - int n; - - void dfs(TreeNode* root) { - if (!root) { - return; - } - dfs(root->left); - nums.push_back(root->val); - dfs(root->right); - } -}; - -/** - * Your BSTIterator object will be instantiated and called as such: - * BSTIterator* obj = new BSTIterator(root); - * bool param_1 = obj->hasNext(); - * int param_2 = obj->next(); - * bool param_3 = obj->hasPrev(); - * int param_4 = obj->prev(); +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class BSTIterator { +public: + BSTIterator(TreeNode* root) { + dfs(root); + n = nums.size(); + } + + bool hasNext() { + return i < n - 1; + } + + int next() { + return nums[++i]; + } + + bool hasPrev() { + return i > 0; + } + + int prev() { + return nums[--i]; + } + +private: + vector nums; + int i = -1; + int n; + + void dfs(TreeNode* root) { + if (!root) { + return; + } + dfs(root->left); + nums.push_back(root->val); + dfs(root->right); + } +}; + +/** + * Your BSTIterator object will be instantiated and called as such: + * BSTIterator* obj = new BSTIterator(root); + * bool param_1 = obj->hasNext(); + * int param_2 = obj->next(); + * bool param_3 = obj->hasPrev(); + * int param_4 = obj->prev(); */ \ No newline at end of file diff --git a/solution/1500-1599/1586.Binary Search Tree Iterator II/Solution.java b/solution/1500-1599/1586.Binary Search Tree Iterator II/Solution.java index 37c0c289604df..b3313c4c083c6 100644 --- a/solution/1500-1599/1586.Binary Search Tree Iterator II/Solution.java +++ b/solution/1500-1599/1586.Binary Search Tree Iterator II/Solution.java @@ -1,57 +1,57 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class BSTIterator { - private List nums = new ArrayList<>(); - private int i = -1; - - public BSTIterator(TreeNode root) { - dfs(root); - } - - public boolean hasNext() { - return i < nums.size() - 1; - } - - public int next() { - return nums.get(++i); - } - - public boolean hasPrev() { - return i > 0; - } - - public int prev() { - return nums.get(--i); - } - - private void dfs(TreeNode root) { - if (root == null) { - return; - } - dfs(root.left); - nums.add(root.val); - dfs(root.right); - } -} - -/** - * Your BSTIterator object will be instantiated and called as such: - * BSTIterator obj = new BSTIterator(root); - * boolean param_1 = obj.hasNext(); - * int param_2 = obj.next(); - * boolean param_3 = obj.hasPrev(); - * int param_4 = obj.prev(); +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class BSTIterator { + private List nums = new ArrayList<>(); + private int i = -1; + + public BSTIterator(TreeNode root) { + dfs(root); + } + + public boolean hasNext() { + return i < nums.size() - 1; + } + + public int next() { + return nums.get(++i); + } + + public boolean hasPrev() { + return i > 0; + } + + public int prev() { + return nums.get(--i); + } + + private void dfs(TreeNode root) { + if (root == null) { + return; + } + dfs(root.left); + nums.add(root.val); + dfs(root.right); + } +} + +/** + * Your BSTIterator object will be instantiated and called as such: + * BSTIterator obj = new BSTIterator(root); + * boolean param_1 = obj.hasNext(); + * int param_2 = obj.next(); + * boolean param_3 = obj.hasPrev(); + * int param_4 = obj.prev(); */ \ No newline at end of file diff --git a/solution/1500-1599/1586.Binary Search Tree Iterator II/Solution.py b/solution/1500-1599/1586.Binary Search Tree Iterator II/Solution.py index 8944ede4f656f..6671c9371849e 100644 --- a/solution/1500-1599/1586.Binary Search Tree Iterator II/Solution.py +++ b/solution/1500-1599/1586.Binary Search Tree Iterator II/Solution.py @@ -1,41 +1,41 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class BSTIterator: - def __init__(self, root: Optional[TreeNode]): - self.nums = [] - - def dfs(root): - if root is None: - return - dfs(root.left) - self.nums.append(root.val) - dfs(root.right) - - dfs(root) - self.i = -1 - - def hasNext(self) -> bool: - return self.i < len(self.nums) - 1 - - def next(self) -> int: - self.i += 1 - return self.nums[self.i] - - def hasPrev(self) -> bool: - return self.i > 0 - - def prev(self) -> int: - self.i -= 1 - return self.nums[self.i] - - -# Your BSTIterator object will be instantiated and called as such: -# obj = BSTIterator(root) -# param_1 = obj.hasNext() -# param_2 = obj.next() -# param_3 = obj.hasPrev() -# param_4 = obj.prev() +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class BSTIterator: + def __init__(self, root: Optional[TreeNode]): + self.nums = [] + + def dfs(root): + if root is None: + return + dfs(root.left) + self.nums.append(root.val) + dfs(root.right) + + dfs(root) + self.i = -1 + + def hasNext(self) -> bool: + return self.i < len(self.nums) - 1 + + def next(self) -> int: + self.i += 1 + return self.nums[self.i] + + def hasPrev(self) -> bool: + return self.i > 0 + + def prev(self) -> int: + self.i -= 1 + return self.nums[self.i] + + +# Your BSTIterator object will be instantiated and called as such: +# obj = BSTIterator(root) +# param_1 = obj.hasNext() +# param_2 = obj.next() +# param_3 = obj.hasPrev() +# param_4 = obj.prev() diff --git a/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/Solution.go b/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/Solution.go index bf50edcf5e4e2..7fb2f1905c106 100644 --- a/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/Solution.go +++ b/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/Solution.go @@ -18,5 +18,4 @@ func maxSumRangeQuery(nums []int, requests [][]int) (ans int) { b := d[i] ans = (ans + a*b) % mod } - return -} \ No newline at end of file + return \ No newline at end of file diff --git a/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution.cpp b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution.cpp index c2c6bb9f1e716..e53ea2af46fe3 100644 --- a/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution.cpp +++ b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution.cpp @@ -1,24 +1,21 @@ -class Solution { -public: - int connectTwoGroups(vector>& cost) { - int m = cost.size(), n = cost[0].size(); - const int inf = 1 << 30; - vector f(1 << n, inf); - f[0] = 0; - vector g = f; - for (int i = 1; i <= m; ++i) { - for (int j = 0; j < 1 << n; ++j) { - g[j] = inf; - for (int k = 0; k < n; ++k) { - if (j >> k & 1) { - int c = cost[i - 1][k]; - int x = min({g[j ^ (1 << k)], f[j], f[j ^ (1 << k)]}) + c; - g[j] = min(g[j], x); - } - } - } - f.swap(g); - } - return f[(1 << n) - 1]; - } +class Solution { +public: + int connectTwoGroups(vector>& cost) { + int m = cost.size(), n = cost[0].size(); + int f[m + 1][1 << n]; + memset(f, 0x3f, sizeof(f)); + f[0][0] = 0; + for (int i = 1; i <= m; ++i) { + for (int j = 0; j < 1 << n; ++j) { + for (int k = 0; k < n; ++k) { + if (j >> k & 1) { + int c = cost[i - 1][k]; + int x = min({f[i][j ^ (1 << k)], f[i - 1][j], f[i - 1][j ^ (1 << k)]}) + c; + f[i][j] = min(f[i][j], x); + } + } + } + } + return f[m][(1 << n) - 1]; + } }; \ No newline at end of file diff --git a/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution.go b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution.go index 7b40563a8d133..d674e919bf578 100644 --- a/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution.go +++ b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution.go @@ -1,25 +1,25 @@ func connectTwoGroups(cost [][]int) int { m, n := len(cost), len(cost[0]) const inf = 1 << 30 - f := make([]int, 1<>k&1 == 1 { - g[j] = min(g[j], g[j^1<> cost) { - int m = cost.size(), n = cost.get(0).size(); - final int inf = 1 << 30; - int[] f = new int[1 << n]; - Arrays.fill(f, inf); - f[0] = 0; - int[] g = f.clone(); - for (int i = 1; i <= m; ++i) { - for (int j = 0; j < 1 << n; ++j) { - g[j] = inf; - for (int k = 0; k < n; ++k) { - if ((j >> k & 1) == 1) { - int c = cost.get(i - 1).get(k); - g[j] = Math.min(g[j], g[j ^ (1 << k)] + c); - g[j] = Math.min(g[j], f[j] + c); - g[j] = Math.min(g[j], f[j ^ (1 << k)] + c); - } - } - } - System.arraycopy(g, 0, f, 0, 1 << n); - } - return f[(1 << n) - 1]; - } +class Solution { + public int connectTwoGroups(List> cost) { + int m = cost.size(), n = cost.get(0).size(); + final int inf = 1 << 30; + int[][] f = new int[m + 1][1 << n]; + for (int[] g : f) { + Arrays.fill(g, inf); + } + f[0][0] = 0; + for (int i = 1; i <= m; ++i) { + for (int j = 0; j < 1 << n; ++j) { + for (int k = 0; k < n; ++k) { + if ((j >> k & 1) == 1) { + int c = cost.get(i - 1).get(k); + f[i][j] = Math.min(f[i][j], f[i][j ^ (1 << k)] + c); + f[i][j] = Math.min(f[i][j], f[i - 1][j] + c); + f[i][j] = Math.min(f[i][j], f[i - 1][j ^ (1 << k)] + c); + } + } + } + } + return f[m][(1 << n) - 1]; + } } \ No newline at end of file diff --git a/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution.py b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution.py index b9e2463f043ba..9f8fcfc38c638 100644 --- a/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution.py +++ b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution.py @@ -1,17 +1,14 @@ -class Solution: - def connectTwoGroups(self, cost: List[List[int]]) -> int: - m, n = len(cost), len(cost[0]) - f = [inf] * (1 << n) - f[0] = 0 - g = f[:] - for i in range(1, m + 1): - for j in range(1 << n): - g[j] = inf - for k in range(n): - if (j >> k & 1) == 0: - continue - c = cost[i - 1][k] - x = min(g[j ^ (1 << k)], f[j], f[j ^ (1 << k)]) + c - g[j] = min(g[j], x) - f = g[:] - return f[-1] +class Solution: + def connectTwoGroups(self, cost: List[List[int]]) -> int: + m, n = len(cost), len(cost[0]) + f = [[inf] * (1 << n) for _ in range(m + 1)] + f[0][0] = 0 + for i in range(1, m + 1): + for j in range(1 << n): + for k in range(n): + if (j >> k & 1) == 0: + continue + c = cost[i - 1][k] + x = min(f[i][j ^ (1 << k)], f[i - 1][j], f[i - 1][j ^ (1 << k)]) + c + f[i][j] = min(f[i][j], x) + return f[m][-1] diff --git a/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution.ts b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution.ts index 096021966a506..fe355ef09af63 100644 --- a/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution.ts +++ b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution.ts @@ -2,22 +2,21 @@ function connectTwoGroups(cost: number[][]): number { const m = cost.length; const n = cost[0].length; const inf = 1 << 30; - const f: number[] = new Array(1 << n).fill(inf); - f[0] = 0; - const g = new Array(1 << n).fill(0); + const f: number[][] = Array(m + 1) + .fill(0) + .map(() => Array(1 << n).fill(inf)); + f[0][0] = 0; for (let i = 1; i <= m; ++i) { for (let j = 0; j < 1 << n; ++j) { - g[j] = inf; for (let k = 0; k < n; ++k) { if (((j >> k) & 1) === 1) { const c = cost[i - 1][k]; - g[j] = Math.min(g[j], g[j ^ (1 << k)] + c); - g[j] = Math.min(g[j], f[j] + c); - g[j] = Math.min(g[j], f[j ^ (1 << k)] + c); + f[i][j] = Math.min(f[i][j], f[i][j ^ (1 << k)] + c); + f[i][j] = Math.min(f[i][j], f[i - 1][j] + c); + f[i][j] = Math.min(f[i][j], f[i - 1][j ^ (1 << k)] + c); } } } - f.splice(0, f.length, ...g); } - return f[(1 << n) - 1]; + return f[m][(1 << n) - 1]; } diff --git a/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution2.cpp b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution2.cpp new file mode 100644 index 0000000000000..d9d9f0a8bffe6 --- /dev/null +++ b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution2.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int connectTwoGroups(vector>& cost) { + int m = cost.size(), n = cost[0].size(); + const int inf = 1 << 30; + vector f(1 << n, inf); + f[0] = 0; + vector g = f; + for (int i = 1; i <= m; ++i) { + for (int j = 0; j < 1 << n; ++j) { + g[j] = inf; + for (int k = 0; k < n; ++k) { + if (j >> k & 1) { + int c = cost[i - 1][k]; + int x = min({g[j ^ (1 << k)], f[j], f[j ^ (1 << k)]}) + c; + g[j] = min(g[j], x); + } + } + } + f.swap(g); + } + return f[(1 << n) - 1]; + } +}; \ No newline at end of file diff --git a/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution2.go b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution2.go new file mode 100644 index 0000000000000..7b40563a8d133 --- /dev/null +++ b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution2.go @@ -0,0 +1,25 @@ +func connectTwoGroups(cost [][]int) int { + m, n := len(cost), len(cost[0]) + const inf = 1 << 30 + f := make([]int, 1<>k&1 == 1 { + g[j] = min(g[j], g[j^1<> cost) { + int m = cost.size(), n = cost.get(0).size(); + final int inf = 1 << 30; + int[] f = new int[1 << n]; + Arrays.fill(f, inf); + f[0] = 0; + int[] g = f.clone(); + for (int i = 1; i <= m; ++i) { + for (int j = 0; j < 1 << n; ++j) { + g[j] = inf; + for (int k = 0; k < n; ++k) { + if ((j >> k & 1) == 1) { + int c = cost.get(i - 1).get(k); + g[j] = Math.min(g[j], g[j ^ (1 << k)] + c); + g[j] = Math.min(g[j], f[j] + c); + g[j] = Math.min(g[j], f[j ^ (1 << k)] + c); + } + } + } + System.arraycopy(g, 0, f, 0, 1 << n); + } + return f[(1 << n) - 1]; + } +} \ No newline at end of file diff --git a/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution2.py b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution2.py new file mode 100644 index 0000000000000..a21e33e28fc76 --- /dev/null +++ b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def connectTwoGroups(self, cost: List[List[int]]) -> int: + m, n = len(cost), len(cost[0]) + f = [inf] * (1 << n) + f[0] = 0 + g = f[:] + for i in range(1, m + 1): + for j in range(1 << n): + g[j] = inf + for k in range(n): + if (j >> k & 1) == 0: + continue + c = cost[i - 1][k] + x = min(g[j ^ (1 << k)], f[j], f[j ^ (1 << k)]) + c + g[j] = min(g[j], x) + f = g[:] + return f[-1] diff --git a/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution2.ts b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution2.ts new file mode 100644 index 0000000000000..096021966a506 --- /dev/null +++ b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution2.ts @@ -0,0 +1,23 @@ +function connectTwoGroups(cost: number[][]): number { + const m = cost.length; + const n = cost[0].length; + const inf = 1 << 30; + const f: number[] = new Array(1 << n).fill(inf); + f[0] = 0; + const g = new Array(1 << n).fill(0); + for (let i = 1; i <= m; ++i) { + for (let j = 0; j < 1 << n; ++j) { + g[j] = inf; + for (let k = 0; k < n; ++k) { + if (((j >> k) & 1) === 1) { + const c = cost[i - 1][k]; + g[j] = Math.min(g[j], g[j ^ (1 << k)] + c); + g[j] = Math.min(g[j], f[j] + c); + g[j] = Math.min(g[j], f[j ^ (1 << k)] + c); + } + } + } + f.splice(0, f.length, ...g); + } + return f[(1 << n) - 1]; +} diff --git a/solution/1500-1599/1598.Crawler Log Folder/Solution.c b/solution/1500-1599/1598.Crawler Log Folder/Solution.c index 45d6c724364b8..bc3db711d9a32 100644 --- a/solution/1500-1599/1598.Crawler Log Folder/Solution.c +++ b/solution/1500-1599/1598.Crawler Log Folder/Solution.c @@ -11,4 +11,4 @@ int minOperations(char** logs, int logsSize) { } } return depth; -} +} \ No newline at end of file diff --git a/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/Solution2.cpp b/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/Solution2.cpp new file mode 100644 index 0000000000000..392d899d1a1a6 --- /dev/null +++ b/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/Solution2.cpp @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* u; + TreeNode* ans; + int d = 0; + + TreeNode* findNearestRightNode(TreeNode* root, TreeNode* u) { + this->u = u; + dfs(root, 1); + return ans; + } + + void dfs(TreeNode* root, int i) { + if (!root || ans) return; + if (d == i) { + ans = root; + return; + } + if (root == u) { + d = i; + return; + } + dfs(root->left, i + 1); + dfs(root->right, i + 1); + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/Solution2.go b/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/Solution2.go new file mode 100644 index 0000000000000..49f7e6a2e26ab --- /dev/null +++ b/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/Solution2.go @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func findNearestRightNode(root *TreeNode, u *TreeNode) *TreeNode { + d := 0 + var ans *TreeNode + var dfs func(*TreeNode, int) + dfs = func(root *TreeNode, i int) { + if root == nil || ans != nil { + return + } + if d == i { + ans = root + return + } + if root == u { + d = i + return + } + dfs(root.Left, i+1) + dfs(root.Right, i+1) + } + dfs(root, 1) + return ans +} \ No newline at end of file diff --git a/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/Solution2.java b/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/Solution2.java new file mode 100644 index 0000000000000..cddb9af8e90f1 --- /dev/null +++ b/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/Solution2.java @@ -0,0 +1,42 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private TreeNode u; + private TreeNode ans; + private int d; + + public TreeNode findNearestRightNode(TreeNode root, TreeNode u) { + this.u = u; + dfs(root, 1); + return ans; + } + + private void dfs(TreeNode root, int i) { + if (root == null || ans != null) { + return; + } + if (d == i) { + ans = root; + return; + } + if (root == u) { + d = i; + return; + } + dfs(root.left, i + 1); + dfs(root.right, i + 1); + } +} \ No newline at end of file diff --git a/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/Solution2.js b/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/Solution2.js new file mode 100644 index 0000000000000..32e24169dc06c --- /dev/null +++ b/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/Solution2.js @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} u + * @return {TreeNode} + */ +var findNearestRightNode = function (root, u) { + let d = 0; + let ans = null; + function dfs(root, i) { + if (!root || ans) { + return; + } + if (d == i) { + ans = root; + return; + } + if (root == u) { + d = i; + return; + } + dfs(root.left, i + 1); + dfs(root.right, i + 1); + } + dfs(root, 1); + return ans; +}; diff --git a/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/Solution2.py b/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/Solution2.py new file mode 100644 index 0000000000000..4ff87ad6e9519 --- /dev/null +++ b/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/Solution2.py @@ -0,0 +1,25 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def findNearestRightNode(self, root: TreeNode, u: TreeNode) -> Optional[TreeNode]: + def dfs(root, i): + nonlocal d, ans + if root is None or ans: + return + if d == i: + ans = root + return + if root == u: + d = i + return + dfs(root.left, i + 1) + dfs(root.right, i + 1) + + d = 0 + ans = None + dfs(root, 1) + return ans diff --git a/solution/1600-1699/1603.Design Parking System/Solution.c b/solution/1600-1699/1603.Design Parking System/Solution.c index b04b9786a16d1..07f0609303f99 100644 --- a/solution/1600-1699/1603.Design Parking System/Solution.c +++ b/solution/1600-1699/1603.Design Parking System/Solution.c @@ -30,4 +30,4 @@ void parkingSystemFree(ParkingSystem* obj) { * bool param_1 = parkingSystemAddCar(obj, carType); * parkingSystemFree(obj); -*/ +*/ \ No newline at end of file diff --git a/solution/1600-1699/1603.Design Parking System/Solution.cs b/solution/1600-1699/1603.Design Parking System/Solution.cs index 62dc3f9fdb59f..6ded709104fb8 100644 --- a/solution/1600-1699/1603.Design Parking System/Solution.cs +++ b/solution/1600-1699/1603.Design Parking System/Solution.cs @@ -19,4 +19,4 @@ public bool AddCar(int carType) { * Your ParkingSystem object will be instantiated and called as such: * ParkingSystem obj = new ParkingSystem(big, medium, small); * bool param_1 = obj.AddCar(carType); - */ \ No newline at end of file + */ diff --git a/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/Solution.cpp b/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/Solution.cpp index 8148ac3a6d08d..539daab5bc383 100644 --- a/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/Solution.cpp +++ b/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - vector> restoreMatrix(vector& rowSum, vector& colSum) { - int m = rowSum.size(), n = colSum.size(); - vector> ans(m, vector(n)); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - int x = min(rowSum[i], colSum[j]); - ans[i][j] = x; - rowSum[i] -= x; - colSum[j] -= x; - } - } - return ans; - } +class Solution { +public: + vector> restoreMatrix(vector& rowSum, vector& colSum) { + int m = rowSum.size(), n = colSum.size(); + vector> ans(m, vector(n)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + int x = min(rowSum[i], colSum[j]); + ans[i][j] = x; + rowSum[i] -= x; + colSum[j] -= x; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/Solution.java b/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/Solution.java index caac243e884b1..50d80c843d430 100644 --- a/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/Solution.java +++ b/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/Solution.java @@ -1,16 +1,16 @@ -class Solution { - public int[][] restoreMatrix(int[] rowSum, int[] colSum) { - int m = rowSum.length; - int n = colSum.length; - int[][] ans = new int[m][n]; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - int x = Math.min(rowSum[i], colSum[j]); - ans[i][j] = x; - rowSum[i] -= x; - colSum[j] -= x; - } - } - return ans; - } +class Solution { + public int[][] restoreMatrix(int[] rowSum, int[] colSum) { + int m = rowSum.length; + int n = colSum.length; + int[][] ans = new int[m][n]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + int x = Math.min(rowSum[i], colSum[j]); + ans[i][j] = x; + rowSum[i] -= x; + colSum[j] -= x; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/Solution.py b/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/Solution.py index a107f27cc42e0..fb60be0fee997 100644 --- a/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/Solution.py +++ b/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]: - m, n = len(rowSum), len(colSum) - ans = [[0] * n for _ in range(m)] - for i in range(m): - for j in range(n): - x = min(rowSum[i], colSum[j]) - ans[i][j] = x - rowSum[i] -= x - colSum[j] -= x - return ans +class Solution: + def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]: + m, n = len(rowSum), len(colSum) + ans = [[0] * n for _ in range(m)] + for i in range(m): + for j in range(n): + x = min(rowSum[i], colSum[j]) + ans[i][j] = x + rowSum[i] -= x + colSum[j] -= x + return ans diff --git a/solution/1600-1699/1606.Find Servers That Handled Most Number of Requests/Solution.java b/solution/1600-1699/1606.Find Servers That Handled Most Number of Requests/Solution.java index bc8bc36d5fcc7..69d4b2812e202 100644 --- a/solution/1600-1699/1606.Find Servers That Handled Most Number of Requests/Solution.java +++ b/solution/1600-1699/1606.Find Servers That Handled Most Number of Requests/Solution.java @@ -1,38 +1,38 @@ -class Solution { - public List busiestServers(int k, int[] arrival, int[] load) { - int[] cnt = new int[k]; - PriorityQueue busy = new PriorityQueue<>((a, b) -> a[0] - b[0]); - TreeSet free = new TreeSet<>(); - for (int i = 0; i < k; ++i) { - free.add(i); - } - for (int i = 0; i < arrival.length; ++i) { - int start = arrival[i]; - int end = start + load[i]; - while (!busy.isEmpty() && busy.peek()[0] <= start) { - free.add(busy.poll()[1]); - } - if (free.isEmpty()) { - continue; - } - Integer server = free.ceiling(i % k); - if (server == null) { - server = free.first(); - } - ++cnt[server]; - busy.offer(new int[] {end, server}); - free.remove(server); - } - int mx = 0; - for (int v : cnt) { - mx = Math.max(mx, v); - } - List ans = new ArrayList<>(); - for (int i = 0; i < k; ++i) { - if (cnt[i] == mx) { - ans.add(i); - } - } - return ans; - } +class Solution { + public List busiestServers(int k, int[] arrival, int[] load) { + int[] cnt = new int[k]; + PriorityQueue busy = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); + TreeSet free = new TreeSet<>(); + for (int i = 0; i < k; ++i) { + free.add(i); + } + for (int i = 0; i < arrival.length; ++i) { + int start = arrival[i]; + int end = start + load[i]; + while (!busy.isEmpty() && busy.peek()[0] <= start) { + free.add(busy.poll()[1]); + } + if (free.isEmpty()) { + continue; + } + Integer server = free.ceiling(i % k); + if (server == null) { + server = free.first(); + } + ++cnt[server]; + busy.offer(new int[] {end, server}); + free.remove(server); + } + int mx = 0; + for (int v : cnt) { + mx = Math.max(mx, v); + } + List ans = new ArrayList<>(); + for (int i = 0; i < k; ++i) { + if (cnt[i] == mx) { + ans.add(i); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1600-1699/1606.Find Servers That Handled Most Number of Requests/Solution.py b/solution/1600-1699/1606.Find Servers That Handled Most Number of Requests/Solution.py index caf7087926f34..577a05324a8a9 100644 --- a/solution/1600-1699/1606.Find Servers That Handled Most Number of Requests/Solution.py +++ b/solution/1600-1699/1606.Find Servers That Handled Most Number of Requests/Solution.py @@ -1,24 +1,24 @@ -from sortedcontainers import SortedList - - -class Solution: - def busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]: - free = SortedList(range(k)) - busy = [] - cnt = [0] * k - for i, (start, t) in enumerate(zip(arrival, load)): - while busy and busy[0][0] <= start: - free.add(busy[0][1]) - heappop(busy) - if not free: - continue - j = free.bisect_left(i % k) - if j == len(free): - j = 0 - server = free[j] - cnt[server] += 1 - heappush(busy, (start + t, server)) - free.remove(server) - - mx = max(cnt) - return [i for i, v in enumerate(cnt) if v == mx] +from sortedcontainers import SortedList + + +class Solution: + def busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]: + free = SortedList(range(k)) + busy = [] + cnt = [0] * k + for i, (start, t) in enumerate(zip(arrival, load)): + while busy and busy[0][0] <= start: + free.add(busy[0][1]) + heappop(busy) + if not free: + continue + j = free.bisect_left(i % k) + if j == len(free): + j = 0 + server = free[j] + cnt[server] += 1 + heappush(busy, (start + t, server)) + free.remove(server) + + mx = max(cnt) + return [i for i, v in enumerate(cnt) if v == mx] diff --git a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.cpp b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.cpp index 4946e333e0d7e..8f36e4783df7c 100644 --- a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.cpp +++ b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.cpp @@ -1,12 +1,11 @@ -class Solution { -public: - int specialArray(vector& nums) { - int n = nums.size(); - sort(nums.begin(), nums.end()); - for (int x = 1; x <= n; ++x) { - int cnt = n - (lower_bound(nums.begin(), nums.end(), x) - nums.begin()); - if (cnt == x) return x; - } - return -1; - } +class Solution { +public: + int specialArray(vector& nums) { + for (int x = 1; x <= nums.size(); ++x) { + int cnt = 0; + for (int v : nums) cnt += v >= x; + if (cnt == x) return x; + } + return -1; + } }; \ No newline at end of file diff --git a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.go b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.go index 7b5eebe79c8ae..b049c24fcc00b 100644 --- a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.go +++ b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.go @@ -1,17 +1,11 @@ func specialArray(nums []int) int { - sort.Ints(nums) - n := len(nums) - for x := 1; x <= n; x++ { - left, right := 0, n - for left < right { - mid := (left + right) >> 1 - if nums[mid] >= x { - right = mid - } else { - left = mid + 1 + for x := 1; x <= len(nums); x++ { + cnt := 0 + for _, v := range nums { + if v >= x { + cnt++ } } - cnt := n - left if cnt == x { return x } diff --git a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.java b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.java index f7c02edbbc3b6..8317f0b33c134 100644 --- a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.java +++ b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.java @@ -1,22 +1,16 @@ -class Solution { - public int specialArray(int[] nums) { - Arrays.sort(nums); - int n = nums.length; - for (int x = 1; x <= n; ++x) { - int left = 0, right = n; - while (left < right) { - int mid = (left + right) >> 1; - if (nums[mid] >= x) { - right = mid; - } else { - left = mid + 1; - } - } - int cnt = n - left; - if (cnt == x) { - return x; - } - } - return -1; - } +class Solution { + public int specialArray(int[] nums) { + for (int x = 1; x <= nums.length; ++x) { + int cnt = 0; + for (int v : nums) { + if (v >= x) { + ++cnt; + } + } + if (cnt == x) { + return x; + } + } + return -1; + } } \ No newline at end of file diff --git a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.py b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.py index d1bfc58725726..d4a4d6a35bd4f 100644 --- a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.py +++ b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.py @@ -1,9 +1,7 @@ -class Solution: - def specialArray(self, nums: List[int]) -> int: - nums.sort() - n = len(nums) - for x in range(1, n + 1): - cnt = n - bisect_left(nums, x) - if cnt == x: - return x - return -1 +class Solution: + def specialArray(self, nums: List[int]) -> int: + for x in range(1, len(nums) + 1): + cnt = sum(v >= x for v in nums) + if cnt == x: + return x + return -1 diff --git a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.rs b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.rs index d3d083daa8107..8e3870ed0b342 100644 --- a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.rs +++ b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.rs @@ -1,27 +1,15 @@ -use std::cmp::Ordering; impl Solution { pub fn special_array(nums: Vec) -> i32 { let n = nums.len() as i32; - let mut left = 0; - let mut right = n + 1; - while left < right { - let mid = left + (right - left) / 2; + for i in 0..=n { let mut count = 0; for &num in nums.iter() { - if num >= mid { + if num >= i { count += 1; } } - match count.cmp(&mid) { - Ordering::Equal => { - return mid; - } - Ordering::Less => { - right = mid; - } - Ordering::Greater => { - left = mid + 1; - } + if count == i { + return i; } } -1 diff --git a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.ts b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.ts index b310d5219e233..95b8f22c2eefc 100644 --- a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.ts +++ b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution.ts @@ -1,19 +1,8 @@ function specialArray(nums: number[]): number { const n = nums.length; - let left = 0; - let right = n + 1; - while (left < right) { - const mid = (left + right) >> 1; - const count = nums.reduce((r, v) => r + (v >= mid ? 1 : 0), 0); - - if (count === mid) { - return mid; - } - - if (count > mid) { - left = mid + 1; - } else { - right = mid; + for (let i = 0; i <= n; i++) { + if (i === nums.reduce((r, v) => r + (v >= i ? 1 : 0), 0)) { + return i; } } return -1; diff --git a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution2.cpp b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution2.cpp new file mode 100644 index 0000000000000..7d15cddc8eb2e --- /dev/null +++ b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution2.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int specialArray(vector& nums) { + int n = nums.size(); + sort(nums.begin(), nums.end()); + for (int x = 1; x <= n; ++x) { + int cnt = n - (lower_bound(nums.begin(), nums.end(), x) - nums.begin()); + if (cnt == x) return x; + } + return -1; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution2.go b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution2.go new file mode 100644 index 0000000000000..7b5eebe79c8ae --- /dev/null +++ b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution2.go @@ -0,0 +1,20 @@ +func specialArray(nums []int) int { + sort.Ints(nums) + n := len(nums) + for x := 1; x <= n; x++ { + left, right := 0, n + for left < right { + mid := (left + right) >> 1 + if nums[mid] >= x { + right = mid + } else { + left = mid + 1 + } + } + cnt := n - left + if cnt == x { + return x + } + } + return -1 +} \ No newline at end of file diff --git a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution2.java b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution2.java new file mode 100644 index 0000000000000..dea1d9784afdb --- /dev/null +++ b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution2.java @@ -0,0 +1,22 @@ +class Solution { + public int specialArray(int[] nums) { + Arrays.sort(nums); + int n = nums.length; + for (int x = 1; x <= n; ++x) { + int left = 0, right = n; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } + } + int cnt = n - left; + if (cnt == x) { + return x; + } + } + return -1; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution2.py b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution2.py new file mode 100644 index 0000000000000..0f087823b3626 --- /dev/null +++ b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def specialArray(self, nums: List[int]) -> int: + nums.sort() + n = len(nums) + for x in range(1, n + 1): + cnt = n - bisect_left(nums, x) + if cnt == x: + return x + return -1 diff --git a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution2.rs b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution2.rs new file mode 100644 index 0000000000000..d3d083daa8107 --- /dev/null +++ b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution2.rs @@ -0,0 +1,29 @@ +use std::cmp::Ordering; +impl Solution { + pub fn special_array(nums: Vec) -> i32 { + let n = nums.len() as i32; + let mut left = 0; + let mut right = n + 1; + while left < right { + let mid = left + (right - left) / 2; + let mut count = 0; + for &num in nums.iter() { + if num >= mid { + count += 1; + } + } + match count.cmp(&mid) { + Ordering::Equal => { + return mid; + } + Ordering::Less => { + right = mid; + } + Ordering::Greater => { + left = mid + 1; + } + } + } + -1 + } +} diff --git a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution2.ts b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution2.ts new file mode 100644 index 0000000000000..b310d5219e233 --- /dev/null +++ b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/Solution2.ts @@ -0,0 +1,20 @@ +function specialArray(nums: number[]): number { + const n = nums.length; + let left = 0; + let right = n + 1; + while (left < right) { + const mid = (left + right) >> 1; + const count = nums.reduce((r, v) => r + (v >= mid ? 1 : 0), 0); + + if (count === mid) { + return mid; + } + + if (count > mid) { + left = mid + 1; + } else { + right = mid; + } + } + return -1; +} diff --git a/solution/1600-1699/1609.Even Odd Tree/Solution2.cpp b/solution/1600-1699/1609.Even Odd Tree/Solution2.cpp new file mode 100644 index 0000000000000..96f3ec3f44d54 --- /dev/null +++ b/solution/1600-1699/1609.Even Odd Tree/Solution2.cpp @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + unordered_map d; + + bool isEvenOddTree(TreeNode* root) { + return dfs(root, 0); + } + + bool dfs(TreeNode* root, int i) { + if (!root) return true; + int even = i % 2 == 0; + int prev = d.count(i) ? d[i] : (even ? 0 : 1e6); + if (even && (root->val % 2 == 0 || prev >= root->val)) return false; + if (!even && (root->val % 2 == 1 || prev <= root->val)) return false; + d[i] = root->val; + return dfs(root->left, i + 1) && dfs(root->right, i + 1); + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1609.Even Odd Tree/Solution2.go b/solution/1600-1699/1609.Even Odd Tree/Solution2.go new file mode 100644 index 0000000000000..faf39c405b976 --- /dev/null +++ b/solution/1600-1699/1609.Even Odd Tree/Solution2.go @@ -0,0 +1,35 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func isEvenOddTree(root *TreeNode) bool { + d := map[int]int{} + var dfs func(*TreeNode, int) bool + dfs = func(root *TreeNode, i int) bool { + if root == nil { + return true + } + even := i%2 == 0 + prev, ok := d[i] + if !ok { + if even { + prev = 0 + } else { + prev = 1000000 + } + } + if even && (root.Val%2 == 0 || prev >= root.Val) { + return false + } + if !even && (root.Val%2 == 1 || prev <= root.Val) { + return false + } + d[i] = root.Val + return dfs(root.Left, i+1) && dfs(root.Right, i+1) + } + return dfs(root, 0) +} \ No newline at end of file diff --git a/solution/1600-1699/1609.Even Odd Tree/Solution2.java b/solution/1600-1699/1609.Even Odd Tree/Solution2.java new file mode 100644 index 0000000000000..5777ede5c7d53 --- /dev/null +++ b/solution/1600-1699/1609.Even Odd Tree/Solution2.java @@ -0,0 +1,38 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private Map d = new HashMap<>(); + + public boolean isEvenOddTree(TreeNode root) { + return dfs(root, 0); + } + + private boolean dfs(TreeNode root, int i) { + if (root == null) { + return true; + } + boolean even = i % 2 == 0; + int prev = d.getOrDefault(i, even ? 0 : 1000000); + if (even && (root.val % 2 == 0 || prev >= root.val)) { + return false; + } + if (!even && (root.val % 2 == 1 || prev <= root.val)) { + return false; + } + d.put(i, root.val); + return dfs(root.left, i + 1) && dfs(root.right, i + 1); + } +} \ No newline at end of file diff --git a/solution/1600-1699/1609.Even Odd Tree/Solution2.py b/solution/1600-1699/1609.Even Odd Tree/Solution2.py new file mode 100644 index 0000000000000..5b62e28346364 --- /dev/null +++ b/solution/1600-1699/1609.Even Odd Tree/Solution2.py @@ -0,0 +1,22 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isEvenOddTree(self, root: Optional[TreeNode]) -> bool: + def dfs(root, i): + if root is None: + return True + even = i % 2 == 0 + prev = d.get(i, 0 if even else inf) + if even and (root.val % 2 == 0 or prev >= root.val): + return False + if not even and (root.val % 2 == 1 or prev <= root.val): + return False + d[i] = root.val + return dfs(root.left, i + 1) and dfs(root.right, i + 1) + + d = {} + return dfs(root, 0) diff --git a/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution.cpp b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution.cpp index 94c0b3a65ad74..fcfd50d7196e6 100644 --- a/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution.cpp +++ b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution.cpp @@ -1,10 +1,10 @@ -class Solution { -public: - int minimumOneBitOperations(int n) { - int ans = 0; - for (; n > 0; n >>= 1) { - ans ^= n; - } - return ans; - } +class Solution { +public: + int minimumOneBitOperations(int n) { + int ans = 0; + for (; n > 0; n >>= 1) { + ans ^= n; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution.java b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution.java index 90760a5722fdb..0deec58d982b3 100644 --- a/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution.java +++ b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution.java @@ -1,9 +1,9 @@ -class Solution { - public int minimumOneBitOperations(int n) { - int ans = 0; - for (; n > 0; n >>= 1) { - ans ^= n; - } - return ans; - } +class Solution { + public int minimumOneBitOperations(int n) { + int ans = 0; + for (; n > 0; n >>= 1) { + ans ^= n; + } + return ans; + } } \ No newline at end of file diff --git a/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution.py b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution.py index 5a6d14803b316..af0cef534839a 100644 --- a/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution.py +++ b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def minimumOneBitOperations(self, n: int) -> int: - ans = 0 - while n: - ans ^= n - n >>= 1 - return ans +class Solution: + def minimumOneBitOperations(self, n: int) -> int: + ans = 0 + while n: + ans ^= n + n >>= 1 + return ans diff --git a/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution2.cpp b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution2.cpp new file mode 100644 index 0000000000000..8d69eaa2d4a84 --- /dev/null +++ b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution2.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + int minimumOneBitOperations(int n) { + if (n == 0) { + return 0; + } + return n ^ minimumOneBitOperations(n >> 1); + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution2.go b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution2.go new file mode 100644 index 0000000000000..cb784a51c1f28 --- /dev/null +++ b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution2.go @@ -0,0 +1,6 @@ +func minimumOneBitOperations(n int) int { + if n == 0 { + return 0 + } + return n ^ minimumOneBitOperations(n>>1) +} \ No newline at end of file diff --git a/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution2.java b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution2.java new file mode 100644 index 0000000000000..a7f663e8c30c4 --- /dev/null +++ b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution2.java @@ -0,0 +1,8 @@ +class Solution { + public int minimumOneBitOperations(int n) { + if (n == 0) { + return 0; + } + return n ^ minimumOneBitOperations(n >> 1); + } +} \ No newline at end of file diff --git a/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution2.py b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution2.py new file mode 100644 index 0000000000000..5b7412abc10a3 --- /dev/null +++ b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution2.py @@ -0,0 +1,5 @@ +class Solution: + def minimumOneBitOperations(self, n: int) -> int: + if n == 0: + return 0 + return n ^ self.minimumOneBitOperations(n >> 1) diff --git a/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution2.ts b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution2.ts new file mode 100644 index 0000000000000..bf6c4dd61d69a --- /dev/null +++ b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/Solution2.ts @@ -0,0 +1,6 @@ +function minimumOneBitOperations(n: number): number { + if (n === 0) { + return 0; + } + return n ^ minimumOneBitOperations(n >> 1); +} diff --git a/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution.cpp b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution.cpp index e37d5473756c7..65d6fd7ebab99 100644 --- a/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution.cpp +++ b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution.cpp @@ -12,23 +12,24 @@ class Solution { public: bool checkEquivalence(Node* root1, Node* root2) { - function(Node*)> dfs = [&](Node* root) -> vector { - vector cnt(26); + int cnt[26]{}; + function dfs = [&](Node* root, int v) { if (!root) { - return cnt; + return; } - if (root->val == '+' || root->val == '-') { - auto l = dfs(root->left); - auto r = dfs(root->right); - int k = root->val == '+' ? 1 : -1; - for (int i = 0; i < 26; ++i) { - cnt[i] += l[i] + r[i] * k; - } - } else { - cnt[root->val - 'a']++; + if (root->val != '+') { + cnt[root->val - 'a'] += v; } - return cnt; + dfs(root->left, v); + dfs(root->right, v); }; - return dfs(root1) == dfs(root2); + dfs(root1, 1); + dfs(root2, -1); + for (int& x : cnt) { + if (x) { + return false; + } + } + return true; } }; \ No newline at end of file diff --git a/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution.java b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution.java index 3ad37e4fbecec..68100fe66369b 100644 --- a/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution.java +++ b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution.java @@ -14,32 +14,27 @@ * } */ class Solution { + private int[] cnt = new int[26]; + public boolean checkEquivalence(Node root1, Node root2) { - int[] cnt1 = dfs(root1); - int[] cnt2 = dfs(root2); - for (int i = 0; i < 26; ++i) { - if (cnt1[i] != cnt2[i]) { + dfs(root1, 1); + dfs(root2, -1); + for (int x : cnt) { + if (x != 0) { return false; } } return true; } - private int[] dfs(Node root) { - int[] cnt = new int[26]; + private void dfs(Node root, int v) { if (root == null) { - return cnt; + return; } - if (root.val == '+' || root.val == '-') { - int[] l = dfs(root.left); - int[] r = dfs(root.right); - int k = root.val == '+' ? 1 : -1; - for (int i = 0; i < 26; ++i) { - cnt[i] += l[i] + r[i] * k; - } - } else { - cnt[root.val - 'a']++; + if (root.val != '+') { + cnt[root.val - 'a'] += v; } - return cnt; + dfs(root.left, v); + dfs(root.right, v); } } \ No newline at end of file diff --git a/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution.js b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution.js index 435c8965fc00d..51f4a1cfc592e 100644 --- a/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution.js +++ b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution.js @@ -12,27 +12,21 @@ * @return {boolean} */ var checkEquivalence = function (root1, root2) { - const dfs = root => { - const cnt = new Array(26).fill(0); + const cnt = new Array(26).fill(0); + const dfs = (root, v) => { if (!root) { - return cnt; + return; } - if (root.val === '+' || root.val === '-') { - const l = dfs(root.left); - const r = dfs(root.right); - const k = root.val === '+' ? 1 : -1; - for (let i = 0; i < 26; ++i) { - cnt[i] = l[i] + k * r[i]; - } - } else { - cnt[root.val.charCodeAt(0) - 'a'.charCodeAt(0)]++; + if (root.val !== '+') { + cnt[root.val.charCodeAt(0) - 'a'.charCodeAt(0)] += v; } - return cnt; + dfs(root.left, v); + dfs(root.right, v); }; - const cnt1 = dfs(root1); - const cnt2 = dfs(root2); - for (let i = 0; i < 26; ++i) { - if (cnt1[i] !== cnt2[i]) { + dfs(root1, 1); + dfs(root2, -1); + for (const x of cnt) { + if (x) { return false; } } diff --git a/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution.py b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution.py index f313d8445afa8..1b5401cf68225 100644 --- a/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution.py +++ b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution.py @@ -6,17 +6,15 @@ # self.right = right class Solution: def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool: - def dfs(root): - cnt = [0] * 26 + def dfs(root, v): if root is None: - return cnt - if root.val in '+-': - l, r = dfs(root.left), dfs(root.right) - k = 1 if root.val == '+' else -1 - for i in range(26): - cnt[i] += l[i] + r[i] * k - else: - cnt[ord(root.val) - ord('a')] += 1 - return cnt + return + if root.val != '+': + cnt[root.val] += v + dfs(root.left, v) + dfs(root.right, v) - return dfs(root1) == dfs(root2) + cnt = Counter() + dfs(root1, 1) + dfs(root2, -1) + return all(x == 0 for x in cnt.values()) diff --git a/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution2.cpp b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution2.cpp new file mode 100644 index 0000000000000..e37d5473756c7 --- /dev/null +++ b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution2.cpp @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * struct Node { + * char val; + * Node *left; + * Node *right; + * Node() : val(' '), left(nullptr), right(nullptr) {} + * Node(char x) : val(x), left(nullptr), right(nullptr) {} + * Node(char x, Node *left, Node *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool checkEquivalence(Node* root1, Node* root2) { + function(Node*)> dfs = [&](Node* root) -> vector { + vector cnt(26); + if (!root) { + return cnt; + } + if (root->val == '+' || root->val == '-') { + auto l = dfs(root->left); + auto r = dfs(root->right); + int k = root->val == '+' ? 1 : -1; + for (int i = 0; i < 26; ++i) { + cnt[i] += l[i] + r[i] * k; + } + } else { + cnt[root->val - 'a']++; + } + return cnt; + }; + return dfs(root1) == dfs(root2); + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution2.java b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution2.java new file mode 100644 index 0000000000000..3ad37e4fbecec --- /dev/null +++ b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution2.java @@ -0,0 +1,45 @@ +/** + * Definition for a binary tree node. + * class Node { + * char val; + * Node left; + * Node right; + * Node() {this.val = ' ';} + * Node(char val) { this.val = val; } + * Node(char val, Node left, Node right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean checkEquivalence(Node root1, Node root2) { + int[] cnt1 = dfs(root1); + int[] cnt2 = dfs(root2); + for (int i = 0; i < 26; ++i) { + if (cnt1[i] != cnt2[i]) { + return false; + } + } + return true; + } + + private int[] dfs(Node root) { + int[] cnt = new int[26]; + if (root == null) { + return cnt; + } + if (root.val == '+' || root.val == '-') { + int[] l = dfs(root.left); + int[] r = dfs(root.right); + int k = root.val == '+' ? 1 : -1; + for (int i = 0; i < 26; ++i) { + cnt[i] += l[i] + r[i] * k; + } + } else { + cnt[root.val - 'a']++; + } + return cnt; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution2.js b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution2.js new file mode 100644 index 0000000000000..435c8965fc00d --- /dev/null +++ b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution2.js @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * function Node(val, left, right) { + * this.val = (val===undefined ? " " : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {Node} root1 + * @param {Node} root2 + * @return {boolean} + */ +var checkEquivalence = function (root1, root2) { + const dfs = root => { + const cnt = new Array(26).fill(0); + if (!root) { + return cnt; + } + if (root.val === '+' || root.val === '-') { + const l = dfs(root.left); + const r = dfs(root.right); + const k = root.val === '+' ? 1 : -1; + for (let i = 0; i < 26; ++i) { + cnt[i] = l[i] + k * r[i]; + } + } else { + cnt[root.val.charCodeAt(0) - 'a'.charCodeAt(0)]++; + } + return cnt; + }; + const cnt1 = dfs(root1); + const cnt2 = dfs(root2); + for (let i = 0; i < 26; ++i) { + if (cnt1[i] !== cnt2[i]) { + return false; + } + } + return true; +}; diff --git a/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution2.py b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution2.py new file mode 100644 index 0000000000000..f313d8445afa8 --- /dev/null +++ b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution2.py @@ -0,0 +1,22 @@ +# Definition for a binary tree node. +# class Node(object): +# def __init__(self, val=" ", left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool: + def dfs(root): + cnt = [0] * 26 + if root is None: + return cnt + if root.val in '+-': + l, r = dfs(root.left), dfs(root.right) + k = 1 if root.val == '+' else -1 + for i in range(26): + cnt[i] += l[i] + r[i] * k + else: + cnt[ord(root.val) - ord('a')] += 1 + return cnt + + return dfs(root1) == dfs(root2) diff --git a/solution/1600-1699/1614.Maximum Nesting Depth of the Parentheses/Solution.cs b/solution/1600-1699/1614.Maximum Nesting Depth of the Parentheses/Solution.cs index 6755beeec3eea..4f8dbac6bff25 100644 --- a/solution/1600-1699/1614.Maximum Nesting Depth of the Parentheses/Solution.cs +++ b/solution/1600-1699/1614.Maximum Nesting Depth of the Parentheses/Solution.cs @@ -10,4 +10,4 @@ public int MaxDepth(string s) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/1600-1699/1615.Maximal Network Rank/Solution2.py b/solution/1600-1699/1615.Maximal Network Rank/Solution2.py new file mode 100644 index 0000000000000..25aadff492eab --- /dev/null +++ b/solution/1600-1699/1615.Maximal Network Rank/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: + g = [[0] * n for _ in range(n)] + cnt = [0] * n + for a, b in roads: + g[a][b] = g[b][a] = 1 + cnt[a] += 1 + cnt[b] += 1 + return max(cnt[a] + cnt[b] - g[a][b] for a in range(n) for b in range(a + 1, n)) diff --git a/solution/1600-1699/1616.Split Two Strings to Make Palindrome/Solution.cpp b/solution/1600-1699/1616.Split Two Strings to Make Palindrome/Solution.cpp index b82d426a40ea5..aa6c4c80432cc 100644 --- a/solution/1600-1699/1616.Split Two Strings to Make Palindrome/Solution.cpp +++ b/solution/1600-1699/1616.Split Two Strings to Make Palindrome/Solution.cpp @@ -21,4 +21,4 @@ class Solution { } return i >= j; } -}; +}; \ No newline at end of file diff --git a/solution/1600-1699/1616.Split Two Strings to Make Palindrome/Solution.java b/solution/1600-1699/1616.Split Two Strings to Make Palindrome/Solution.java index 3ff47b17252c0..d22e8798bb7fb 100644 --- a/solution/1600-1699/1616.Split Two Strings to Make Palindrome/Solution.java +++ b/solution/1600-1699/1616.Split Two Strings to Make Palindrome/Solution.java @@ -20,4 +20,4 @@ private boolean check2(String a, int i, int j) { } return i >= j; } -} +} \ No newline at end of file diff --git a/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/Solution2.cpp b/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/Solution2.cpp new file mode 100644 index 0000000000000..33f2780b23fa5 --- /dev/null +++ b/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/Solution2.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + vector countSubgraphsForEachDiameter(int n, vector>& edges) { + vector> g(n); + for (auto& e : edges) { + int u = e[0] - 1, v = e[1] - 1; + g[u].emplace_back(v); + g[v].emplace_back(u); + } + vector ans(n - 1); + int nxt = 0, msk = 0; + auto bfs = [&](int u) -> int { + int d = -1; + msk ^= 1 << u; + queue q{{u}}; + while (!q.empty()) { + ++d; + for (int k = q.size(); k; --k) { + u = q.front(); + nxt = u; + q.pop(); + for (int& v : g[u]) { + if (msk >> v & 1) { + msk ^= 1 << v; + q.push(v); + } + } + } + } + return d; + }; + for (int mask = 1; mask < 1 << n; ++mask) { + if ((mask & (mask - 1)) == 0) { + continue; + } + msk = mask; + int cur = 31 - __builtin_clz(msk); + bfs(cur); + if (msk == 0) { + msk = mask; + int mx = bfs(nxt); + ++ans[mx - 1]; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/Solution2.go b/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/Solution2.go new file mode 100644 index 0000000000000..445c329ef3a28 --- /dev/null +++ b/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/Solution2.go @@ -0,0 +1,44 @@ +func countSubgraphsForEachDiameter(n int, edges [][]int) []int { + g := make([][]int, n) + for _, e := range edges { + u, v := e[0]-1, e[1]-1 + g[u] = append(g[u], v) + g[v] = append(g[v], u) + } + ans := make([]int, n-1) + var msk, nxt int + bfs := func(u int) int { + d := -1 + q := []int{u} + msk ^= 1 << u + for len(q) > 0 { + d++ + for k := len(q); k > 0; k-- { + u = q[0] + q = q[1:] + nxt = u + for _, v := range g[u] { + if msk>>v&1 == 1 { + msk ^= 1 << v + q = append(q, v) + } + } + } + } + return d + } + for mask := 1; mask < 1<[] g; + private int msk; + private int nxt; + + public int[] countSubgraphsForEachDiameter(int n, int[][] edges) { + g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (int[] e : edges) { + int u = e[0] - 1, v = e[1] - 1; + g[u].add(v); + g[v].add(u); + } + int[] ans = new int[n - 1]; + for (int mask = 1; mask < 1 << n; ++mask) { + if ((mask & (mask - 1)) == 0) { + continue; + } + msk = mask; + int cur = 31 - Integer.numberOfLeadingZeros(msk); + bfs(cur); + if (msk == 0) { + msk = mask; + int mx = bfs(nxt); + ++ans[mx - 1]; + } + } + return ans; + } + + private int bfs(int u) { + int d = -1; + Deque q = new ArrayDeque<>(); + q.offer(u); + msk ^= 1 << u; + while (!q.isEmpty()) { + ++d; + for (int k = q.size(); k > 0; --k) { + u = q.poll(); + nxt = u; + for (int v : g[u]) { + if ((msk >> v & 1) == 1) { + msk ^= 1 << v; + q.offer(v); + } + } + } + } + return d; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/Solution2.py b/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/Solution2.py new file mode 100644 index 0000000000000..a3f9fa523e375 --- /dev/null +++ b/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/Solution2.py @@ -0,0 +1,37 @@ +class Solution: + def countSubgraphsForEachDiameter( + self, n: int, edges: List[List[int]] + ) -> List[int]: + def bfs(u: int) -> int: + d = -1 + q = deque([u]) + nonlocal msk, nxt + msk ^= 1 << u + while q: + d += 1 + for _ in range(len(q)): + nxt = u = q.popleft() + for v in g[u]: + if msk >> v & 1: + msk ^= 1 << v + q.append(v) + return d + + g = defaultdict(list) + for u, v in edges: + u, v = u - 1, v - 1 + g[u].append(v) + g[v].append(u) + ans = [0] * (n - 1) + nxt = 0 + for mask in range(1, 1 << n): + if mask & (mask - 1) == 0: + continue + msk = mask + cur = msk.bit_length() - 1 + bfs(cur) + if msk == 0: + msk = mask + mx = bfs(nxt) + ans[mx - 1] += 1 + return ans diff --git a/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/Solution2.ts b/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/Solution2.ts new file mode 100644 index 0000000000000..f4c71c0f6ed0d --- /dev/null +++ b/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/Solution2.ts @@ -0,0 +1,65 @@ +function countSubgraphsForEachDiameter(n: number, edges: number[][]): number[] { + const g = Array.from({ length: n }, () => []); + for (const [u, v] of edges) { + g[u - 1].push(v - 1); + g[v - 1].push(u - 1); + } + const ans: number[] = new Array(n - 1).fill(0); + let [msk, nxt] = [0, 0]; + const bfs = (u: number) => { + let d = -1; + const q = [u]; + msk ^= 1 << u; + while (q.length) { + ++d; + for (let k = q.length; k; --k) { + u = q.shift()!; + nxt = u; + for (const v of g[u]) { + if ((msk >> v) & 1) { + msk ^= 1 << v; + q.push(v); + } + } + } + } + return d; + }; + for (let mask = 1; mask < 1 << n; ++mask) { + if ((mask & (mask - 1)) === 0) { + continue; + } + msk = mask; + const cur = 31 - numberOfLeadingZeros(msk); + bfs(cur); + if (msk === 0) { + msk = mask; + const mx = bfs(nxt); + ++ans[mx - 1]; + } + } + return ans; +} + +function numberOfLeadingZeros(i: number): number { + if (i == 0) return 32; + let n = 1; + if (i >>> 16 == 0) { + n += 16; + i <<= 16; + } + if (i >>> 24 == 0) { + n += 8; + i <<= 8; + } + if (i >>> 28 == 0) { + n += 4; + i <<= 4; + } + if (i >>> 30 == 0) { + n += 2; + i <<= 2; + } + n -= i >>> 31; + return n; +} diff --git a/solution/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/Solution.cpp b/solution/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/Solution.cpp index 41093c27c2de1..644666fcdab7b 100644 --- a/solution/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/Solution.cpp +++ b/solution/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/Solution.cpp @@ -32,4 +32,4 @@ class Solution { } return check(fonts[left]) ? fonts[left] : -1; } -}; +}; \ No newline at end of file diff --git a/solution/1600-1699/1622.Fancy Sequence/Solution.cpp b/solution/1600-1699/1622.Fancy Sequence/Solution.cpp index 8b32e0a4d6fa2..326dbf0f723b8 100644 --- a/solution/1600-1699/1622.Fancy Sequence/Solution.cpp +++ b/solution/1600-1699/1622.Fancy Sequence/Solution.cpp @@ -1,140 +1,140 @@ -const int MOD = 1e9 + 7; - -class Node { -public: - Node* left; - Node* right; - int l; - int r; - int mid; - long long v; - long long add; - long long mul; - - Node(int l, int r) { - this->l = l; - this->r = r; - this->mid = (l + r) >> 1; - this->left = this->right = nullptr; - v = add = 0; - mul = 1; - } -}; - -class SegmentTree { -private: - Node* root; - -public: - SegmentTree() { - root = new Node(1, 1e5 + 1); - } - - void modifyAdd(int l, int r, int inc) { - modifyAdd(l, r, inc, root); - } - - void modifyAdd(int l, int r, int inc, Node* node) { - if (l > r) return; - if (node->l >= l && node->r <= r) { - node->v = (node->v + (node->r - node->l + 1) * inc) % MOD; - node->add = (node->add + inc) % MOD; - return; - } - pushdown(node); - if (l <= node->mid) modifyAdd(l, r, inc, node->left); - if (r > node->mid) modifyAdd(l, r, inc, node->right); - pushup(node); - } - - void modifyMul(int l, int r, int m) { - modifyMul(l, r, m, root); - } - - void modifyMul(int l, int r, int m, Node* node) { - if (l > r) return; - if (node->l >= l && node->r <= r) { - node->v = (node->v * m) % MOD; - node->add = (node->add * m) % MOD; - node->mul = (node->mul * m) % MOD; - return; - } - pushdown(node); - if (l <= node->mid) modifyMul(l, r, m, node->left); - if (r > node->mid) modifyMul(l, r, m, node->right); - pushup(node); - } - - int query(int l, int r) { - return query(l, r, root); - } - - int query(int l, int r, Node* node) { - if (l > r) return 0; - if (node->l >= l && node->r <= r) return node->v; - pushdown(node); - int v = 0; - if (l <= node->mid) v = (v + query(l, r, node->left)) % MOD; - if (r > node->mid) v = (v + query(l, r, node->right)) % MOD; - return v; - } - - void pushup(Node* node) { - node->v = (node->left->v + node->right->v) % MOD; - } - - void pushdown(Node* node) { - if (!node->left) node->left = new Node(node->l, node->mid); - if (!node->right) node->right = new Node(node->mid + 1, node->r); - if (node->add || node->mul != 1) { - long add = node->add, mul = node->mul; - Node* left = node->left; - Node* right = node->right; - left->v = (left->v * mul + (left->r - left->l + 1) * add) % MOD; - right->v = (right->v * mul + (right->r - right->l + 1) * add) % MOD; - left->add = (left->add * mul + add) % MOD; - right->add = (right->add * mul + add) % MOD; - left->mul = (left->mul * mul) % MOD; - right->mul = (right->mul * mul) % MOD; - node->add = 0; - node->mul = 1; - } - } -}; - -class Fancy { -public: - int n; - SegmentTree* tree; - - Fancy() { - n = 0; - tree = new SegmentTree(); - } - - void append(int val) { - ++n; - tree->modifyAdd(n, n, val); - } - - void addAll(int inc) { - tree->modifyAdd(1, n, inc); - } - - void multAll(int m) { - tree->modifyMul(1, n, m); - } - - int getIndex(int idx) { - return idx >= n ? -1 : tree->query(idx + 1, idx + 1); - } -}; - -/** - * Your Fancy object will be instantiated and called as such: - * Fancy* obj = new Fancy(); - * obj->append(val); - * obj->addAll(inc); - * obj->multAll(m); - * int param_4 = obj->getIndex(idx); +const int MOD = 1e9 + 7; + +class Node { +public: + Node* left; + Node* right; + int l; + int r; + int mid; + long long v; + long long add; + long long mul; + + Node(int l, int r) { + this->l = l; + this->r = r; + this->mid = (l + r) >> 1; + this->left = this->right = nullptr; + v = add = 0; + mul = 1; + } +}; + +class SegmentTree { +private: + Node* root; + +public: + SegmentTree() { + root = new Node(1, 1e5 + 1); + } + + void modifyAdd(int l, int r, int inc) { + modifyAdd(l, r, inc, root); + } + + void modifyAdd(int l, int r, int inc, Node* node) { + if (l > r) return; + if (node->l >= l && node->r <= r) { + node->v = (node->v + (node->r - node->l + 1) * inc) % MOD; + node->add = (node->add + inc) % MOD; + return; + } + pushdown(node); + if (l <= node->mid) modifyAdd(l, r, inc, node->left); + if (r > node->mid) modifyAdd(l, r, inc, node->right); + pushup(node); + } + + void modifyMul(int l, int r, int m) { + modifyMul(l, r, m, root); + } + + void modifyMul(int l, int r, int m, Node* node) { + if (l > r) return; + if (node->l >= l && node->r <= r) { + node->v = (node->v * m) % MOD; + node->add = (node->add * m) % MOD; + node->mul = (node->mul * m) % MOD; + return; + } + pushdown(node); + if (l <= node->mid) modifyMul(l, r, m, node->left); + if (r > node->mid) modifyMul(l, r, m, node->right); + pushup(node); + } + + int query(int l, int r) { + return query(l, r, root); + } + + int query(int l, int r, Node* node) { + if (l > r) return 0; + if (node->l >= l && node->r <= r) return node->v; + pushdown(node); + int v = 0; + if (l <= node->mid) v = (v + query(l, r, node->left)) % MOD; + if (r > node->mid) v = (v + query(l, r, node->right)) % MOD; + return v; + } + + void pushup(Node* node) { + node->v = (node->left->v + node->right->v) % MOD; + } + + void pushdown(Node* node) { + if (!node->left) node->left = new Node(node->l, node->mid); + if (!node->right) node->right = new Node(node->mid + 1, node->r); + if (node->add || node->mul != 1) { + long add = node->add, mul = node->mul; + Node* left = node->left; + Node* right = node->right; + left->v = (left->v * mul + (left->r - left->l + 1) * add) % MOD; + right->v = (right->v * mul + (right->r - right->l + 1) * add) % MOD; + left->add = (left->add * mul + add) % MOD; + right->add = (right->add * mul + add) % MOD; + left->mul = (left->mul * mul) % MOD; + right->mul = (right->mul * mul) % MOD; + node->add = 0; + node->mul = 1; + } + } +}; + +class Fancy { +public: + int n; + SegmentTree* tree; + + Fancy() { + n = 0; + tree = new SegmentTree(); + } + + void append(int val) { + ++n; + tree->modifyAdd(n, n, val); + } + + void addAll(int inc) { + tree->modifyAdd(1, n, inc); + } + + void multAll(int m) { + tree->modifyMul(1, n, m); + } + + int getIndex(int idx) { + return idx >= n ? -1 : tree->query(idx + 1, idx + 1); + } +}; + +/** + * Your Fancy object will be instantiated and called as such: + * Fancy* obj = new Fancy(); + * obj->append(val); + * obj->addAll(inc); + * obj->multAll(m); + * int param_4 = obj->getIndex(idx); */ \ No newline at end of file diff --git a/solution/1600-1699/1622.Fancy Sequence/Solution.java b/solution/1600-1699/1622.Fancy Sequence/Solution.java index 7721dde8b0cda..9c2393904c850 100644 --- a/solution/1600-1699/1622.Fancy Sequence/Solution.java +++ b/solution/1600-1699/1622.Fancy Sequence/Solution.java @@ -1,151 +1,151 @@ -class Node { - Node left; - Node right; - int l; - int r; - int mid; - long v; - long add; - long mul = 1; - - public Node(int l, int r) { - this.l = l; - this.r = r; - this.mid = (l + r) >> 1; - } -} - -class SegmentTree { - private Node root = new Node(1, (int) 1e5 + 1); - private static final int MOD = (int) 1e9 + 7; - - public SegmentTree() { - } - - public void modifyAdd(int l, int r, int inc) { - modifyAdd(l, r, inc, root); - } - - public void modifyAdd(int l, int r, int inc, Node node) { - if (l > r) { - return; - } - if (node.l >= l && node.r <= r) { - node.v = (node.v + (node.r - node.l + 1) * inc) % MOD; - node.add = (node.add + inc) % MOD; - return; - } - pushdown(node); - if (l <= node.mid) { - modifyAdd(l, r, inc, node.left); - } - if (r > node.mid) { - modifyAdd(l, r, inc, node.right); - } - pushup(node); - } - - public void modifyMul(int l, int r, int m) { - modifyMul(l, r, m, root); - } - - public void modifyMul(int l, int r, int m, Node node) { - if (l > r) { - return; - } - if (node.l >= l && node.r <= r) { - node.v = (node.v * m) % MOD; - node.add = (node.add * m) % MOD; - node.mul = (node.mul * m) % MOD; - return; - } - pushdown(node); - if (l <= node.mid) { - modifyMul(l, r, m, node.left); - } - if (r > node.mid) { - modifyMul(l, r, m, node.right); - } - pushup(node); - } - - public int query(int l, int r) { - return query(l, r, root); - } - - public int query(int l, int r, Node node) { - if (l > r) { - return 0; - } - if (node.l >= l && node.r <= r) { - return (int) node.v; - } - pushdown(node); - int v = 0; - if (l <= node.mid) { - v = (v + query(l, r, node.left)) % MOD; - } - if (r > node.mid) { - v = (v + query(l, r, node.right)) % MOD; - } - return v; - } - - public void pushup(Node node) { - node.v = (node.left.v + node.right.v) % MOD; - } - - public void pushdown(Node node) { - if (node.left == null) { - node.left = new Node(node.l, node.mid); - } - if (node.right == null) { - node.right = new Node(node.mid + 1, node.r); - } - if (node.add != 0 || node.mul != 1) { - Node left = node.left, right = node.right; - left.v = (left.v * node.mul + (left.r - left.l + 1) * node.add) % MOD; - right.v = (right.v * node.mul + (right.r - right.l + 1) * node.add) % MOD; - left.add = (left.add * node.mul + node.add) % MOD; - right.add = (right.add * node.mul + node.add) % MOD; - left.mul = (left.mul * node.mul) % MOD; - right.mul = (right.mul * node.mul) % MOD; - node.add = 0; - node.mul = 1; - } - } -} - -class Fancy { - private int n; - private SegmentTree tree = new SegmentTree(); - - public Fancy() { - } - - public void append(int val) { - ++n; - tree.modifyAdd(n, n, val); - } - - public void addAll(int inc) { - tree.modifyAdd(1, n, inc); - } - - public void multAll(int m) { - tree.modifyMul(1, n, m); - } - - public int getIndex(int idx) { - return idx >= n ? -1 : tree.query(idx + 1, idx + 1); - } -} - -/** - * Your Fancy object will be instantiated and called as such: - * Fancy obj = new Fancy(); - * obj.append(val); - * obj.addAll(inc); - * obj.multAll(m); - * int param_4 = obj.getIndex(idx); +class Node { + Node left; + Node right; + int l; + int r; + int mid; + long v; + long add; + long mul = 1; + + public Node(int l, int r) { + this.l = l; + this.r = r; + this.mid = (l + r) >> 1; + } +} + +class SegmentTree { + private Node root = new Node(1, (int) 1e5 + 1); + private static final int MOD = (int) 1e9 + 7; + + public SegmentTree() { + } + + public void modifyAdd(int l, int r, int inc) { + modifyAdd(l, r, inc, root); + } + + public void modifyAdd(int l, int r, int inc, Node node) { + if (l > r) { + return; + } + if (node.l >= l && node.r <= r) { + node.v = (node.v + (node.r - node.l + 1) * inc) % MOD; + node.add = (node.add + inc) % MOD; + return; + } + pushdown(node); + if (l <= node.mid) { + modifyAdd(l, r, inc, node.left); + } + if (r > node.mid) { + modifyAdd(l, r, inc, node.right); + } + pushup(node); + } + + public void modifyMul(int l, int r, int m) { + modifyMul(l, r, m, root); + } + + public void modifyMul(int l, int r, int m, Node node) { + if (l > r) { + return; + } + if (node.l >= l && node.r <= r) { + node.v = (node.v * m) % MOD; + node.add = (node.add * m) % MOD; + node.mul = (node.mul * m) % MOD; + return; + } + pushdown(node); + if (l <= node.mid) { + modifyMul(l, r, m, node.left); + } + if (r > node.mid) { + modifyMul(l, r, m, node.right); + } + pushup(node); + } + + public int query(int l, int r) { + return query(l, r, root); + } + + public int query(int l, int r, Node node) { + if (l > r) { + return 0; + } + if (node.l >= l && node.r <= r) { + return (int) node.v; + } + pushdown(node); + int v = 0; + if (l <= node.mid) { + v = (v + query(l, r, node.left)) % MOD; + } + if (r > node.mid) { + v = (v + query(l, r, node.right)) % MOD; + } + return v; + } + + public void pushup(Node node) { + node.v = (node.left.v + node.right.v) % MOD; + } + + public void pushdown(Node node) { + if (node.left == null) { + node.left = new Node(node.l, node.mid); + } + if (node.right == null) { + node.right = new Node(node.mid + 1, node.r); + } + if (node.add != 0 || node.mul != 1) { + Node left = node.left, right = node.right; + left.v = (left.v * node.mul + (left.r - left.l + 1) * node.add) % MOD; + right.v = (right.v * node.mul + (right.r - right.l + 1) * node.add) % MOD; + left.add = (left.add * node.mul + node.add) % MOD; + right.add = (right.add * node.mul + node.add) % MOD; + left.mul = (left.mul * node.mul) % MOD; + right.mul = (right.mul * node.mul) % MOD; + node.add = 0; + node.mul = 1; + } + } +} + +class Fancy { + private int n; + private SegmentTree tree = new SegmentTree(); + + public Fancy() { + } + + public void append(int val) { + ++n; + tree.modifyAdd(n, n, val); + } + + public void addAll(int inc) { + tree.modifyAdd(1, n, inc); + } + + public void multAll(int m) { + tree.modifyMul(1, n, m); + } + + public int getIndex(int idx) { + return idx >= n ? -1 : tree.query(idx + 1, idx + 1); + } +} + +/** + * Your Fancy object will be instantiated and called as such: + * Fancy obj = new Fancy(); + * obj.append(val); + * obj.addAll(inc); + * obj.multAll(m); + * int param_4 = obj.getIndex(idx); */ \ No newline at end of file diff --git a/solution/1600-1699/1622.Fancy Sequence/Solution.py b/solution/1600-1699/1622.Fancy Sequence/Solution.py index 1d1d2dd912118..c4051425ead4e 100644 --- a/solution/1600-1699/1622.Fancy Sequence/Solution.py +++ b/solution/1600-1699/1622.Fancy Sequence/Solution.py @@ -1,112 +1,112 @@ -MOD = int(1e9 + 7) - - -class Node: - def __init__(self, l, r): - self.left = None - self.right = None - self.l = l - self.r = r - self.mid = (l + r) >> 1 - self.v = 0 - self.add = 0 - self.mul = 1 - - -class SegmentTree: - def __init__(self): - self.root = Node(1, int(1e5 + 1)) - - def modifyAdd(self, l, r, inc, node=None): - if l > r: - return - if node is None: - node = self.root - if node.l >= l and node.r <= r: - node.v = (node.v + (node.r - node.l + 1) * inc) % MOD - node.add += inc - return - self.pushdown(node) - if l <= node.mid: - self.modifyAdd(l, r, inc, node.left) - if r > node.mid: - self.modifyAdd(l, r, inc, node.right) - self.pushup(node) - - def modifyMul(self, l, r, m, node=None): - if l > r: - return - if node is None: - node = self.root - if node.l >= l and node.r <= r: - node.v = (node.v * m) % MOD - node.add = (node.add * m) % MOD - node.mul = (node.mul * m) % MOD - return - self.pushdown(node) - if l <= node.mid: - self.modifyMul(l, r, m, node.left) - if r > node.mid: - self.modifyMul(l, r, m, node.right) - self.pushup(node) - - def query(self, l, r, node=None): - if l > r: - return 0 - if node is None: - node = self.root - if node.l >= l and node.r <= r: - return node.v - self.pushdown(node) - v = 0 - if l <= node.mid: - v = (v + self.query(l, r, node.left)) % MOD - if r > node.mid: - v = (v + self.query(l, r, node.right)) % MOD - return v - - def pushup(self, node): - node.v = (node.left.v + node.right.v) % MOD - - def pushdown(self, node): - if node.left is None: - node.left = Node(node.l, node.mid) - if node.right is None: - node.right = Node(node.mid + 1, node.r) - left, right = node.left, node.right - if node.add != 0 or node.mul != 1: - left.v = (left.v * node.mul + (left.r - left.l + 1) * node.add) % MOD - right.v = (right.v * node.mul + (right.r - right.l + 1) * node.add) % MOD - left.add = (left.add * node.mul + node.add) % MOD - right.add = (right.add * node.mul + node.add) % MOD - left.mul = (left.mul * node.mul) % MOD - right.mul = (right.mul * node.mul) % MOD - node.add = 0 - node.mul = 1 - - -class Fancy: - def __init__(self): - self.n = 0 - self.tree = SegmentTree() - - def append(self, val: int) -> None: - self.n += 1 - self.tree.modifyAdd(self.n, self.n, val) - - def addAll(self, inc: int) -> None: - self.tree.modifyAdd(1, self.n, inc) - - def multAll(self, m: int) -> None: - self.tree.modifyMul(1, self.n, m) - - def getIndex(self, idx: int) -> int: - return -1 if idx >= self.n else self.tree.query(idx + 1, idx + 1) - - -# Your Fancy object will be instantiated and called as such: -# obj = Fancy() -# obj.append(val) -# obj.addAll(inc) -# obj.multAll(m) -# param_4 = obj.getIndex(idx) +MOD = int(1e9 + 7) + + +class Node: + def __init__(self, l, r): + self.left = None + self.right = None + self.l = l + self.r = r + self.mid = (l + r) >> 1 + self.v = 0 + self.add = 0 + self.mul = 1 + + +class SegmentTree: + def __init__(self): + self.root = Node(1, int(1e5 + 1)) + + def modifyAdd(self, l, r, inc, node=None): + if l > r: + return + if node is None: + node = self.root + if node.l >= l and node.r <= r: + node.v = (node.v + (node.r - node.l + 1) * inc) % MOD + node.add += inc + return + self.pushdown(node) + if l <= node.mid: + self.modifyAdd(l, r, inc, node.left) + if r > node.mid: + self.modifyAdd(l, r, inc, node.right) + self.pushup(node) + + def modifyMul(self, l, r, m, node=None): + if l > r: + return + if node is None: + node = self.root + if node.l >= l and node.r <= r: + node.v = (node.v * m) % MOD + node.add = (node.add * m) % MOD + node.mul = (node.mul * m) % MOD + return + self.pushdown(node) + if l <= node.mid: + self.modifyMul(l, r, m, node.left) + if r > node.mid: + self.modifyMul(l, r, m, node.right) + self.pushup(node) + + def query(self, l, r, node=None): + if l > r: + return 0 + if node is None: + node = self.root + if node.l >= l and node.r <= r: + return node.v + self.pushdown(node) + v = 0 + if l <= node.mid: + v = (v + self.query(l, r, node.left)) % MOD + if r > node.mid: + v = (v + self.query(l, r, node.right)) % MOD + return v + + def pushup(self, node): + node.v = (node.left.v + node.right.v) % MOD + + def pushdown(self, node): + if node.left is None: + node.left = Node(node.l, node.mid) + if node.right is None: + node.right = Node(node.mid + 1, node.r) + left, right = node.left, node.right + if node.add != 0 or node.mul != 1: + left.v = (left.v * node.mul + (left.r - left.l + 1) * node.add) % MOD + right.v = (right.v * node.mul + (right.r - right.l + 1) * node.add) % MOD + left.add = (left.add * node.mul + node.add) % MOD + right.add = (right.add * node.mul + node.add) % MOD + left.mul = (left.mul * node.mul) % MOD + right.mul = (right.mul * node.mul) % MOD + node.add = 0 + node.mul = 1 + + +class Fancy: + def __init__(self): + self.n = 0 + self.tree = SegmentTree() + + def append(self, val: int) -> None: + self.n += 1 + self.tree.modifyAdd(self.n, self.n, val) + + def addAll(self, inc: int) -> None: + self.tree.modifyAdd(1, self.n, inc) + + def multAll(self, m: int) -> None: + self.tree.modifyMul(1, self.n, m) + + def getIndex(self, idx: int) -> int: + return -1 if idx >= self.n else self.tree.query(idx + 1, idx + 1) + + +# Your Fancy object will be instantiated and called as such: +# obj = Fancy() +# obj.append(val) +# obj.addAll(inc) +# obj.multAll(m) +# param_4 = obj.getIndex(idx) diff --git a/solution/1600-1699/1624.Largest Substring Between Two Equal Characters/Solution.c b/solution/1600-1699/1624.Largest Substring Between Two Equal Characters/Solution.c index e9afe9321d4cf..8a80a66b19274 100644 --- a/solution/1600-1699/1624.Largest Substring Between Two Equal Characters/Solution.c +++ b/solution/1600-1699/1624.Largest Substring Between Two Equal Characters/Solution.c @@ -15,4 +15,4 @@ int maxLengthBetweenEqualCharacters(char* s) { } } return res; -} +} \ No newline at end of file diff --git a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.cpp b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.cpp index 284e176e87ea2..aa9373fcdca5e 100644 --- a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.cpp +++ b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.cpp @@ -1,23 +1,23 @@ class Solution { public: string findLexSmallestString(string s, int a, int b) { - int n = s.size(); + queue q{{s}}; + unordered_set vis{{s}}; string ans = s; - for (int i = 0; i < n; ++i) { - s = s.substr(n - b) + s.substr(0, n - b); - for (int j = 0; j < 10; ++j) { - for (int k = 1; k < n; k += 2) { - s[k] = (s[k] - '0' + a) % 10 + '0'; - } - if (b & 1) { - for (int p = 0; p < 10; ++p) { - for (int k = 0; k < n; k += 2) { - s[k] = (s[k] - '0' + a) % 10 + '0'; - } - ans = min(ans, s); - } - } else { - ans = min(ans, s); + int n = s.size(); + while (!q.empty()) { + s = q.front(); + q.pop(); + ans = min(ans, s); + string t1 = s; + for (int i = 1; i < n; i += 2) { + t1[i] = (t1[i] - '0' + a) % 10 + '0'; + } + string t2 = s.substr(n - b) + s.substr(0, n - b); + for (auto& t : {t1, t2}) { + if (!vis.count(t)) { + vis.insert(t); + q.emplace(t); } } } diff --git a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.go b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.go index b6057be63faf2..9ae6d23c5c7fb 100644 --- a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.go +++ b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.go @@ -1,28 +1,23 @@ func findLexSmallestString(s string, a int, b int) string { - n := len(s) + q := []string{s} + vis := map[string]bool{s: true} ans := s - for _ = range s { - s = s[n-b:] + s[:n-b] - cs := []byte(s) - for j := 0; j < 10; j++ { - for k := 1; k < n; k += 2 { - cs[k] = byte((int(cs[k]-'0')+a)%10 + '0') - } - if b&1 == 1 { - for p := 0; p < 10; p++ { - for k := 0; k < n; k += 2 { - cs[k] = byte((int(cs[k]-'0')+a)%10 + '0') - } - s = string(cs) - if ans > s { - ans = s - } - } - } else { - s = string(cs) - if ans > s { - ans = s - } + n := len(s) + for len(q) > 0 { + s = q[0] + q = q[1:] + if ans > s { + ans = s + } + t1 := []byte(s) + for i := 1; i < n; i += 2 { + t1[i] = byte((int(t1[i]-'0')+a)%10 + '0') + } + t2 := s[n-b:] + s[:n-b] + for _, t := range []string{string(t1), t2} { + if !vis[t] { + vis[t] = true + q = append(q, t) } } } diff --git a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.java b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.java index 12f1c40ec78e2..b81ce5abf4b78 100644 --- a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.java +++ b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.java @@ -1,29 +1,25 @@ class Solution { public String findLexSmallestString(String s, int a, int b) { - int n = s.length(); + Deque q = new ArrayDeque<>(); + q.offer(s); + Set vis = new HashSet<>(); + vis.add(s); String ans = s; - for (int i = 0; i < n; ++i) { - s = s.substring(b) + s.substring(0, b); + int n = s.length(); + while (!q.isEmpty()) { + s = q.poll(); + if (ans.compareTo(s) > 0) { + ans = s; + } char[] cs = s.toCharArray(); - for (int j = 0; j < 10; ++j) { - for (int k = 1; k < n; k += 2) { - cs[k] = (char) (((cs[k] - '0' + a) % 10) + '0'); - } - if ((b & 1) == 1) { - for (int p = 0; p < 10; ++p) { - for (int k = 0; k < n; k += 2) { - cs[k] = (char) (((cs[k] - '0' + a) % 10) + '0'); - } - s = String.valueOf(cs); - if (ans.compareTo(s) > 0) { - ans = s; - } - } - } else { - s = String.valueOf(cs); - if (ans.compareTo(s) > 0) { - ans = s; - } + for (int i = 1; i < n; i += 2) { + cs[i] = (char) (((cs[i] - '0' + a) % 10) + '0'); + } + String t1 = String.valueOf(cs); + String t2 = s.substring(n - b) + s.substring(0, n - b); + for (String t : List.of(t1, t2)) { + if (vis.add(t)) { + q.offer(t); } } } diff --git a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.py b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.py index b412bc2214a79..d1fc53ce93976 100644 --- a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.py +++ b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.py @@ -1,22 +1,18 @@ class Solution: def findLexSmallestString(self, s: str, a: int, b: int) -> str: + q = deque([s]) + vis = {s} ans = s - n = len(s) - s = list(s) - for _ in range(n): - s = s[-b:] + s[:-b] - for j in range(10): - for k in range(1, n, 2): - s[k] = str((int(s[k]) + a) % 10) - if b & 1: - for p in range(10): - for k in range(0, n, 2): - s[k] = str((int(s[k]) + a) % 10) - t = ''.join(s) - if ans > t: - ans = t - else: - t = ''.join(s) - if ans > t: - ans = t + while q: + s = q.popleft() + if ans > s: + ans = s + t1 = ''.join( + [str((int(c) + a) % 10) if i & 1 else c for i, c in enumerate(s)] + ) + t2 = s[-b:] + s[:-b] + for t in (t1, t2): + if t not in vis: + vis.add(t) + q.append(t) return ans diff --git a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution2.cpp b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution2.cpp new file mode 100644 index 0000000000000..284e176e87ea2 --- /dev/null +++ b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution2.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + string findLexSmallestString(string s, int a, int b) { + int n = s.size(); + string ans = s; + for (int i = 0; i < n; ++i) { + s = s.substr(n - b) + s.substr(0, n - b); + for (int j = 0; j < 10; ++j) { + for (int k = 1; k < n; k += 2) { + s[k] = (s[k] - '0' + a) % 10 + '0'; + } + if (b & 1) { + for (int p = 0; p < 10; ++p) { + for (int k = 0; k < n; k += 2) { + s[k] = (s[k] - '0' + a) % 10 + '0'; + } + ans = min(ans, s); + } + } else { + ans = min(ans, s); + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution2.go b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution2.go new file mode 100644 index 0000000000000..b6057be63faf2 --- /dev/null +++ b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution2.go @@ -0,0 +1,30 @@ +func findLexSmallestString(s string, a int, b int) string { + n := len(s) + ans := s + for _ = range s { + s = s[n-b:] + s[:n-b] + cs := []byte(s) + for j := 0; j < 10; j++ { + for k := 1; k < n; k += 2 { + cs[k] = byte((int(cs[k]-'0')+a)%10 + '0') + } + if b&1 == 1 { + for p := 0; p < 10; p++ { + for k := 0; k < n; k += 2 { + cs[k] = byte((int(cs[k]-'0')+a)%10 + '0') + } + s = string(cs) + if ans > s { + ans = s + } + } + } else { + s = string(cs) + if ans > s { + ans = s + } + } + } + } + return ans +} \ No newline at end of file diff --git a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution2.java b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution2.java new file mode 100644 index 0000000000000..12f1c40ec78e2 --- /dev/null +++ b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution2.java @@ -0,0 +1,32 @@ +class Solution { + public String findLexSmallestString(String s, int a, int b) { + int n = s.length(); + String ans = s; + for (int i = 0; i < n; ++i) { + s = s.substring(b) + s.substring(0, b); + char[] cs = s.toCharArray(); + for (int j = 0; j < 10; ++j) { + for (int k = 1; k < n; k += 2) { + cs[k] = (char) (((cs[k] - '0' + a) % 10) + '0'); + } + if ((b & 1) == 1) { + for (int p = 0; p < 10; ++p) { + for (int k = 0; k < n; k += 2) { + cs[k] = (char) (((cs[k] - '0' + a) % 10) + '0'); + } + s = String.valueOf(cs); + if (ans.compareTo(s) > 0) { + ans = s; + } + } + } else { + s = String.valueOf(cs); + if (ans.compareTo(s) > 0) { + ans = s; + } + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution2.py b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution2.py new file mode 100644 index 0000000000000..b412bc2214a79 --- /dev/null +++ b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution2.py @@ -0,0 +1,22 @@ +class Solution: + def findLexSmallestString(self, s: str, a: int, b: int) -> str: + ans = s + n = len(s) + s = list(s) + for _ in range(n): + s = s[-b:] + s[:-b] + for j in range(10): + for k in range(1, n, 2): + s[k] = str((int(s[k]) + a) % 10) + if b & 1: + for p in range(10): + for k in range(0, n, 2): + s[k] = str((int(s[k]) + a) % 10) + t = ''.join(s) + if ans > t: + ans = t + else: + t = ''.join(s) + if ans > t: + ans = t + return ans diff --git a/solution/1600-1699/1626.Best Team With No Conflicts/Solution.cpp b/solution/1600-1699/1626.Best Team With No Conflicts/Solution.cpp index a670d40eb118f..20c156fefcc7e 100644 --- a/solution/1600-1699/1626.Best Team With No Conflicts/Solution.cpp +++ b/solution/1600-1699/1626.Best Team With No Conflicts/Solution.cpp @@ -1,30 +1,3 @@ -class BinaryIndexedTree { -public: - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int val) { - while (x <= n) { - c[x] = max(c[x], val); - x += x & -x; - } - } - - int query(int x) { - int s = 0; - while (x) { - s = max(s, c[x]); - x -= x & -x; - } - return s; - } - -private: - int n; - vector c; -}; - class Solution { public: int bestTeamScore(vector& scores, vector& ages) { @@ -34,11 +7,15 @@ class Solution { arr[i] = {scores[i], ages[i]}; } sort(arr.begin(), arr.end()); - int m = *max_element(ages.begin(), ages.end()); - BinaryIndexedTree tree(m); - for (auto& [score, age] : arr) { - tree.update(age, score + tree.query(age)); + vector f(n); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (arr[i].second >= arr[j].second) { + f[i] = max(f[i], f[j]); + } + } + f[i] += arr[i].first; } - return tree.query(m); + return *max_element(f.begin(), f.end()); } }; \ No newline at end of file diff --git a/solution/1600-1699/1626.Best Team With No Conflicts/Solution.go b/solution/1600-1699/1626.Best Team With No Conflicts/Solution.go index d959ae5550eff..0e08a1ad6a69f 100644 --- a/solution/1600-1699/1626.Best Team With No Conflicts/Solution.go +++ b/solution/1600-1699/1626.Best Team With No Conflicts/Solution.go @@ -1,44 +1,21 @@ -type BinaryIndexedTree struct { - n int - c []int -} - -func newBinaryIndexedTree(n int) *BinaryIndexedTree { - c := make([]int, n+1) - return &BinaryIndexedTree{n, c} -} - -func (this *BinaryIndexedTree) update(x, val int) { - for x <= this.n { - this.c[x] = max(this.c[x], val) - x += x & -x - } -} - -func (this *BinaryIndexedTree) query(x int) int { - s := 0 - for x > 0 { - s = max(s, this.c[x]) - x -= x & -x - } - return s -} - func bestTeamScore(scores []int, ages []int) int { n := len(ages) arr := make([][2]int, n) - m := 0 - for i, age := range ages { - m = max(m, age) - arr[i] = [2]int{scores[i], age} + for i := range ages { + arr[i] = [2]int{scores[i], ages[i]} } sort.Slice(arr, func(i, j int) bool { a, b := arr[i], arr[j] return a[0] < b[0] || a[0] == b[0] && a[1] < b[1] }) - tree := newBinaryIndexedTree(m) - for _, x := range arr { - tree.update(x[1], x[0]+tree.query(x[1])) + f := make([]int, n) + for i := range arr { + for j := 0; j < i; j++ { + if arr[i][1] >= arr[j][1] { + f[i] = max(f[i], f[j]) + } + } + f[i] += arr[i][0] } - return tree.query(m) + return slices.Max(f) } \ No newline at end of file diff --git a/solution/1600-1699/1626.Best Team With No Conflicts/Solution.java b/solution/1600-1699/1626.Best Team With No Conflicts/Solution.java index 25fea41b033ec..57db89ac9d219 100644 --- a/solution/1600-1699/1626.Best Team With No Conflicts/Solution.java +++ b/solution/1600-1699/1626.Best Team With No Conflicts/Solution.java @@ -1,29 +1,3 @@ -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void update(int x, int val) { - while (x <= n) { - c[x] = Math.max(c[x], val); - x += x & -x; - } - } - - public int query(int x) { - int s = 0; - while (x > 0) { - s = Math.max(s, c[x]); - x -= x & -x; - } - return s; - } -} - class Solution { public int bestTeamScore(int[] scores, int[] ages) { int n = ages.length; @@ -32,14 +6,17 @@ public int bestTeamScore(int[] scores, int[] ages) { arr[i] = new int[] {scores[i], ages[i]}; } Arrays.sort(arr, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); - int m = 0; - for (int age : ages) { - m = Math.max(m, age); - } - BinaryIndexedTree tree = new BinaryIndexedTree(m); - for (int[] x : arr) { - tree.update(x[1], x[0] + tree.query(x[1])); + int[] f = new int[n]; + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (arr[i][1] >= arr[j][1]) { + f[i] = Math.max(f[i], f[j]); + } + } + f[i] += arr[i][0]; + ans = Math.max(ans, f[i]); } - return tree.query(m); + return ans; } } \ No newline at end of file diff --git a/solution/1600-1699/1626.Best Team With No Conflicts/Solution.py b/solution/1600-1699/1626.Best Team With No Conflicts/Solution.py index 6a21a31c45688..4c1c7419f4264 100644 --- a/solution/1600-1699/1626.Best Team With No Conflicts/Solution.py +++ b/solution/1600-1699/1626.Best Team With No Conflicts/Solution.py @@ -1,25 +1,11 @@ -class BinaryIndexedTree: - def __init__(self, n): - self.n = n - self.c = [0] * (n + 1) - - def update(self, x, val): - while x <= self.n: - self.c[x] = max(self.c[x], val) - x += x & -x - - def query(self, x): - s = 0 - while x: - s = max(s, self.c[x]) - x -= x & -x - return s - - class Solution: def bestTeamScore(self, scores: List[int], ages: List[int]) -> int: - m = max(ages) - tree = BinaryIndexedTree(m) - for score, age in sorted(zip(scores, ages)): - tree.update(age, score + tree.query(age)) - return tree.query(m) + arr = sorted(zip(scores, ages)) + n = len(arr) + f = [0] * n + for i, (score, age) in enumerate(arr): + for j in range(i): + if age >= arr[j][1]: + f[i] = max(f[i], f[j]) + f[i] += score + return max(f) diff --git a/solution/1600-1699/1626.Best Team With No Conflicts/Solution2.cpp b/solution/1600-1699/1626.Best Team With No Conflicts/Solution2.cpp new file mode 100644 index 0000000000000..a670d40eb118f --- /dev/null +++ b/solution/1600-1699/1626.Best Team With No Conflicts/Solution2.cpp @@ -0,0 +1,44 @@ +class BinaryIndexedTree { +public: + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int val) { + while (x <= n) { + c[x] = max(c[x], val); + x += x & -x; + } + } + + int query(int x) { + int s = 0; + while (x) { + s = max(s, c[x]); + x -= x & -x; + } + return s; + } + +private: + int n; + vector c; +}; + +class Solution { +public: + int bestTeamScore(vector& scores, vector& ages) { + int n = ages.size(); + vector> arr(n); + for (int i = 0; i < n; ++i) { + arr[i] = {scores[i], ages[i]}; + } + sort(arr.begin(), arr.end()); + int m = *max_element(ages.begin(), ages.end()); + BinaryIndexedTree tree(m); + for (auto& [score, age] : arr) { + tree.update(age, score + tree.query(age)); + } + return tree.query(m); + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1626.Best Team With No Conflicts/Solution2.go b/solution/1600-1699/1626.Best Team With No Conflicts/Solution2.go new file mode 100644 index 0000000000000..d959ae5550eff --- /dev/null +++ b/solution/1600-1699/1626.Best Team With No Conflicts/Solution2.go @@ -0,0 +1,44 @@ +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) update(x, val int) { + for x <= this.n { + this.c[x] = max(this.c[x], val) + x += x & -x + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s = max(s, this.c[x]) + x -= x & -x + } + return s +} + +func bestTeamScore(scores []int, ages []int) int { + n := len(ages) + arr := make([][2]int, n) + m := 0 + for i, age := range ages { + m = max(m, age) + arr[i] = [2]int{scores[i], age} + } + sort.Slice(arr, func(i, j int) bool { + a, b := arr[i], arr[j] + return a[0] < b[0] || a[0] == b[0] && a[1] < b[1] + }) + tree := newBinaryIndexedTree(m) + for _, x := range arr { + tree.update(x[1], x[0]+tree.query(x[1])) + } + return tree.query(m) +} \ No newline at end of file diff --git a/solution/1600-1699/1626.Best Team With No Conflicts/Solution2.java b/solution/1600-1699/1626.Best Team With No Conflicts/Solution2.java new file mode 100644 index 0000000000000..25fea41b033ec --- /dev/null +++ b/solution/1600-1699/1626.Best Team With No Conflicts/Solution2.java @@ -0,0 +1,45 @@ +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int val) { + while (x <= n) { + c[x] = Math.max(c[x], val); + x += x & -x; + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s = Math.max(s, c[x]); + x -= x & -x; + } + return s; + } +} + +class Solution { + public int bestTeamScore(int[] scores, int[] ages) { + int n = ages.length; + int[][] arr = new int[n][2]; + for (int i = 0; i < n; ++i) { + arr[i] = new int[] {scores[i], ages[i]}; + } + Arrays.sort(arr, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); + int m = 0; + for (int age : ages) { + m = Math.max(m, age); + } + BinaryIndexedTree tree = new BinaryIndexedTree(m); + for (int[] x : arr) { + tree.update(x[1], x[0] + tree.query(x[1])); + } + return tree.query(m); + } +} \ No newline at end of file diff --git a/solution/1600-1699/1626.Best Team With No Conflicts/Solution2.py b/solution/1600-1699/1626.Best Team With No Conflicts/Solution2.py new file mode 100644 index 0000000000000..6a21a31c45688 --- /dev/null +++ b/solution/1600-1699/1626.Best Team With No Conflicts/Solution2.py @@ -0,0 +1,25 @@ +class BinaryIndexedTree: + def __init__(self, n): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x, val): + while x <= self.n: + self.c[x] = max(self.c[x], val) + x += x & -x + + def query(self, x): + s = 0 + while x: + s = max(s, self.c[x]) + x -= x & -x + return s + + +class Solution: + def bestTeamScore(self, scores: List[int], ages: List[int]) -> int: + m = max(ages) + tree = BinaryIndexedTree(m) + for score, age in sorted(zip(scores, ages)): + tree.update(age, score + tree.query(age)) + return tree.query(m) diff --git a/solution/1600-1699/1627.Graph Connectivity With Threshold/Solution.cpp b/solution/1600-1699/1627.Graph Connectivity With Threshold/Solution.cpp index fca098e75549b..5c6d3d6829c51 100644 --- a/solution/1600-1699/1627.Graph Connectivity With Threshold/Solution.cpp +++ b/solution/1600-1699/1627.Graph Connectivity With Threshold/Solution.cpp @@ -1,50 +1,50 @@ -class UnionFind { -public: - UnionFind(int n) { - p = vector(n); - size = vector(n, 1); - iota(p.begin(), p.end(), 0); - } - - bool unite(int a, int b) { - int pa = find(a), pb = find(b); - if (pa == pb) { - return false; - } - if (size[pa] > size[pb]) { - p[pb] = pa; - size[pa] += size[pb]; - } else { - p[pa] = pb; - size[pb] += size[pa]; - } - return true; - } - - int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } - -private: - vector p, size; -}; - -class Solution { -public: - vector areConnected(int n, int threshold, vector>& queries) { - UnionFind uf(n + 1); - for (int a = threshold + 1; a <= n; ++a) { - for (int b = a + a; b <= n; b += a) { - uf.unite(a, b); - } - } - vector ans; - for (auto& q : queries) { - ans.push_back(uf.find(q[0]) == uf.find(q[1])); - } - return ans; - } +class UnionFind { +public: + UnionFind(int n) { + p = vector(n); + size = vector(n, 1); + iota(p.begin(), p.end(), 0); + } + + bool unite(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) { + return false; + } + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + return true; + } + + int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + +private: + vector p, size; +}; + +class Solution { +public: + vector areConnected(int n, int threshold, vector>& queries) { + UnionFind uf(n + 1); + for (int a = threshold + 1; a <= n; ++a) { + for (int b = a + a; b <= n; b += a) { + uf.unite(a, b); + } + } + vector ans; + for (auto& q : queries) { + ans.push_back(uf.find(q[0]) == uf.find(q[1])); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1600-1699/1627.Graph Connectivity With Threshold/Solution.java b/solution/1600-1699/1627.Graph Connectivity With Threshold/Solution.java index ef41ff93b3271..69545ec9eb112 100644 --- a/solution/1600-1699/1627.Graph Connectivity With Threshold/Solution.java +++ b/solution/1600-1699/1627.Graph Connectivity With Threshold/Solution.java @@ -1,51 +1,51 @@ -class UnionFind { - private int[] p; - private int[] size; - - public UnionFind(int n) { - p = new int[n]; - size = new int[n]; - for (int i = 0; i < n; ++i) { - p[i] = i; - size[i] = 1; - } - } - - public int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } - - public boolean union(int a, int b) { - int pa = find(a), pb = find(b); - if (pa == pb) { - return false; - } - if (size[pa] > size[pb]) { - p[pb] = pa; - size[pa] += size[pb]; - } else { - p[pa] = pb; - size[pb] += size[pa]; - } - return true; - } -} - -class Solution { - public List areConnected(int n, int threshold, int[][] queries) { - UnionFind uf = new UnionFind(n + 1); - for (int a = threshold + 1; a <= n; ++a) { - for (int b = a + a; b <= n; b += a) { - uf.union(a, b); - } - } - List ans = new ArrayList<>(); - for (var q : queries) { - ans.add(uf.find(q[0]) == uf.find(q[1])); - } - return ans; - } +class UnionFind { + private int[] p; + private int[] size; + + public UnionFind(int n) { + p = new int[n]; + size = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + size[i] = 1; + } + } + + public int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + + public boolean union(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) { + return false; + } + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + return true; + } +} + +class Solution { + public List areConnected(int n, int threshold, int[][] queries) { + UnionFind uf = new UnionFind(n + 1); + for (int a = threshold + 1; a <= n; ++a) { + for (int b = a + a; b <= n; b += a) { + uf.union(a, b); + } + } + List ans = new ArrayList<>(); + for (var q : queries) { + ans.add(uf.find(q[0]) == uf.find(q[1])); + } + return ans; + } } \ No newline at end of file diff --git a/solution/1600-1699/1627.Graph Connectivity With Threshold/Solution.py b/solution/1600-1699/1627.Graph Connectivity With Threshold/Solution.py index 500491f1ad98e..e7431cac03483 100644 --- a/solution/1600-1699/1627.Graph Connectivity With Threshold/Solution.py +++ b/solution/1600-1699/1627.Graph Connectivity With Threshold/Solution.py @@ -1,32 +1,32 @@ -class UnionFind: - def __init__(self, n): - self.p = list(range(n)) - self.size = [1] * n - - def find(self, x): - if self.p[x] != x: - self.p[x] = self.find(self.p[x]) - return self.p[x] - - def union(self, a, b): - pa, pb = self.find(a), self.find(b) - if pa == pb: - return False - if self.size[pa] > self.size[pb]: - self.p[pb] = pa - self.size[pa] += self.size[pb] - else: - self.p[pa] = pb - self.size[pb] += self.size[pa] - return True - - -class Solution: - def areConnected( - self, n: int, threshold: int, queries: List[List[int]] - ) -> List[bool]: - uf = UnionFind(n + 1) - for a in range(threshold + 1, n + 1): - for b in range(a + a, n + 1, a): - uf.union(a, b) - return [uf.find(a) == uf.find(b) for a, b in queries] +class UnionFind: + def __init__(self, n): + self.p = list(range(n)) + self.size = [1] * n + + def find(self, x): + if self.p[x] != x: + self.p[x] = self.find(self.p[x]) + return self.p[x] + + def union(self, a, b): + pa, pb = self.find(a), self.find(b) + if pa == pb: + return False + if self.size[pa] > self.size[pb]: + self.p[pb] = pa + self.size[pa] += self.size[pb] + else: + self.p[pa] = pb + self.size[pb] += self.size[pa] + return True + + +class Solution: + def areConnected( + self, n: int, threshold: int, queries: List[List[int]] + ) -> List[bool]: + uf = UnionFind(n + 1) + for a in range(threshold + 1, n + 1): + for b in range(a + a, n + 1, a): + uf.union(a, b) + return [uf.find(a) == uf.find(b) for a, b in queries] diff --git a/solution/1600-1699/1628.Design an Expression Tree With Evaluate Function/Solution.py b/solution/1600-1699/1628.Design an Expression Tree With Evaluate Function/Solution.py index 1d68bf308c35d..9a846ee7c93bb 100644 --- a/solution/1600-1699/1628.Design an Expression Tree With Evaluate Function/Solution.py +++ b/solution/1600-1699/1628.Design an Expression Tree With Evaluate Function/Solution.py @@ -36,7 +36,7 @@ def evaluate(self) -> int: return left // right -""" +""" This is the TreeBuilder class. You can treat it as the driver code that takes the postinfix input and returns the expression tree represnting it as a Node. diff --git a/solution/1600-1699/1630.Arithmetic Subarrays/Solution.cs b/solution/1600-1699/1630.Arithmetic Subarrays/Solution.cs index 22f2e09d06cac..0cfccc3090e44 100644 --- a/solution/1600-1699/1630.Arithmetic Subarrays/Solution.cs +++ b/solution/1600-1699/1630.Arithmetic Subarrays/Solution.cs @@ -22,3 +22,4 @@ public IList CheckArithmeticSubarrays(int[] nums, int[] l, int[] r) { return ans; } } + diff --git a/solution/1600-1699/1631.Path With Minimum Effort/Solution.cpp b/solution/1600-1699/1631.Path With Minimum Effort/Solution.cpp index acf2dfedc7e94..bd9867f657089 100644 --- a/solution/1600-1699/1631.Path With Minimum Effort/Solution.cpp +++ b/solution/1600-1699/1631.Path With Minimum Effort/Solution.cpp @@ -1,29 +1,65 @@ -class Solution { -public: - int minimumEffortPath(vector>& heights) { - int m = heights.size(), n = heights[0].size(); - int dist[m][n]; - memset(dist, 0x3f, sizeof(dist)); - dist[0][0] = 0; - int dirs[5] = {0, 1, 0, -1, 0}; - using T = tuple; - priority_queue, greater> pq; - pq.emplace(0, 0, 0); - while (!pq.empty()) { - auto [t, i, j] = pq.top(); - pq.pop(); - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x < 0 || x >= m || y < 0 || y >= n) { - continue; - } - int d = max(t, abs(heights[x][y] - heights[i][j])); - if (d < dist[x][y]) { - dist[x][y] = d; - pq.emplace(d, x, y); - } - } - } - return dist[m - 1][n - 1]; - } +class UnionFind { +public: + UnionFind(int n) { + p = vector(n); + size = vector(n, 1); + iota(p.begin(), p.end(), 0); + } + + bool unite(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) { + return false; + } + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + return true; + } + + int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + + bool connected(int a, int b) { + return find(a) == find(b); + } + +private: + vector p, size; +}; + +class Solution { +public: + int minimumEffortPath(vector>& heights) { + int m = heights.size(), n = heights[0].size(); + vector> edges; + int dirs[3] = {0, 1, 0}; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k < 2; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n) { + edges.push_back({abs(heights[i][j] - heights[x][y]), i * n + j, x * n + y}); + } + } + } + } + sort(edges.begin(), edges.end()); + UnionFind uf(m * n); + for (auto& [h, a, b] : edges) { + uf.unite(a, b); + if (uf.connected(0, m * n - 1)) { + return h; + } + } + return 0; + } }; \ No newline at end of file diff --git a/solution/1600-1699/1631.Path With Minimum Effort/Solution.go b/solution/1600-1699/1631.Path With Minimum Effort/Solution.go index 720c20d4cec79..61f5224f8edce 100644 --- a/solution/1600-1699/1631.Path With Minimum Effort/Solution.go +++ b/solution/1600-1699/1631.Path With Minimum Effort/Solution.go @@ -1,30 +1,66 @@ +type unionFind struct { + p, size []int +} + +func newUnionFind(n int) *unionFind { + p := make([]int, n) + size := make([]int, n) + for i := range p { + p[i] = i + size[i] = 1 + } + return &unionFind{p, size} +} + +func (uf *unionFind) find(x int) int { + if uf.p[x] != x { + uf.p[x] = uf.find(uf.p[x]) + } + return uf.p[x] +} + +func (uf *unionFind) union(a, b int) bool { + pa, pb := uf.find(a), uf.find(b) + if pa == pb { + return false + } + if uf.size[pa] > uf.size[pb] { + uf.p[pb] = pa + uf.size[pa] += uf.size[pb] + } else { + uf.p[pa] = pb + uf.size[pb] += uf.size[pa] + } + return true +} + +func (uf *unionFind) connected(a, b int) bool { + return uf.find(a) == uf.find(b) +} + func minimumEffortPath(heights [][]int) int { m, n := len(heights), len(heights[0]) - dist := make([][]int, m) - for i := range dist { - dist[i] = make([]int, n) - for j := range dist[i] { - dist[i][j] = 1 << 30 - } - } - dirs := [5]int{-1, 0, 1, 0, -1} - dist[0][0] = 0 - pq := hp{} - heap.Push(&pq, tuple{0, 0, 0}) - for pq.Len() > 0 { - p := heap.Pop(&pq).(tuple) - t, i, j := p.t, p.i, p.j - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < m && y >= 0 && y < n { - if d := max(t, abs(heights[x][y]-heights[i][j])); d < dist[x][y] { - dist[x][y] = d - heap.Push(&pq, tuple{d, x, y}) + edges := make([][3]int, 0, m*n*2) + dirs := [3]int{0, 1, 0} + for i, row := range heights { + for j, h := range row { + for k := 0; k < 2; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n { + edges = append(edges, [3]int{abs(h - heights[x][y]), i*n + j, x*n + y}) } } } } - return dist[m-1][n-1] + sort.Slice(edges, func(i, j int) bool { return edges[i][0] < edges[j][0] }) + uf := newUnionFind(m * n) + for _, e := range edges { + uf.union(e[1], e[2]) + if uf.connected(0, m*n-1) { + return e[0] + } + } + return 0 } func abs(x int) int { @@ -32,13 +68,4 @@ func abs(x int) int { return -x } return x -} - -type tuple struct{ t, i, j int } -type hp []tuple - -func (h hp) Len() int { return len(h) } -func (h hp) Less(i, j int) bool { return h[i].t < h[j].t } -func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } -func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } \ No newline at end of file +} \ No newline at end of file diff --git a/solution/1600-1699/1631.Path With Minimum Effort/Solution.java b/solution/1600-1699/1631.Path With Minimum Effort/Solution.java index bca23f677acbd..7b65cacb63478 100644 --- a/solution/1600-1699/1631.Path With Minimum Effort/Solution.java +++ b/solution/1600-1699/1631.Path With Minimum Effort/Solution.java @@ -1,28 +1,67 @@ -class Solution { - public int minimumEffortPath(int[][] heights) { - int m = heights.length, n = heights[0].length; - int[][] dist = new int[m][n]; - for (var row : dist) { - Arrays.fill(row, 1 << 30); - } - dist[0][0] = 0; - int[] dirs = {-1, 0, 1, 0, -1}; - PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); - pq.offer(new int[] {0, 0, 0}); - while (!pq.isEmpty()) { - var p = pq.poll(); - int t = p[0], i = p[1], j = p[2]; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n) { - int d = Math.max(t, Math.abs(heights[x][y] - heights[i][j])); - if (d < dist[x][y]) { - dist[x][y] = d; - pq.offer(new int[] {d, x, y}); - } - } - } - } - return dist[m - 1][n - 1]; - } +class UnionFind { + private final int[] p; + private final int[] size; + + public UnionFind(int n) { + p = new int[n]; + size = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + size[i] = 1; + } + } + + public int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + + public boolean union(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) { + return false; + } + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + return true; + } + + public boolean connected(int a, int b) { + return find(a) == find(b); + } +} + +class Solution { + public int minimumEffortPath(int[][] heights) { + int m = heights.length, n = heights[0].length; + UnionFind uf = new UnionFind(m * n); + List edges = new ArrayList<>(); + int[] dirs = {1, 0, 1}; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k < 2; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n) { + int d = Math.abs(heights[i][j] - heights[x][y]); + edges.add(new int[] {d, i * n + j, x * n + y}); + } + } + } + } + Collections.sort(edges, (a, b) -> a[0] - b[0]); + for (int[] e : edges) { + uf.union(e[1], e[2]); + if (uf.connected(0, m * n - 1)) { + return e[0]; + } + } + return 0; + } } \ No newline at end of file diff --git a/solution/1600-1699/1631.Path With Minimum Effort/Solution.py b/solution/1600-1699/1631.Path With Minimum Effort/Solution.py index d3b5b9a7c46ce..3c57e58e8cd28 100644 --- a/solution/1600-1699/1631.Path With Minimum Effort/Solution.py +++ b/solution/1600-1699/1631.Path With Minimum Effort/Solution.py @@ -1,19 +1,46 @@ -class Solution: - def minimumEffortPath(self, heights: List[List[int]]) -> int: - m, n = len(heights), len(heights[0]) - dist = [[inf] * n for _ in range(m)] - dist[0][0] = 0 - dirs = (-1, 0, 1, 0, -1) - q = [(0, 0, 0)] - while q: - t, i, j = heappop(q) - for a, b in pairwise(dirs): - x, y = i + a, j + b - if ( - 0 <= x < m - and 0 <= y < n - and (d := max(t, abs(heights[i][j] - heights[x][y]))) < dist[x][y] - ): - dist[x][y] = d - heappush(q, (d, x, y)) - return int(dist[-1][-1]) +class UnionFind: + def __init__(self, n): + self.p = list(range(n)) + self.size = [1] * n + + def find(self, x): + if self.p[x] != x: + self.p[x] = self.find(self.p[x]) + return self.p[x] + + def union(self, a, b): + pa, pb = self.find(a), self.find(b) + if pa == pb: + return False + if self.size[pa] > self.size[pb]: + self.p[pb] = pa + self.size[pa] += self.size[pb] + else: + self.p[pa] = pb + self.size[pb] += self.size[pa] + return True + + def connected(self, a, b): + return self.find(a) == self.find(b) + + +class Solution: + def minimumEffortPath(self, heights: List[List[int]]) -> int: + m, n = len(heights), len(heights[0]) + uf = UnionFind(m * n) + e = [] + dirs = (0, 1, 0) + for i in range(m): + for j in range(n): + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n: + e.append( + (abs(heights[i][j] - heights[x][y]), i * n + j, x * n + y) + ) + e.sort() + for h, a, b in e: + uf.union(a, b) + if uf.connected(0, m * n - 1): + return h + return 0 diff --git a/solution/1600-1699/1631.Path With Minimum Effort/Solution.ts b/solution/1600-1699/1631.Path With Minimum Effort/Solution.ts index e118242bb00e3..fab1b7782713f 100644 --- a/solution/1600-1699/1631.Path With Minimum Effort/Solution.ts +++ b/solution/1600-1699/1631.Path With Minimum Effort/Solution.ts @@ -1,23 +1,68 @@ +class UnionFind { + private p: number[]; + private size: number[]; + + constructor(n: number) { + this.p = Array.from({ length: n }, (_, i) => i); + this.size = Array(n).fill(1); + } + + find(x: number): number { + if (this.p[x] !== x) { + this.p[x] = this.find(this.p[x]); + } + return this.p[x]; + } + + union(a: number, b: number): boolean { + const pa = this.find(a); + const pb = this.find(b); + if (pa === pb) { + return false; + } + if (this.size[pa] > this.size[pb]) { + this.p[pb] = pa; + this.size[pa] += this.size[pb]; + } else { + this.p[pa] = pb; + this.size[pb] += this.size[pa]; + } + return true; + } + + connected(a: number, b: number): boolean { + return this.find(a) === this.find(b); + } +} + function minimumEffortPath(heights: number[][]): number { const m = heights.length; const n = heights[0].length; - const pq = new PriorityQueue({ compare: (a, b) => a[0] - b[0] }); - pq.enqueue([0, 0, 0]); - const dist = Array.from({ length: m }, () => Array.from({ length: n }, () => Infinity)); - dist[0][0] = 0; - const dirs = [-1, 0, 1, 0, -1]; - while (pq.size() > 0) { - const [t, i, j] = pq.dequeue()!; - for (let k = 0; k < 4; ++k) { - const [x, y] = [i + dirs[k], j + dirs[k + 1]]; - if (x >= 0 && x < m && y >= 0 && y < n) { - const d = Math.max(t, Math.abs(heights[x][y] - heights[i][j])); - if (d < dist[x][y]) { - dist[x][y] = d; - pq.enqueue([d, x, y]); + const uf = new UnionFind(m * n); + const edges: number[][] = []; + const dirs = [1, 0, 1]; + + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + for (let k = 0; k < 2; ++k) { + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n) { + const d = Math.abs(heights[i][j] - heights[x][y]); + edges.push([d, i * n + j, x * n + y]); } } } } - return dist[m - 1][n - 1]; + + edges.sort((a, b) => a[0] - b[0]); + + for (const [h, a, b] of edges) { + uf.union(a, b); + if (uf.connected(0, m * n - 1)) { + return h; + } + } + + return 0; } diff --git a/solution/1600-1699/1631.Path With Minimum Effort/Solution2.cpp b/solution/1600-1699/1631.Path With Minimum Effort/Solution2.cpp new file mode 100644 index 0000000000000..0ed5b603600f9 --- /dev/null +++ b/solution/1600-1699/1631.Path With Minimum Effort/Solution2.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + int minimumEffortPath(vector>& heights) { + auto check = [&](int h) { + int m = heights.size(), n = heights[0].size(); + bool vis[m][n]; + memset(vis, false, sizeof(vis)); + queue> q{{{0, 0}}}; + vis[0][0] = true; + int dirs[5] = {-1, 0, 1, 0, -1}; + while (!q.empty()) { + auto [i, j] = q.front(); + q.pop(); + if (i == m - 1 && j == n - 1) { + return true; + } + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && abs(heights[x][y] - heights[i][j]) <= h) { + q.push({x, y}); + vis[x][y] = true; + } + } + } + return false; + }; + int l = 0, r = 1e6; + while (l < r) { + int mid = (l + r) >> 1; + if (check(mid)) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1631.Path With Minimum Effort/Solution2.go b/solution/1600-1699/1631.Path With Minimum Effort/Solution2.go new file mode 100644 index 0000000000000..ed8727e61f0d8 --- /dev/null +++ b/solution/1600-1699/1631.Path With Minimum Effort/Solution2.go @@ -0,0 +1,36 @@ +func minimumEffortPath(heights [][]int) int { + return sort.Search(1e6, func(h int) bool { + m, n := len(heights), len(heights[0]) + vis := make([][]bool, m) + for i := range vis { + vis[i] = make([]bool, n) + } + vis[0][0] = true + q := [][2]int{} + q = append(q, [2]int{0, 0}) + dirs := [5]int{-1, 0, 1, 0, -1} + for len(q) > 0 { + p := q[0] + q = q[1:] + i, j := p[0], p[1] + if i == m-1 && j == n-1 { + return true + } + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && abs(heights[x][y]-heights[i][j]) <= h { + vis[x][y] = true + q = append(q, [2]int{x, y}) + } + } + } + return false + }) +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} \ No newline at end of file diff --git a/solution/1600-1699/1631.Path With Minimum Effort/Solution2.java b/solution/1600-1699/1631.Path With Minimum Effort/Solution2.java new file mode 100644 index 0000000000000..dd348330aa9c7 --- /dev/null +++ b/solution/1600-1699/1631.Path With Minimum Effort/Solution2.java @@ -0,0 +1,39 @@ +class Solution { + public int minimumEffortPath(int[][] heights) { + int l = 0, r = 1000000; + while (l < r) { + int mid = (l + r) >> 1; + if (check(heights, mid)) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } + + private boolean check(int[][] heights, int h) { + int m = heights.length, n = heights[0].length; + boolean[][] vis = new boolean[m][n]; + Deque q = new ArrayDeque<>(); + q.add(new int[] {0, 0}); + vis[0][0] = true; + int[] dirs = {-1, 0, 1, 0, -1}; + while (!q.isEmpty()) { + var p = q.poll(); + int i = p[0], j = p[1]; + if (i == m - 1 && j == n - 1) { + return true; + } + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] + && Math.abs(heights[x][y] - heights[i][j]) <= h) { + q.add(new int[] {x, y}); + vis[x][y] = true; + } + } + } + return false; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1631.Path With Minimum Effort/Solution2.py b/solution/1600-1699/1631.Path With Minimum Effort/Solution2.py new file mode 100644 index 0000000000000..100ee50da010b --- /dev/null +++ b/solution/1600-1699/1631.Path With Minimum Effort/Solution2.py @@ -0,0 +1,25 @@ +class Solution: + def minimumEffortPath(self, heights: List[List[int]]) -> int: + def check(h: int) -> bool: + q = deque([(0, 0)]) + vis = {(0, 0)} + dirs = (-1, 0, 1, 0, -1) + while q: + for _ in range(len(q)): + i, j = q.popleft() + if i == m - 1 and j == n - 1: + return True + for a, b in pairwise(dirs): + x, y = i + a, j + b + if ( + 0 <= x < m + and 0 <= y < n + and (x, y) not in vis + and abs(heights[i][j] - heights[x][y]) <= h + ): + q.append((x, y)) + vis.add((x, y)) + return False + + m, n = len(heights), len(heights[0]) + return bisect_left(range(10**6), True, key=check) diff --git a/solution/1600-1699/1631.Path With Minimum Effort/Solution2.ts b/solution/1600-1699/1631.Path With Minimum Effort/Solution2.ts new file mode 100644 index 0000000000000..3c434eea5d3c7 --- /dev/null +++ b/solution/1600-1699/1631.Path With Minimum Effort/Solution2.ts @@ -0,0 +1,45 @@ +function minimumEffortPath(heights: number[][]): number { + const check = (h: number): boolean => { + const m = heights.length; + const n = heights[0].length; + const vis: boolean[][] = Array.from({ length: m }, () => Array(n).fill(false)); + const dirs: number[] = [-1, 0, 1, 0, -1]; + const q: [number, number][] = [[0, 0]]; + vis[0][0] = true; + + while (q.length > 0) { + const [i, j] = q.pop()!; + if (i === m - 1 && j === n - 1) { + return true; + } + + for (let k = 0; k < 4; ++k) { + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if ( + x >= 0 && + x < m && + y >= 0 && + y < n && + !vis[x][y] && + Math.abs(heights[x][y] - heights[i][j]) <= h + ) { + q.push([x, y]); + vis[x][y] = true; + } + } + } + return false; + }; + + let [l, r] = [0, 10 ** 6]; + while (l < r) { + const mid = (l + r) >> 1; + if (check(mid)) { + r = mid; + } else { + l = mid + 1; + } + } + return l; +} diff --git a/solution/1600-1699/1631.Path With Minimum Effort/Solution3.cpp b/solution/1600-1699/1631.Path With Minimum Effort/Solution3.cpp new file mode 100644 index 0000000000000..fd9102f3ae375 --- /dev/null +++ b/solution/1600-1699/1631.Path With Minimum Effort/Solution3.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int minimumEffortPath(vector>& heights) { + int m = heights.size(), n = heights[0].size(); + int dist[m][n]; + memset(dist, 0x3f, sizeof(dist)); + dist[0][0] = 0; + int dirs[5] = {0, 1, 0, -1, 0}; + using T = tuple; + priority_queue, greater> pq; + pq.emplace(0, 0, 0); + while (!pq.empty()) { + auto [t, i, j] = pq.top(); + pq.pop(); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x < 0 || x >= m || y < 0 || y >= n) { + continue; + } + int d = max(t, abs(heights[x][y] - heights[i][j])); + if (d < dist[x][y]) { + dist[x][y] = d; + pq.emplace(d, x, y); + } + } + } + return dist[m - 1][n - 1]; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1631.Path With Minimum Effort/Solution3.go b/solution/1600-1699/1631.Path With Minimum Effort/Solution3.go new file mode 100644 index 0000000000000..720c20d4cec79 --- /dev/null +++ b/solution/1600-1699/1631.Path With Minimum Effort/Solution3.go @@ -0,0 +1,44 @@ +func minimumEffortPath(heights [][]int) int { + m, n := len(heights), len(heights[0]) + dist := make([][]int, m) + for i := range dist { + dist[i] = make([]int, n) + for j := range dist[i] { + dist[i][j] = 1 << 30 + } + } + dirs := [5]int{-1, 0, 1, 0, -1} + dist[0][0] = 0 + pq := hp{} + heap.Push(&pq, tuple{0, 0, 0}) + for pq.Len() > 0 { + p := heap.Pop(&pq).(tuple) + t, i, j := p.t, p.i, p.j + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n { + if d := max(t, abs(heights[x][y]-heights[i][j])); d < dist[x][y] { + dist[x][y] = d + heap.Push(&pq, tuple{d, x, y}) + } + } + } + } + return dist[m-1][n-1] +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} + +type tuple struct{ t, i, j int } +type hp []tuple + +func (h hp) Len() int { return len(h) } +func (h hp) Less(i, j int) bool { return h[i].t < h[j].t } +func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } +func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } \ No newline at end of file diff --git a/solution/1600-1699/1631.Path With Minimum Effort/Solution3.java b/solution/1600-1699/1631.Path With Minimum Effort/Solution3.java new file mode 100644 index 0000000000000..2b5fedbd7f850 --- /dev/null +++ b/solution/1600-1699/1631.Path With Minimum Effort/Solution3.java @@ -0,0 +1,28 @@ +class Solution { + public int minimumEffortPath(int[][] heights) { + int m = heights.length, n = heights[0].length; + int[][] dist = new int[m][n]; + for (var row : dist) { + Arrays.fill(row, 1 << 30); + } + dist[0][0] = 0; + int[] dirs = {-1, 0, 1, 0, -1}; + PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); + pq.offer(new int[] {0, 0, 0}); + while (!pq.isEmpty()) { + var p = pq.poll(); + int t = p[0], i = p[1], j = p[2]; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n) { + int d = Math.max(t, Math.abs(heights[x][y] - heights[i][j])); + if (d < dist[x][y]) { + dist[x][y] = d; + pq.offer(new int[] {d, x, y}); + } + } + } + } + return dist[m - 1][n - 1]; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1631.Path With Minimum Effort/Solution3.py b/solution/1600-1699/1631.Path With Minimum Effort/Solution3.py new file mode 100644 index 0000000000000..b895018b17662 --- /dev/null +++ b/solution/1600-1699/1631.Path With Minimum Effort/Solution3.py @@ -0,0 +1,19 @@ +class Solution: + def minimumEffortPath(self, heights: List[List[int]]) -> int: + m, n = len(heights), len(heights[0]) + dist = [[inf] * n for _ in range(m)] + dist[0][0] = 0 + dirs = (-1, 0, 1, 0, -1) + q = [(0, 0, 0)] + while q: + t, i, j = heappop(q) + for a, b in pairwise(dirs): + x, y = i + a, j + b + if ( + 0 <= x < m + and 0 <= y < n + and (d := max(t, abs(heights[i][j] - heights[x][y]))) < dist[x][y] + ): + dist[x][y] = d + heappush(q, (d, x, y)) + return int(dist[-1][-1]) diff --git a/solution/1600-1699/1631.Path With Minimum Effort/Solution3.ts b/solution/1600-1699/1631.Path With Minimum Effort/Solution3.ts new file mode 100644 index 0000000000000..e118242bb00e3 --- /dev/null +++ b/solution/1600-1699/1631.Path With Minimum Effort/Solution3.ts @@ -0,0 +1,23 @@ +function minimumEffortPath(heights: number[][]): number { + const m = heights.length; + const n = heights[0].length; + const pq = new PriorityQueue({ compare: (a, b) => a[0] - b[0] }); + pq.enqueue([0, 0, 0]); + const dist = Array.from({ length: m }, () => Array.from({ length: n }, () => Infinity)); + dist[0][0] = 0; + const dirs = [-1, 0, 1, 0, -1]; + while (pq.size() > 0) { + const [t, i, j] = pq.dequeue()!; + for (let k = 0; k < 4; ++k) { + const [x, y] = [i + dirs[k], j + dirs[k + 1]]; + if (x >= 0 && x < m && y >= 0 && y < n) { + const d = Math.max(t, Math.abs(heights[x][y] - heights[i][j])); + if (d < dist[x][y]) { + dist[x][y] = d; + pq.enqueue([d, x, y]); + } + } + } + } + return dist[m - 1][n - 1]; +} diff --git a/solution/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/Solution.cs b/solution/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/Solution.cs index 823732d31c977..8febec6aa97c6 100644 --- a/solution/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/Solution.cs +++ b/solution/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/Solution.cs @@ -43,4 +43,4 @@ public PolyNode AddPoly(PolyNode poly1, PolyNode poly2) { } return dummy.next; } -} \ No newline at end of file +} diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.cpp b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.cpp index f30c039ffe5cc..3e0a01ca907c2 100644 --- a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.cpp +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.cpp @@ -1,31 +1,10 @@ class Solution { public: int maxWidthOfVerticalArea(vector>& points) { - int n = points.size(); - vector nums; - for (auto& p : points) { - nums.push_back(p[0]); - } - const int inf = 1 << 30; - int mi = inf, mx = -inf; - for (int v : nums) { - mi = min(mi, v); - mx = max(mx, v); - } - int bucketSize = max(1, (mx - mi) / (n - 1)); - int bucketCount = (mx - mi) / bucketSize + 1; - vector> buckets(bucketCount, {inf, -inf}); - for (int v : nums) { - int i = (v - mi) / bucketSize; - buckets[i].first = min(buckets[i].first, v); - buckets[i].second = max(buckets[i].second, v); - } + sort(points.begin(), points.end()); int ans = 0; - int prev = inf; - for (auto [curmin, curmax] : buckets) { - if (curmin > curmax) continue; - ans = max(ans, curmin - prev); - prev = curmax; + for (int i = 0; i < points.size() - 1; ++i) { + ans = max(ans, points[i + 1][0] - points[i][0]); } return ans; } diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.go b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.go index 0ccd452935487..1e7fa10187b34 100644 --- a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.go +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.go @@ -1,33 +1,7 @@ func maxWidthOfVerticalArea(points [][]int) (ans int) { - n := len(points) - nums := make([]int, 0, n) - for _, p := range points { - nums = append(nums, p[0]) + sort.Slice(points, func(i, j int) bool { return points[i][0] < points[j][0] }) + for i, p := range points[1:] { + ans = max(ans, p[0]-points[i][0]) } - const inf = 1 << 30 - mi, mx := inf, -inf - for _, v := range nums { - mi = min(mi, v) - mx = max(mx, v) - } - bucketSize := max(1, (mx-mi)/(n-1)) - bucketCount := (mx-mi)/bucketSize + 1 - buckets := make([][]int, bucketCount) - for i := range buckets { - buckets[i] = []int{inf, -inf} - } - for _, v := range nums { - i := (v - mi) / bucketSize - buckets[i][0] = min(buckets[i][0], v) - buckets[i][1] = max(buckets[i][1], v) - } - prev := inf - for _, bucket := range buckets { - if bucket[0] > bucket[1] { - continue - } - ans = max(ans, bucket[0]-prev) - prev = bucket[1] - } - return ans + return } \ No newline at end of file diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.java b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.java index 843c855848d09..84685fb326daa 100644 --- a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.java +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.java @@ -1,36 +1,9 @@ class Solution { public int maxWidthOfVerticalArea(int[][] points) { - int n = points.length; - int[] nums = new int[n]; - for (int i = 0; i < n; ++i) { - nums[i] = points[i][0]; - } - final int inf = 1 << 30; - int mi = inf, mx = -inf; - for (int v : nums) { - mi = Math.min(mi, v); - mx = Math.max(mx, v); - } - int bucketSize = Math.max(1, (mx - mi) / (n - 1)); - int bucketCount = (mx - mi) / bucketSize + 1; - int[][] buckets = new int[bucketCount][2]; - for (var bucket : buckets) { - bucket[0] = inf; - bucket[1] = -inf; - } - for (int v : nums) { - int i = (v - mi) / bucketSize; - buckets[i][0] = Math.min(buckets[i][0], v); - buckets[i][1] = Math.max(buckets[i][1], v); - } - int prev = inf; + Arrays.sort(points, (a, b) -> a[0] - b[0]); int ans = 0; - for (var bucket : buckets) { - if (bucket[0] > bucket[1]) { - continue; - } - ans = Math.max(ans, bucket[0] - prev); - prev = bucket[1]; + for (int i = 0; i < points.length - 1; ++i) { + ans = Math.max(ans, points[i + 1][0] - points[i][0]); } return ans; } diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.js b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.js index be0cdd917bfe1..0235cf3ea183a 100644 --- a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.js +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.js @@ -3,31 +3,12 @@ * @return {number} */ var maxWidthOfVerticalArea = function (points) { - const nums = points.map(point => point[0]); - const inf = 1 << 30; - const n = nums.length; - let mi = inf; - let mx = -inf; - for (const x of nums) { - mi = Math.min(mi, x); - mx = Math.max(mx, x); - } - const bucketSize = Math.max(1, Math.floor((mx - mi) / (n - 1))); - const bucketCount = Math.floor((mx - mi) / bucketSize) + 1; - const buckets = new Array(bucketCount).fill(0).map(() => [inf, -inf]); - for (const x of nums) { - const i = Math.floor((x - mi) / bucketSize); - buckets[i][0] = Math.min(buckets[i][0], x); - buckets[i][1] = Math.max(buckets[i][1], x); - } - let prev = inf; + points.sort((a, b) => a[0] - b[0]); let ans = 0; - for (const [left, right] of buckets) { - if (left > right) { - continue; - } - ans = Math.max(ans, left - prev); - prev = right; + let px = points[0][0]; + for (const [x, _] of points) { + ans = Math.max(ans, x - px); + px = x; } return ans; }; diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.py b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.py index c039ce6e66b6b..59eda36d0dc14 100644 --- a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.py +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.py @@ -1,20 +1,4 @@ class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: - nums = [x for x, _ in points] - n = len(nums) - mi, mx = min(nums), max(nums) - bucket_size = max(1, (mx - mi) // (n - 1)) - bucket_count = (mx - mi) // bucket_size + 1 - buckets = [[inf, -inf] for _ in range(bucket_count)] - for x in nums: - i = (x - mi) // bucket_size - buckets[i][0] = min(buckets[i][0], x) - buckets[i][1] = max(buckets[i][1], x) - ans = 0 - prev = inf - for curmin, curmax in buckets: - if curmin > curmax: - continue - ans = max(ans, curmin - prev) - prev = curmax - return ans + points.sort() + return max(b[0] - a[0] for a, b in pairwise(points)) diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.ts b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.ts index a924094593e5c..73c5f6e96f80d 100644 --- a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.ts +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.ts @@ -1,29 +1,8 @@ function maxWidthOfVerticalArea(points: number[][]): number { - const nums: number[] = points.map(point => point[0]); - const inf = 1 << 30; - const n = nums.length; - let mi = inf; - let mx = -inf; - for (const x of nums) { - mi = Math.min(mi, x); - mx = Math.max(mx, x); - } - const bucketSize = Math.max(1, Math.floor((mx - mi) / (n - 1))); - const bucketCount = Math.floor((mx - mi) / bucketSize) + 1; - const buckets = new Array(bucketCount).fill(0).map(() => [inf, -inf]); - for (const x of nums) { - const i = Math.floor((x - mi) / bucketSize); - buckets[i][0] = Math.min(buckets[i][0], x); - buckets[i][1] = Math.max(buckets[i][1], x); - } - let prev = inf; + points.sort((a, b) => a[0] - b[0]); let ans = 0; - for (const [left, right] of buckets) { - if (left > right) { - continue; - } - ans = Math.max(ans, left - prev); - prev = right; + for (let i = 1; i < points.length; ++i) { + ans = Math.max(ans, points[i][0] - points[i - 1][0]); } return ans; } diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution2.cpp b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution2.cpp new file mode 100644 index 0000000000000..f30c039ffe5cc --- /dev/null +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution2.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int maxWidthOfVerticalArea(vector>& points) { + int n = points.size(); + vector nums; + for (auto& p : points) { + nums.push_back(p[0]); + } + const int inf = 1 << 30; + int mi = inf, mx = -inf; + for (int v : nums) { + mi = min(mi, v); + mx = max(mx, v); + } + int bucketSize = max(1, (mx - mi) / (n - 1)); + int bucketCount = (mx - mi) / bucketSize + 1; + vector> buckets(bucketCount, {inf, -inf}); + for (int v : nums) { + int i = (v - mi) / bucketSize; + buckets[i].first = min(buckets[i].first, v); + buckets[i].second = max(buckets[i].second, v); + } + int ans = 0; + int prev = inf; + for (auto [curmin, curmax] : buckets) { + if (curmin > curmax) continue; + ans = max(ans, curmin - prev); + prev = curmax; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution2.go b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution2.go new file mode 100644 index 0000000000000..0ccd452935487 --- /dev/null +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution2.go @@ -0,0 +1,33 @@ +func maxWidthOfVerticalArea(points [][]int) (ans int) { + n := len(points) + nums := make([]int, 0, n) + for _, p := range points { + nums = append(nums, p[0]) + } + const inf = 1 << 30 + mi, mx := inf, -inf + for _, v := range nums { + mi = min(mi, v) + mx = max(mx, v) + } + bucketSize := max(1, (mx-mi)/(n-1)) + bucketCount := (mx-mi)/bucketSize + 1 + buckets := make([][]int, bucketCount) + for i := range buckets { + buckets[i] = []int{inf, -inf} + } + for _, v := range nums { + i := (v - mi) / bucketSize + buckets[i][0] = min(buckets[i][0], v) + buckets[i][1] = max(buckets[i][1], v) + } + prev := inf + for _, bucket := range buckets { + if bucket[0] > bucket[1] { + continue + } + ans = max(ans, bucket[0]-prev) + prev = bucket[1] + } + return ans +} \ No newline at end of file diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution2.java b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution2.java new file mode 100644 index 0000000000000..843c855848d09 --- /dev/null +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution2.java @@ -0,0 +1,37 @@ +class Solution { + public int maxWidthOfVerticalArea(int[][] points) { + int n = points.length; + int[] nums = new int[n]; + for (int i = 0; i < n; ++i) { + nums[i] = points[i][0]; + } + final int inf = 1 << 30; + int mi = inf, mx = -inf; + for (int v : nums) { + mi = Math.min(mi, v); + mx = Math.max(mx, v); + } + int bucketSize = Math.max(1, (mx - mi) / (n - 1)); + int bucketCount = (mx - mi) / bucketSize + 1; + int[][] buckets = new int[bucketCount][2]; + for (var bucket : buckets) { + bucket[0] = inf; + bucket[1] = -inf; + } + for (int v : nums) { + int i = (v - mi) / bucketSize; + buckets[i][0] = Math.min(buckets[i][0], v); + buckets[i][1] = Math.max(buckets[i][1], v); + } + int prev = inf; + int ans = 0; + for (var bucket : buckets) { + if (bucket[0] > bucket[1]) { + continue; + } + ans = Math.max(ans, bucket[0] - prev); + prev = bucket[1]; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution2.js b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution2.js new file mode 100644 index 0000000000000..be0cdd917bfe1 --- /dev/null +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution2.js @@ -0,0 +1,33 @@ +/** + * @param {number[][]} points + * @return {number} + */ +var maxWidthOfVerticalArea = function (points) { + const nums = points.map(point => point[0]); + const inf = 1 << 30; + const n = nums.length; + let mi = inf; + let mx = -inf; + for (const x of nums) { + mi = Math.min(mi, x); + mx = Math.max(mx, x); + } + const bucketSize = Math.max(1, Math.floor((mx - mi) / (n - 1))); + const bucketCount = Math.floor((mx - mi) / bucketSize) + 1; + const buckets = new Array(bucketCount).fill(0).map(() => [inf, -inf]); + for (const x of nums) { + const i = Math.floor((x - mi) / bucketSize); + buckets[i][0] = Math.min(buckets[i][0], x); + buckets[i][1] = Math.max(buckets[i][1], x); + } + let prev = inf; + let ans = 0; + for (const [left, right] of buckets) { + if (left > right) { + continue; + } + ans = Math.max(ans, left - prev); + prev = right; + } + return ans; +}; diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution2.py b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution2.py new file mode 100644 index 0000000000000..c039ce6e66b6b --- /dev/null +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution2.py @@ -0,0 +1,20 @@ +class Solution: + def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: + nums = [x for x, _ in points] + n = len(nums) + mi, mx = min(nums), max(nums) + bucket_size = max(1, (mx - mi) // (n - 1)) + bucket_count = (mx - mi) // bucket_size + 1 + buckets = [[inf, -inf] for _ in range(bucket_count)] + for x in nums: + i = (x - mi) // bucket_size + buckets[i][0] = min(buckets[i][0], x) + buckets[i][1] = max(buckets[i][1], x) + ans = 0 + prev = inf + for curmin, curmax in buckets: + if curmin > curmax: + continue + ans = max(ans, curmin - prev) + prev = curmax + return ans diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution2.ts b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution2.ts new file mode 100644 index 0000000000000..a924094593e5c --- /dev/null +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution2.ts @@ -0,0 +1,29 @@ +function maxWidthOfVerticalArea(points: number[][]): number { + const nums: number[] = points.map(point => point[0]); + const inf = 1 << 30; + const n = nums.length; + let mi = inf; + let mx = -inf; + for (const x of nums) { + mi = Math.min(mi, x); + mx = Math.max(mx, x); + } + const bucketSize = Math.max(1, Math.floor((mx - mi) / (n - 1))); + const bucketCount = Math.floor((mx - mi) / bucketSize) + 1; + const buckets = new Array(bucketCount).fill(0).map(() => [inf, -inf]); + for (const x of nums) { + const i = Math.floor((x - mi) / bucketSize); + buckets[i][0] = Math.min(buckets[i][0], x); + buckets[i][1] = Math.max(buckets[i][1], x); + } + let prev = inf; + let ans = 0; + for (const [left, right] of buckets) { + if (left > right) { + continue; + } + ans = Math.max(ans, left - prev); + prev = right; + } + return ans; +} diff --git a/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution.cpp b/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution.cpp index 57d870e12139b..e792f7376884f 100644 --- a/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution.cpp +++ b/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution.cpp @@ -2,24 +2,18 @@ class Solution { public: int countSubstrings(string s, string t) { int ans = 0; - int m = s.length(), n = t.length(); - int f[m + 1][n + 1]; - int g[m + 1][n + 1]; - memset(f, 0, sizeof(f)); - memset(g, 0, sizeof(g)); + int m = s.size(), n = t.size(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { - if (s[i] == t[j]) { - f[i + 1][j + 1] = f[i][j] + 1; - } - } - } - for (int i = m - 1; i >= 0; --i) { - for (int j = n - 1; j >= 0; --j) { - if (s[i] == t[j]) { - g[i][j] = g[i + 1][j + 1] + 1; - } else { - ans += (f[i][j] + 1) * (g[i + 1][j + 1] + 1); + if (s[i] != t[j]) { + int l = 0, r = 0; + while (i - l > 0 && j - l > 0 && s[i - l - 1] == t[j - l - 1]) { + ++l; + } + while (i + r + 1 < m && j + r + 1 < n && s[i + r + 1] == t[j + r + 1]) { + ++r; + } + ans += (l + 1) * (r + 1); } } } diff --git a/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution.go b/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution.go index 96c92ec4007b4..5c1bf85fd2938 100644 --- a/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution.go +++ b/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution.go @@ -1,24 +1,16 @@ func countSubstrings(s string, t string) (ans int) { m, n := len(s), len(t) - f := make([][]int, m+1) - g := make([][]int, m+1) - for i := range f { - f[i] = make([]int, n+1) - g[i] = make([]int, n+1) - } for i, a := range s { for j, b := range t { - if a == b { - f[i+1][j+1] = f[i][j] + 1 - } - } - } - for i := m - 1; i >= 0; i-- { - for j := n - 1; j >= 0; j-- { - if s[i] == t[j] { - g[i][j] = g[i+1][j+1] + 1 - } else { - ans += (f[i][j] + 1) * (g[i+1][j+1] + 1) + if a != b { + l, r := 0, 0 + for i > l && j > l && s[i-l-1] == t[j-l-1] { + l++ + } + for i+r+1 < m && j+r+1 < n && s[i+r+1] == t[j+r+1] { + r++ + } + ans += (l + 1) * (r + 1) } } } diff --git a/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution.java b/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution.java index 80d91f277fa24..75ef243330bf7 100644 --- a/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution.java +++ b/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution.java @@ -2,21 +2,18 @@ class Solution { public int countSubstrings(String s, String t) { int ans = 0; int m = s.length(), n = t.length(); - int[][] f = new int[m + 1][n + 1]; - int[][] g = new int[m + 1][n + 1]; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { - if (s.charAt(i) == t.charAt(j)) { - f[i + 1][j + 1] = f[i][j] + 1; - } - } - } - for (int i = m - 1; i >= 0; --i) { - for (int j = n - 1; j >= 0; --j) { - if (s.charAt(i) == t.charAt(j)) { - g[i][j] = g[i + 1][j + 1] + 1; - } else { - ans += (f[i][j] + 1) * (g[i + 1][j + 1] + 1); + if (s.charAt(i) != t.charAt(j)) { + int l = 0, r = 0; + while (i - l > 0 && j - l > 0 && s.charAt(i - l - 1) == t.charAt(j - l - 1)) { + ++l; + } + while (i + r + 1 < m && j + r + 1 < n + && s.charAt(i + r + 1) == t.charAt(j + r + 1)) { + ++r; + } + ans += (l + 1) * (r + 1); } } } diff --git a/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution.py b/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution.py index 063dcc07c4fcb..7c2da4147301a 100644 --- a/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution.py +++ b/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution.py @@ -2,16 +2,15 @@ class Solution: def countSubstrings(self, s: str, t: str) -> int: ans = 0 m, n = len(s), len(t) - f = [[0] * (n + 1) for _ in range(m + 1)] - g = [[0] * (n + 1) for _ in range(m + 1)] - for i, a in enumerate(s, 1): - for j, b in enumerate(t, 1): - if a == b: - f[i][j] = f[i - 1][j - 1] + 1 - for i in range(m - 1, -1, -1): - for j in range(n - 1, -1, -1): - if s[i] == t[j]: - g[i][j] = g[i + 1][j + 1] + 1 - else: - ans += (f[i][j] + 1) * (g[i + 1][j + 1] + 1) + for i, a in enumerate(s): + for j, b in enumerate(t): + if a != b: + l = r = 0 + while i > l and j > l and s[i - l - 1] == t[j - l - 1]: + l += 1 + while ( + i + r + 1 < m and j + r + 1 < n and s[i + r + 1] == t[j + r + 1] + ): + r += 1 + ans += (l + 1) * (r + 1) return ans diff --git a/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution2.cpp b/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution2.cpp new file mode 100644 index 0000000000000..57d870e12139b --- /dev/null +++ b/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution2.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int countSubstrings(string s, string t) { + int ans = 0; + int m = s.length(), n = t.length(); + int f[m + 1][n + 1]; + int g[m + 1][n + 1]; + memset(f, 0, sizeof(f)); + memset(g, 0, sizeof(g)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (s[i] == t[j]) { + f[i + 1][j + 1] = f[i][j] + 1; + } + } + } + for (int i = m - 1; i >= 0; --i) { + for (int j = n - 1; j >= 0; --j) { + if (s[i] == t[j]) { + g[i][j] = g[i + 1][j + 1] + 1; + } else { + ans += (f[i][j] + 1) * (g[i + 1][j + 1] + 1); + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution2.go b/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution2.go new file mode 100644 index 0000000000000..96c92ec4007b4 --- /dev/null +++ b/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution2.go @@ -0,0 +1,26 @@ +func countSubstrings(s string, t string) (ans int) { + m, n := len(s), len(t) + f := make([][]int, m+1) + g := make([][]int, m+1) + for i := range f { + f[i] = make([]int, n+1) + g[i] = make([]int, n+1) + } + for i, a := range s { + for j, b := range t { + if a == b { + f[i+1][j+1] = f[i][j] + 1 + } + } + } + for i := m - 1; i >= 0; i-- { + for j := n - 1; j >= 0; j-- { + if s[i] == t[j] { + g[i][j] = g[i+1][j+1] + 1 + } else { + ans += (f[i][j] + 1) * (g[i+1][j+1] + 1) + } + } + } + return +} \ No newline at end of file diff --git a/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution2.java b/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution2.java new file mode 100644 index 0000000000000..80d91f277fa24 --- /dev/null +++ b/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution2.java @@ -0,0 +1,25 @@ +class Solution { + public int countSubstrings(String s, String t) { + int ans = 0; + int m = s.length(), n = t.length(); + int[][] f = new int[m + 1][n + 1]; + int[][] g = new int[m + 1][n + 1]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (s.charAt(i) == t.charAt(j)) { + f[i + 1][j + 1] = f[i][j] + 1; + } + } + } + for (int i = m - 1; i >= 0; --i) { + for (int j = n - 1; j >= 0; --j) { + if (s.charAt(i) == t.charAt(j)) { + g[i][j] = g[i + 1][j + 1] + 1; + } else { + ans += (f[i][j] + 1) * (g[i + 1][j + 1] + 1); + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution2.py b/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution2.py new file mode 100644 index 0000000000000..063dcc07c4fcb --- /dev/null +++ b/solution/1600-1699/1638.Count Substrings That Differ by One Character/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def countSubstrings(self, s: str, t: str) -> int: + ans = 0 + m, n = len(s), len(t) + f = [[0] * (n + 1) for _ in range(m + 1)] + g = [[0] * (n + 1) for _ in range(m + 1)] + for i, a in enumerate(s, 1): + for j, b in enumerate(t, 1): + if a == b: + f[i][j] = f[i - 1][j - 1] + 1 + for i in range(m - 1, -1, -1): + for j in range(n - 1, -1, -1): + if s[i] == t[j]: + g[i][j] = g[i + 1][j + 1] + 1 + else: + ans += (f[i][j] + 1) * (g[i + 1][j + 1] + 1) + return ans diff --git a/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/Solution2.cpp b/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/Solution2.cpp new file mode 100644 index 0000000000000..c6f6008441844 --- /dev/null +++ b/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/Solution2.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int numWays(vector& words, string target) { + int m = target.size(), n = words[0].size(); + const int mod = 1e9 + 7; + long long f[m + 1][n + 1]; + memset(f, 0, sizeof(f)); + fill(f[0], f[0] + n + 1, 1); + vector> cnt(n, vector(26)); + for (auto& w : words) { + for (int j = 0; j < n; ++j) { + ++cnt[j][w[j] - 'a']; + } + } + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + f[i][j] = f[i][j - 1] + f[i - 1][j - 1] * cnt[j - 1][target[i - 1] - 'a']; + f[i][j] %= mod; + } + } + return f[m][n]; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/Solution2.go b/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/Solution2.go new file mode 100644 index 0000000000000..1d8b219a60db4 --- /dev/null +++ b/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/Solution2.go @@ -0,0 +1,24 @@ +func numWays(words []string, target string) int { + const mod = 1e9 + 7 + m, n := len(target), len(words[0]) + f := make([][]int, m+1) + for i := range f { + f[i] = make([]int, n+1) + } + for j := range f[0] { + f[0][j] = 1 + } + cnt := make([][26]int, n) + for _, w := range words { + for j, c := range w { + cnt[j][c-'a']++ + } + } + for i := 1; i <= m; i++ { + for j := 1; j <= n; j++ { + f[i][j] = f[i][j-1] + f[i-1][j-1]*cnt[j-1][target[i-1]-'a'] + f[i][j] %= mod + } + } + return f[m][n] +} \ No newline at end of file diff --git a/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/Solution2.java b/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/Solution2.java new file mode 100644 index 0000000000000..5e1022e17481a --- /dev/null +++ b/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/Solution2.java @@ -0,0 +1,22 @@ +class Solution { + public int numWays(String[] words, String target) { + int m = target.length(); + int n = words[0].length(); + final int mod = (int) 1e9 + 7; + long[][] f = new long[m + 1][n + 1]; + Arrays.fill(f[0], 1); + int[][] cnt = new int[n][26]; + for (var w : words) { + for (int j = 0; j < n; ++j) { + cnt[j][w.charAt(j) - 'a']++; + } + } + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + f[i][j] = f[i][j - 1] + f[i - 1][j - 1] * cnt[j - 1][target.charAt(i - 1) - 'a']; + f[i][j] %= mod; + } + } + return (int) f[m][n]; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/Solution2.py b/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/Solution2.py new file mode 100644 index 0000000000000..ce7160caa3c86 --- /dev/null +++ b/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def numWays(self, words: List[str], target: str) -> int: + m, n = len(target), len(words[0]) + cnt = [[0] * 26 for _ in range(n)] + for w in words: + for j, c in enumerate(w): + cnt[j][ord(c) - ord('a')] += 1 + mod = 10**9 + 7 + f = [[0] * (n + 1) for _ in range(m + 1)] + f[0] = [1] * (n + 1) + for i in range(1, m + 1): + for j in range(1, n + 1): + f[i][j] = ( + f[i][j - 1] + + f[i - 1][j - 1] * cnt[j - 1][ord(target[i - 1]) - ord('a')] + ) + f[i][j] %= mod + return f[m][n] diff --git a/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution.cpp b/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution.cpp index 14e10d8dd0a61..906eeaeec24be 100644 --- a/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution.cpp +++ b/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution.cpp @@ -1,18 +1,18 @@ class Solution { public: bool canFormArray(vector& arr, vector>& pieces) { - unordered_map> d; - for (auto& p : pieces) { - d[p[0]] = p; - } for (int i = 0; i < arr.size();) { - if (!d.count(arr[i])) { + int k = 0; + while (k < pieces.size() && pieces[k][0] != arr[i]) { + ++k; + } + if (k == pieces.size()) { return false; } - for (int& v : d[arr[i]]) { - if (arr[i++] != v) { - return false; - } + int j = 0; + while (j < pieces[k].size() && arr[i] == pieces[k][j]) { + ++i; + ++j; } } return true; diff --git a/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution.go b/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution.go index ed3ac0246ac37..4f1010496c369 100644 --- a/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution.go +++ b/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution.go @@ -1,18 +1,15 @@ func canFormArray(arr []int, pieces [][]int) bool { - d := map[int][]int{} - for _, p := range pieces { - d[p[0]] = p - } for i := 0; i < len(arr); { - p, ok := d[arr[i]] - if !ok { + k := 0 + for k < len(pieces) && pieces[k][0] != arr[i] { + k++ + } + if k == len(pieces) { return false } - for _, v := range p { - if arr[i] != v { - return false - } - i++ + j := 0 + for j < len(pieces[k]) && arr[i] == pieces[k][j] { + i, j = i+1, j+1 } } return true diff --git a/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution.java b/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution.java index 85133b7d2bce5..0d5e94062246a 100644 --- a/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution.java +++ b/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution.java @@ -1,17 +1,17 @@ class Solution { public boolean canFormArray(int[] arr, int[][] pieces) { - Map d = new HashMap<>(); - for (var p : pieces) { - d.put(p[0], p); - } for (int i = 0; i < arr.length;) { - if (!d.containsKey(arr[i])) { + int k = 0; + while (k < pieces.length && pieces[k][0] != arr[i]) { + ++k; + } + if (k == pieces.length) { return false; } - for (int v : d.get(arr[i])) { - if (arr[i++] != v) { - return false; - } + int j = 0; + while (j < pieces[k].length && arr[i] == pieces[k][j]) { + ++i; + ++j; } } return true; diff --git a/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution.py b/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution.py index 1bd49bcba3f45..a115eb58f6067 100644 --- a/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution.py +++ b/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution.py @@ -1,12 +1,13 @@ class Solution: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: - d = {p[0]: p for p in pieces} - i, n = 0, len(arr) - while i < n: - if arr[i] not in d: + i = 0 + while i < len(arr): + k = 0 + while k < len(pieces) and pieces[k][0] != arr[i]: + k += 1 + if k == len(pieces): return False - p = d[arr[i]] - if arr[i : i + len(p)] != p: - return False - i += len(p) + j = 0 + while j < len(pieces[k]) and arr[i] == pieces[k][j]: + i, j = i + 1, j + 1 return True diff --git a/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution2.cpp b/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution2.cpp new file mode 100644 index 0000000000000..14e10d8dd0a61 --- /dev/null +++ b/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution2.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + bool canFormArray(vector& arr, vector>& pieces) { + unordered_map> d; + for (auto& p : pieces) { + d[p[0]] = p; + } + for (int i = 0; i < arr.size();) { + if (!d.count(arr[i])) { + return false; + } + for (int& v : d[arr[i]]) { + if (arr[i++] != v) { + return false; + } + } + } + return true; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution2.go b/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution2.go new file mode 100644 index 0000000000000..ed3ac0246ac37 --- /dev/null +++ b/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution2.go @@ -0,0 +1,19 @@ +func canFormArray(arr []int, pieces [][]int) bool { + d := map[int][]int{} + for _, p := range pieces { + d[p[0]] = p + } + for i := 0; i < len(arr); { + p, ok := d[arr[i]] + if !ok { + return false + } + for _, v := range p { + if arr[i] != v { + return false + } + i++ + } + } + return true +} \ No newline at end of file diff --git a/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution2.java b/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution2.java new file mode 100644 index 0000000000000..85133b7d2bce5 --- /dev/null +++ b/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution2.java @@ -0,0 +1,19 @@ +class Solution { + public boolean canFormArray(int[] arr, int[][] pieces) { + Map d = new HashMap<>(); + for (var p : pieces) { + d.put(p[0], p); + } + for (int i = 0; i < arr.length;) { + if (!d.containsKey(arr[i])) { + return false; + } + for (int v : d.get(arr[i])) { + if (arr[i++] != v) { + return false; + } + } + } + return true; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution2.py b/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution2.py new file mode 100644 index 0000000000000..1bd49bcba3f45 --- /dev/null +++ b/solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: + d = {p[0]: p for p in pieces} + i, n = 0, len(arr) + while i < n: + if arr[i] not in d: + return False + p = d[arr[i]] + if arr[i : i + len(p)] != p: + return False + i += len(p) + return True diff --git a/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution.cpp b/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution.cpp index 5d8c01a2c00d0..600a753d8f07c 100644 --- a/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution.cpp +++ b/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution.cpp @@ -1,14 +1,21 @@ class Solution { public: int countVowelStrings(int n) { - int f[5] = {1, 1, 1, 1, 1}; - for (int i = 0; i < n - 1; ++i) { - int s = 0; - for (int j = 0; j < 5; ++j) { - s += f[j]; - f[j] = s; + int f[n][5]; + memset(f, 0, sizeof f); + function dfs = [&](int i, int j) { + if (i >= n) { + return 1; } - } - return accumulate(f, f + 5, 0); + if (f[i][j]) { + return f[i][j]; + } + int ans = 0; + for (int k = j; k < 5; ++k) { + ans += dfs(i + 1, k); + } + return f[i][j] = ans; + }; + return dfs(0, 0); } }; \ No newline at end of file diff --git a/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution.go b/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution.go index 0ea71766e4bbd..0488534660def 100644 --- a/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution.go +++ b/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution.go @@ -1,14 +1,19 @@ -func countVowelStrings(n int) (ans int) { - f := [5]int{1, 1, 1, 1, 1} - for i := 0; i < n-1; i++ { - s := 0 - for j := 0; j < 5; j++ { - s += f[j] - f[j] = s +func countVowelStrings(n int) int { + f := make([][5]int, n) + var dfs func(i, j int) int + dfs = func(i, j int) int { + if i >= n { + return 1 } + if f[i][j] != 0 { + return f[i][j] + } + ans := 0 + for k := j; k < 5; k++ { + ans += dfs(i+1, k) + } + f[i][j] = ans + return ans } - for _, v := range f { - ans += v - } - return + return dfs(0, 0) } \ No newline at end of file diff --git a/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution.java b/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution.java index 2664e1f57cbf8..2b663643dd748 100644 --- a/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution.java +++ b/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution.java @@ -1,13 +1,24 @@ class Solution { + private Integer[][] f; + private int n; + public int countVowelStrings(int n) { - int[] f = {1, 1, 1, 1, 1}; - for (int i = 0; i < n - 1; ++i) { - int s = 0; - for (int j = 0; j < 5; ++j) { - s += f[j]; - f[j] = s; - } + this.n = n; + f = new Integer[n][5]; + return dfs(0, 0); + } + + private int dfs(int i, int j) { + if (i >= n) { + return 1; + } + if (f[i][j] != null) { + return f[i][j]; + } + int ans = 0; + for (int k = j; k < 5; ++k) { + ans += dfs(i + 1, k); } - return Arrays.stream(f).sum(); + return f[i][j] = ans; } } \ No newline at end of file diff --git a/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution.py b/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution.py index 933ffb9921ff8..479cee9175c28 100644 --- a/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution.py +++ b/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution.py @@ -1,9 +1,7 @@ class Solution: def countVowelStrings(self, n: int) -> int: - f = [1] * 5 - for _ in range(n - 1): - s = 0 - for j in range(5): - s += f[j] - f[j] = s - return sum(f) + @cache + def dfs(i, j): + return 1 if i >= n else sum(dfs(i + 1, k) for k in range(j, 5)) + + return dfs(0, 0) diff --git a/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution2.cpp b/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution2.cpp new file mode 100644 index 0000000000000..5d8c01a2c00d0 --- /dev/null +++ b/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int countVowelStrings(int n) { + int f[5] = {1, 1, 1, 1, 1}; + for (int i = 0; i < n - 1; ++i) { + int s = 0; + for (int j = 0; j < 5; ++j) { + s += f[j]; + f[j] = s; + } + } + return accumulate(f, f + 5, 0); + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution2.go b/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution2.go new file mode 100644 index 0000000000000..0ea71766e4bbd --- /dev/null +++ b/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution2.go @@ -0,0 +1,14 @@ +func countVowelStrings(n int) (ans int) { + f := [5]int{1, 1, 1, 1, 1} + for i := 0; i < n-1; i++ { + s := 0 + for j := 0; j < 5; j++ { + s += f[j] + f[j] = s + } + } + for _, v := range f { + ans += v + } + return +} \ No newline at end of file diff --git a/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution2.java b/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution2.java new file mode 100644 index 0000000000000..2664e1f57cbf8 --- /dev/null +++ b/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution2.java @@ -0,0 +1,13 @@ +class Solution { + public int countVowelStrings(int n) { + int[] f = {1, 1, 1, 1, 1}; + for (int i = 0; i < n - 1; ++i) { + int s = 0; + for (int j = 0; j < 5; ++j) { + s += f[j]; + f[j] = s; + } + } + return Arrays.stream(f).sum(); + } +} \ No newline at end of file diff --git a/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution2.py b/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution2.py new file mode 100644 index 0000000000000..933ffb9921ff8 --- /dev/null +++ b/solution/1600-1699/1641.Count Sorted Vowel Strings/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def countVowelStrings(self, n: int) -> int: + f = [1] * 5 + for _ in range(n - 1): + s = 0 + for j in range(5): + s += f[j] + f[j] = s + return sum(f) diff --git a/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/Solution.java b/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/Solution.java index 57f7661681373..d6517abb7cbba 100644 --- a/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/Solution.java +++ b/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/Solution.java @@ -5,16 +5,11 @@ public int minDeletions(String s) { ++cnt[s.charAt(i) - 'a']; } Arrays.sort(cnt); - int ans = 0, pre = 1 << 30; - for (int i = 25; i >= 0; --i) { - int v = cnt[i]; - if (pre == 0) { - ans += v; - } else if (v >= pre) { - ans += v - pre + 1; - --pre; - } else { - pre = v; + int ans = 0; + for (int i = 24; i >= 0; --i) { + while (cnt[i] >= cnt[i + 1] && cnt[i] > 0) { + --cnt[i]; + ++ans; } } return ans; diff --git a/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/Solution2.cpp b/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/Solution2.cpp new file mode 100644 index 0000000000000..946fc1a248363 --- /dev/null +++ b/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/Solution2.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int minDeletions(string s) { + vector cnt(26); + for (char& c : s) ++cnt[c - 'a']; + sort(cnt.rbegin(), cnt.rend()); + int ans = 0, pre = 1 << 30; + for (int& v : cnt) { + if (pre == 0) { + ans += v; + } else if (v >= pre) { + ans += v - pre + 1; + --pre; + } else { + pre = v; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/Solution2.go b/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/Solution2.go new file mode 100644 index 0000000000000..83c02991ea6fb --- /dev/null +++ b/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/Solution2.go @@ -0,0 +1,19 @@ +func minDeletions(s string) (ans int) { + cnt := make([]int, 26) + for _, c := range s { + cnt[c-'a']++ + } + sort.Sort(sort.Reverse(sort.IntSlice(cnt))) + pre := 1 << 30 + for _, v := range cnt { + if pre == 0 { + ans += v + } else if v >= pre { + ans += v - pre + 1 + pre-- + } else { + pre = v + } + } + return +} \ No newline at end of file diff --git a/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/Solution2.java b/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/Solution2.java new file mode 100644 index 0000000000000..57f7661681373 --- /dev/null +++ b/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/Solution2.java @@ -0,0 +1,22 @@ +class Solution { + public int minDeletions(String s) { + int[] cnt = new int[26]; + for (int i = 0; i < s.length(); ++i) { + ++cnt[s.charAt(i) - 'a']; + } + Arrays.sort(cnt); + int ans = 0, pre = 1 << 30; + for (int i = 25; i >= 0; --i) { + int v = cnt[i]; + if (pre == 0) { + ans += v; + } else if (v >= pre) { + ans += v - pre + 1; + --pre; + } else { + pre = v; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/Solution2.py b/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/Solution2.py new file mode 100644 index 0000000000000..ea9a6f0c9ccc0 --- /dev/null +++ b/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def minDeletions(self, s: str) -> int: + cnt = Counter(s) + vals = sorted(cnt.values(), reverse=True) + ans = 0 + for i in range(1, len(vals)): + while vals[i] >= vals[i - 1] and vals[i] > 0: + vals[i] -= 1 + ans += 1 + return ans diff --git a/solution/1600-1699/1649.Create Sorted Array through Instructions/Solution2.cpp b/solution/1600-1699/1649.Create Sorted Array through Instructions/Solution2.cpp new file mode 100644 index 0000000000000..a4a10b1edd420 --- /dev/null +++ b/solution/1600-1699/1649.Create Sorted Array through Instructions/Solution2.cpp @@ -0,0 +1,70 @@ +class Node { +public: + int l; + int r; + int v; +}; + +class SegmentTree { +public: + vector tr; + + SegmentTree(int n) { + tr.resize(4 * n); + for (int i = 0; i < tr.size(); ++i) tr[i] = new Node(); + build(1, 1, n); + } + + void build(int u, int l, int r) { + tr[u]->l = l; + tr[u]->r = r; + if (l == r) return; + int mid = (l + r) >> 1; + build(u << 1, l, mid); + build(u << 1 | 1, mid + 1, r); + } + + void modify(int u, int x, int v) { + if (tr[u]->l == x && tr[u]->r == x) { + tr[u]->v += v; + return; + } + int mid = (tr[u]->l + tr[u]->r) >> 1; + if (x <= mid) + modify(u << 1, x, v); + else + modify(u << 1 | 1, x, v); + pushup(u); + } + + void pushup(int u) { + tr[u]->v = tr[u << 1]->v + tr[u << 1 | 1]->v; + } + + int query(int u, int l, int r) { + if (tr[u]->l >= l && tr[u]->r <= r) return tr[u]->v; + int mid = (tr[u]->l + tr[u]->r) >> 1; + int v = 0; + if (l <= mid) v = query(u << 1, l, r); + if (r > mid) v += query(u << 1 | 1, l, r); + return v; + } +}; + +class Solution { +public: + int createSortedArray(vector& instructions) { + int n = *max_element(instructions.begin(), instructions.end()); + int mod = 1e9 + 7; + SegmentTree* tree = new SegmentTree(n); + int ans = 0; + for (int num : instructions) { + int a = tree->query(1, 1, num - 1); + int b = tree->query(1, 1, n) - tree->query(1, 1, num); + ans += min(a, b); + ans %= mod; + tree->modify(1, num, 1); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1649.Create Sorted Array through Instructions/Solution2.java b/solution/1600-1699/1649.Create Sorted Array through Instructions/Solution2.java new file mode 100644 index 0000000000000..20f3de0fb74b8 --- /dev/null +++ b/solution/1600-1699/1649.Create Sorted Array through Instructions/Solution2.java @@ -0,0 +1,78 @@ +class Solution { + public int createSortedArray(int[] instructions) { + int n = 100010; + int mod = (int) 1e9 + 7; + SegmentTree tree = new SegmentTree(n); + int ans = 0; + for (int num : instructions) { + int a = tree.query(1, 1, num - 1); + int b = tree.query(1, 1, n) - tree.query(1, 1, num); + ans += Math.min(a, b); + ans %= mod; + tree.modify(1, num, 1); + } + return ans; + } +} + +class Node { + int l; + int r; + int v; +} + +class SegmentTree { + private Node[] tr; + + public SegmentTree(int n) { + tr = new Node[4 * n]; + for (int i = 0; i < tr.length; ++i) { + tr[i] = new Node(); + } + build(1, 1, n); + } + + public void build(int u, int l, int r) { + tr[u].l = l; + tr[u].r = r; + if (l == r) { + return; + } + int mid = (l + r) >> 1; + build(u << 1, l, mid); + build(u << 1 | 1, mid + 1, r); + } + + public void modify(int u, int x, int v) { + if (tr[u].l == x && tr[u].r == x) { + tr[u].v += v; + return; + } + int mid = (tr[u].l + tr[u].r) >> 1; + if (x <= mid) { + modify(u << 1, x, v); + } else { + modify(u << 1 | 1, x, v); + } + pushup(u); + } + + public void pushup(int u) { + tr[u].v = tr[u << 1].v + tr[u << 1 | 1].v; + } + + public int query(int u, int l, int r) { + if (tr[u].l >= l && tr[u].r <= r) { + return tr[u].v; + } + int mid = (tr[u].l + tr[u].r) >> 1; + int v = 0; + if (l <= mid) { + v += query(u << 1, l, r); + } + if (r > mid) { + v += query(u << 1 | 1, l, r); + } + return v; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1649.Create Sorted Array through Instructions/Solution2.py b/solution/1600-1699/1649.Create Sorted Array through Instructions/Solution2.py new file mode 100644 index 0000000000000..6d88798d8e682 --- /dev/null +++ b/solution/1600-1699/1649.Create Sorted Array through Instructions/Solution2.py @@ -0,0 +1,58 @@ +class Node: + def __init__(self): + self.l = 0 + self.r = 0 + self.v = 0 + + +class SegmentTree: + def __init__(self, n): + self.tr = [Node() for _ in range(4 * n)] + self.build(1, 1, n) + + def build(self, u, l, r): + self.tr[u].l = l + self.tr[u].r = r + if l == r: + return + mid = (l + r) >> 1 + self.build(u << 1, l, mid) + self.build(u << 1 | 1, mid + 1, r) + + def modify(self, u, x, v): + if self.tr[u].l == x and self.tr[u].r == x: + self.tr[u].v += v + return + mid = (self.tr[u].l + self.tr[u].r) >> 1 + if x <= mid: + self.modify(u << 1, x, v) + else: + self.modify(u << 1 | 1, x, v) + self.pushup(u) + + def pushup(self, u): + self.tr[u].v = self.tr[u << 1].v + self.tr[u << 1 | 1].v + + def query(self, u, l, r): + if self.tr[u].l >= l and self.tr[u].r <= r: + return self.tr[u].v + mid = (self.tr[u].l + self.tr[u].r) >> 1 + v = 0 + if l <= mid: + v = self.query(u << 1, l, r) + if r > mid: + v += self.query(u << 1 | 1, l, r) + return v + + +class Solution: + def createSortedArray(self, instructions: List[int]) -> int: + n = max(instructions) + tree = SegmentTree(n) + ans = 0 + for num in instructions: + a = tree.query(1, 1, num - 1) + b = tree.query(1, 1, n) - tree.query(1, 1, num) + ans += min(a, b) + tree.modify(1, num, 1) + return ans % int((1e9 + 7)) diff --git a/solution/1600-1699/1652.Defuse the Bomb/Solution.cpp b/solution/1600-1699/1652.Defuse the Bomb/Solution.cpp index dd75d6692fc0b..d3d6a15f0a258 100644 --- a/solution/1600-1699/1652.Defuse the Bomb/Solution.cpp +++ b/solution/1600-1699/1652.Defuse the Bomb/Solution.cpp @@ -6,15 +6,15 @@ class Solution { if (k == 0) { return ans; } - vector s(n << 1 | 1); - for (int i = 0; i < n << 1; ++i) { - s[i + 1] = s[i] + code[i % n]; - } for (int i = 0; i < n; ++i) { if (k > 0) { - ans[i] = s[i + k + 1] - s[i + 1]; + for (int j = i + 1; j < i + k + 1; ++j) { + ans[i] += code[j % n]; + } } else { - ans[i] = s[i + n] - s[i + k + n]; + for (int j = i + k; j < i; ++j) { + ans[i] += code[(j + n) % n]; + } } } return ans; diff --git a/solution/1600-1699/1652.Defuse the Bomb/Solution.go b/solution/1600-1699/1652.Defuse the Bomb/Solution.go index bc85d85ea0098..193334501af80 100644 --- a/solution/1600-1699/1652.Defuse the Bomb/Solution.go +++ b/solution/1600-1699/1652.Defuse the Bomb/Solution.go @@ -4,15 +4,15 @@ func decrypt(code []int, k int) []int { if k == 0 { return ans } - s := make([]int, n<<1|1) - for i := 0; i < n<<1; i++ { - s[i+1] = s[i] + code[i%n] - } - for i := range code { + for i := 0; i < n; i++ { if k > 0 { - ans[i] = s[i+k+1] - s[i+1] + for j := i + 1; j < i+k+1; j++ { + ans[i] += code[j%n] + } } else { - ans[i] = s[i+n] - s[i+k+n] + for j := i + k; j < i; j++ { + ans[i] += code[(j+n)%n] + } } } return ans diff --git a/solution/1600-1699/1652.Defuse the Bomb/Solution.java b/solution/1600-1699/1652.Defuse the Bomb/Solution.java index 343419b76aad9..e33e43d15e5fb 100644 --- a/solution/1600-1699/1652.Defuse the Bomb/Solution.java +++ b/solution/1600-1699/1652.Defuse the Bomb/Solution.java @@ -5,15 +5,15 @@ public int[] decrypt(int[] code, int k) { if (k == 0) { return ans; } - int[] s = new int[n << 1 | 1]; - for (int i = 0; i < n << 1; ++i) { - s[i + 1] = s[i] + code[i % n]; - } for (int i = 0; i < n; ++i) { if (k > 0) { - ans[i] = s[i + k + 1] - s[i + 1]; + for (int j = i + 1; j < i + k + 1; ++j) { + ans[i] += code[j % n]; + } } else { - ans[i] = s[i + n] - s[i + k + n]; + for (int j = i + k; j < i; ++j) { + ans[i] += code[(j + n) % n]; + } } } return ans; diff --git a/solution/1600-1699/1652.Defuse the Bomb/Solution.py b/solution/1600-1699/1652.Defuse the Bomb/Solution.py index 48882e061831e..4198ef1db1d7c 100644 --- a/solution/1600-1699/1652.Defuse the Bomb/Solution.py +++ b/solution/1600-1699/1652.Defuse the Bomb/Solution.py @@ -4,10 +4,11 @@ def decrypt(self, code: List[int], k: int) -> List[int]: ans = [0] * n if k == 0: return ans - s = list(accumulate(code + code, initial=0)) for i in range(n): if k > 0: - ans[i] = s[i + k + 1] - s[i + 1] + for j in range(i + 1, i + k + 1): + ans[i] += code[j % n] else: - ans[i] = s[i + n] - s[i + k + n] + for j in range(i + k, i): + ans[i] += code[(j + n) % n] return ans diff --git a/solution/1600-1699/1652.Defuse the Bomb/Solution2.cpp b/solution/1600-1699/1652.Defuse the Bomb/Solution2.cpp new file mode 100644 index 0000000000000..dd75d6692fc0b --- /dev/null +++ b/solution/1600-1699/1652.Defuse the Bomb/Solution2.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + vector decrypt(vector& code, int k) { + int n = code.size(); + vector ans(n); + if (k == 0) { + return ans; + } + vector s(n << 1 | 1); + for (int i = 0; i < n << 1; ++i) { + s[i + 1] = s[i] + code[i % n]; + } + for (int i = 0; i < n; ++i) { + if (k > 0) { + ans[i] = s[i + k + 1] - s[i + 1]; + } else { + ans[i] = s[i + n] - s[i + k + n]; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1652.Defuse the Bomb/Solution2.go b/solution/1600-1699/1652.Defuse the Bomb/Solution2.go new file mode 100644 index 0000000000000..bc85d85ea0098 --- /dev/null +++ b/solution/1600-1699/1652.Defuse the Bomb/Solution2.go @@ -0,0 +1,19 @@ +func decrypt(code []int, k int) []int { + n := len(code) + ans := make([]int, n) + if k == 0 { + return ans + } + s := make([]int, n<<1|1) + for i := 0; i < n<<1; i++ { + s[i+1] = s[i] + code[i%n] + } + for i := range code { + if k > 0 { + ans[i] = s[i+k+1] - s[i+1] + } else { + ans[i] = s[i+n] - s[i+k+n] + } + } + return ans +} \ No newline at end of file diff --git a/solution/1600-1699/1652.Defuse the Bomb/Solution2.java b/solution/1600-1699/1652.Defuse the Bomb/Solution2.java new file mode 100644 index 0000000000000..343419b76aad9 --- /dev/null +++ b/solution/1600-1699/1652.Defuse the Bomb/Solution2.java @@ -0,0 +1,21 @@ +class Solution { + public int[] decrypt(int[] code, int k) { + int n = code.length; + int[] ans = new int[n]; + if (k == 0) { + return ans; + } + int[] s = new int[n << 1 | 1]; + for (int i = 0; i < n << 1; ++i) { + s[i + 1] = s[i] + code[i % n]; + } + for (int i = 0; i < n; ++i) { + if (k > 0) { + ans[i] = s[i + k + 1] - s[i + 1]; + } else { + ans[i] = s[i + n] - s[i + k + n]; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1652.Defuse the Bomb/Solution2.py b/solution/1600-1699/1652.Defuse the Bomb/Solution2.py new file mode 100644 index 0000000000000..48882e061831e --- /dev/null +++ b/solution/1600-1699/1652.Defuse the Bomb/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def decrypt(self, code: List[int], k: int) -> List[int]: + n = len(code) + ans = [0] * n + if k == 0: + return ans + s = list(accumulate(code + code, initial=0)) + for i in range(n): + if k > 0: + ans[i] = s[i + k + 1] - s[i + 1] + else: + ans[i] = s[i + n] - s[i + k + n] + return ans diff --git a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.cpp b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.cpp index 56a35491710ff..ffe50b16c51a7 100644 --- a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.cpp +++ b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.cpp @@ -1,14 +1,18 @@ class Solution { public: int minimumDeletions(string s) { - int ans = 0, b = 0; - for (char& c : s) { - if (c == 'b') { + int n = s.size(); + int f[n + 1]; + memset(f, 0, sizeof(f)); + int b = 0; + for (int i = 1; i <= n; ++i) { + if (s[i - 1] == 'b') { + f[i] = f[i - 1]; ++b; } else { - ans = min(ans + 1, b); + f[i] = min(f[i - 1] + 1, b); } } - return ans; + return f[n]; } }; \ No newline at end of file diff --git a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.go b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.go index fee3d89d7cff9..677975ed9120e 100644 --- a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.go +++ b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.go @@ -1,11 +1,15 @@ func minimumDeletions(s string) int { - ans, b := 0, 0 - for _, c := range s { + n := len(s) + f := make([]int, n+1) + b := 0 + for i, c := range s { + i++ if c == 'b' { + f[i] = f[i-1] b++ } else { - ans = min(ans+1, b) + f[i] = min(f[i-1]+1, b) } } - return ans + return f[n] } \ No newline at end of file diff --git a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.java b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.java index 5611c482cce7e..4219588e9143d 100644 --- a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.java +++ b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.java @@ -1,14 +1,16 @@ class Solution { public int minimumDeletions(String s) { int n = s.length(); - int ans = 0, b = 0; - for (int i = 0; i < n; ++i) { - if (s.charAt(i) == 'b') { + int[] f = new int[n + 1]; + int b = 0; + for (int i = 1; i <= n; ++i) { + if (s.charAt(i - 1) == 'b') { + f[i] = f[i - 1]; ++b; } else { - ans = Math.min(ans + 1, b); + f[i] = Math.min(f[i - 1] + 1, b); } } - return ans; + return f[n]; } } \ No newline at end of file diff --git a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.py b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.py index 97a8bc364fedc..7c9f3ad23aaa1 100644 --- a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.py +++ b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.py @@ -1,9 +1,12 @@ class Solution: def minimumDeletions(self, s: str) -> int: - ans = b = 0 - for c in s: + n = len(s) + f = [0] * (n + 1) + b = 0 + for i, c in enumerate(s, 1): if c == 'b': + f[i] = f[i - 1] b += 1 else: - ans = min(ans + 1, b) - return ans + f[i] = min(f[i - 1] + 1, b) + return f[n] diff --git a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.ts b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.ts index 35cdc37e29f98..9800753821a5d 100644 --- a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.ts +++ b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.ts @@ -1,13 +1,14 @@ function minimumDeletions(s: string): number { const n = s.length; - let ans = 0, - b = 0; - for (let i = 0; i < n; ++i) { - if (s.charAt(i) === 'b') { + const f = new Array(n + 1).fill(0); + let b = 0; + for (let i = 1; i <= n; ++i) { + if (s.charAt(i - 1) === 'b') { + f[i] = f[i - 1]; ++b; } else { - ans = Math.min(ans + 1, b); + f[i] = Math.min(f[i - 1] + 1, b); } } - return ans; + return f[n]; } diff --git a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution2.cpp b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution2.cpp new file mode 100644 index 0000000000000..56a35491710ff --- /dev/null +++ b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int minimumDeletions(string s) { + int ans = 0, b = 0; + for (char& c : s) { + if (c == 'b') { + ++b; + } else { + ans = min(ans + 1, b); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution2.go b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution2.go new file mode 100644 index 0000000000000..fee3d89d7cff9 --- /dev/null +++ b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution2.go @@ -0,0 +1,11 @@ +func minimumDeletions(s string) int { + ans, b := 0, 0 + for _, c := range s { + if c == 'b' { + b++ + } else { + ans = min(ans+1, b) + } + } + return ans +} \ No newline at end of file diff --git a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution2.java b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution2.java new file mode 100644 index 0000000000000..5611c482cce7e --- /dev/null +++ b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public int minimumDeletions(String s) { + int n = s.length(); + int ans = 0, b = 0; + for (int i = 0; i < n; ++i) { + if (s.charAt(i) == 'b') { + ++b; + } else { + ans = Math.min(ans + 1, b); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution2.py b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution2.py new file mode 100644 index 0000000000000..97a8bc364fedc --- /dev/null +++ b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def minimumDeletions(self, s: str) -> int: + ans = b = 0 + for c in s: + if c == 'b': + b += 1 + else: + ans = min(ans + 1, b) + return ans diff --git a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution2.ts b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution2.ts new file mode 100644 index 0000000000000..35cdc37e29f98 --- /dev/null +++ b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution2.ts @@ -0,0 +1,13 @@ +function minimumDeletions(s: string): number { + const n = s.length; + let ans = 0, + b = 0; + for (let i = 0; i < n; ++i) { + if (s.charAt(i) === 'b') { + ++b; + } else { + ans = Math.min(ans + 1, b); + } + } + return ans; +} diff --git a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution3.cpp b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution3.cpp new file mode 100644 index 0000000000000..e30fe75f52ba0 --- /dev/null +++ b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution3.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int minimumDeletions(string s) { + int lb = 0, ra = count(s.begin(), s.end(), 'a'); + int ans = ra; + for (char& c : s) { + ra -= c == 'a'; + ans = min(ans, lb + ra); + lb += c == 'b'; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution3.go b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution3.go new file mode 100644 index 0000000000000..49c7cd10f68bc --- /dev/null +++ b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution3.go @@ -0,0 +1,16 @@ +func minimumDeletions(s string) int { + lb, ra := 0, strings.Count(s, "a") + ans := ra + for _, c := range s { + if c == 'a' { + ra-- + } + if t := lb + ra; ans > t { + ans = t + } + if c == 'b' { + lb++ + } + } + return ans +} \ No newline at end of file diff --git a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution3.java b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution3.java new file mode 100644 index 0000000000000..6a20488474486 --- /dev/null +++ b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution3.java @@ -0,0 +1,18 @@ +class Solution { + public int minimumDeletions(String s) { + int lb = 0, ra = 0; + int n = s.length(); + for (int i = 0; i < n; ++i) { + if (s.charAt(i) == 'a') { + ++ra; + } + } + int ans = n; + for (int i = 0; i < n; ++i) { + ra -= (s.charAt(i) == 'a' ? 1 : 0); + ans = Math.min(ans, lb + ra); + lb += (s.charAt(i) == 'b' ? 1 : 0); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution3.py b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution3.py new file mode 100644 index 0000000000000..531fb051f20ea --- /dev/null +++ b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution3.py @@ -0,0 +1,9 @@ +class Solution: + def minimumDeletions(self, s: str) -> int: + lb, ra = 0, s.count('a') + ans = len(s) + for c in s: + ra -= c == 'a' + ans = min(ans, lb + ra) + lb += c == 'b' + return ans diff --git a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution3.ts b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution3.ts new file mode 100644 index 0000000000000..0364c8ddafe8c --- /dev/null +++ b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution3.ts @@ -0,0 +1,17 @@ +function minimumDeletions(s: string): number { + let lb = 0, + ra = 0; + const n = s.length; + for (let i = 0; i < n; ++i) { + if (s.charAt(i) === 'a') { + ++ra; + } + } + let ans = n; + for (let i = 0; i < n; ++i) { + ra -= s.charAt(i) === 'a' ? 1 : 0; + ans = Math.min(ans, lb + ra); + lb += s.charAt(i) === 'b' ? 1 : 0; + } + return ans; +} diff --git a/solution/1600-1699/1654.Minimum Jumps to Reach Home/Solution.cpp b/solution/1600-1699/1654.Minimum Jumps to Reach Home/Solution.cpp index d754c1d668eff..6cc128aac4a60 100644 --- a/solution/1600-1699/1654.Minimum Jumps to Reach Home/Solution.cpp +++ b/solution/1600-1699/1654.Minimum Jumps to Reach Home/Solution.cpp @@ -1,32 +1,32 @@ -class Solution { -public: - int minimumJumps(vector& forbidden, int a, int b, int x) { - unordered_set s(forbidden.begin(), forbidden.end()); - queue> q; - q.emplace(0, 1); - const int n = 6000; - bool vis[n][2]; - memset(vis, false, sizeof(vis)); - vis[0][1] = true; - for (int ans = 0; q.size(); ++ans) { - for (int t = q.size(); t; --t) { - auto [i, k] = q.front(); - q.pop(); - if (i == x) { - return ans; - } - vector> nxts = {{i + a, 1}}; - if (k & 1) { - nxts.emplace_back(i - b, 0); - } - for (auto [j, l] : nxts) { - if (j >= 0 && j < n && !s.count(j) && !vis[j][l]) { - vis[j][l] = true; - q.emplace(j, l); - } - } - } - } - return -1; - } +class Solution { +public: + int minimumJumps(vector& forbidden, int a, int b, int x) { + unordered_set s(forbidden.begin(), forbidden.end()); + queue> q; + q.emplace(0, 1); + const int n = 6000; + bool vis[n][2]; + memset(vis, false, sizeof(vis)); + vis[0][1] = true; + for (int ans = 0; q.size(); ++ans) { + for (int t = q.size(); t; --t) { + auto [i, k] = q.front(); + q.pop(); + if (i == x) { + return ans; + } + vector> nxts = {{i + a, 1}}; + if (k & 1) { + nxts.emplace_back(i - b, 0); + } + for (auto [j, l] : nxts) { + if (j >= 0 && j < n && !s.count(j) && !vis[j][l]) { + vis[j][l] = true; + q.emplace(j, l); + } + } + } + } + return -1; + } }; \ No newline at end of file diff --git a/solution/1600-1699/1654.Minimum Jumps to Reach Home/Solution.java b/solution/1600-1699/1654.Minimum Jumps to Reach Home/Solution.java index 99d03b5beb2fb..1bc4159bf32e5 100644 --- a/solution/1600-1699/1654.Minimum Jumps to Reach Home/Solution.java +++ b/solution/1600-1699/1654.Minimum Jumps to Reach Home/Solution.java @@ -1,36 +1,36 @@ -class Solution { - public int minimumJumps(int[] forbidden, int a, int b, int x) { - Set s = new HashSet<>(); - for (int v : forbidden) { - s.add(v); - } - Deque q = new ArrayDeque<>(); - q.offer(new int[] {0, 1}); - final int n = 6000; - boolean[][] vis = new boolean[n][2]; - vis[0][1] = true; - for (int ans = 0; !q.isEmpty(); ++ans) { - for (int t = q.size(); t > 0; --t) { - var p = q.poll(); - int i = p[0], k = p[1]; - if (i == x) { - return ans; - } - List nxt = new ArrayList<>(); - nxt.add(new int[] {i + a, 1}); - if ((k & 1) == 1) { - nxt.add(new int[] {i - b, 0}); - } - for (var e : nxt) { - int j = e[0]; - k = e[1]; - if (j >= 0 && j < n && !s.contains(j) && !vis[j][k]) { - q.offer(new int[] {j, k}); - vis[j][k] = true; - } - } - } - } - return -1; - } +class Solution { + public int minimumJumps(int[] forbidden, int a, int b, int x) { + Set s = new HashSet<>(); + for (int v : forbidden) { + s.add(v); + } + Deque q = new ArrayDeque<>(); + q.offer(new int[] {0, 1}); + final int n = 6000; + boolean[][] vis = new boolean[n][2]; + vis[0][1] = true; + for (int ans = 0; !q.isEmpty(); ++ans) { + for (int t = q.size(); t > 0; --t) { + var p = q.poll(); + int i = p[0], k = p[1]; + if (i == x) { + return ans; + } + List nxt = new ArrayList<>(); + nxt.add(new int[] {i + a, 1}); + if ((k & 1) == 1) { + nxt.add(new int[] {i - b, 0}); + } + for (var e : nxt) { + int j = e[0]; + k = e[1]; + if (j >= 0 && j < n && !s.contains(j) && !vis[j][k]) { + q.offer(new int[] {j, k}); + vis[j][k] = true; + } + } + } + } + return -1; + } } \ No newline at end of file diff --git a/solution/1600-1699/1657.Determine if Two Strings Are Close/Solution.cpp b/solution/1600-1699/1657.Determine if Two Strings Are Close/Solution.cpp index 36a617ebc94f1..2c7d7711bb5ff 100644 --- a/solution/1600-1699/1657.Determine if Two Strings Are Close/Solution.cpp +++ b/solution/1600-1699/1657.Determine if Two Strings Are Close/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - bool closeStrings(string word1, string word2) { - int cnt1[26]{}; - int cnt2[26]{}; - for (char& c : word1) { - ++cnt1[c - 'a']; - } - for (char& c : word2) { - ++cnt2[c - 'a']; - } - for (int i = 0; i < 26; ++i) { - if ((cnt1[i] == 0) != (cnt2[i] == 0)) { - return false; - } - } - sort(cnt1, cnt1 + 26); - sort(cnt2, cnt2 + 26); - return equal(cnt1, cnt1 + 26, cnt2); - } +class Solution { +public: + bool closeStrings(string word1, string word2) { + int cnt1[26]{}; + int cnt2[26]{}; + for (char& c : word1) { + ++cnt1[c - 'a']; + } + for (char& c : word2) { + ++cnt2[c - 'a']; + } + for (int i = 0; i < 26; ++i) { + if ((cnt1[i] == 0) != (cnt2[i] == 0)) { + return false; + } + } + sort(cnt1, cnt1 + 26); + sort(cnt2, cnt2 + 26); + return equal(cnt1, cnt1 + 26, cnt2); + } }; \ No newline at end of file diff --git a/solution/1600-1699/1657.Determine if Two Strings Are Close/Solution.java b/solution/1600-1699/1657.Determine if Two Strings Are Close/Solution.java index b0f0c7d75e61b..782f19084120d 100644 --- a/solution/1600-1699/1657.Determine if Two Strings Are Close/Solution.java +++ b/solution/1600-1699/1657.Determine if Two Strings Are Close/Solution.java @@ -1,20 +1,20 @@ -class Solution { - public boolean closeStrings(String word1, String word2) { - int[] cnt1 = new int[26]; - int[] cnt2 = new int[26]; - for (int i = 0; i < word1.length(); ++i) { - ++cnt1[word1.charAt(i) - 'a']; - } - for (int i = 0; i < word2.length(); ++i) { - ++cnt2[word2.charAt(i) - 'a']; - } - for (int i = 0; i < 26; ++i) { - if ((cnt1[i] == 0) != (cnt2[i] == 0)) { - return false; - } - } - Arrays.sort(cnt1); - Arrays.sort(cnt2); - return Arrays.equals(cnt1, cnt2); - } +class Solution { + public boolean closeStrings(String word1, String word2) { + int[] cnt1 = new int[26]; + int[] cnt2 = new int[26]; + for (int i = 0; i < word1.length(); ++i) { + ++cnt1[word1.charAt(i) - 'a']; + } + for (int i = 0; i < word2.length(); ++i) { + ++cnt2[word2.charAt(i) - 'a']; + } + for (int i = 0; i < 26; ++i) { + if ((cnt1[i] == 0) != (cnt2[i] == 0)) { + return false; + } + } + Arrays.sort(cnt1); + Arrays.sort(cnt2); + return Arrays.equals(cnt1, cnt2); + } } \ No newline at end of file diff --git a/solution/1600-1699/1657.Determine if Two Strings Are Close/Solution.py b/solution/1600-1699/1657.Determine if Two Strings Are Close/Solution.py index 395180f8aea3c..81d6e30975d9c 100644 --- a/solution/1600-1699/1657.Determine if Two Strings Are Close/Solution.py +++ b/solution/1600-1699/1657.Determine if Two Strings Are Close/Solution.py @@ -1,7 +1,6 @@ -class Solution: - def closeStrings(self, word1: str, word2: str) -> bool: - cnt1 = Counter(word1) - cnt2 = Counter(word2) - return set(cnt1.keys()) == set(cnt2.keys()) and Counter( - cnt1.values() - ) == Counter(cnt2.values()) +class Solution: + def closeStrings(self, word1: str, word2: str) -> bool: + cnt1, cnt2 = Counter(word1), Counter(word2) + return sorted(cnt1.values()) == sorted(cnt2.values()) and set( + cnt1.keys() + ) == set(cnt2.keys()) diff --git a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.c b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.c index 96845040d3e7a..386b6de7e2955 100644 --- a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.c +++ b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.c @@ -24,4 +24,4 @@ int minOperations(int* nums, int numsSize, int x) { return -1; } return ans; -} +} \ No newline at end of file diff --git a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.go b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.go index e900da722c758..df468c39f1462 100644 --- a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.go +++ b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.go @@ -3,17 +3,16 @@ func minOperations(nums []int, x int) int { for _, v := range nums { x += v } + vis := map[int]int{0: -1} ans := 1 << 30 s, n := 0, len(nums) - j := 0 for i, v := range nums { s += v - for j <= i && s > x { - s -= nums[j] - j++ + if _, ok := vis[s]; !ok { + vis[s] = i } - if s == x { - ans = min(ans, n-(i-j+1)) + if j, ok := vis[s-x]; ok { + ans = min(ans, n-(i-j)) } } if ans == 1<<30 { diff --git a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.java b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.java index 15902f37cef3e..1fda2dcf11a25 100644 --- a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.java +++ b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.java @@ -4,15 +4,16 @@ public int minOperations(int[] nums, int x) { for (int v : nums) { x += v; } + Map vis = new HashMap<>(); + vis.put(0, -1); int n = nums.length; int ans = 1 << 30; - for (int i = 0, j = 0, s = 0; i < n; ++i) { + for (int i = 0, s = 0; i < n; ++i) { s += nums[i]; - while (j <= i && s > x) { - s -= nums[j++]; - } - if (s == x) { - ans = Math.min(ans, n - (i - j + 1)); + vis.putIfAbsent(s, i); + if (vis.containsKey(s - x)) { + int j = vis.get(s - x); + ans = Math.min(ans, n - (i - j)); } } return ans == 1 << 30 ? -1 : ans; diff --git a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.py b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.py index 38e18fc805418..a124eb004a18f 100644 --- a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.py +++ b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.py @@ -1,14 +1,14 @@ class Solution: def minOperations(self, nums: List[int], x: int) -> int: x = sum(nums) - x + vis = {0: -1} ans = inf - n = len(nums) - s = j = 0 + s, n = 0, len(nums) for i, v in enumerate(nums): s += v - while j <= i and s > x: - s -= nums[j] - j += 1 - if s == x: - ans = min(ans, n - (i - j + 1)) + if s not in vis: + vis[s] = i + if s - x in vis: + j = vis[s - x] + ans = min(ans, n - (i - j)) return -1 if ans == inf else ans diff --git a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.ts b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.ts index 8dfb6bc212caf..42fd0c850ffb5 100644 --- a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.ts +++ b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution.ts @@ -1,14 +1,17 @@ function minOperations(nums: number[], x: number): number { x = nums.reduce((a, b) => a + b, 0) - x; + const vis = new Map(); + vis.set(0, -1); const n = nums.length; let ans = 1 << 30; - for (let i = 0, j = 0, s = 0; i < n; ++i) { + for (let i = 0, s = 0; i < n; ++i) { s += nums[i]; - while (j <= i && s > x) { - s -= nums[j++]; + if (!vis.has(s)) { + vis.set(s, i); } - if (s == x) { - ans = Math.min(ans, n - (i - j + 1)); + if (vis.has(s - x)) { + const j = vis.get(s - x); + ans = Math.min(ans, n - (i - j)); } } return ans == 1 << 30 ? -1 : ans; diff --git a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution2.cpp b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution2.cpp new file mode 100644 index 0000000000000..53511235a5b74 --- /dev/null +++ b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution2.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int minOperations(vector& nums, int x) { + x = accumulate(nums.begin(), nums.end(), 0) - x; + int n = nums.size(); + int ans = 1 << 30; + for (int i = 0, j = 0, s = 0; i < n; ++i) { + s += nums[i]; + while (j <= i && s > x) { + s -= nums[j++]; + } + if (s == x) { + ans = min(ans, n - (i - j + 1)); + } + } + return ans == 1 << 30 ? -1 : ans; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution2.go b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution2.go new file mode 100644 index 0000000000000..e900da722c758 --- /dev/null +++ b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution2.go @@ -0,0 +1,23 @@ +func minOperations(nums []int, x int) int { + x = -x + for _, v := range nums { + x += v + } + ans := 1 << 30 + s, n := 0, len(nums) + j := 0 + for i, v := range nums { + s += v + for j <= i && s > x { + s -= nums[j] + j++ + } + if s == x { + ans = min(ans, n-(i-j+1)) + } + } + if ans == 1<<30 { + return -1 + } + return ans +} \ No newline at end of file diff --git a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution2.java b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution2.java new file mode 100644 index 0000000000000..15902f37cef3e --- /dev/null +++ b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution2.java @@ -0,0 +1,20 @@ +class Solution { + public int minOperations(int[] nums, int x) { + x = -x; + for (int v : nums) { + x += v; + } + int n = nums.length; + int ans = 1 << 30; + for (int i = 0, j = 0, s = 0; i < n; ++i) { + s += nums[i]; + while (j <= i && s > x) { + s -= nums[j++]; + } + if (s == x) { + ans = Math.min(ans, n - (i - j + 1)); + } + } + return ans == 1 << 30 ? -1 : ans; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution2.py b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution2.py new file mode 100644 index 0000000000000..38e18fc805418 --- /dev/null +++ b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def minOperations(self, nums: List[int], x: int) -> int: + x = sum(nums) - x + ans = inf + n = len(nums) + s = j = 0 + for i, v in enumerate(nums): + s += v + while j <= i and s > x: + s -= nums[j] + j += 1 + if s == x: + ans = min(ans, n - (i - j + 1)) + return -1 if ans == inf else ans diff --git a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution2.ts b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution2.ts new file mode 100644 index 0000000000000..8dfb6bc212caf --- /dev/null +++ b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/Solution2.ts @@ -0,0 +1,15 @@ +function minOperations(nums: number[], x: number): number { + x = nums.reduce((a, b) => a + b, 0) - x; + const n = nums.length; + let ans = 1 << 30; + for (let i = 0, j = 0, s = 0; i < n; ++i) { + s += nums[i]; + while (j <= i && s > x) { + s -= nums[j++]; + } + if (s == x) { + ans = Math.min(ans, n - (i - j + 1)); + } + } + return ans == 1 << 30 ? -1 : ans; +} diff --git a/solution/1600-1699/1659.Maximize Grid Happiness/Solution.cpp b/solution/1600-1699/1659.Maximize Grid Happiness/Solution.cpp index 9158ee5123fc2..eafe64220ec73 100644 --- a/solution/1600-1699/1659.Maximize Grid Happiness/Solution.cpp +++ b/solution/1600-1699/1659.Maximize Grid Happiness/Solution.cpp @@ -1,31 +1,59 @@ class Solution { public: int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { + int mx = pow(3, n); + int f[mx]; + int g[mx][mx]; + int bits[mx][n]; + int ix[mx]; + int ex[mx]; + int memo[m][mx][introvertsCount + 1][extrovertsCount + 1]; int h[3][3] = {{0, 0, 0}, {0, -60, -10}, {0, -10, 40}}; - int p = pow(3, n - 1); - int memo[m * n][p * 3][introvertsCount + 1][extrovertsCount + 1]; + memset(f, 0, sizeof(f)); + memset(g, 0, sizeof(g)); + memset(bits, 0, sizeof(bits)); + memset(ix, 0, sizeof(ix)); + memset(ex, 0, sizeof(ex)); memset(memo, -1, sizeof(memo)); - function dfs = [&](int pos, int pre, int ic, int ec) { - if (pos == m * n || (ic == 0 && ec == 0)) { + for (int i = 0; i < mx; ++i) { + int mask = i; + for (int j = 0; j < n; ++j) { + int x = mask % 3; + mask /= 3; + bits[i][j] = x; + if (x == 1) { + ix[i]++; + f[i] += 120; + } else if (x == 2) { + ex[i]++; + f[i] += 40; + } + if (j) { + f[i] += h[x][bits[i][j - 1]]; + } + } + } + for (int i = 0; i < mx; ++i) { + for (int j = 0; j < mx; ++j) { + for (int k = 0; k < n; ++k) { + g[i][j] += h[bits[i][k]][bits[j][k]]; + } + } + } + function dfs = [&](int i, int pre, int ic, int ec) { + if (i == m || (ic == 0 && ec == 0)) { return 0; } - if (memo[pos][pre][ic][ec] != -1) { - return memo[pos][pre][ic][ec]; + if (memo[i][pre][ic][ec] != -1) { + return memo[i][pre][ic][ec]; } int ans = 0; - int up = pre / p; - int left = pos % n == 0 ? 0 : pre % 3; - for (int i = 0; i < 3; ++i) { - if ((i == 1 && ic == 0) || (i == 2 && ec == 0)) { - continue; + for (int cur = 0; cur < mx; ++cur) { + if (ix[cur] <= ic && ex[cur] <= ec) { + ans = max(ans, f[cur] + g[pre][cur] + dfs(i + 1, cur, ic - ix[cur], ec - ex[cur])); } - int cur = pre % p * 3 + i; - int a = h[up][i] + h[left][i]; - int b = dfs(pos + 1, cur, ic - (i == 1), ec - (i == 2)); - int c = i == 1 ? 120 : (i == 2 ? 40 : 0); - ans = max(ans, a + b + c); } - return memo[pos][pre][ic][ec] = ans; + return memo[i][pre][ic][ec] = ans; }; return dfs(0, 0, introvertsCount, extrovertsCount); } diff --git a/solution/1600-1699/1659.Maximize Grid Happiness/Solution.go b/solution/1600-1699/1659.Maximize Grid Happiness/Solution.go index 5472421b35093..8259158150087 100644 --- a/solution/1600-1699/1659.Maximize Grid Happiness/Solution.go +++ b/solution/1600-1699/1659.Maximize Grid Happiness/Solution.go @@ -1,9 +1,18 @@ func getMaxGridHappiness(m int, n int, introvertsCount int, extrovertsCount int) int { - p := int(math.Pow(3, float64(n-1))) + mx := int(math.Pow(3, float64(n))) + f := make([]int, mx) + g := make([][]int, mx) h := [3][3]int{{0, 0, 0}, {0, -60, -10}, {0, -10, 40}} - memo := make([][][][]int, m*n) + bits := make([][]int, mx) + ix := make([]int, mx) + ex := make([]int, mx) + memo := make([][][][]int, m) + for i := range g { + g[i] = make([]int, mx) + bits[i] = make([]int, n) + } for i := range memo { - memo[i] = make([][][]int, p*3) + memo[i] = make([][][]int, mx) for j := range memo[i] { memo[i][j] = make([][]int, introvertsCount+1) for k := range memo[i][j] { @@ -14,39 +23,46 @@ func getMaxGridHappiness(m int, n int, introvertsCount int, extrovertsCount int) } } } + for i := 0; i < mx; i++ { + mask := i + for j := 0; j < n; j++ { + x := mask % 3 + mask /= 3 + bits[i][j] = x + if x == 1 { + ix[i]++ + f[i] += 120 + } else if x == 2 { + ex[i]++ + f[i] += 40 + } + if j > 0 { + f[i] += h[x][bits[i][j-1]] + } + } + } + for i := 0; i < mx; i++ { + for j := 0; j < mx; j++ { + for k := 0; k < n; k++ { + g[i][j] += h[bits[i][k]][bits[j][k]] + } + } + } var dfs func(int, int, int, int) int - dfs = func(pos, pre, ic, ec int) int { - if pos == m*n || (ic == 0 && ec == 0) { + dfs = func(i, pre, ic, ec int) int { + if i == m || (ic == 0 && ec == 0) { return 0 } - if memo[pos][pre][ic][ec] != -1 { - return memo[pos][pre][ic][ec] + if memo[i][pre][ic][ec] != -1 { + return memo[i][pre][ic][ec] } ans := 0 - up := pre / p - left := pre % 3 - if pos%n == 0 { - left = 0 - } - for i := 0; i < 3; i++ { - if (i == 1 && ic == 0) || (i == 2 && ec == 0) { - continue - } - cur := pre%p*3 + i - nic, nec := ic, ec - c := 0 - if i == 1 { - nic-- - c = 120 - } else if i == 2 { - nec-- - c = 40 + for cur := 0; cur < mx; cur++ { + if ix[cur] <= ic && ex[cur] <= ec { + ans = max(ans, f[cur]+g[pre][cur]+dfs(i+1, cur, ic-ix[cur], ec-ex[cur])) } - a := h[up][i] + h[left][i] - b := dfs(pos+1, cur, nic, nec) - ans = max(ans, a+b+c) } - memo[pos][pre][ic][ec] = ans + memo[i][pre][ic][ec] = ans return ans } return dfs(0, 0, introvertsCount, extrovertsCount) diff --git a/solution/1600-1699/1659.Maximize Grid Happiness/Solution.java b/solution/1600-1699/1659.Maximize Grid Happiness/Solution.java index 3a9bbdb0c7828..cc9747dbacc34 100644 --- a/solution/1600-1699/1659.Maximize Grid Happiness/Solution.java +++ b/solution/1600-1699/1659.Maximize Grid Happiness/Solution.java @@ -1,38 +1,65 @@ class Solution { private int m; - private int n; - private int p; - private final int[][] h = {{0, 0, 0}, {0, -60, -10}, {0, -10, 40}}; + private int mx; + private int[] f; + private int[][] g; + private int[][] bits; + private int[] ix; + private int[] ex; private Integer[][][][] memo; + private final int[][] h = {{0, 0, 0}, {0, -60, -10}, {0, -10, 40}}; public int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { this.m = m; - this.n = n; - p = (int) Math.pow(3, n - 1); - memo = new Integer[m * n][p * 3][introvertsCount + 1][extrovertsCount + 1]; + mx = (int) Math.pow(3, n); + f = new int[mx]; + g = new int[mx][mx]; + bits = new int[mx][n]; + ix = new int[mx]; + ex = new int[mx]; + memo = new Integer[m][mx][introvertsCount + 1][extrovertsCount + 1]; + for (int i = 0; i < mx; ++i) { + int mask = i; + for (int j = 0; j < n; ++j) { + int x = mask % 3; + mask /= 3; + bits[i][j] = x; + if (x == 1) { + ix[i]++; + f[i] += 120; + } else if (x == 2) { + ex[i]++; + f[i] += 40; + } + if (j > 0) { + f[i] += h[x][bits[i][j - 1]]; + } + } + } + for (int i = 0; i < mx; ++i) { + for (int j = 0; j < mx; ++j) { + for (int k = 0; k < n; ++k) { + g[i][j] += h[bits[i][k]][bits[j][k]]; + } + } + } return dfs(0, 0, introvertsCount, extrovertsCount); } - private int dfs(int pos, int pre, int ic, int ec) { - if (pos == m * n || (ic == 0 && ec == 0)) { + private int dfs(int i, int pre, int ic, int ec) { + if (i == m || (ic == 0 && ec == 0)) { return 0; } - if (memo[pos][pre][ic][ec] != null) { - return memo[pos][pre][ic][ec]; + if (memo[i][pre][ic][ec] != null) { + return memo[i][pre][ic][ec]; } int ans = 0; - int up = pre / p; - int left = pos % n == 0 ? 0 : pre % 3; - for (int i = 0; i < 3; ++i) { - if (i == 1 && (ic == 0) || (i == 2 && ec == 0)) { - continue; + for (int cur = 0; cur < mx; ++cur) { + if (ix[cur] <= ic && ex[cur] <= ec) { + ans = Math.max( + ans, f[cur] + g[pre][cur] + dfs(i + 1, cur, ic - ix[cur], ec - ex[cur])); } - int cur = pre % p * 3 + i; - int a = h[up][i] + h[left][i]; - int b = dfs(pos + 1, cur, ic - (i == 1 ? 1 : 0), ec - (i == 2 ? 1 : 0)); - int c = i == 1 ? 120 : (i == 2 ? 40 : 0); - ans = Math.max(ans, a + b + c); } - return memo[pos][pre][ic][ec] = ans; + return memo[i][pre][ic][ec] = ans; } } \ No newline at end of file diff --git a/solution/1600-1699/1659.Maximize Grid Happiness/Solution.py b/solution/1600-1699/1659.Maximize Grid Happiness/Solution.py index c0daa2ae08954..891dad947bb4b 100644 --- a/solution/1600-1699/1659.Maximize Grid Happiness/Solution.py +++ b/solution/1600-1699/1659.Maximize Grid Happiness/Solution.py @@ -3,26 +3,39 @@ def getMaxGridHappiness( self, m: int, n: int, introvertsCount: int, extrovertsCount: int ) -> int: @cache - def dfs(pos: int, pre: int, ic: int, ec: int) -> int: - if pos == m * n or (ic == 0 and ec == 0): + def dfs(i: int, pre: int, ic: int, ec: int) -> int: + if i == m or (ic == 0 and ec == 0): return 0 ans = 0 - up = pre // p - left = 0 if pos % n == 0 else pre % 3 - for i in range(3): - if (i == 1 and ic == 0) or (i == 2 and ec == 0): - continue - cur = pre % p * 3 + i - a = h[up][i] + h[left][i] - b = dfs(pos + 1, cur, ic - (i == 1), ec - (i == 2)) - c = 0 - if i == 1: - c = 120 - elif i == 2: - c = 40 - ans = max(ans, a + b + c) + for cur in range(mx): + if ix[cur] <= ic and ex[cur] <= ec: + a = f[cur] + g[pre][cur] + b = dfs(i + 1, cur, ic - ix[cur], ec - ex[cur]) + ans = max(ans, a + b) return ans - p = pow(3, n - 1) + mx = pow(3, n) + f = [0] * mx + g = [[0] * mx for _ in range(mx)] h = [[0, 0, 0], [0, -60, -10], [0, -10, 40]] + bits = [[0] * n for _ in range(mx)] + ix = [0] * mx + ex = [0] * mx + for i in range(mx): + mask = i + for j in range(n): + mask, x = divmod(mask, 3) + bits[i][j] = x + if x == 1: + ix[i] += 1 + f[i] += 120 + elif x == 2: + ex[i] += 1 + f[i] += 40 + if j: + f[i] += h[x][bits[i][j - 1]] + for i in range(mx): + for j in range(mx): + for k in range(n): + g[i][j] += h[bits[i][k]][bits[j][k]] return dfs(0, 0, introvertsCount, extrovertsCount) diff --git a/solution/1600-1699/1659.Maximize Grid Happiness/Solution.ts b/solution/1600-1699/1659.Maximize Grid Happiness/Solution.ts index 49ee24d7aa57f..94ebe36a71b36 100644 --- a/solution/1600-1699/1659.Maximize Grid Happiness/Solution.ts +++ b/solution/1600-1699/1659.Maximize Grid Happiness/Solution.ts @@ -4,16 +4,25 @@ function getMaxGridHappiness( introvertsCount: number, extrovertsCount: number, ): number { - const p = 3 ** (n - 1); + const mx = 3 ** n; + const f: number[] = Array(mx).fill(0); + const g: number[][] = Array(mx) + .fill(0) + .map(() => Array(mx).fill(0)); const h: number[][] = [ [0, 0, 0], [0, -60, -10], [0, -10, 40], ]; - const memo: number[][][][] = Array(m * n) + const bits: number[][] = Array(mx) + .fill(0) + .map(() => Array(n).fill(0)); + const ix: number[] = Array(mx).fill(0); + const ex: number[] = Array(mx).fill(0); + const memo: number[][][][] = Array(m) .fill(0) .map(() => - Array(p * 3) + Array(mx) .fill(0) .map(() => Array(introvertsCount + 1) @@ -21,29 +30,47 @@ function getMaxGridHappiness( .map(() => Array(extrovertsCount + 1).fill(-1)), ), ); - const dfs = (pos: number, pre: number, ic: number, ec: number): number => { - if (pos === m * n || (ic === 0 && ec === 0)) { + for (let i = 0; i < mx; ++i) { + let mask = i; + for (let j = 0; j < n; ++j) { + const x = mask % 3; + mask = Math.floor(mask / 3); + bits[i][j] = x; + if (x === 1) { + ix[i] += 1; + f[i] += 120; + } else if (x === 2) { + ex[i] += 1; + f[i] += 40; + } + if (j > 0) { + f[i] += h[x][bits[i][j - 1]]; + } + } + } + for (let i = 0; i < mx; ++i) { + for (let j = 0; j < mx; ++j) { + for (let k = 0; k < n; ++k) { + g[i][j] += h[bits[i][k]][bits[j][k]]; + } + } + } + const dfs = (i: number, pre: number, ic: number, ec: number): number => { + if (i === m || (ic === 0 && ec === 0)) { return 0; } - if (memo[pos][pre][ic][ec] !== -1) { - return memo[pos][pre][ic][ec]; + if (memo[i][pre][ic][ec] !== -1) { + return memo[i][pre][ic][ec]; } let ans = 0; - const up = Math.floor(pre / p); - const left = pos % n == 0 ? 0 : pre % 3; - for (let i = 0; i < 3; ++i) { - if ((i === 1 && ic === 0) || (i === 2 && ec === 0)) { - continue; + for (let cur = 0; cur < mx; ++cur) { + if (ix[cur] <= ic && ex[cur] <= ec) { + const a = f[cur] + g[pre][cur]; + const b = dfs(i + 1, cur, ic - ix[cur], ec - ex[cur]); + ans = Math.max(ans, a + b); } - const cur = (pre % p) * 3 + i; - const a = h[up][i] + h[left][i]; - const nic = i === 1 ? ic - 1 : ic; - const nec = i === 2 ? ec - 1 : ec; - const b = dfs(pos + 1, cur, nic, nec); - const c = i === 1 ? 120 : i === 2 ? 40 : 0; - ans = Math.max(ans, a + b + c); } - return (memo[pos][pre][ic][ec] = ans); + return (memo[i][pre][ic][ec] = ans); }; return dfs(0, 0, introvertsCount, extrovertsCount); } diff --git a/solution/1600-1699/1659.Maximize Grid Happiness/Solution2.cpp b/solution/1600-1699/1659.Maximize Grid Happiness/Solution2.cpp new file mode 100644 index 0000000000000..9158ee5123fc2 --- /dev/null +++ b/solution/1600-1699/1659.Maximize Grid Happiness/Solution2.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { + int h[3][3] = {{0, 0, 0}, {0, -60, -10}, {0, -10, 40}}; + int p = pow(3, n - 1); + int memo[m * n][p * 3][introvertsCount + 1][extrovertsCount + 1]; + memset(memo, -1, sizeof(memo)); + function dfs = [&](int pos, int pre, int ic, int ec) { + if (pos == m * n || (ic == 0 && ec == 0)) { + return 0; + } + if (memo[pos][pre][ic][ec] != -1) { + return memo[pos][pre][ic][ec]; + } + int ans = 0; + int up = pre / p; + int left = pos % n == 0 ? 0 : pre % 3; + for (int i = 0; i < 3; ++i) { + if ((i == 1 && ic == 0) || (i == 2 && ec == 0)) { + continue; + } + int cur = pre % p * 3 + i; + int a = h[up][i] + h[left][i]; + int b = dfs(pos + 1, cur, ic - (i == 1), ec - (i == 2)); + int c = i == 1 ? 120 : (i == 2 ? 40 : 0); + ans = max(ans, a + b + c); + } + return memo[pos][pre][ic][ec] = ans; + }; + return dfs(0, 0, introvertsCount, extrovertsCount); + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1659.Maximize Grid Happiness/Solution2.go b/solution/1600-1699/1659.Maximize Grid Happiness/Solution2.go new file mode 100644 index 0000000000000..5472421b35093 --- /dev/null +++ b/solution/1600-1699/1659.Maximize Grid Happiness/Solution2.go @@ -0,0 +1,53 @@ +func getMaxGridHappiness(m int, n int, introvertsCount int, extrovertsCount int) int { + p := int(math.Pow(3, float64(n-1))) + h := [3][3]int{{0, 0, 0}, {0, -60, -10}, {0, -10, 40}} + memo := make([][][][]int, m*n) + for i := range memo { + memo[i] = make([][][]int, p*3) + for j := range memo[i] { + memo[i][j] = make([][]int, introvertsCount+1) + for k := range memo[i][j] { + memo[i][j][k] = make([]int, extrovertsCount+1) + for l := range memo[i][j][k] { + memo[i][j][k][l] = -1 + } + } + } + } + var dfs func(int, int, int, int) int + dfs = func(pos, pre, ic, ec int) int { + if pos == m*n || (ic == 0 && ec == 0) { + return 0 + } + if memo[pos][pre][ic][ec] != -1 { + return memo[pos][pre][ic][ec] + } + ans := 0 + up := pre / p + left := pre % 3 + if pos%n == 0 { + left = 0 + } + for i := 0; i < 3; i++ { + if (i == 1 && ic == 0) || (i == 2 && ec == 0) { + continue + } + cur := pre%p*3 + i + nic, nec := ic, ec + c := 0 + if i == 1 { + nic-- + c = 120 + } else if i == 2 { + nec-- + c = 40 + } + a := h[up][i] + h[left][i] + b := dfs(pos+1, cur, nic, nec) + ans = max(ans, a+b+c) + } + memo[pos][pre][ic][ec] = ans + return ans + } + return dfs(0, 0, introvertsCount, extrovertsCount) +} \ No newline at end of file diff --git a/solution/1600-1699/1659.Maximize Grid Happiness/Solution2.java b/solution/1600-1699/1659.Maximize Grid Happiness/Solution2.java new file mode 100644 index 0000000000000..3a9bbdb0c7828 --- /dev/null +++ b/solution/1600-1699/1659.Maximize Grid Happiness/Solution2.java @@ -0,0 +1,38 @@ +class Solution { + private int m; + private int n; + private int p; + private final int[][] h = {{0, 0, 0}, {0, -60, -10}, {0, -10, 40}}; + private Integer[][][][] memo; + + public int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { + this.m = m; + this.n = n; + p = (int) Math.pow(3, n - 1); + memo = new Integer[m * n][p * 3][introvertsCount + 1][extrovertsCount + 1]; + return dfs(0, 0, introvertsCount, extrovertsCount); + } + + private int dfs(int pos, int pre, int ic, int ec) { + if (pos == m * n || (ic == 0 && ec == 0)) { + return 0; + } + if (memo[pos][pre][ic][ec] != null) { + return memo[pos][pre][ic][ec]; + } + int ans = 0; + int up = pre / p; + int left = pos % n == 0 ? 0 : pre % 3; + for (int i = 0; i < 3; ++i) { + if (i == 1 && (ic == 0) || (i == 2 && ec == 0)) { + continue; + } + int cur = pre % p * 3 + i; + int a = h[up][i] + h[left][i]; + int b = dfs(pos + 1, cur, ic - (i == 1 ? 1 : 0), ec - (i == 2 ? 1 : 0)); + int c = i == 1 ? 120 : (i == 2 ? 40 : 0); + ans = Math.max(ans, a + b + c); + } + return memo[pos][pre][ic][ec] = ans; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1659.Maximize Grid Happiness/Solution2.py b/solution/1600-1699/1659.Maximize Grid Happiness/Solution2.py new file mode 100644 index 0000000000000..c0daa2ae08954 --- /dev/null +++ b/solution/1600-1699/1659.Maximize Grid Happiness/Solution2.py @@ -0,0 +1,28 @@ +class Solution: + def getMaxGridHappiness( + self, m: int, n: int, introvertsCount: int, extrovertsCount: int + ) -> int: + @cache + def dfs(pos: int, pre: int, ic: int, ec: int) -> int: + if pos == m * n or (ic == 0 and ec == 0): + return 0 + ans = 0 + up = pre // p + left = 0 if pos % n == 0 else pre % 3 + for i in range(3): + if (i == 1 and ic == 0) or (i == 2 and ec == 0): + continue + cur = pre % p * 3 + i + a = h[up][i] + h[left][i] + b = dfs(pos + 1, cur, ic - (i == 1), ec - (i == 2)) + c = 0 + if i == 1: + c = 120 + elif i == 2: + c = 40 + ans = max(ans, a + b + c) + return ans + + p = pow(3, n - 1) + h = [[0, 0, 0], [0, -60, -10], [0, -10, 40]] + return dfs(0, 0, introvertsCount, extrovertsCount) diff --git a/solution/1600-1699/1659.Maximize Grid Happiness/Solution2.ts b/solution/1600-1699/1659.Maximize Grid Happiness/Solution2.ts new file mode 100644 index 0000000000000..49ee24d7aa57f --- /dev/null +++ b/solution/1600-1699/1659.Maximize Grid Happiness/Solution2.ts @@ -0,0 +1,49 @@ +function getMaxGridHappiness( + m: number, + n: number, + introvertsCount: number, + extrovertsCount: number, +): number { + const p = 3 ** (n - 1); + const h: number[][] = [ + [0, 0, 0], + [0, -60, -10], + [0, -10, 40], + ]; + const memo: number[][][][] = Array(m * n) + .fill(0) + .map(() => + Array(p * 3) + .fill(0) + .map(() => + Array(introvertsCount + 1) + .fill(0) + .map(() => Array(extrovertsCount + 1).fill(-1)), + ), + ); + const dfs = (pos: number, pre: number, ic: number, ec: number): number => { + if (pos === m * n || (ic === 0 && ec === 0)) { + return 0; + } + if (memo[pos][pre][ic][ec] !== -1) { + return memo[pos][pre][ic][ec]; + } + let ans = 0; + const up = Math.floor(pre / p); + const left = pos % n == 0 ? 0 : pre % 3; + for (let i = 0; i < 3; ++i) { + if ((i === 1 && ic === 0) || (i === 2 && ec === 0)) { + continue; + } + const cur = (pre % p) * 3 + i; + const a = h[up][i] + h[left][i]; + const nic = i === 1 ? ic - 1 : ic; + const nec = i === 2 ? ec - 1 : ec; + const b = dfs(pos + 1, cur, nic, nec); + const c = i === 1 ? 120 : i === 2 ? 40 : 0; + ans = Math.max(ans, a + b + c); + } + return (memo[pos][pre][ic][ec] = ans); + }; + return dfs(0, 0, introvertsCount, extrovertsCount); +} diff --git a/solution/1600-1699/1661.Average Time of Process per Machine/Solution2.sql b/solution/1600-1699/1661.Average Time of Process per Machine/Solution2.sql new file mode 100644 index 0000000000000..098b3d994eb21 --- /dev/null +++ b/solution/1600-1699/1661.Average Time of Process per Machine/Solution2.sql @@ -0,0 +1,6 @@ +# Write your MySQL query statement below +SELECT + machine_id, + ROUND(AVG(IF(activity_type = 'start', -1, 1) * timestamp) * 2, 3) AS processing_time +FROM Activity +GROUP BY 1; diff --git a/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution.c b/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution.c index b6c096a6eab04..fe39a0b48727f 100644 --- a/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution.c +++ b/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution.c @@ -18,4 +18,4 @@ bool arrayStringsAreEqual(char** word1, int word1Size, char** word2, int word2Si } } return i == word1Size && j == word2Size; -} +} \ No newline at end of file diff --git a/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution2.cpp b/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution2.cpp new file mode 100644 index 0000000000000..2469d4ae33a18 --- /dev/null +++ b/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution2.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + bool arrayStringsAreEqual(vector& word1, vector& word2) { + int i = 0, j = 0, x = 0, y = 0; + while (i < word1.size() && j < word2.size()) { + if (word1[i][x++] != word2[j][y++]) return false; + if (x == word1[i].size()) x = 0, i++; + if (y == word2[j].size()) y = 0, j++; + } + return i == word1.size() && j == word2.size(); + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution2.go b/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution2.go new file mode 100644 index 0000000000000..de2f5d2ca3004 --- /dev/null +++ b/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution2.go @@ -0,0 +1,16 @@ +func arrayStringsAreEqual(word1 []string, word2 []string) bool { + var i, j, x, y int + for i < len(word1) && j < len(word2) { + if word1[i][x] != word2[j][y] { + return false + } + x, y = x+1, y+1 + if x == len(word1[i]) { + x, i = 0, i+1 + } + if y == len(word2[j]) { + y, j = 0, j+1 + } + } + return i == len(word1) && j == len(word2) +} \ No newline at end of file diff --git a/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution2.java b/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution2.java new file mode 100644 index 0000000000000..0bf1094689f01 --- /dev/null +++ b/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution2.java @@ -0,0 +1,20 @@ +class Solution { + public boolean arrayStringsAreEqual(String[] word1, String[] word2) { + int i = 0, j = 0; + int x = 0, y = 0; + while (i < word1.length && j < word2.length) { + if (word1[i].charAt(x++) != word2[j].charAt(y++)) { + return false; + } + if (x == word1[i].length()) { + x = 0; + ++i; + } + if (y == word2[j].length()) { + y = 0; + ++j; + } + } + return i == word1.length && j == word2.length; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution2.py b/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution2.py new file mode 100644 index 0000000000000..d16c039bf5524 --- /dev/null +++ b/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: + i = j = x = y = 0 + while i < len(word1) and j < len(word2): + if word1[i][x] != word2[j][y]: + return False + x, y = x + 1, y + 1 + if x == len(word1[i]): + x, i = 0, i + 1 + if y == len(word2[j]): + y, j = 0, j + 1 + return i == len(word1) and j == len(word2) diff --git a/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution2.rs b/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution2.rs new file mode 100644 index 0000000000000..ca89d5a2723f0 --- /dev/null +++ b/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution2.rs @@ -0,0 +1,22 @@ +impl Solution { + pub fn array_strings_are_equal(word1: Vec, word2: Vec) -> bool { + let (n, m) = (word1.len(), word2.len()); + let (mut i, mut j, mut x, mut y) = (0, 0, 0, 0); + while i < n && j < m { + if word1[i].as_bytes()[x] != word2[j].as_bytes()[y] { + return false; + } + x += 1; + y += 1; + if x == word1[i].len() { + x = 0; + i += 1; + } + if y == word2[j].len() { + y = 0; + j += 1; + } + } + i == n && j == m + } +} diff --git a/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution2.ts b/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution2.ts new file mode 100644 index 0000000000000..217ed0b916a53 --- /dev/null +++ b/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/Solution2.ts @@ -0,0 +1,17 @@ +function arrayStringsAreEqual(word1: string[], word2: string[]): boolean { + let [i, j, x, y] = [0, 0, 0, 0]; + while (i < word1.length && j < word2.length) { + if (word1[i][x++] !== word2[j][y++]) { + return false; + } + if (x === word1[i].length) { + x = 0; + ++i; + } + if (y === word2[j].length) { + y = 0; + ++j; + } + } + return i === word1.length && j === word2.length; +} diff --git a/solution/1600-1699/1666.Change the Root of a Binary Tree/Solution.cs b/solution/1600-1699/1666.Change the Root of a Binary Tree/Solution.cs index 01d4d6ef8eb8b..fe475368ff7f0 100644 --- a/solution/1600-1699/1666.Change the Root of a Binary Tree/Solution.cs +++ b/solution/1600-1699/1666.Change the Root of a Binary Tree/Solution.cs @@ -30,4 +30,4 @@ public Node FlipBinaryTree(Node root, Node leaf) { leaf.parent = null; return leaf; } -} \ No newline at end of file +} diff --git a/solution/1600-1699/1667.Fix Names in a Table/Solution.sql b/solution/1600-1699/1667.Fix Names in a Table/Solution.sql index 644f22e061687..b4982d2f55c98 100644 --- a/solution/1600-1699/1667.Fix Names in a Table/Solution.sql +++ b/solution/1600-1699/1667.Fix Names in a Table/Solution.sql @@ -1,5 +1,5 @@ SELECT user_id, - CONCAT(UPPER(LEFT(name, 1)), LOWER(SUBSTRING(name, 2, DATALENGTH(name)))) AS name + CONCAT(UPPER(LEFT(name, 1)), LOWER(SUBSTRING(name, 2))) AS name FROM users ORDER BY user_id; diff --git a/solution/1600-1699/1667.Fix Names in a Table/Solution2.sql b/solution/1600-1699/1667.Fix Names in a Table/Solution2.sql new file mode 100644 index 0000000000000..644f22e061687 --- /dev/null +++ b/solution/1600-1699/1667.Fix Names in a Table/Solution2.sql @@ -0,0 +1,5 @@ +SELECT + user_id, + CONCAT(UPPER(LEFT(name, 1)), LOWER(SUBSTRING(name, 2, DATALENGTH(name)))) AS name +FROM users +ORDER BY user_id; diff --git a/solution/1600-1699/1668.Maximum Repeating Substring/Solution.c b/solution/1600-1699/1668.Maximum Repeating Substring/Solution.c index d6403a1f455ef..e0f36582237d4 100644 --- a/solution/1600-1699/1668.Maximum Repeating Substring/Solution.c +++ b/solution/1600-1699/1668.Maximum Repeating Substring/Solution.c @@ -18,4 +18,4 @@ int maxRepeating(char* sequence, char* word) { ans = max(ans, findWord(i, sequence, word)); } return ans; -} +} \ No newline at end of file diff --git a/solution/1600-1699/1668.Maximum Repeating Substring/Solution.cpp b/solution/1600-1699/1668.Maximum Repeating Substring/Solution.cpp index 8064dbe8c69ed..24997683327e7 100644 --- a/solution/1600-1699/1668.Maximum Repeating Substring/Solution.cpp +++ b/solution/1600-1699/1668.Maximum Repeating Substring/Solution.cpp @@ -5,6 +5,7 @@ class Solution { string t = word; int x = sequence.size() / word.size(); for (int k = 1; k <= x; ++k) { + // C++ 这里从小到大枚举重复值 if (sequence.find(t) != string::npos) { ans = k; } diff --git a/solution/1600-1699/1669.Merge In Between Linked Lists/Solution.cs b/solution/1600-1699/1669.Merge In Between Linked Lists/Solution.cs index 40a401d2e340e..c32a802e38b00 100644 --- a/solution/1600-1699/1669.Merge In Between Linked Lists/Solution.cs +++ b/solution/1600-1699/1669.Merge In Between Linked Lists/Solution.cs @@ -26,4 +26,4 @@ public ListNode MergeInBetween(ListNode list1, int a, int b, ListNode list2) { q.next = null; return list1; } -} \ No newline at end of file +} diff --git a/solution/1600-1699/1672.Richest Customer Wealth/Solution.c b/solution/1600-1699/1672.Richest Customer Wealth/Solution.c index 9058e28b60752..ecdf69f9e2fee 100644 --- a/solution/1600-1699/1672.Richest Customer Wealth/Solution.c +++ b/solution/1600-1699/1672.Richest Customer Wealth/Solution.c @@ -10,4 +10,4 @@ int maximumWealth(int** accounts, int accountsSize, int* accountsColSize) { ans = max(ans, sum); } return ans; -} +} \ No newline at end of file diff --git a/solution/1600-1699/1672.Richest Customer Wealth/Solution.kt b/solution/1600-1699/1672.Richest Customer Wealth/Solution.kt index 0134c062a135e..c35dd601aef52 100644 --- a/solution/1600-1699/1672.Richest Customer Wealth/Solution.kt +++ b/solution/1600-1699/1672.Richest Customer Wealth/Solution.kt @@ -8,5 +8,5 @@ class Solution { } } return max - } + } } diff --git a/solution/1600-1699/1672.Richest Customer Wealth/Solution.php b/solution/1600-1699/1672.Richest Customer Wealth/Solution.php index 76870e41b671f..57cbf96b1e152 100644 --- a/solution/1600-1699/1672.Richest Customer Wealth/Solution.php +++ b/solution/1600-1699/1672.Richest Customer Wealth/Solution.php @@ -16,4 +16,4 @@ function maximumWealth($accounts) { } return $rs; } -} \ No newline at end of file +} diff --git a/solution/1600-1699/1678.Goal Parser Interpretation/Solution.c b/solution/1600-1699/1678.Goal Parser Interpretation/Solution.c index 7393c7b9f54d4..31ce6460b9c9d 100644 --- a/solution/1600-1699/1678.Goal Parser Interpretation/Solution.c +++ b/solution/1600-1699/1678.Goal Parser Interpretation/Solution.c @@ -17,4 +17,4 @@ char* interpret(char* command) { } ans[i] = '\0'; return ans; -} +} \ No newline at end of file diff --git a/solution/1600-1699/1678.Goal Parser Interpretation/Solution.cpp b/solution/1600-1699/1678.Goal Parser Interpretation/Solution.cpp index 9ae40af196975..59fe7e7154752 100644 --- a/solution/1600-1699/1678.Goal Parser Interpretation/Solution.cpp +++ b/solution/1600-1699/1678.Goal Parser Interpretation/Solution.cpp @@ -1,14 +1,8 @@ class Solution { public: string interpret(string command) { - string ans; - for (int i = 0; i < command.size(); ++i) { - char c = command[i]; - if (c == 'G') - ans += c; - else if (c == '(') - ans += command[i + 1] == ')' ? "o" : "al"; - } - return ans; + while (command.find("()") != -1) command.replace(command.find("()"), 2, "o"); + while (command.find("(al)") != -1) command.replace(command.find("(al)"), 4, "al"); + return command; } }; \ No newline at end of file diff --git a/solution/1600-1699/1678.Goal Parser Interpretation/Solution.go b/solution/1600-1699/1678.Goal Parser Interpretation/Solution.go index 684356e64d87a..ea5e7a4d15b2e 100644 --- a/solution/1600-1699/1678.Goal Parser Interpretation/Solution.go +++ b/solution/1600-1699/1678.Goal Parser Interpretation/Solution.go @@ -1,15 +1,5 @@ func interpret(command string) string { - ans := &strings.Builder{} - for i, c := range command { - if c == 'G' { - ans.WriteRune(c) - } else if c == '(' { - if command[i+1] == ')' { - ans.WriteByte('o') - } else { - ans.WriteString("al") - } - } - } - return ans.String() + command = strings.ReplaceAll(command, "()", "o") + command = strings.ReplaceAll(command, "(al)", "al") + return command } \ No newline at end of file diff --git a/solution/1600-1699/1678.Goal Parser Interpretation/Solution.java b/solution/1600-1699/1678.Goal Parser Interpretation/Solution.java index df50da6958f16..af2d4dfe2477b 100644 --- a/solution/1600-1699/1678.Goal Parser Interpretation/Solution.java +++ b/solution/1600-1699/1678.Goal Parser Interpretation/Solution.java @@ -1,14 +1,5 @@ class Solution { public String interpret(String command) { - StringBuilder ans = new StringBuilder(); - for (int i = 0; i < command.length(); ++i) { - char c = command.charAt(i); - if (c == 'G') { - ans.append(c); - } else if (c == '(') { - ans.append(command.charAt(i + 1) == ')' ? "o" : "al"); - } - } - return ans.toString(); + return command.replace("()", "o").replace("(al)", "al"); } } \ No newline at end of file diff --git a/solution/1600-1699/1678.Goal Parser Interpretation/Solution.py b/solution/1600-1699/1678.Goal Parser Interpretation/Solution.py index 9f191903812f4..c92fc8c632085 100644 --- a/solution/1600-1699/1678.Goal Parser Interpretation/Solution.py +++ b/solution/1600-1699/1678.Goal Parser Interpretation/Solution.py @@ -1,9 +1,3 @@ class Solution: def interpret(self, command: str) -> str: - ans = [] - for i, c in enumerate(command): - if c == 'G': - ans.append(c) - elif c == '(': - ans.append('o' if command[i + 1] == ')' else 'al') - return ''.join(ans) + return command.replace('()', 'o').replace('(al)', 'al') diff --git a/solution/1600-1699/1678.Goal Parser Interpretation/Solution.rs b/solution/1600-1699/1678.Goal Parser Interpretation/Solution.rs index 73f8139f01e3b..5dd479bce3a1c 100644 --- a/solution/1600-1699/1678.Goal Parser Interpretation/Solution.rs +++ b/solution/1600-1699/1678.Goal Parser Interpretation/Solution.rs @@ -1,17 +1,5 @@ impl Solution { pub fn interpret(command: String) -> String { - let mut ans = String::new(); - let bs = command.as_bytes(); - for i in 0..bs.len() { - if bs[i] == b'G' { - ans.push_str("G"); - } - if bs[i] == b'(' { - ans.push_str({ - if bs[i + 1] == b')' { "o" } else { "al" } - }); - } - } - ans + command.replace("()", "o").replace("(al)", "al") } } diff --git a/solution/1600-1699/1678.Goal Parser Interpretation/Solution.ts b/solution/1600-1699/1678.Goal Parser Interpretation/Solution.ts index f5e18be18c1a6..a5dce7a077eb4 100644 --- a/solution/1600-1699/1678.Goal Parser Interpretation/Solution.ts +++ b/solution/1600-1699/1678.Goal Parser Interpretation/Solution.ts @@ -1,13 +1,3 @@ function interpret(command: string): string { - const n = command.length; - const ans: string[] = []; - for (let i = 0; i < n; i++) { - const c = command[i]; - if (c === 'G') { - ans.push(c); - } else if (c === '(') { - ans.push(command[i + 1] === ')' ? 'o' : 'al'); - } - } - return ans.join(''); + return command.replace(/\(\)/g, 'o').replace(/\(al\)/g, 'al'); } diff --git a/solution/1600-1699/1678.Goal Parser Interpretation/Solution2.cpp b/solution/1600-1699/1678.Goal Parser Interpretation/Solution2.cpp new file mode 100644 index 0000000000000..9ae40af196975 --- /dev/null +++ b/solution/1600-1699/1678.Goal Parser Interpretation/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + string interpret(string command) { + string ans; + for (int i = 0; i < command.size(); ++i) { + char c = command[i]; + if (c == 'G') + ans += c; + else if (c == '(') + ans += command[i + 1] == ')' ? "o" : "al"; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1678.Goal Parser Interpretation/Solution2.go b/solution/1600-1699/1678.Goal Parser Interpretation/Solution2.go new file mode 100644 index 0000000000000..684356e64d87a --- /dev/null +++ b/solution/1600-1699/1678.Goal Parser Interpretation/Solution2.go @@ -0,0 +1,15 @@ +func interpret(command string) string { + ans := &strings.Builder{} + for i, c := range command { + if c == 'G' { + ans.WriteRune(c) + } else if c == '(' { + if command[i+1] == ')' { + ans.WriteByte('o') + } else { + ans.WriteString("al") + } + } + } + return ans.String() +} \ No newline at end of file diff --git a/solution/1600-1699/1678.Goal Parser Interpretation/Solution2.java b/solution/1600-1699/1678.Goal Parser Interpretation/Solution2.java new file mode 100644 index 0000000000000..df50da6958f16 --- /dev/null +++ b/solution/1600-1699/1678.Goal Parser Interpretation/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public String interpret(String command) { + StringBuilder ans = new StringBuilder(); + for (int i = 0; i < command.length(); ++i) { + char c = command.charAt(i); + if (c == 'G') { + ans.append(c); + } else if (c == '(') { + ans.append(command.charAt(i + 1) == ')' ? "o" : "al"); + } + } + return ans.toString(); + } +} \ No newline at end of file diff --git a/solution/1600-1699/1678.Goal Parser Interpretation/Solution2.py b/solution/1600-1699/1678.Goal Parser Interpretation/Solution2.py new file mode 100644 index 0000000000000..9f191903812f4 --- /dev/null +++ b/solution/1600-1699/1678.Goal Parser Interpretation/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def interpret(self, command: str) -> str: + ans = [] + for i, c in enumerate(command): + if c == 'G': + ans.append(c) + elif c == '(': + ans.append('o' if command[i + 1] == ')' else 'al') + return ''.join(ans) diff --git a/solution/1600-1699/1678.Goal Parser Interpretation/Solution2.rs b/solution/1600-1699/1678.Goal Parser Interpretation/Solution2.rs new file mode 100644 index 0000000000000..73f8139f01e3b --- /dev/null +++ b/solution/1600-1699/1678.Goal Parser Interpretation/Solution2.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn interpret(command: String) -> String { + let mut ans = String::new(); + let bs = command.as_bytes(); + for i in 0..bs.len() { + if bs[i] == b'G' { + ans.push_str("G"); + } + if bs[i] == b'(' { + ans.push_str({ + if bs[i + 1] == b')' { "o" } else { "al" } + }); + } + } + ans + } +} diff --git a/solution/1600-1699/1678.Goal Parser Interpretation/Solution2.ts b/solution/1600-1699/1678.Goal Parser Interpretation/Solution2.ts new file mode 100644 index 0000000000000..f5e18be18c1a6 --- /dev/null +++ b/solution/1600-1699/1678.Goal Parser Interpretation/Solution2.ts @@ -0,0 +1,13 @@ +function interpret(command: string): string { + const n = command.length; + const ans: string[] = []; + for (let i = 0; i < n; i++) { + const c = command[i]; + if (c === 'G') { + ans.push(c); + } else if (c === '(') { + ans.push(command[i + 1] === ')' ? 'o' : 'al'); + } + } + return ans.join(''); +} diff --git a/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution.rs b/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution.rs index 2d9572bed95e2..21428c32bc21d 100644 --- a/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution.rs +++ b/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution.rs @@ -1,19 +1,21 @@ impl Solution { pub fn max_operations(nums: Vec, k: i32) -> i32 { - let mut cnt = std::collections::HashMap::new(); - let mut ans = 0; - for x in nums { - let m = k - x; - if let Some(v) = cnt.get_mut(&m) { - ans += 1; - *v -= 1; - if *v == 0 { - cnt.remove(&m); + let mut nums = nums.clone(); + nums.sort(); + let (mut l, mut r, mut ans) = (0, nums.len() - 1, 0); + while l < r { + match nums[l] + nums[r] { + sum if sum == k => { + ans += 1; + l += 1; + r -= 1; + } + sum if sum > k => { + r -= 1; + } + _ => { + l += 1; } - } else if let Some(v) = cnt.get_mut(&x) { - *v += 1; - } else { - cnt.insert(x, 1); } } ans diff --git a/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution2.cpp b/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution2.cpp new file mode 100644 index 0000000000000..b53d2ba93c6bc --- /dev/null +++ b/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int maxOperations(vector& nums, int k) { + unordered_map cnt; + int ans = 0; + for (int& x : nums) { + if (cnt[k - x]) { + --cnt[k - x]; + ++ans; + } else { + ++cnt[x]; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution2.go b/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution2.go new file mode 100644 index 0000000000000..3baf62120f74c --- /dev/null +++ b/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution2.go @@ -0,0 +1,12 @@ +func maxOperations(nums []int, k int) (ans int) { + cnt := map[int]int{} + for _, x := range nums { + if cnt[k-x] > 0 { + cnt[k-x]-- + ans++ + } else { + cnt[x]++ + } + } + return +} \ No newline at end of file diff --git a/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution2.java b/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution2.java new file mode 100644 index 0000000000000..bab40cc4672f6 --- /dev/null +++ b/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution2.java @@ -0,0 +1,17 @@ +class Solution { + public int maxOperations(int[] nums, int k) { + Map cnt = new HashMap<>(); + int ans = 0; + for (int x : nums) { + if (cnt.containsKey(k - x)) { + ++ans; + if (cnt.merge(k - x, -1, Integer::sum) == 0) { + cnt.remove(k - x); + } + } else { + cnt.merge(x, 1, Integer::sum); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution2.py b/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution2.py new file mode 100644 index 0000000000000..fec91c097a947 --- /dev/null +++ b/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def maxOperations(self, nums: List[int], k: int) -> int: + cnt = Counter() + ans = 0 + for x in nums: + if cnt[k - x]: + ans += 1 + cnt[k - x] -= 1 + else: + cnt[x] += 1 + return ans diff --git a/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution2.rs b/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution2.rs new file mode 100644 index 0000000000000..2d9572bed95e2 --- /dev/null +++ b/solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution2.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn max_operations(nums: Vec, k: i32) -> i32 { + let mut cnt = std::collections::HashMap::new(); + let mut ans = 0; + for x in nums { + let m = k - x; + if let Some(v) = cnt.get_mut(&m) { + ans += 1; + *v -= 1; + if *v == 0 { + cnt.remove(&m); + } + } else if let Some(v) = cnt.get_mut(&x) { + *v += 1; + } else { + cnt.insert(x, 1); + } + } + ans + } +} diff --git a/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/Solution.cpp b/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/Solution.cpp index 9fece96842f8d..80c681f50b979 100644 --- a/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/Solution.cpp +++ b/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/Solution.cpp @@ -3,12 +3,8 @@ class Solution { int concatenatedBinary(int n) { const int mod = 1e9 + 7; long ans = 0; - int shift = 0; for (int i = 1; i <= n; ++i) { - if ((i & (i - 1)) == 0) { - ++shift; - } - ans = (ans << shift | i) % mod; + ans = (ans << (32 - __builtin_clz(i)) | i) % mod; } return ans; } diff --git a/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/Solution.go b/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/Solution.go index dd3541b8da1fd..3bdb01238ee42 100644 --- a/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/Solution.go +++ b/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/Solution.go @@ -1,11 +1,7 @@ func concatenatedBinary(n int) (ans int) { const mod = 1e9 + 7 - shift := 0 for i := 1; i <= n; i++ { - if i&(i-1) == 0 { - shift++ - } - ans = (ans< int: mod = 10**9 + 7 - ans = shift = 0 + ans = 0 for i in range(1, n + 1): - if (i & (i - 1)) == 0: - shift += 1 - ans = (ans << shift | i) % mod + ans = (ans << i.bit_length() | i) % mod return ans diff --git a/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/Solution2.cpp b/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/Solution2.cpp new file mode 100644 index 0000000000000..9fece96842f8d --- /dev/null +++ b/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int concatenatedBinary(int n) { + const int mod = 1e9 + 7; + long ans = 0; + int shift = 0; + for (int i = 1; i <= n; ++i) { + if ((i & (i - 1)) == 0) { + ++shift; + } + ans = (ans << shift | i) % mod; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/Solution2.go b/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/Solution2.go new file mode 100644 index 0000000000000..dd3541b8da1fd --- /dev/null +++ b/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/Solution2.go @@ -0,0 +1,11 @@ +func concatenatedBinary(n int) (ans int) { + const mod = 1e9 + 7 + shift := 0 + for i := 1; i <= n; i++ { + if i&(i-1) == 0 { + shift++ + } + ans = (ans< int: + mod = 10**9 + 7 + ans = shift = 0 + for i in range(1, n + 1): + if (i & (i - 1)) == 0: + shift += 1 + ans = (ans << shift | i) % mod + return ans diff --git a/solution/1600-1699/1681.Minimum Incompatibility/Solution.cpp b/solution/1600-1699/1681.Minimum Incompatibility/Solution.cpp index e775ce8cafff0..53d54a55f1f9c 100644 --- a/solution/1600-1699/1681.Minimum Incompatibility/Solution.cpp +++ b/solution/1600-1699/1681.Minimum Incompatibility/Solution.cpp @@ -1,54 +1,54 @@ -class Solution { -public: - int minimumIncompatibility(vector& nums, int k) { - int n = nums.size(); - int m = n / k; - int g[1 << n]; - memset(g, -1, sizeof(g)); - for (int i = 1; i < 1 << n; ++i) { - if (__builtin_popcount(i) != m) { - continue; - } - unordered_set s; - int mi = 20, mx = 0; - for (int j = 0; j < n; ++j) { - if (i >> j & 1) { - if (s.count(nums[j])) { - break; - } - s.insert(nums[j]); - mi = min(mi, nums[j]); - mx = max(mx, nums[j]); - } - } - if (s.size() == m) { - g[i] = mx - mi; - } - } - int f[1 << n]; - memset(f, 0x3f, sizeof(f)); - f[0] = 0; - for (int i = 0; i < 1 << n; ++i) { - if (f[i] == 0x3f3f3f3f) { - continue; - } - unordered_set s; - int mask = 0; - for (int j = 0; j < n; ++j) { - if ((i >> j & 1) == 0 && !s.count(nums[j])) { - s.insert(nums[j]); - mask |= 1 << j; - } - } - if (s.size() < m) { - continue; - } - for (int j = mask; j; j = (j - 1) & mask) { - if (g[j] != -1) { - f[i | j] = min(f[i | j], f[i] + g[j]); - } - } - } - return f[(1 << n) - 1] == 0x3f3f3f3f ? -1 : f[(1 << n) - 1]; - } +class Solution { +public: + int minimumIncompatibility(vector& nums, int k) { + int n = nums.size(); + int m = n / k; + int g[1 << n]; + memset(g, -1, sizeof(g)); + for (int i = 1; i < 1 << n; ++i) { + if (__builtin_popcount(i) != m) { + continue; + } + unordered_set s; + int mi = 20, mx = 0; + for (int j = 0; j < n; ++j) { + if (i >> j & 1) { + if (s.count(nums[j])) { + break; + } + s.insert(nums[j]); + mi = min(mi, nums[j]); + mx = max(mx, nums[j]); + } + } + if (s.size() == m) { + g[i] = mx - mi; + } + } + int f[1 << n]; + memset(f, 0x3f, sizeof(f)); + f[0] = 0; + for (int i = 0; i < 1 << n; ++i) { + if (f[i] == 0x3f3f3f3f) { + continue; + } + unordered_set s; + int mask = 0; + for (int j = 0; j < n; ++j) { + if ((i >> j & 1) == 0 && !s.count(nums[j])) { + s.insert(nums[j]); + mask |= 1 << j; + } + } + if (s.size() < m) { + continue; + } + for (int j = mask; j; j = (j - 1) & mask) { + if (g[j] != -1) { + f[i | j] = min(f[i | j], f[i] + g[j]); + } + } + } + return f[(1 << n) - 1] == 0x3f3f3f3f ? -1 : f[(1 << n) - 1]; + } }; \ No newline at end of file diff --git a/solution/1600-1699/1681.Minimum Incompatibility/Solution.cs b/solution/1600-1699/1681.Minimum Incompatibility/Solution.cs index 756fc401780f6..b9016c9c1b183 100644 --- a/solution/1600-1699/1681.Minimum Incompatibility/Solution.cs +++ b/solution/1600-1699/1681.Minimum Incompatibility/Solution.cs @@ -1,63 +1,63 @@ -public class Solution { - public int MinimumIncompatibility(int[] nums, int k) { - int n = nums.Length; - int m = n / k; - int[] g = new int[1 << n]; - Array.Fill(g, -1); - for (int i = 1; i < 1 << n; ++i) { - if (bitCount(i) != m) { - continue; - } - HashSet s = new(); - int mi = 20, mx = 0; - for (int j = 0; j < n; ++j) { - if ((i >> j & 1) == 1) { - if (s.Contains(nums[j])) { - break; - } - s.Add(nums[j]); - mi = Math.Min(mi, nums[j]); - mx = Math.Max(mx, nums[j]); - } - } - if (s.Count == m) { - g[i] = mx - mi; - } - } - int[] f = new int[1 << n]; - int inf = 1 << 30; - Array.Fill(f, inf); - f[0] = 0; - for (int i = 0; i < 1 << n; ++i) { - if (f[i] == inf) { - continue; - } - HashSet s = new(); - int mask = 0; - for (int j = 0; j < n; ++j) { - if ((i >> j & 1) == 0 && !s.Contains(nums[j])) { - s.Add(nums[j]); - mask |= 1 << j; - } - } - if (s.Count < m) { - continue; - } - for (int j = mask; j > 0; j = (j - 1) & mask) { - if (g[j] != -1) { - f[i | j] = Math.Min(f[i | j], f[i] + g[j]); - } - } - } - return f[(1 << n) - 1] == inf ? -1 : f[(1 << n) - 1]; - } - - private int bitCount(int x) { - int cnt = 0; - while (x > 0) { - x &= x - 1; - ++cnt; - } - return cnt; - } -} \ No newline at end of file +public class Solution { + public int MinimumIncompatibility(int[] nums, int k) { + int n = nums.Length; + int m = n / k; + int[] g = new int[1 << n]; + Array.Fill(g, -1); + for (int i = 1; i < 1 << n; ++i) { + if (bitCount(i) != m) { + continue; + } + HashSet s = new(); + int mi = 20, mx = 0; + for (int j = 0; j < n; ++j) { + if ((i >> j & 1) == 1) { + if (s.Contains(nums[j])) { + break; + } + s.Add(nums[j]); + mi = Math.Min(mi, nums[j]); + mx = Math.Max(mx, nums[j]); + } + } + if (s.Count == m) { + g[i] = mx - mi; + } + } + int[] f = new int[1 << n]; + int inf = 1 << 30; + Array.Fill(f, inf); + f[0] = 0; + for (int i = 0; i < 1 << n; ++i) { + if (f[i] == inf) { + continue; + } + HashSet s = new(); + int mask = 0; + for (int j = 0; j < n; ++j) { + if ((i >> j & 1) == 0 && !s.Contains(nums[j])) { + s.Add(nums[j]); + mask |= 1 << j; + } + } + if (s.Count < m) { + continue; + } + for (int j = mask; j > 0; j = (j - 1) & mask) { + if (g[j] != -1) { + f[i | j] = Math.Min(f[i | j], f[i] + g[j]); + } + } + } + return f[(1 << n) - 1] == inf ? -1 : f[(1 << n) - 1]; + } + + private int bitCount(int x) { + int cnt = 0; + while (x > 0) { + x &= x - 1; + ++cnt; + } + return cnt; + } +} diff --git a/solution/1600-1699/1681.Minimum Incompatibility/Solution.java b/solution/1600-1699/1681.Minimum Incompatibility/Solution.java index 4fdc6e31d1f82..1b45807718b43 100644 --- a/solution/1600-1699/1681.Minimum Incompatibility/Solution.java +++ b/solution/1600-1699/1681.Minimum Incompatibility/Solution.java @@ -1,53 +1,53 @@ -class Solution { - public int minimumIncompatibility(int[] nums, int k) { - int n = nums.length; - int m = n / k; - int[] g = new int[1 << n]; - Arrays.fill(g, -1); - for (int i = 1; i < 1 << n; ++i) { - if (Integer.bitCount(i) != m) { - continue; - } - Set s = new HashSet<>(); - int mi = 20, mx = 0; - for (int j = 0; j < n; ++j) { - if ((i >> j & 1) == 1) { - if (!s.add(nums[j])) { - break; - } - mi = Math.min(mi, nums[j]); - mx = Math.max(mx, nums[j]); - } - } - if (s.size() == m) { - g[i] = mx - mi; - } - } - int[] f = new int[1 << n]; - final int inf = 1 << 30; - Arrays.fill(f, inf); - f[0] = 0; - for (int i = 0; i < 1 << n; ++i) { - if (f[i] == inf) { - continue; - } - Set s = new HashSet<>(); - int mask = 0; - for (int j = 0; j < n; ++j) { - if ((i >> j & 1) == 0 && !s.contains(nums[j])) { - s.add(nums[j]); - mask |= 1 << j; - } - } - if (s.size() < m) { - continue; - } - for (int j = mask; j > 0; j = (j - 1) & mask) { - if (g[j] != -1) { - f[i | j] = Math.min(f[i | j], f[i] + g[j]); - } - } - } - return f[(1 << n) - 1] == inf ? -1 : f[(1 << n) - 1]; - } +class Solution { + public int minimumIncompatibility(int[] nums, int k) { + int n = nums.length; + int m = n / k; + int[] g = new int[1 << n]; + Arrays.fill(g, -1); + for (int i = 1; i < 1 << n; ++i) { + if (Integer.bitCount(i) != m) { + continue; + } + Set s = new HashSet<>(); + int mi = 20, mx = 0; + for (int j = 0; j < n; ++j) { + if ((i >> j & 1) == 1) { + if (!s.add(nums[j])) { + break; + } + mi = Math.min(mi, nums[j]); + mx = Math.max(mx, nums[j]); + } + } + if (s.size() == m) { + g[i] = mx - mi; + } + } + int[] f = new int[1 << n]; + final int inf = 1 << 30; + Arrays.fill(f, inf); + f[0] = 0; + for (int i = 0; i < 1 << n; ++i) { + if (f[i] == inf) { + continue; + } + Set s = new HashSet<>(); + int mask = 0; + for (int j = 0; j < n; ++j) { + if ((i >> j & 1) == 0 && !s.contains(nums[j])) { + s.add(nums[j]); + mask |= 1 << j; + } + } + if (s.size() < m) { + continue; + } + for (int j = mask; j > 0; j = (j - 1) & mask) { + if (g[j] != -1) { + f[i | j] = Math.min(f[i | j], f[i] + g[j]); + } + } + } + return f[(1 << n) - 1] == inf ? -1 : f[(1 << n) - 1]; + } } \ No newline at end of file diff --git a/solution/1600-1699/1681.Minimum Incompatibility/Solution.py b/solution/1600-1699/1681.Minimum Incompatibility/Solution.py index bafaa2b600db0..2a17ee5d32ca1 100644 --- a/solution/1600-1699/1681.Minimum Incompatibility/Solution.py +++ b/solution/1600-1699/1681.Minimum Incompatibility/Solution.py @@ -1,38 +1,38 @@ -class Solution: - def minimumIncompatibility(self, nums: List[int], k: int) -> int: - n = len(nums) - m = n // k - g = [-1] * (1 << n) - for i in range(1, 1 << n): - if i.bit_count() != m: - continue - s = set() - mi, mx = 20, 0 - for j, x in enumerate(nums): - if i >> j & 1: - if x in s: - break - s.add(x) - mi = min(mi, x) - mx = max(mx, x) - if len(s) == m: - g[i] = mx - mi - f = [inf] * (1 << n) - f[0] = 0 - for i in range(1 << n): - if f[i] == inf: - continue - s = set() - mask = 0 - for j, x in enumerate(nums): - if (i >> j & 1) == 0 and x not in s: - s.add(x) - mask |= 1 << j - if len(s) < m: - continue - j = mask - while j: - if g[j] != -1: - f[i | j] = min(f[i | j], f[i] + g[j]) - j = (j - 1) & mask - return f[-1] if f[-1] != inf else -1 +class Solution: + def minimumIncompatibility(self, nums: List[int], k: int) -> int: + n = len(nums) + m = n // k + g = [-1] * (1 << n) + for i in range(1, 1 << n): + if i.bit_count() != m: + continue + s = set() + mi, mx = 20, 0 + for j, x in enumerate(nums): + if i >> j & 1: + if x in s: + break + s.add(x) + mi = min(mi, x) + mx = max(mx, x) + if len(s) == m: + g[i] = mx - mi + f = [inf] * (1 << n) + f[0] = 0 + for i in range(1 << n): + if f[i] == inf: + continue + s = set() + mask = 0 + for j, x in enumerate(nums): + if (i >> j & 1) == 0 and x not in s: + s.add(x) + mask |= 1 << j + if len(s) < m: + continue + j = mask + while j: + if g[j] != -1: + f[i | j] = min(f[i | j], f[i] + g[j]) + j = (j - 1) & mask + return f[-1] if f[-1] != inf else -1 diff --git a/solution/1600-1699/1681.Minimum Incompatibility/Solution2.py b/solution/1600-1699/1681.Minimum Incompatibility/Solution2.py new file mode 100644 index 0000000000000..40fe763df8dd3 --- /dev/null +++ b/solution/1600-1699/1681.Minimum Incompatibility/Solution2.py @@ -0,0 +1,22 @@ +class Solution: + def minimumIncompatibility(self, nums: List[int], k: int) -> int: + @cache + def dfs(mask): + if mask == (1 << n) - 1: + return 0 + d = {v: i for i, v in enumerate(nums) if (mask >> i & 1) == 0} + ans = inf + if len(d) < m: + return ans + for vs in combinations(d.keys(), m): + nxt = mask + for v in vs: + nxt |= 1 << d[v] + ans = min(ans, max(vs) - min(vs) + dfs(nxt)) + return ans + + n = len(nums) + m = n // k + ans = dfs(0) + dfs.cache_clear() + return ans if ans < inf else -1 diff --git a/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution.c b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution.c index cb3457e324089..7a5bd9654833f 100644 --- a/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution.c +++ b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution.c @@ -1,19 +1,18 @@ -int helper(char* s) { - int res = 0; - int n = strlen(s); +int countConsistentStrings(char* allowed, char** words, int wordsSize) { + int n = strlen(allowed); + int make[26] = {0}; for (int i = 0; i < n; i++) { - res |= 1 << (s[i] - 'a'); + make[allowed[i] - 'a'] = 1; } - return res; -} - -int countConsistentStrings(char* allowed, char** words, int wordsSize) { - int mask = helper(allowed); - int ans = 0; + int ans = wordsSize; for (int i = 0; i < wordsSize; i++) { - if ((mask | helper(words[i])) == mask) { - ans++; + char* word = words[i]; + for (int j = 0; j < strlen(word); j++) { + if (!make[word[j] - 'a']) { + ans--; + break; + } } } return ans; -} +} \ No newline at end of file diff --git a/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution.rs b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution.rs index 0158dff409bd1..60f01f6fb08f9 100644 --- a/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution.rs +++ b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution.rs @@ -1,18 +1,17 @@ impl Solution { - fn helper(s: &String) -> i32 { - let mut res = 0; - for c in s.as_bytes().iter() { - res |= 1 << ((c - b'a') as i32); - } - res - } - pub fn count_consistent_strings(allowed: String, words: Vec) -> i32 { - let mask = Self::helper(&allowed); - let mut ans = 0; + let n = words.len(); + let mut make = [false; 26]; + for c in allowed.as_bytes() { + make[(c - b'a') as usize] = true; + } + let mut ans = n as i32; for word in words.iter() { - if (mask | Self::helper(word)) == mask { - ans += 1; + for c in word.as_bytes().iter() { + if !make[(c - b'a') as usize] { + ans -= 1; + break; + } } } ans diff --git a/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution.ts b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution.ts index f16f64d83768b..df3aab0421dd0 100644 --- a/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution.ts +++ b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution.ts @@ -1,16 +1,13 @@ function countConsistentStrings(allowed: string, words: string[]): number { - const helper = (s: string) => { - let res = 0; - for (const c of s) { - res |= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0)); - } - return res; - }; - const mask = helper(allowed); - let ans = 0; + const set = new Set([...allowed]); + const n = words.length; + let ans = n; for (const word of words) { - if ((mask | helper(word)) === mask) { - ans++; + for (const c of word) { + if (!set.has(c)) { + ans--; + break; + } } } return ans; diff --git a/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.c b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.c new file mode 100644 index 0000000000000..8feadeb58f8b0 --- /dev/null +++ b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.c @@ -0,0 +1,19 @@ +int helper(char* s) { + int res = 0; + int n = strlen(s); + for (int i = 0; i < n; i++) { + res |= 1 << (s[i] - 'a'); + } + return res; +} + +int countConsistentStrings(char* allowed, char** words, int wordsSize) { + int mask = helper(allowed); + int ans = 0; + for (int i = 0; i < wordsSize; i++) { + if ((mask | helper(words[i])) == mask) { + ans++; + } + } + return ans; +} \ No newline at end of file diff --git a/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.cpp b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.cpp new file mode 100644 index 0000000000000..50758e7797b22 --- /dev/null +++ b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int countConsistentStrings(string allowed, vector& words) { + auto f = [](string& w) { + int mask = 0; + for (auto& c : w) mask |= 1 << (c - 'a'); + return mask; + }; + int mask = f(allowed); + int ans = 0; + for (auto& w : words) ans += (mask | f(w)) == mask; + return ans; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.go b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.go new file mode 100644 index 0000000000000..4e5105cec99c1 --- /dev/null +++ b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.go @@ -0,0 +1,16 @@ +func countConsistentStrings(allowed string, words []string) (ans int) { + f := func(w string) (mask int) { + for _, c := range w { + mask |= 1 << (c - 'a') + } + return + } + + mask := f(allowed) + for _, w := range words { + if (mask | f(w)) == mask { + ans++ + } + } + return +} \ No newline at end of file diff --git a/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.java b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.java new file mode 100644 index 0000000000000..b3b3dc8b7038e --- /dev/null +++ b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.java @@ -0,0 +1,20 @@ +class Solution { + public int countConsistentStrings(String allowed, String[] words) { + int mask = f(allowed); + int ans = 0; + for (String w : words) { + if ((mask | f(w)) == mask) { + ++ans; + } + } + return ans; + } + + private int f(String w) { + int mask = 0; + for (int i = 0; i < w.length(); ++i) { + mask |= 1 << (w.charAt(i) - 'a'); + } + return mask; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.py b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.py new file mode 100644 index 0000000000000..2b5c1db6e66b6 --- /dev/null +++ b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def countConsistentStrings(self, allowed: str, words: List[str]) -> int: + def f(w): + return reduce(or_, (1 << (ord(c) - ord('a')) for c in w)) + + mask = f(allowed) + return sum((mask | f(w)) == mask for w in words) diff --git a/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.rs b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.rs new file mode 100644 index 0000000000000..0158dff409bd1 --- /dev/null +++ b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.rs @@ -0,0 +1,20 @@ +impl Solution { + fn helper(s: &String) -> i32 { + let mut res = 0; + for c in s.as_bytes().iter() { + res |= 1 << ((c - b'a') as i32); + } + res + } + + pub fn count_consistent_strings(allowed: String, words: Vec) -> i32 { + let mask = Self::helper(&allowed); + let mut ans = 0; + for word in words.iter() { + if (mask | Self::helper(word)) == mask { + ans += 1; + } + } + ans + } +} diff --git a/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.ts b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.ts new file mode 100644 index 0000000000000..f16f64d83768b --- /dev/null +++ b/solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.ts @@ -0,0 +1,17 @@ +function countConsistentStrings(allowed: string, words: string[]): number { + const helper = (s: string) => { + let res = 0; + for (const c of s) { + res |= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0)); + } + return res; + }; + const mask = helper(allowed); + let ans = 0; + for (const word of words) { + if ((mask | helper(word)) === mask) { + ans++; + } + } + return ans; +} diff --git a/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/Solution.cs b/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/Solution.cs index ee1d753329a5e..2aece386cc1e0 100644 --- a/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/Solution.cs +++ b/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/Solution.cs @@ -13,4 +13,4 @@ public int[] GetSumAbsoluteDifferences(int[] nums) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/Solution.c b/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/Solution.c index c801ed63dc8d0..7baebb73e5038 100644 --- a/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/Solution.c +++ b/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/Solution.c @@ -7,4 +7,4 @@ int minPartitions(char* n) { } } return ans; -} +} \ No newline at end of file diff --git a/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/Solution.cpp b/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/Solution.cpp index 05370a575898f..73c0c4104adf6 100644 --- a/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/Solution.cpp +++ b/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/Solution.cpp @@ -1,18 +1,18 @@ -class Solution { -public: - int maxHeight(vector>& cuboids) { - for (auto& c : cuboids) sort(c.begin(), c.end()); - sort(cuboids.begin(), cuboids.end()); - int n = cuboids.size(); - vector f(n); - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (cuboids[j][1] <= cuboids[i][1] && cuboids[j][2] <= cuboids[i][2]) { - f[i] = max(f[i], f[j]); - } - } - f[i] += cuboids[i][2]; - } - return *max_element(f.begin(), f.end()); - } +class Solution { +public: + int maxHeight(vector>& cuboids) { + for (auto& c : cuboids) sort(c.begin(), c.end()); + sort(cuboids.begin(), cuboids.end()); + int n = cuboids.size(); + vector f(n); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (cuboids[j][1] <= cuboids[i][1] && cuboids[j][2] <= cuboids[i][2]) { + f[i] = max(f[i], f[j]); + } + } + f[i] += cuboids[i][2]; + } + return *max_element(f.begin(), f.end()); + } }; \ No newline at end of file diff --git a/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/Solution.java b/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/Solution.java index 8f56129c5be43..08010a5e3c61f 100644 --- a/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/Solution.java +++ b/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/Solution.java @@ -1,20 +1,20 @@ -class Solution { - public int maxHeight(int[][] cuboids) { - for (var c : cuboids) { - Arrays.sort(c); - } - Arrays.sort(cuboids, - (a, b) -> a[0] == b[0] ? (a[1] == b[1] ? a[2] - b[2] : a[1] - b[1]) : a[0] - b[0]); - int n = cuboids.length; - int[] f = new int[n]; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (cuboids[j][1] <= cuboids[i][1] && cuboids[j][2] <= cuboids[i][2]) { - f[i] = Math.max(f[i], f[j]); - } - } - f[i] += cuboids[i][2]; - } - return Arrays.stream(f).max().getAsInt(); - } +class Solution { + public int maxHeight(int[][] cuboids) { + for (var c : cuboids) { + Arrays.sort(c); + } + Arrays.sort(cuboids, + (a, b) -> a[0] == b[0] ? (a[1] == b[1] ? a[2] - b[2] : a[1] - b[1]) : a[0] - b[0]); + int n = cuboids.length; + int[] f = new int[n]; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (cuboids[j][1] <= cuboids[i][1] && cuboids[j][2] <= cuboids[i][2]) { + f[i] = Math.max(f[i], f[j]); + } + } + f[i] += cuboids[i][2]; + } + return Arrays.stream(f).max().getAsInt(); + } } \ No newline at end of file diff --git a/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/Solution.py b/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/Solution.py index ad243efcf1bed..06c0a610272dd 100644 --- a/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/Solution.py +++ b/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def maxHeight(self, cuboids: List[List[int]]) -> int: - for c in cuboids: - c.sort() - cuboids.sort() - n = len(cuboids) - f = [0] * n - for i in range(n): - for j in range(i): - if cuboids[j][1] <= cuboids[i][1] and cuboids[j][2] <= cuboids[i][2]: - f[i] = max(f[i], f[j]) - f[i] += cuboids[i][2] - return max(f) +class Solution: + def maxHeight(self, cuboids: List[List[int]]) -> int: + for c in cuboids: + c.sort() + cuboids.sort() + n = len(cuboids) + f = [0] * n + for i in range(n): + for j in range(i): + if cuboids[j][1] <= cuboids[i][1] and cuboids[j][2] <= cuboids[i][2]: + f[i] = max(f[i], f[j]) + f[i] += cuboids[i][2] + return max(f) diff --git a/solution/1600-1699/1698.Number of Distinct Substrings in a String/Solution2.cpp b/solution/1600-1699/1698.Number of Distinct Substrings in a String/Solution2.cpp new file mode 100644 index 0000000000000..6a028845d45cb --- /dev/null +++ b/solution/1600-1699/1698.Number of Distinct Substrings in a String/Solution2.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int countDistinct(string s) { + using ull = unsigned long long; + int n = s.size(); + ull p[n + 10]; + ull h[n + 10]; + int base = 131; + p[0] = 1; + for (int i = 0; i < n; ++i) { + p[i + 1] = p[i] * base; + h[i + 1] = h[i] * base + s[i]; + } + unordered_set ss; + for (int i = 1; i <= n; ++i) { + for (int j = i; j <= n; ++j) { + ss.insert(h[j] - h[i - 1] * p[j - i + 1]); + } + } + return ss.size(); + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1698.Number of Distinct Substrings in a String/Solution2.go b/solution/1600-1699/1698.Number of Distinct Substrings in a String/Solution2.go new file mode 100644 index 0000000000000..9054ca84af5d9 --- /dev/null +++ b/solution/1600-1699/1698.Number of Distinct Substrings in a String/Solution2.go @@ -0,0 +1,18 @@ +func countDistinct(s string) int { + n := len(s) + p := make([]int, n+10) + h := make([]int, n+10) + p[0] = 1 + base := 131 + for i, c := range s { + p[i+1] = p[i] * base + h[i+1] = h[i]*base + int(c) + } + ss := map[int]struct{}{} + for i := 1; i <= n; i++ { + for j := i; j <= n; j++ { + ss[h[j]-h[i-1]*p[j-i+1]] = struct{}{} + } + } + return len(ss) +} \ No newline at end of file diff --git a/solution/1600-1699/1698.Number of Distinct Substrings in a String/Solution2.java b/solution/1600-1699/1698.Number of Distinct Substrings in a String/Solution2.java new file mode 100644 index 0000000000000..743a0a0e4f997 --- /dev/null +++ b/solution/1600-1699/1698.Number of Distinct Substrings in a String/Solution2.java @@ -0,0 +1,21 @@ +class Solution { + public int countDistinct(String s) { + int base = 131; + int n = s.length(); + long[] p = new long[n + 10]; + long[] h = new long[n + 10]; + p[0] = 1; + for (int i = 0; i < n; ++i) { + p[i + 1] = p[i] * base; + h[i + 1] = h[i] * base + s.charAt(i); + } + Set ss = new HashSet<>(); + for (int i = 1; i <= n; ++i) { + for (int j = i; j <= n; ++j) { + long t = h[j] - h[i - 1] * p[j - i + 1]; + ss.add(t); + } + } + return ss.size(); + } +} \ No newline at end of file diff --git a/solution/1600-1699/1698.Number of Distinct Substrings in a String/Solution2.py b/solution/1600-1699/1698.Number of Distinct Substrings in a String/Solution2.py new file mode 100644 index 0000000000000..d2c6a0c36b3f6 --- /dev/null +++ b/solution/1600-1699/1698.Number of Distinct Substrings in a String/Solution2.py @@ -0,0 +1,16 @@ +class Solution: + def countDistinct(self, s: str) -> int: + base = 131 + n = len(s) + p = [0] * (n + 10) + h = [0] * (n + 10) + p[0] = 1 + for i, c in enumerate(s): + p[i + 1] = p[i] * base + h[i + 1] = h[i] * base + ord(c) + ss = set() + for i in range(1, n + 1): + for j in range(i, n + 1): + t = h[j] - h[i - 1] * p[j - i + 1] + ss.add(t) + return len(ss) diff --git a/solution/1600-1699/1699.Number of Calls Between Two Persons/Solution.sql b/solution/1600-1699/1699.Number of Calls Between Two Persons/Solution.sql index e70c4702e8660..03a0a95f93db9 100644 --- a/solution/1600-1699/1699.Number of Calls Between Two Persons/Solution.sql +++ b/solution/1600-1699/1699.Number of Calls Between Two Persons/Solution.sql @@ -1,7 +1,7 @@ # Write your MySQL query statement below SELECT - LEAST(from_id, to_id) AS person1, - GREATEST(from_id, to_id) AS person2, + IF(from_id < to_id, from_id, to_id) AS person1, + IF(from_id < to_id, to_id, from_id) AS person2, COUNT(1) AS call_count, SUM(duration) AS total_duration FROM Calls diff --git a/solution/1600-1699/1699.Number of Calls Between Two Persons/Solution2.sql b/solution/1600-1699/1699.Number of Calls Between Two Persons/Solution2.sql new file mode 100644 index 0000000000000..e70c4702e8660 --- /dev/null +++ b/solution/1600-1699/1699.Number of Calls Between Two Persons/Solution2.sql @@ -0,0 +1,8 @@ +# Write your MySQL query statement below +SELECT + LEAST(from_id, to_id) AS person1, + GREATEST(from_id, to_id) AS person2, + COUNT(1) AS call_count, + SUM(duration) AS total_duration +FROM Calls +GROUP BY 1, 2; diff --git a/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/Solution.c b/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/Solution.c index e9c2e07738944..b6a94c831613a 100644 --- a/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/Solution.c +++ b/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/Solution.c @@ -11,4 +11,4 @@ int countStudents(int* students, int studentsSize, int* sandwiches, int sandwich count[j]--; } return 0; -} +} \ No newline at end of file diff --git a/solution/1700-1799/1704.Determine if String Halves Are Alike/Solution.php b/solution/1700-1799/1704.Determine if String Halves Are Alike/Solution.php index bf437c2b3ea0a..7669dc689bf48 100644 --- a/solution/1700-1799/1704.Determine if String Halves Are Alike/Solution.php +++ b/solution/1700-1799/1704.Determine if String Halves Are Alike/Solution.php @@ -15,4 +15,4 @@ function halvesAreAlike($s) { } return $cnt == 0; } -} \ No newline at end of file +} diff --git a/solution/1700-1799/1704.Determine if String Halves Are Alike/Solution2.py b/solution/1700-1799/1704.Determine if String Halves Are Alike/Solution2.py new file mode 100644 index 0000000000000..f4f6f6fb556e6 --- /dev/null +++ b/solution/1700-1799/1704.Determine if String Halves Are Alike/Solution2.py @@ -0,0 +1,5 @@ +class Solution: + def halvesAreAlike(self, s: str) -> bool: + vowels = set('aeiouAEIOU') + a, b = s[: len(s) >> 1], s[len(s) >> 1 :] + return sum(c in vowels for c in a) == sum(c in vowels for c in b) diff --git a/solution/1700-1799/1706.Where Will the Ball Fall/Solution.cpp b/solution/1700-1799/1706.Where Will the Ball Fall/Solution.cpp index b633b3b3b1208..c72e6443931db 100644 --- a/solution/1700-1799/1706.Where Will the Ball Fall/Solution.cpp +++ b/solution/1700-1799/1706.Where Will the Ball Fall/Solution.cpp @@ -1,29 +1,29 @@ -class Solution { -public: - vector findBall(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - vector ans(n); - function dfs = [&](int i, int j) { - if (i == m) { - return j; - } - if (j == 0 && grid[i][j] == -1) { - return -1; - } - if (j == n - 1 && grid[i][j] == 1) { - return -1; - } - if (grid[i][j] == 1 && grid[i][j + 1] == -1) { - return -1; - } - if (grid[i][j] == -1 && grid[i][j - 1] == 1) { - return -1; - } - return grid[i][j] == 1 ? dfs(i + 1, j + 1) : dfs(i + 1, j - 1); - }; - for (int j = 0; j < n; ++j) { - ans[j] = dfs(0, j); - } - return ans; - } +class Solution { +public: + vector findBall(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + vector ans(n); + function dfs = [&](int i, int j) { + if (i == m) { + return j; + } + if (j == 0 && grid[i][j] == -1) { + return -1; + } + if (j == n - 1 && grid[i][j] == 1) { + return -1; + } + if (grid[i][j] == 1 && grid[i][j + 1] == -1) { + return -1; + } + if (grid[i][j] == -1 && grid[i][j - 1] == 1) { + return -1; + } + return grid[i][j] == 1 ? dfs(i + 1, j + 1) : dfs(i + 1, j - 1); + }; + for (int j = 0; j < n; ++j) { + ans[j] = dfs(0, j); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1700-1799/1706.Where Will the Ball Fall/Solution.py b/solution/1700-1799/1706.Where Will the Ball Fall/Solution.py index e4ec502d1364e..607ab510a1e0b 100644 --- a/solution/1700-1799/1706.Where Will the Ball Fall/Solution.py +++ b/solution/1700-1799/1706.Where Will the Ball Fall/Solution.py @@ -1,17 +1,17 @@ -class Solution: - def findBall(self, grid: List[List[int]]) -> List[int]: - def dfs(i: int, j: int) -> int: - if i == m: - return j - if j == 0 and grid[i][j] == -1: - return -1 - if j == n - 1 and grid[i][j] == 1: - return -1 - if grid[i][j] == 1 and grid[i][j + 1] == -1: - return -1 - if grid[i][j] == -1 and grid[i][j - 1] == 1: - return -1 - return dfs(i + 1, j + 1) if grid[i][j] == 1 else dfs(i + 1, j - 1) - - m, n = len(grid), len(grid[0]) - return [dfs(0, j) for j in range(n)] +class Solution: + def findBall(self, grid: List[List[int]]) -> List[int]: + def dfs(i: int, j: int) -> int: + if i == m: + return j + if j == 0 and grid[i][j] == -1: + return -1 + if j == n - 1 and grid[i][j] == 1: + return -1 + if grid[i][j] == 1 and grid[i][j + 1] == -1: + return -1 + if grid[i][j] == -1 and grid[i][j - 1] == 1: + return -1 + return dfs(i + 1, j + 1) if grid[i][j] == 1 else dfs(i + 1, j - 1) + + m, n = len(grid), len(grid[0]) + return [dfs(0, j) for j in range(n)] diff --git a/solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.cpp b/solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.cpp index b6402041d1aec..dd0637c1bdfdb 100644 --- a/solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.cpp +++ b/solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.cpp @@ -1,58 +1,58 @@ -class Trie { -private: - Trie* children[2]; - -public: - Trie() - : children{nullptr, nullptr} {} - - void insert(int x) { - Trie* node = this; - for (int i = 30; ~i; --i) { - int v = (x >> i) & 1; - if (!node->children[v]) { - node->children[v] = new Trie(); - } - node = node->children[v]; - } - } - - int search(int x) { - Trie* node = this; - int ans = 0; - for (int i = 30; ~i; --i) { - int v = (x >> i) & 1; - if (node->children[v ^ 1]) { - ans |= 1 << i; - node = node->children[v ^ 1]; - } else if (node->children[v]) { - node = node->children[v]; - } else { - return -1; - } - } - return ans; - } -}; - -class Solution { -public: - vector maximizeXor(vector& nums, vector>& queries) { - sort(nums.begin(), nums.end()); - int n = queries.size(); - vector idx(n); - iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) { return queries[i][1] < queries[j][1]; }); - vector ans(n); - Trie trie; - int j = 0; - for (int i : idx) { - int x = queries[i][0], m = queries[i][1]; - while (j < nums.size() && nums[j] <= m) { - trie.insert(nums[j++]); - } - ans[i] = trie.search(x); - } - return ans; - } +class Trie { +private: + Trie* children[2]; + +public: + Trie() + : children{nullptr, nullptr} {} + + void insert(int x) { + Trie* node = this; + for (int i = 30; ~i; --i) { + int v = (x >> i) & 1; + if (!node->children[v]) { + node->children[v] = new Trie(); + } + node = node->children[v]; + } + } + + int search(int x) { + Trie* node = this; + int ans = 0; + for (int i = 30; ~i; --i) { + int v = (x >> i) & 1; + if (node->children[v ^ 1]) { + ans |= 1 << i; + node = node->children[v ^ 1]; + } else if (node->children[v]) { + node = node->children[v]; + } else { + return -1; + } + } + return ans; + } +}; + +class Solution { +public: + vector maximizeXor(vector& nums, vector>& queries) { + sort(nums.begin(), nums.end()); + int n = queries.size(); + vector idx(n); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { return queries[i][1] < queries[j][1]; }); + vector ans(n); + Trie trie; + int j = 0; + for (int i : idx) { + int x = queries[i][0], m = queries[i][1]; + while (j < nums.size() && nums[j] <= m) { + trie.insert(nums[j++]); + } + ans[i] = trie.search(x); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.java b/solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.java index 8be4febaebd6a..ddaca27459a9d 100644 --- a/solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.java +++ b/solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.java @@ -1,54 +1,54 @@ -class Trie { - private Trie[] children = new Trie[2]; - - public void insert(int x) { - Trie node = this; - for (int i = 30; i >= 0; --i) { - int v = x >> i & 1; - if (node.children[v] == null) { - node.children[v] = new Trie(); - } - node = node.children[v]; - } - } - - public int search(int x) { - Trie node = this; - int ans = 0; - for (int i = 30; i >= 0; --i) { - int v = x >> i & 1; - if (node.children[v ^ 1] != null) { - ans |= 1 << i; - node = node.children[v ^ 1]; - } else if (node.children[v] != null) { - node = node.children[v]; - } else { - return -1; - } - } - return ans; - } -} - -class Solution { - public int[] maximizeXor(int[] nums, int[][] queries) { - Arrays.sort(nums); - int n = queries.length; - Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } - Arrays.sort(idx, (i, j) -> queries[i][1] - queries[j][1]); - int[] ans = new int[n]; - Trie trie = new Trie(); - int j = 0; - for (int i : idx) { - int x = queries[i][0], m = queries[i][1]; - while (j < nums.length && nums[j] <= m) { - trie.insert(nums[j++]); - } - ans[i] = trie.search(x); - } - return ans; - } +class Trie { + private Trie[] children = new Trie[2]; + + public void insert(int x) { + Trie node = this; + for (int i = 30; i >= 0; --i) { + int v = x >> i & 1; + if (node.children[v] == null) { + node.children[v] = new Trie(); + } + node = node.children[v]; + } + } + + public int search(int x) { + Trie node = this; + int ans = 0; + for (int i = 30; i >= 0; --i) { + int v = x >> i & 1; + if (node.children[v ^ 1] != null) { + ans |= 1 << i; + node = node.children[v ^ 1]; + } else if (node.children[v] != null) { + node = node.children[v]; + } else { + return -1; + } + } + return ans; + } +} + +class Solution { + public int[] maximizeXor(int[] nums, int[][] queries) { + Arrays.sort(nums); + int n = queries.length; + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; ++i) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> queries[i][1] - queries[j][1]); + int[] ans = new int[n]; + Trie trie = new Trie(); + int j = 0; + for (int i : idx) { + int x = queries[i][0], m = queries[i][1]; + while (j < nums.length && nums[j] <= m) { + trie.insert(nums[j++]); + } + ans[i] = trie.search(x); + } + return ans; + } } \ No newline at end of file diff --git a/solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.py b/solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.py index 73848b8cd9709..33ff15803eb61 100644 --- a/solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.py +++ b/solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.py @@ -1,41 +1,41 @@ -class Trie: - __slots__ = ["children"] - - def __init__(self): - self.children = [None] * 2 - - def insert(self, x: int): - node = self - for i in range(30, -1, -1): - v = x >> i & 1 - if node.children[v] is None: - node.children[v] = Trie() - node = node.children[v] - - def search(self, x: int) -> int: - node = self - ans = 0 - for i in range(30, -1, -1): - v = x >> i & 1 - if node.children[v ^ 1]: - ans |= 1 << i - node = node.children[v ^ 1] - elif node.children[v]: - node = node.children[v] - else: - return -1 - return ans - - -class Solution: - def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]: - trie = Trie() - nums.sort() - j, n = 0, len(queries) - ans = [-1] * n - for i, (x, m) in sorted(zip(range(n), queries), key=lambda x: x[1][1]): - while j < len(nums) and nums[j] <= m: - trie.insert(nums[j]) - j += 1 - ans[i] = trie.search(x) - return ans +class Trie: + __slots__ = ["children"] + + def __init__(self): + self.children = [None] * 2 + + def insert(self, x: int): + node = self + for i in range(30, -1, -1): + v = x >> i & 1 + if node.children[v] is None: + node.children[v] = Trie() + node = node.children[v] + + def search(self, x: int) -> int: + node = self + ans = 0 + for i in range(30, -1, -1): + v = x >> i & 1 + if node.children[v ^ 1]: + ans |= 1 << i + node = node.children[v ^ 1] + elif node.children[v]: + node = node.children[v] + else: + return -1 + return ans + + +class Solution: + def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]: + trie = Trie() + nums.sort() + j, n = 0, len(queries) + ans = [-1] * n + for i, (x, m) in sorted(zip(range(n), queries), key=lambda x: x[1][1]): + while j < len(nums) and nums[j] <= m: + trie.insert(nums[j]) + j += 1 + ans[i] = trie.search(x) + return ans diff --git a/solution/1700-1799/1708.Largest Subarray Length K/Solution.cpp b/solution/1700-1799/1708.Largest Subarray Length K/Solution.cpp index 2d3ab1aa0b9ea..947af2753ef97 100644 --- a/solution/1700-1799/1708.Largest Subarray Length K/Solution.cpp +++ b/solution/1700-1799/1708.Largest Subarray Length K/Solution.cpp @@ -1,7 +1,7 @@ -class Solution { -public: - vector largestSubarray(vector& nums, int k) { - auto i = max_element(nums.begin(), nums.end() - k + 1); - return {i, i + k}; - } +class Solution { +public: + vector largestSubarray(vector& nums, int k) { + auto i = max_element(nums.begin(), nums.end() - k + 1); + return {i, i + k}; + } }; \ No newline at end of file diff --git a/solution/1700-1799/1708.Largest Subarray Length K/Solution.java b/solution/1700-1799/1708.Largest Subarray Length K/Solution.java index ae998c3c268d9..7781444c11621 100644 --- a/solution/1700-1799/1708.Largest Subarray Length K/Solution.java +++ b/solution/1700-1799/1708.Largest Subarray Length K/Solution.java @@ -1,11 +1,11 @@ -class Solution { - public int[] largestSubarray(int[] nums, int k) { - int j = 0; - for (int i = 1; i < nums.length - k + 1; ++i) { - if (nums[j] < nums[i]) { - j = i; - } - } - return Arrays.copyOfRange(nums, j, j + k); - } +class Solution { + public int[] largestSubarray(int[] nums, int k) { + int j = 0; + for (int i = 1; i < nums.length - k + 1; ++i) { + if (nums[j] < nums[i]) { + j = i; + } + } + return Arrays.copyOfRange(nums, j, j + k); + } } \ No newline at end of file diff --git a/solution/1700-1799/1708.Largest Subarray Length K/Solution.py b/solution/1700-1799/1708.Largest Subarray Length K/Solution.py index dacfa4d0921a0..e0bb0027dc26e 100644 --- a/solution/1700-1799/1708.Largest Subarray Length K/Solution.py +++ b/solution/1700-1799/1708.Largest Subarray Length K/Solution.py @@ -1,4 +1,4 @@ -class Solution: - def largestSubarray(self, nums: List[int], k: int) -> List[int]: - i = nums.index(max(nums[: len(nums) - k + 1])) - return nums[i : i + k] +class Solution: + def largestSubarray(self, nums: List[int], k: int) -> List[int]: + i = nums.index(max(nums[: len(nums) - k + 1])) + return nums[i : i + k] diff --git a/solution/1700-1799/1710.Maximum Units on a Truck/Solution2.cpp b/solution/1700-1799/1710.Maximum Units on a Truck/Solution2.cpp new file mode 100644 index 0000000000000..8693e9f4d5c66 --- /dev/null +++ b/solution/1700-1799/1710.Maximum Units on a Truck/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int maximumUnits(vector>& boxTypes, int truckSize) { + int cnt[1001] = {0}; + for (auto& e : boxTypes) { + int a = e[0], b = e[1]; + cnt[b] += a; + } + int ans = 0; + for (int b = 1000; b > 0 && truckSize > 0; --b) { + int a = cnt[b]; + if (a) { + ans += b * min(truckSize, a); + truckSize -= a; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1700-1799/1710.Maximum Units on a Truck/Solution2.go b/solution/1700-1799/1710.Maximum Units on a Truck/Solution2.go new file mode 100644 index 0000000000000..e06d5820a8091 --- /dev/null +++ b/solution/1700-1799/1710.Maximum Units on a Truck/Solution2.go @@ -0,0 +1,15 @@ +func maximumUnits(boxTypes [][]int, truckSize int) (ans int) { + cnt := [1001]int{} + for _, e := range boxTypes { + a, b := e[0], e[1] + cnt[b] += a + } + for b := 1000; b > 0 && truckSize > 0; b-- { + a := cnt[b] + if a > 0 { + ans += b * min(truckSize, a) + truckSize -= a + } + } + return +} \ No newline at end of file diff --git a/solution/1700-1799/1710.Maximum Units on a Truck/Solution2.java b/solution/1700-1799/1710.Maximum Units on a Truck/Solution2.java new file mode 100644 index 0000000000000..1b5622344ed20 --- /dev/null +++ b/solution/1700-1799/1710.Maximum Units on a Truck/Solution2.java @@ -0,0 +1,18 @@ +class Solution { + public int maximumUnits(int[][] boxTypes, int truckSize) { + int[] cnt = new int[1001]; + for (var e : boxTypes) { + int a = e[0], b = e[1]; + cnt[b] += a; + } + int ans = 0; + for (int b = 1000; b > 0 && truckSize > 0; --b) { + int a = cnt[b]; + if (a > 0) { + ans += b * Math.min(truckSize, a); + truckSize -= a; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1700-1799/1710.Maximum Units on a Truck/Solution2.py b/solution/1700-1799/1710.Maximum Units on a Truck/Solution2.py new file mode 100644 index 0000000000000..4a7b964524b15 --- /dev/null +++ b/solution/1700-1799/1710.Maximum Units on a Truck/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: + cnt = [0] * 1001 + for a, b in boxTypes: + cnt[b] += a + ans = 0 + for b in range(1000, 0, -1): + a = cnt[b] + if a: + ans += b * min(truckSize, a) + truckSize -= a + if truckSize <= 0: + break + return ans diff --git a/solution/1700-1799/1710.Maximum Units on a Truck/Solution2.ts b/solution/1700-1799/1710.Maximum Units on a Truck/Solution2.ts new file mode 100644 index 0000000000000..dcd3649202e88 --- /dev/null +++ b/solution/1700-1799/1710.Maximum Units on a Truck/Solution2.ts @@ -0,0 +1,15 @@ +function maximumUnits(boxTypes: number[][], truckSize: number): number { + const cnt = new Array(1001).fill(0); + for (const [a, b] of boxTypes) { + cnt[b] += a; + } + let ans = 0; + for (let b = 1000; b > 0 && truckSize > 0; --b) { + const a = cnt[b]; + if (a > 0) { + ans += b * Math.min(truckSize, a); + truckSize -= a; + } + } + return ans; +} diff --git a/solution/1700-1799/1711.Count Good Meals/Solution.cpp b/solution/1700-1799/1711.Count Good Meals/Solution.cpp index 4ae675d90efd0..3767759fc1dcd 100644 --- a/solution/1700-1799/1711.Count Good Meals/Solution.cpp +++ b/solution/1700-1799/1711.Count Good Meals/Solution.cpp @@ -3,18 +3,15 @@ class Solution { const int mod = 1e9 + 7; int countPairs(vector& deliciousness) { + int mx = *max_element(deliciousness.begin(), deliciousness.end()) << 1; unordered_map cnt; - for (int& d : deliciousness) ++cnt[d]; - long long ans = 0; - for (int i = 0; i < 22; ++i) { - int s = 1 << i; - for (auto& [a, m] : cnt) { - int b = s - a; - if (!cnt.count(b)) continue; - ans += 1ll * m * (a == b ? (m - 1) : cnt[b]); + int ans = 0; + for (auto& d : deliciousness) { + for (int s = 1; s <= mx; s <<= 1) { + ans = (ans + cnt[s - d]) % mod; } + ++cnt[d]; } - ans >>= 1; - return ans % mod; + return ans; } }; \ No newline at end of file diff --git a/solution/1700-1799/1711.Count Good Meals/Solution.go b/solution/1700-1799/1711.Count Good Meals/Solution.go index 3e2a457129809..21403ba9b2dba 100644 --- a/solution/1700-1799/1711.Count Good Meals/Solution.go +++ b/solution/1700-1799/1711.Count Good Meals/Solution.go @@ -1,22 +1,12 @@ func countPairs(deliciousness []int) (ans int) { + mx := slices.Max(deliciousness) << 1 + const mod int = 1e9 + 7 cnt := map[int]int{} for _, d := range deliciousness { - cnt[d]++ - } - const mod int = 1e9 + 7 - for i := 0; i < 22; i++ { - s := 1 << i - for a, m := range cnt { - b := s - a - if n, ok := cnt[b]; ok { - if a == b { - ans += m * (m - 1) - } else { - ans += m * n - } - } + for s := 1; s <= mx; s <<= 1 { + ans = (ans + cnt[s-d]) % mod } + cnt[d]++ } - ans >>= 1 - return ans % mod + return } \ No newline at end of file diff --git a/solution/1700-1799/1711.Count Good Meals/Solution.java b/solution/1700-1799/1711.Count Good Meals/Solution.java index 282c9f0d8c63d..3e175621ce04f 100644 --- a/solution/1700-1799/1711.Count Good Meals/Solution.java +++ b/solution/1700-1799/1711.Count Good Meals/Solution.java @@ -2,23 +2,15 @@ class Solution { private static final int MOD = (int) 1e9 + 7; public int countPairs(int[] deliciousness) { + int mx = Arrays.stream(deliciousness).max().getAsInt() << 1; + int ans = 0; Map cnt = new HashMap<>(); for (int d : deliciousness) { - cnt.put(d, cnt.getOrDefault(d, 0) + 1); - } - long ans = 0; - for (int i = 0; i < 22; ++i) { - int s = 1 << i; - for (var x : cnt.entrySet()) { - int a = x.getKey(), m = x.getValue(); - int b = s - a; - if (!cnt.containsKey(b)) { - continue; - } - ans += 1L * m * (a == b ? m - 1 : cnt.get(b)); + for (int s = 1; s <= mx; s <<= 1) { + ans = (ans + cnt.getOrDefault(s - d, 0)) % MOD; } + cnt.merge(d, 1, Integer::sum); } - ans >>= 1; - return (int) (ans % MOD); + return ans; } } \ No newline at end of file diff --git a/solution/1700-1799/1711.Count Good Meals/Solution.py b/solution/1700-1799/1711.Count Good Meals/Solution.py index 35364b1604079..c8dc7e7d2a0d2 100644 --- a/solution/1700-1799/1711.Count Good Meals/Solution.py +++ b/solution/1700-1799/1711.Count Good Meals/Solution.py @@ -1,11 +1,13 @@ class Solution: def countPairs(self, deliciousness: List[int]) -> int: mod = 10**9 + 7 - cnt = Counter(deliciousness) + mx = max(deliciousness) << 1 + cnt = Counter() ans = 0 - for i in range(22): - s = 1 << i - for a, m in cnt.items(): - if (b := s - a) in cnt: - ans += m * (m - 1) if a == b else m * cnt[b] - return (ans >> 1) % mod + for d in deliciousness: + s = 1 + while s <= mx: + ans = (ans + cnt[s - d]) % mod + s <<= 1 + cnt[d] += 1 + return ans diff --git a/solution/1700-1799/1711.Count Good Meals/Solution2.cpp b/solution/1700-1799/1711.Count Good Meals/Solution2.cpp new file mode 100644 index 0000000000000..4ae675d90efd0 --- /dev/null +++ b/solution/1700-1799/1711.Count Good Meals/Solution2.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + const int mod = 1e9 + 7; + + int countPairs(vector& deliciousness) { + unordered_map cnt; + for (int& d : deliciousness) ++cnt[d]; + long long ans = 0; + for (int i = 0; i < 22; ++i) { + int s = 1 << i; + for (auto& [a, m] : cnt) { + int b = s - a; + if (!cnt.count(b)) continue; + ans += 1ll * m * (a == b ? (m - 1) : cnt[b]); + } + } + ans >>= 1; + return ans % mod; + } +}; \ No newline at end of file diff --git a/solution/1700-1799/1711.Count Good Meals/Solution2.go b/solution/1700-1799/1711.Count Good Meals/Solution2.go new file mode 100644 index 0000000000000..3e2a457129809 --- /dev/null +++ b/solution/1700-1799/1711.Count Good Meals/Solution2.go @@ -0,0 +1,22 @@ +func countPairs(deliciousness []int) (ans int) { + cnt := map[int]int{} + for _, d := range deliciousness { + cnt[d]++ + } + const mod int = 1e9 + 7 + for i := 0; i < 22; i++ { + s := 1 << i + for a, m := range cnt { + b := s - a + if n, ok := cnt[b]; ok { + if a == b { + ans += m * (m - 1) + } else { + ans += m * n + } + } + } + } + ans >>= 1 + return ans % mod +} \ No newline at end of file diff --git a/solution/1700-1799/1711.Count Good Meals/Solution2.java b/solution/1700-1799/1711.Count Good Meals/Solution2.java new file mode 100644 index 0000000000000..282c9f0d8c63d --- /dev/null +++ b/solution/1700-1799/1711.Count Good Meals/Solution2.java @@ -0,0 +1,24 @@ +class Solution { + private static final int MOD = (int) 1e9 + 7; + + public int countPairs(int[] deliciousness) { + Map cnt = new HashMap<>(); + for (int d : deliciousness) { + cnt.put(d, cnt.getOrDefault(d, 0) + 1); + } + long ans = 0; + for (int i = 0; i < 22; ++i) { + int s = 1 << i; + for (var x : cnt.entrySet()) { + int a = x.getKey(), m = x.getValue(); + int b = s - a; + if (!cnt.containsKey(b)) { + continue; + } + ans += 1L * m * (a == b ? m - 1 : cnt.get(b)); + } + } + ans >>= 1; + return (int) (ans % MOD); + } +} \ No newline at end of file diff --git a/solution/1700-1799/1711.Count Good Meals/Solution2.py b/solution/1700-1799/1711.Count Good Meals/Solution2.py new file mode 100644 index 0000000000000..35364b1604079 --- /dev/null +++ b/solution/1700-1799/1711.Count Good Meals/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def countPairs(self, deliciousness: List[int]) -> int: + mod = 10**9 + 7 + cnt = Counter(deliciousness) + ans = 0 + for i in range(22): + s = 1 << i + for a, m in cnt.items(): + if (b := s - a) in cnt: + ans += m * (m - 1) if a == b else m * cnt[b] + return (ans >> 1) % mod diff --git a/solution/1700-1799/1721.Swapping Nodes in a Linked List/Solution.cpp b/solution/1700-1799/1721.Swapping Nodes in a Linked List/Solution.cpp index f1a70d671d629..d6c6a6f12c00b 100644 --- a/solution/1700-1799/1721.Swapping Nodes in a Linked List/Solution.cpp +++ b/solution/1700-1799/1721.Swapping Nodes in a Linked List/Solution.cpp @@ -1,28 +1,28 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* swapNodes(ListNode* head, int k) { - ListNode* fast = head; - while (--k) { - fast = fast->next; - } - ListNode* slow = head; - ListNode* p = fast; - while (fast->next) { - fast = fast->next; - slow = slow->next; - } - ListNode* q = slow; - swap(p->val, q->val); - return head; - } +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* swapNodes(ListNode* head, int k) { + ListNode* fast = head; + while (--k) { + fast = fast->next; + } + ListNode* slow = head; + ListNode* p = fast; + while (fast->next) { + fast = fast->next; + slow = slow->next; + } + ListNode* q = slow; + swap(p->val, q->val); + return head; + } }; \ No newline at end of file diff --git a/solution/1700-1799/1721.Swapping Nodes in a Linked List/Solution.cs b/solution/1700-1799/1721.Swapping Nodes in a Linked List/Solution.cs index fe89510bed625..51b4a6668eaf8 100644 --- a/solution/1700-1799/1721.Swapping Nodes in a Linked List/Solution.cs +++ b/solution/1700-1799/1721.Swapping Nodes in a Linked List/Solution.cs @@ -1,30 +1,30 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } - * } - */ -public class Solution { - public ListNode SwapNodes(ListNode head, int k) { - ListNode fast = head; - while (--k > 0) { - fast = fast.next; - } - ListNode p = fast; - ListNode slow = head; - while (fast.next != null) { - fast = fast.next; - slow = slow.next; - } - ListNode q = slow; - int t = p.val; - p.val = q.val; - q.val = t; - return head; - } -} \ No newline at end of file +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode SwapNodes(ListNode head, int k) { + ListNode fast = head; + while (--k > 0) { + fast = fast.next; + } + ListNode p = fast; + ListNode slow = head; + while (fast.next != null) { + fast = fast.next; + slow = slow.next; + } + ListNode q = slow; + int t = p.val; + p.val = q.val; + q.val = t; + return head; + } +} diff --git a/solution/1700-1799/1721.Swapping Nodes in a Linked List/Solution.java b/solution/1700-1799/1721.Swapping Nodes in a Linked List/Solution.java index 5c485bc619214..be3834f3d29e9 100644 --- a/solution/1700-1799/1721.Swapping Nodes in a Linked List/Solution.java +++ b/solution/1700-1799/1721.Swapping Nodes in a Linked List/Solution.java @@ -1,29 +1,29 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode swapNodes(ListNode head, int k) { - ListNode fast = head; - while (--k > 0) { - fast = fast.next; - } - ListNode p = fast; - ListNode slow = head; - while (fast.next != null) { - fast = fast.next; - slow = slow.next; - } - ListNode q = slow; - int t = p.val; - p.val = q.val; - q.val = t; - return head; - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode swapNodes(ListNode head, int k) { + ListNode fast = head; + while (--k > 0) { + fast = fast.next; + } + ListNode p = fast; + ListNode slow = head; + while (fast.next != null) { + fast = fast.next; + slow = slow.next; + } + ListNode q = slow; + int t = p.val; + p.val = q.val; + q.val = t; + return head; + } } \ No newline at end of file diff --git a/solution/1700-1799/1721.Swapping Nodes in a Linked List/Solution.py b/solution/1700-1799/1721.Swapping Nodes in a Linked List/Solution.py index 5402c8f3a632e..d6dbdea2bd692 100644 --- a/solution/1700-1799/1721.Swapping Nodes in a Linked List/Solution.py +++ b/solution/1700-1799/1721.Swapping Nodes in a Linked List/Solution.py @@ -1,16 +1,16 @@ -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: - fast = slow = head - for _ in range(k - 1): - fast = fast.next - p = fast - while fast.next: - fast, slow = fast.next, slow.next - q = slow - p.val, q.val = q.val, p.val - return head +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: + fast = slow = head + for _ in range(k - 1): + fast = fast.next + p = fast + while fast.next: + fast, slow = fast.next, slow.next + q = slow + p.val, q.val = q.val, p.val + return head diff --git a/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/Solution.cpp b/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/Solution.cpp index 9f06ac04c126a..b7d026c700ed9 100644 --- a/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/Solution.cpp +++ b/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/Solution.cpp @@ -1,25 +1,25 @@ -class Solution { -public: - int minimumHammingDistance(vector& source, vector& target, vector>& allowedSwaps) { - int n = source.size(); - vector p(n); - iota(p.begin(), p.end(), 0); - function find = [&](int x) { - return x == p[x] ? x : p[x] = find(p[x]); - }; - for (auto& a : allowedSwaps) { - p[find(a[0])] = find(a[1]); - } - unordered_map> cnt; - for (int i = 0; i < n; ++i) { - ++cnt[find(i)][source[i]]; - } - int ans = 0; - for (int i = 0; i < n; ++i) { - if (--cnt[find(i)][target[i]] < 0) { - ++ans; - } - } - return ans; - } +class Solution { +public: + int minimumHammingDistance(vector& source, vector& target, vector>& allowedSwaps) { + int n = source.size(); + vector p(n); + iota(p.begin(), p.end(), 0); + function find = [&](int x) { + return x == p[x] ? x : p[x] = find(p[x]); + }; + for (auto& a : allowedSwaps) { + p[find(a[0])] = find(a[1]); + } + unordered_map> cnt; + for (int i = 0; i < n; ++i) { + ++cnt[find(i)][source[i]]; + } + int ans = 0; + for (int i = 0; i < n; ++i) { + if (--cnt[find(i)][target[i]] < 0) { + ++ans; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/Solution.java b/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/Solution.java index b33f5b0b1ae4e..a4f14d85302cb 100644 --- a/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/Solution.java +++ b/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/Solution.java @@ -1,35 +1,35 @@ -class Solution { - private int[] p; - - public int minimumHammingDistance(int[] source, int[] target, int[][] allowedSwaps) { - int n = source.length; - p = new int[n]; - for (int i = 0; i < n; i++) { - p[i] = i; - } - for (int[] a : allowedSwaps) { - p[find(a[0])] = find(a[1]); - } - Map> cnt = new HashMap<>(); - for (int i = 0; i < n; ++i) { - int j = find(i); - cnt.computeIfAbsent(j, k -> new HashMap<>()).merge(source[i], 1, Integer::sum); - } - int ans = 0; - for (int i = 0; i < n; ++i) { - int j = find(i); - Map t = cnt.get(j); - if (t.merge(target[i], -1, Integer::sum) < 0) { - ++ans; - } - } - return ans; - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } +class Solution { + private int[] p; + + public int minimumHammingDistance(int[] source, int[] target, int[][] allowedSwaps) { + int n = source.length; + p = new int[n]; + for (int i = 0; i < n; i++) { + p[i] = i; + } + for (int[] a : allowedSwaps) { + p[find(a[0])] = find(a[1]); + } + Map> cnt = new HashMap<>(); + for (int i = 0; i < n; ++i) { + int j = find(i); + cnt.computeIfAbsent(j, k -> new HashMap<>()).merge(source[i], 1, Integer::sum); + } + int ans = 0; + for (int i = 0; i < n; ++i) { + int j = find(i); + Map t = cnt.get(j); + if (t.merge(target[i], -1, Integer::sum) < 0) { + ++ans; + } + } + return ans; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } } \ No newline at end of file diff --git a/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/Solution.py b/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/Solution.py index c64fba92b2783..c9d74a888877a 100644 --- a/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/Solution.py +++ b/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/Solution.py @@ -1,23 +1,23 @@ -class Solution: - def minimumHammingDistance( - self, source: List[int], target: List[int], allowedSwaps: List[List[int]] - ) -> int: - def find(x: int) -> int: - if p[x] != x: - p[x] = find(p[x]) - return p[x] - - n = len(source) - p = list(range(n)) - for a, b in allowedSwaps: - p[find(a)] = find(b) - cnt = defaultdict(Counter) - for i, x in enumerate(source): - j = find(i) - cnt[j][x] += 1 - ans = 0 - for i, x in enumerate(target): - j = find(i) - cnt[j][x] -= 1 - ans += cnt[j][x] < 0 - return ans +class Solution: + def minimumHammingDistance( + self, source: List[int], target: List[int], allowedSwaps: List[List[int]] + ) -> int: + def find(x: int) -> int: + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + n = len(source) + p = list(range(n)) + for a, b in allowedSwaps: + p[find(a)] = find(b) + cnt = defaultdict(Counter) + for i, x in enumerate(source): + j = find(i) + cnt[j][x] += 1 + ans = 0 + for i, x in enumerate(target): + j = find(i) + cnt[j][x] -= 1 + ans += cnt[j][x] < 0 + return ans diff --git a/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/Solution.cpp b/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/Solution.cpp index 5b9a49720d440..7098af7c7c47c 100644 --- a/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/Solution.cpp +++ b/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/Solution.cpp @@ -1,70 +1,70 @@ -class PersistentUnionFind { -private: - vector rank; - vector parent; - vector version; - -public: - PersistentUnionFind(int n) - : rank(n, 0) - , parent(n) - , version(n, INT_MAX) { - for (int i = 0; i < n; i++) { - parent[i] = i; - } - } - - int find(int x, int t) { - if (parent[x] == x || version[x] >= t) { - return x; - } - return find(parent[x], t); - } - - bool unionSet(int a, int b, int t) { - int pa = find(a, INT_MAX); - int pb = find(b, INT_MAX); - if (pa == pb) { - return false; - } - if (rank[pa] > rank[pb]) { - version[pb] = t; - parent[pb] = pa; - } else { - version[pa] = t; - parent[pa] = pb; - if (rank[pa] == rank[pb]) { - rank[pb]++; - } - } - return true; - } -}; - -class DistanceLimitedPathsExist { -private: - PersistentUnionFind puf; - -public: - DistanceLimitedPathsExist(int n, vector>& edgeList) - : puf(n) { - sort(edgeList.begin(), edgeList.end(), - [](const vector& a, const vector& b) { - return a[2] < b[2]; - }); - - for (const auto& edge : edgeList) { - puf.unionSet(edge[0], edge[1], edge[2]); - } - } - - bool query(int p, int q, int limit) { - return puf.find(p, limit) == puf.find(q, limit); - } -}; - -/** - * Your DistanceLimitedPathsExist object will be instantiated and called as such: - * DistanceLimitedPathsExist* obj = new DistanceLimitedPathsExist(n, edgeList); - * bool param_1 = obj->query(p,q,limit); +class PersistentUnionFind { +private: + vector rank; + vector parent; + vector version; + +public: + PersistentUnionFind(int n) + : rank(n, 0) + , parent(n) + , version(n, INT_MAX) { + for (int i = 0; i < n; i++) { + parent[i] = i; + } + } + + int find(int x, int t) { + if (parent[x] == x || version[x] >= t) { + return x; + } + return find(parent[x], t); + } + + bool unionSet(int a, int b, int t) { + int pa = find(a, INT_MAX); + int pb = find(b, INT_MAX); + if (pa == pb) { + return false; + } + if (rank[pa] > rank[pb]) { + version[pb] = t; + parent[pb] = pa; + } else { + version[pa] = t; + parent[pa] = pb; + if (rank[pa] == rank[pb]) { + rank[pb]++; + } + } + return true; + } +}; + +class DistanceLimitedPathsExist { +private: + PersistentUnionFind puf; + +public: + DistanceLimitedPathsExist(int n, vector>& edgeList) + : puf(n) { + sort(edgeList.begin(), edgeList.end(), + [](const vector& a, const vector& b) { + return a[2] < b[2]; + }); + + for (const auto& edge : edgeList) { + puf.unionSet(edge[0], edge[1], edge[2]); + } + } + + bool query(int p, int q, int limit) { + return puf.find(p, limit) == puf.find(q, limit); + } +}; + +/** + * Your DistanceLimitedPathsExist object will be instantiated and called as such: + * DistanceLimitedPathsExist* obj = new DistanceLimitedPathsExist(n, edgeList); + * bool param_1 = obj->query(p,q,limit); */ \ No newline at end of file diff --git a/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/Solution.java b/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/Solution.java index 47b6276c9dbff..717690c665f65 100644 --- a/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/Solution.java +++ b/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/Solution.java @@ -1,64 +1,64 @@ -class PersistentUnionFind { - private final int inf = 1 << 30; - private int[] rank; - private int[] parent; - private int[] version; - - public PersistentUnionFind(int n) { - rank = new int[n]; - parent = new int[n]; - version = new int[n]; - for (int i = 0; i < n; i++) { - parent[i] = i; - version[i] = inf; - } - } - - public int find(int x, int t) { - if (parent[x] == x || version[x] >= t) { - return x; - } - return find(parent[x], t); - } - - public boolean union(int a, int b, int t) { - int pa = find(a, inf); - int pb = find(b, inf); - if (pa == pb) { - return false; - } - if (rank[pa] > rank[pb]) { - version[pb] = t; - parent[pb] = pa; - } else { - version[pa] = t; - parent[pa] = pb; - if (rank[pa] == rank[pb]) { - rank[pb]++; - } - } - return true; - } -} - -public class DistanceLimitedPathsExist { - private PersistentUnionFind puf; - - public DistanceLimitedPathsExist(int n, int[][] edgeList) { - puf = new PersistentUnionFind(n); - Arrays.sort(edgeList, (a, b) -> a[2] - b[2]); - for (var e : edgeList) { - puf.union(e[0], e[1], e[2]); - } - } - - public boolean query(int p, int q, int limit) { - return puf.find(p, limit) == puf.find(q, limit); - } -} - -/** - * Your DistanceLimitedPathsExist object will be instantiated and called as such: - * DistanceLimitedPathsExist obj = new DistanceLimitedPathsExist(n, edgeList); - * boolean param_1 = obj.query(p,q,limit); +class PersistentUnionFind { + private final int inf = 1 << 30; + private int[] rank; + private int[] parent; + private int[] version; + + public PersistentUnionFind(int n) { + rank = new int[n]; + parent = new int[n]; + version = new int[n]; + for (int i = 0; i < n; i++) { + parent[i] = i; + version[i] = inf; + } + } + + public int find(int x, int t) { + if (parent[x] == x || version[x] >= t) { + return x; + } + return find(parent[x], t); + } + + public boolean union(int a, int b, int t) { + int pa = find(a, inf); + int pb = find(b, inf); + if (pa == pb) { + return false; + } + if (rank[pa] > rank[pb]) { + version[pb] = t; + parent[pb] = pa; + } else { + version[pa] = t; + parent[pa] = pb; + if (rank[pa] == rank[pb]) { + rank[pb]++; + } + } + return true; + } +} + +public class DistanceLimitedPathsExist { + private PersistentUnionFind puf; + + public DistanceLimitedPathsExist(int n, int[][] edgeList) { + puf = new PersistentUnionFind(n); + Arrays.sort(edgeList, (a, b) -> a[2] - b[2]); + for (var e : edgeList) { + puf.union(e[0], e[1], e[2]); + } + } + + public boolean query(int p, int q, int limit) { + return puf.find(p, limit) == puf.find(q, limit); + } +} + +/** + * Your DistanceLimitedPathsExist object will be instantiated and called as such: + * DistanceLimitedPathsExist obj = new DistanceLimitedPathsExist(n, edgeList); + * boolean param_1 = obj.query(p,q,limit); */ \ No newline at end of file diff --git a/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/Solution.py b/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/Solution.py index ec712afb724a0..8d9a2be6c54a9 100644 --- a/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/Solution.py +++ b/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/Solution.py @@ -1,35 +1,35 @@ -class PersistentUnionFind: - def __init__(self, n): - self.rank = [0] * n - self.p = list(range(n)) - self.version = [inf] * n - - def find(self, x, t=inf): - if self.p[x] == x or self.version[x] >= t: - return x - return self.find(self.p[x], t) - - def union(self, a, b, t): - pa, pb = self.find(a), self.find(b) - if pa == pb: - return False - if self.rank[pa] > self.rank[pb]: - self.version[pb] = t - self.p[pb] = pa - else: - self.version[pa] = t - self.p[pa] = pb - if self.rank[pa] == self.rank[pb]: - self.rank[pb] += 1 - return True - - -class DistanceLimitedPathsExist: - def __init__(self, n: int, edgeList: List[List[int]]): - self.puf = PersistentUnionFind(n) - edgeList.sort(key=lambda x: x[2]) - for u, v, dis in edgeList: - self.puf.union(u, v, dis) - - def query(self, p: int, q: int, limit: int) -> bool: - return self.puf.find(p, limit) == self.puf.find(q, limit) +class PersistentUnionFind: + def __init__(self, n): + self.rank = [0] * n + self.p = list(range(n)) + self.version = [inf] * n + + def find(self, x, t=inf): + if self.p[x] == x or self.version[x] >= t: + return x + return self.find(self.p[x], t) + + def union(self, a, b, t): + pa, pb = self.find(a), self.find(b) + if pa == pb: + return False + if self.rank[pa] > self.rank[pb]: + self.version[pb] = t + self.p[pb] = pa + else: + self.version[pa] = t + self.p[pa] = pb + if self.rank[pa] == self.rank[pb]: + self.rank[pb] += 1 + return True + + +class DistanceLimitedPathsExist: + def __init__(self, n: int, edgeList: List[List[int]]): + self.puf = PersistentUnionFind(n) + edgeList.sort(key=lambda x: x[2]) + for u, v, dis in edgeList: + self.puf.union(u, v, dis) + + def query(self, p: int, q: int, limit: int) -> bool: + return self.puf.find(p, limit) == self.puf.find(q, limit) diff --git a/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/Solution.cpp b/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/Solution.cpp index 167ee2325e5b9..a5094305e2d25 100644 --- a/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/Solution.cpp +++ b/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - int countGoodRectangles(vector>& rectangles) { - int ans = 0, mx = 0; - for (auto& e : rectangles) { - int x = min(e[0], e[1]); - if (mx < x) { - mx = x; - ans = 1; - } else if (mx == x) { - ++ans; - } - } - return ans; - } +class Solution { +public: + int countGoodRectangles(vector>& rectangles) { + int ans = 0, mx = 0; + for (auto& e : rectangles) { + int x = min(e[0], e[1]); + if (mx < x) { + mx = x; + ans = 1; + } else if (mx == x) { + ++ans; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/Solution.java b/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/Solution.java index eda3cedcc5ee7..9ce088dcebf5c 100644 --- a/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/Solution.java +++ b/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public int countGoodRectangles(int[][] rectangles) { - int ans = 0, mx = 0; - for (var e : rectangles) { - int x = Math.min(e[0], e[1]); - if (mx < x) { - mx = x; - ans = 1; - } else if (mx == x) { - ++ans; - } - } - return ans; - } +class Solution { + public int countGoodRectangles(int[][] rectangles) { + int ans = 0, mx = 0; + for (var e : rectangles) { + int x = Math.min(e[0], e[1]); + if (mx < x) { + mx = x; + ans = 1; + } else if (mx == x) { + ++ans; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/Solution.py b/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/Solution.py index bf0b05847b281..d42018d311592 100644 --- a/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/Solution.py +++ b/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def countGoodRectangles(self, rectangles: List[List[int]]) -> int: - ans = mx = 0 - for l, w in rectangles: - x = min(l, w) - if mx < x: - ans = 1 - mx = x - elif mx == x: - ans += 1 - return ans +class Solution: + def countGoodRectangles(self, rectangles: List[List[int]]) -> int: + ans = mx = 0 + for l, w in rectangles: + x = min(l, w) + if mx < x: + ans = 1 + mx = x + elif mx == x: + ans += 1 + return ans diff --git a/solution/1700-1799/1726.Tuple with Same Product/Solution.go b/solution/1700-1799/1726.Tuple with Same Product/Solution.go index 2ed1f8f186348..cf42723857031 100644 --- a/solution/1700-1799/1726.Tuple with Same Product/Solution.go +++ b/solution/1700-1799/1726.Tuple with Same Product/Solution.go @@ -1,4 +1,4 @@ -func tupleSameProduct(nums []int) (ans int) { +func tupleSameProduct(nums []int) int { cnt := map[int]int{} for i := 1; i < len(nums); i++ { for j := 0; j < i; j++ { @@ -6,6 +6,7 @@ func tupleSameProduct(nums []int) (ans int) { cnt[x]++ } } + ans := 0 for _, v := range cnt { ans += v * (v - 1) / 2 } diff --git a/solution/1700-1799/1726.Tuple with Same Product/Solution.java b/solution/1700-1799/1726.Tuple with Same Product/Solution.java index 2430d3444baad..928420e2c9cf7 100644 --- a/solution/1700-1799/1726.Tuple with Same Product/Solution.java +++ b/solution/1700-1799/1726.Tuple with Same Product/Solution.java @@ -1,16 +1,16 @@ -class Solution { - public int tupleSameProduct(int[] nums) { - Map cnt = new HashMap<>(); - for (int i = 1; i < nums.length; ++i) { - for (int j = 0; j < i; ++j) { - int x = nums[i] * nums[j]; - cnt.merge(x, 1, Integer::sum); - } - } - int ans = 0; - for (int v : cnt.values()) { - ans += v * (v - 1) / 2; - } - return ans << 3; - } +class Solution { + public int tupleSameProduct(int[] nums) { + Map cnt = new HashMap<>(); + for (int i = 1; i < nums.length; ++i) { + for (int j = 0; j < i; ++j) { + int x = nums[i] * nums[j]; + cnt.merge(x, 1, Integer::sum); + } + } + int ans = 0; + for (int v : cnt.values()) { + ans += v * (v - 1) / 2; + } + return ans << 3; + } } \ No newline at end of file diff --git a/solution/1700-1799/1730.Shortest Path to Get Food/Solution.py b/solution/1700-1799/1730.Shortest Path to Get Food/Solution.py index 1330c9967c353..132faea08cd1a 100644 --- a/solution/1700-1799/1730.Shortest Path to Get Food/Solution.py +++ b/solution/1700-1799/1730.Shortest Path to Get Food/Solution.py @@ -1,20 +1,20 @@ -class Solution: - def getFood(self, grid: List[List[str]]) -> int: - m, n = len(grid), len(grid[0]) - i, j = next((i, j) for i in range(m) for j in range(n) if grid[i][j] == '*') - q = deque([(i, j)]) - dirs = (-1, 0, 1, 0, -1) - ans = 0 - while q: - ans += 1 - for _ in range(len(q)): - i, j = q.popleft() - for a, b in pairwise(dirs): - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n: - if grid[x][y] == '#': - return ans - if grid[x][y] == 'O': - grid[x][y] = 'X' - q.append((x, y)) - return -1 +class Solution: + def getFood(self, grid: List[List[str]]) -> int: + m, n = len(grid), len(grid[0]) + i, j = next((i, j) for i in range(m) for j in range(n) if grid[i][j] == '*') + q = deque([(i, j)]) + dirs = (-1, 0, 1, 0, -1) + ans = 0 + while q: + ans += 1 + for _ in range(len(q)): + i, j = q.popleft() + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n: + if grid[x][y] == '#': + return ans + if grid[x][y] == 'O': + grid[x][y] = 'X' + q.append((x, y)) + return -1 diff --git a/solution/1700-1799/1732.Find the Highest Altitude/Solution.c b/solution/1700-1799/1732.Find the Highest Altitude/Solution.c index 210dbf50a3039..b32d46c386cb0 100644 --- a/solution/1700-1799/1732.Find the Highest Altitude/Solution.c +++ b/solution/1700-1799/1732.Find the Highest Altitude/Solution.c @@ -8,4 +8,4 @@ int largestAltitude(int* gain, int gainSize) { ans = max(ans, h); } return ans; -} +} \ No newline at end of file diff --git a/solution/1700-1799/1732.Find the Highest Altitude/Solution.php b/solution/1700-1799/1732.Find the Highest Altitude/Solution.php index beb4d395e1b10..5e9f22afa8dd6 100644 --- a/solution/1700-1799/1732.Find the Highest Altitude/Solution.php +++ b/solution/1700-1799/1732.Find the Highest Altitude/Solution.php @@ -13,4 +13,4 @@ function largestAltitude($gain) { } return $max; } -} \ No newline at end of file +} diff --git a/solution/1700-1799/1732.Find the Highest Altitude/Solution.py b/solution/1700-1799/1732.Find the Highest Altitude/Solution.py index 597a0262863d9..16a5f4316f792 100644 --- a/solution/1700-1799/1732.Find the Highest Altitude/Solution.py +++ b/solution/1700-1799/1732.Find the Highest Altitude/Solution.py @@ -1,7 +1,3 @@ class Solution: def largestAltitude(self, gain: List[int]) -> int: - ans = h = 0 - for v in gain: - h += v - ans = max(ans, h) - return ans + return max(accumulate(gain, initial=0)) diff --git a/solution/1700-1799/1732.Find the Highest Altitude/Solution2.py b/solution/1700-1799/1732.Find the Highest Altitude/Solution2.py new file mode 100644 index 0000000000000..597a0262863d9 --- /dev/null +++ b/solution/1700-1799/1732.Find the Highest Altitude/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def largestAltitude(self, gain: List[int]) -> int: + ans = h = 0 + for v in gain: + h += v + ans = max(ans, h) + return ans diff --git a/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/Solution.cs b/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/Solution.cs index b2763f7f20b93..60fa69672e650 100644 --- a/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/Solution.cs +++ b/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/Solution.cs @@ -2,7 +2,7 @@ public class Solution { public int[] RestoreArray(int[][] adjacentPairs) { int n = adjacentPairs.Length + 1; Dictionary> g = new Dictionary>(); - + foreach (int[] e in adjacentPairs) { int a = e[0], b = e[1]; if (!g.ContainsKey(a)) { @@ -14,9 +14,9 @@ public int[] RestoreArray(int[][] adjacentPairs) { g[a].Add(b); g[b].Add(a); } - + int[] ans = new int[n]; - + foreach (var entry in g) { if (entry.Value.Count == 1) { ans[0] = entry.Key; @@ -24,12 +24,12 @@ public int[] RestoreArray(int[][] adjacentPairs) { break; } } - + for (int i = 2; i < n; ++i) { List v = g[ans[i - 1]]; ans[i] = v[1] == ans[i - 2] ? v[0] : v[1]; } - + return ans; } } diff --git a/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/Solution2.cpp b/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/Solution2.cpp new file mode 100644 index 0000000000000..06c198abeaf5a --- /dev/null +++ b/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/Solution2.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + vector restoreArray(vector>& adjacentPairs) { + unordered_map> g; + for (auto& e : adjacentPairs) { + int a = e[0], b = e[1]; + g[a].emplace_back(b); + g[b].emplace_back(a); + } + int n = adjacentPairs.size() + 1; + vector ans; + function dfs = [&](int i, int fa) { + ans.emplace_back(i); + for (int& j : g[i]) { + if (j != fa) { + dfs(j, i); + } + } + }; + for (auto& [i, v] : g) { + if (v.size() == 1) { + dfs(i, 1e6); + break; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/Solution2.go b/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/Solution2.go new file mode 100644 index 0000000000000..4b0a421eec604 --- /dev/null +++ b/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/Solution2.go @@ -0,0 +1,25 @@ +func restoreArray(adjacentPairs [][]int) []int { + g := map[int][]int{} + for _, e := range adjacentPairs { + a, b := e[0], e[1] + g[a] = append(g[a], b) + g[b] = append(g[b], a) + } + ans := []int{} + var dfs func(i, fa int) + dfs = func(i, fa int) { + ans = append(ans, i) + for _, j := range g[i] { + if j != fa { + dfs(j, i) + } + } + } + for i, v := range g { + if len(v) == 1 { + dfs(i, 1000000) + break + } + } + return ans +} \ No newline at end of file diff --git a/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/Solution2.java b/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/Solution2.java new file mode 100644 index 0000000000000..1fb802031fee0 --- /dev/null +++ b/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/Solution2.java @@ -0,0 +1,30 @@ +class Solution { + private Map> g = new HashMap<>(); + private int[] ans; + + public int[] restoreArray(int[][] adjacentPairs) { + for (var e : adjacentPairs) { + int a = e[0], b = e[1]; + g.computeIfAbsent(a, k -> new ArrayList<>()).add(b); + g.computeIfAbsent(b, k -> new ArrayList<>()).add(a); + } + int n = adjacentPairs.length + 1; + ans = new int[n]; + for (var e : g.entrySet()) { + if (e.getValue().size() == 1) { + dfs(e.getKey(), 1000000, 0); + break; + } + } + return ans; + } + + private void dfs(int i, int fa, int k) { + ans[k++] = i; + for (int j : g.get(i)) { + if (j != fa) { + dfs(j, i, k); + } + } + } +} \ No newline at end of file diff --git a/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/Solution2.py b/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/Solution2.py new file mode 100644 index 0000000000000..6586fabc14aaa --- /dev/null +++ b/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/Solution2.py @@ -0,0 +1,16 @@ +class Solution: + def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]: + def dfs(i, fa): + ans.append(i) + for j in g[i]: + if j != fa: + dfs(j, i) + + g = defaultdict(list) + for a, b in adjacentPairs: + g[a].append(b) + g[b].append(a) + i = next(i for i, v in g.items() if len(v) == 1) + ans = [] + dfs(i, 1e6) + return ans diff --git a/solution/1700-1799/1748.Sum of Unique Elements/Solution.php b/solution/1700-1799/1748.Sum of Unique Elements/Solution.php index b08750945852e..37b3a0bae7241 100644 --- a/solution/1700-1799/1748.Sum of Unique Elements/Solution.php +++ b/solution/1700-1799/1748.Sum of Unique Elements/Solution.php @@ -16,4 +16,4 @@ function sumOfUnique($nums) { } return $sum; } -} \ No newline at end of file +} diff --git a/solution/1700-1799/1748.Sum of Unique Elements/Solution.ts b/solution/1700-1799/1748.Sum of Unique Elements/Solution.ts index 7b8f9526d861c..faccea73d8240 100644 --- a/solution/1700-1799/1748.Sum of Unique Elements/Solution.ts +++ b/solution/1700-1799/1748.Sum of Unique Elements/Solution.ts @@ -5,7 +5,7 @@ function sumOfUnique(nums: number[]): number { } let ans = 0; for (let x = 0; x < 101; ++x) { - if (cnt[x] === 1) { + if (cnt[x] == 1) { ans += x; } } diff --git a/solution/1700-1799/1748.Sum of Unique Elements/Solution2.cpp b/solution/1700-1799/1748.Sum of Unique Elements/Solution2.cpp new file mode 100644 index 0000000000000..05944d9a8161b --- /dev/null +++ b/solution/1700-1799/1748.Sum of Unique Elements/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int sumOfUnique(vector& nums) { + int ans = 0; + int cnt[101]{}; + for (int& x : nums) { + if (++cnt[x] == 1) { + ans += x; + } else if (cnt[x] == 2) { + ans -= x; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1700-1799/1748.Sum of Unique Elements/Solution2.go b/solution/1700-1799/1748.Sum of Unique Elements/Solution2.go new file mode 100644 index 0000000000000..1098e729b66b7 --- /dev/null +++ b/solution/1700-1799/1748.Sum of Unique Elements/Solution2.go @@ -0,0 +1,12 @@ +func sumOfUnique(nums []int) (ans int) { + cnt := [101]int{} + for _, x := range nums { + cnt[x]++ + if cnt[x] == 1 { + ans += x + } else if cnt[x] == 2 { + ans -= x + } + } + return +} \ No newline at end of file diff --git a/solution/1700-1799/1748.Sum of Unique Elements/Solution2.java b/solution/1700-1799/1748.Sum of Unique Elements/Solution2.java new file mode 100644 index 0000000000000..a710bdaea2148 --- /dev/null +++ b/solution/1700-1799/1748.Sum of Unique Elements/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public int sumOfUnique(int[] nums) { + int ans = 0; + int[] cnt = new int[101]; + for (int x : nums) { + if (++cnt[x] == 1) { + ans += x; + } else if (cnt[x] == 2) { + ans -= x; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1700-1799/1748.Sum of Unique Elements/Solution2.rs b/solution/1700-1799/1748.Sum of Unique Elements/Solution2.rs new file mode 100644 index 0000000000000..25972b278fbf9 --- /dev/null +++ b/solution/1700-1799/1748.Sum of Unique Elements/Solution2.rs @@ -0,0 +1,20 @@ +use std::collections::HashMap; + +impl Solution { + pub fn sum_of_unique(nums: Vec) -> i32 { + let mut res = 0; + let mut map = HashMap::new(); + for num in nums { + if map.contains_key(&num) { + if *map.get(&num).unwrap() { + map.insert(num, false); + res -= num; + } + } else { + map.insert(num, true); + res += num; + } + } + res + } +} diff --git a/solution/1700-1799/1748.Sum of Unique Elements/Solution2.ts b/solution/1700-1799/1748.Sum of Unique Elements/Solution2.ts new file mode 100644 index 0000000000000..0983c78ace41b --- /dev/null +++ b/solution/1700-1799/1748.Sum of Unique Elements/Solution2.ts @@ -0,0 +1,12 @@ +function sumOfUnique(nums: number[]): number { + let ans = 0; + const cnt = new Array(101).fill(0); + for (const x of nums) { + if (++cnt[x] === 1) { + ans += x; + } else if (cnt[x] === 2) { + ans -= x; + } + } + return ans; +} diff --git a/solution/1700-1799/1750.Minimum Length of String After Deleting Similar Ends/Solution.c b/solution/1700-1799/1750.Minimum Length of String After Deleting Similar Ends/Solution.c index e39c9cfa54cb7..c235bd97e8aba 100644 --- a/solution/1700-1799/1750.Minimum Length of String After Deleting Similar Ends/Solution.c +++ b/solution/1700-1799/1750.Minimum Length of String After Deleting Similar Ends/Solution.c @@ -16,4 +16,4 @@ int minimumLength(char* s) { return 0; } return end - start + 1; -} +} \ No newline at end of file diff --git a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.cpp b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.cpp index 40ac2f155e388..42e112883fae4 100644 --- a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.cpp +++ b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.cpp @@ -1,18 +1,23 @@ class Solution { public: int maxValue(vector>& events, int k) { - sort(events.begin(), events.end(), [](const auto& a, const auto& b) { return a[1] < b[1]; }); + sort(events.begin(), events.end()); int n = events.size(); - int f[n + 1][k + 1]; + int f[n][k + 1]; memset(f, 0, sizeof(f)); - for (int i = 1; i <= n; ++i) { - int st = events[i - 1][0], val = events[i - 1][2]; - vector t = {st}; - int p = lower_bound(events.begin(), events.begin() + i - 1, t, [](const auto& a, const auto& b) { return a[1] < b[0]; }) - events.begin(); - for (int j = 1; j <= k; ++j) { - f[i][j] = max(f[i - 1][j], f[p][j - 1] + val); + function dfs = [&](int i, int k) -> int { + if (i >= n || k <= 0) { + return 0; } - } - return f[n][k]; + if (f[i][k] > 0) { + return f[i][k]; + } + int ed = events[i][1], val = events[i][2]; + vector t = {ed}; + int p = upper_bound(events.begin() + i + 1, events.end(), t, [](const auto& a, const auto& b) { return a[0] < b[0]; }) - events.begin(); + f[i][k] = max(dfs(i + 1, k), dfs(p, k - 1) + val); + return f[i][k]; + }; + return dfs(0, k); } }; \ No newline at end of file diff --git a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.go b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.go index bff23bb4a60ab..7ba586726d57c 100644 --- a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.go +++ b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.go @@ -1,16 +1,22 @@ func maxValue(events [][]int, k int) int { - sort.Slice(events, func(i, j int) bool { return events[i][1] < events[j][1] }) + sort.Slice(events, func(i, j int) bool { return events[i][0] < events[j][0] }) n := len(events) - f := make([][]int, n+1) + f := make([][]int, n) for i := range f { f[i] = make([]int, k+1) } - for i := 1; i <= n; i++ { - st, val := events[i-1][0], events[i-1][2] - p := sort.Search(i, func(j int) bool { return events[j][1] >= st }) - for j := 1; j <= k; j++ { - f[i][j] = max(f[i-1][j], f[p][j-1]+val) + var dfs func(i, k int) int + dfs = func(i, k int) int { + if i >= n || k <= 0 { + return 0 } + if f[i][k] > 0 { + return f[i][k] + } + j := sort.Search(n, func(h int) bool { return events[h][0] > events[i][1] }) + ans := max(dfs(i+1, k), dfs(j, k-1)+events[i][2]) + f[i][k] = ans + return ans } - return f[n][k] + return dfs(0, k) } \ No newline at end of file diff --git a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.java b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.java index 33a5a05a07bc5..fbab6672f3804 100644 --- a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.java +++ b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.java @@ -1,23 +1,33 @@ class Solution { + private int[][] events; + private int[][] f; + private int n; + public int maxValue(int[][] events, int k) { - Arrays.sort(events, (a, b) -> a[1] - b[1]); - int n = events.length; - int[][] f = new int[n + 1][k + 1]; - for (int i = 1; i <= n; ++i) { - int st = events[i - 1][0], val = events[i - 1][2]; - int p = search(events, st, i - 1); - for (int j = 1; j <= k; ++j) { - f[i][j] = Math.max(f[i - 1][j], f[p][j - 1] + val); - } + Arrays.sort(events, (a, b) -> a[0] - b[0]); + this.events = events; + n = events.length; + f = new int[n][k + 1]; + return dfs(0, k); + } + + private int dfs(int i, int k) { + if (i >= n || k <= 0) { + return 0; + } + if (f[i][k] != 0) { + return f[i][k]; } - return f[n][k]; + int j = search(events, events[i][1], i + 1); + int ans = Math.max(dfs(i + 1, k), dfs(j, k - 1) + events[i][2]); + return f[i][k] = ans; } - private int search(int[][] events, int x, int hi) { - int l = 0, r = hi; + private int search(int[][] events, int x, int lo) { + int l = lo, r = n; while (l < r) { int mid = (l + r) >> 1; - if (events[mid][1] >= x) { + if (events[mid][0] > x) { r = mid; } else { l = mid + 1; diff --git a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.py b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.py index 70f724fac05d6..b00755942e0a7 100644 --- a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.py +++ b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.py @@ -1,10 +1,15 @@ class Solution: def maxValue(self, events: List[List[int]], k: int) -> int: - events.sort(key=lambda x: x[1]) - n = len(events) - f = [[0] * (k + 1) for _ in range(n + 1)] - for i, (st, _, val) in enumerate(events, 1): - p = bisect_left(events, st, hi=i - 1, key=lambda x: x[1]) - for j in range(1, k + 1): - f[i][j] = max(f[i - 1][j], f[p][j - 1] + val) - return f[n][k] + @cache + def dfs(i: int, k: int) -> int: + if i >= len(events): + return 0 + _, ed, val = events[i] + ans = dfs(i + 1, k) + if k: + j = bisect_right(events, ed, lo=i + 1, key=lambda x: x[0]) + ans = max(ans, dfs(j, k - 1) + val) + return ans + + events.sort() + return dfs(0, k) diff --git a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution2.cpp b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution2.cpp new file mode 100644 index 0000000000000..40ac2f155e388 --- /dev/null +++ b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution2.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int maxValue(vector>& events, int k) { + sort(events.begin(), events.end(), [](const auto& a, const auto& b) { return a[1] < b[1]; }); + int n = events.size(); + int f[n + 1][k + 1]; + memset(f, 0, sizeof(f)); + for (int i = 1; i <= n; ++i) { + int st = events[i - 1][0], val = events[i - 1][2]; + vector t = {st}; + int p = lower_bound(events.begin(), events.begin() + i - 1, t, [](const auto& a, const auto& b) { return a[1] < b[0]; }) - events.begin(); + for (int j = 1; j <= k; ++j) { + f[i][j] = max(f[i - 1][j], f[p][j - 1] + val); + } + } + return f[n][k]; + } +}; \ No newline at end of file diff --git a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution2.go b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution2.go new file mode 100644 index 0000000000000..bff23bb4a60ab --- /dev/null +++ b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution2.go @@ -0,0 +1,16 @@ +func maxValue(events [][]int, k int) int { + sort.Slice(events, func(i, j int) bool { return events[i][1] < events[j][1] }) + n := len(events) + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, k+1) + } + for i := 1; i <= n; i++ { + st, val := events[i-1][0], events[i-1][2] + p := sort.Search(i, func(j int) bool { return events[j][1] >= st }) + for j := 1; j <= k; j++ { + f[i][j] = max(f[i-1][j], f[p][j-1]+val) + } + } + return f[n][k] +} \ No newline at end of file diff --git a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution2.java b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution2.java new file mode 100644 index 0000000000000..33a5a05a07bc5 --- /dev/null +++ b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution2.java @@ -0,0 +1,28 @@ +class Solution { + public int maxValue(int[][] events, int k) { + Arrays.sort(events, (a, b) -> a[1] - b[1]); + int n = events.length; + int[][] f = new int[n + 1][k + 1]; + for (int i = 1; i <= n; ++i) { + int st = events[i - 1][0], val = events[i - 1][2]; + int p = search(events, st, i - 1); + for (int j = 1; j <= k; ++j) { + f[i][j] = Math.max(f[i - 1][j], f[p][j - 1] + val); + } + } + return f[n][k]; + } + + private int search(int[][] events, int x, int hi) { + int l = 0, r = hi; + while (l < r) { + int mid = (l + r) >> 1; + if (events[mid][1] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } +} \ No newline at end of file diff --git a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution2.py b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution2.py new file mode 100644 index 0000000000000..70f724fac05d6 --- /dev/null +++ b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def maxValue(self, events: List[List[int]], k: int) -> int: + events.sort(key=lambda x: x[1]) + n = len(events) + f = [[0] * (k + 1) for _ in range(n + 1)] + for i, (st, _, val) in enumerate(events, 1): + p = bisect_left(events, st, hi=i - 1, key=lambda x: x[1]) + for j in range(1, k + 1): + f[i][j] = max(f[i - 1][j], f[p][j - 1] + val) + return f[n][k] diff --git a/solution/1700-1799/1752.Check if Array Is Sorted and Rotated/Solution.c b/solution/1700-1799/1752.Check if Array Is Sorted and Rotated/Solution.c index 6505a11ee8409..d9f23cd1222cc 100644 --- a/solution/1700-1799/1752.Check if Array Is Sorted and Rotated/Solution.c +++ b/solution/1700-1799/1752.Check if Array Is Sorted and Rotated/Solution.c @@ -6,4 +6,4 @@ bool check(int* nums, int numsSize) { } } return count <= 1; -} +} \ No newline at end of file diff --git a/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution.cpp b/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution.cpp index 8532abd5ad6fd..080c8107ffc7a 100644 --- a/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution.cpp +++ b/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution.cpp @@ -3,7 +3,13 @@ class Solution { int maximumScore(int a, int b, int c) { vector s = {a, b, c}; sort(s.begin(), s.end()); - if (s[0] + s[1] < s[2]) return s[0] + s[1]; - return (a + b + c) >> 1; + int ans = 0; + while (s[1]) { + ++ans; + s[1]--; + s[2]--; + sort(s.begin(), s.end()); + } + return ans; } }; \ No newline at end of file diff --git a/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution.go b/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution.go index c3e33a86118af..2d1230539f5cd 100644 --- a/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution.go +++ b/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution.go @@ -1,8 +1,11 @@ -func maximumScore(a int, b int, c int) int { +func maximumScore(a int, b int, c int) (ans int) { s := []int{a, b, c} sort.Ints(s) - if s[0]+s[1] < s[2] { - return s[0] + s[1] + for s[1] > 0 { + ans++ + s[1]-- + s[2]-- + sort.Ints(s) } - return (a + b + c) >> 1 + return } \ No newline at end of file diff --git a/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution.java b/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution.java index a3f087f93ed25..5c5b3be3486ff 100644 --- a/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution.java +++ b/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution.java @@ -2,9 +2,13 @@ class Solution { public int maximumScore(int a, int b, int c) { int[] s = new int[] {a, b, c}; Arrays.sort(s); - if (s[0] + s[1] < s[2]) { - return s[0] + s[1]; + int ans = 0; + while (s[1] > 0) { + ++ans; + s[1]--; + s[2]--; + Arrays.sort(s); } - return (a + b + c) >> 1; + return ans; } } \ No newline at end of file diff --git a/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution.py b/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution.py index 6912a06eb7b77..5322f472cc1d7 100644 --- a/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution.py +++ b/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution.py @@ -1,6 +1,10 @@ class Solution: def maximumScore(self, a: int, b: int, c: int) -> int: - a, b, c = sorted([a, b, c]) - if a + b < c: - return a + b - return (a + b + c) >> 1 + s = sorted([a, b, c]) + ans = 0 + while s[1]: + ans += 1 + s[1] -= 1 + s[2] -= 1 + s.sort() + return ans diff --git a/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution2.cpp b/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution2.cpp new file mode 100644 index 0000000000000..8532abd5ad6fd --- /dev/null +++ b/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution2.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + int maximumScore(int a, int b, int c) { + vector s = {a, b, c}; + sort(s.begin(), s.end()); + if (s[0] + s[1] < s[2]) return s[0] + s[1]; + return (a + b + c) >> 1; + } +}; \ No newline at end of file diff --git a/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution2.go b/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution2.go new file mode 100644 index 0000000000000..c3e33a86118af --- /dev/null +++ b/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution2.go @@ -0,0 +1,8 @@ +func maximumScore(a int, b int, c int) int { + s := []int{a, b, c} + sort.Ints(s) + if s[0]+s[1] < s[2] { + return s[0] + s[1] + } + return (a + b + c) >> 1 +} \ No newline at end of file diff --git a/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution2.java b/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution2.java new file mode 100644 index 0000000000000..a3f087f93ed25 --- /dev/null +++ b/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution2.java @@ -0,0 +1,10 @@ +class Solution { + public int maximumScore(int a, int b, int c) { + int[] s = new int[] {a, b, c}; + Arrays.sort(s); + if (s[0] + s[1] < s[2]) { + return s[0] + s[1]; + } + return (a + b + c) >> 1; + } +} \ No newline at end of file diff --git a/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution2.py b/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution2.py new file mode 100644 index 0000000000000..6912a06eb7b77 --- /dev/null +++ b/solution/1700-1799/1753.Maximum Score From Removing Stones/Solution2.py @@ -0,0 +1,6 @@ +class Solution: + def maximumScore(self, a: int, b: int, c: int) -> int: + a, b, c = sorted([a, b, c]) + if a + b < c: + return a + b + return (a + b + c) >> 1 diff --git a/solution/1700-1799/1754.Largest Merge Of Two Strings/Solution.c b/solution/1700-1799/1754.Largest Merge Of Two Strings/Solution.c index 563def318208f..27b9250d6ad25 100644 --- a/solution/1700-1799/1754.Largest Merge Of Two Strings/Solution.c +++ b/solution/1700-1799/1754.Largest Merge Of Two Strings/Solution.c @@ -27,4 +27,4 @@ char* largestMerge(char* word1, char* word2) { } ans[m + n] = '\0'; return ans; -} +} \ No newline at end of file diff --git a/solution/1700-1799/1755.Closest Subsequence Sum/Solution.cpp b/solution/1700-1799/1755.Closest Subsequence Sum/Solution.cpp index 478b77949b97d..7495039907bb7 100644 --- a/solution/1700-1799/1755.Closest Subsequence Sum/Solution.cpp +++ b/solution/1700-1799/1755.Closest Subsequence Sum/Solution.cpp @@ -42,4 +42,4 @@ class Solution { dfs(nums, sum, i + 1, n, cur); dfs(nums, sum, i + 1, n, cur + nums[i]); } -}; +}; \ No newline at end of file diff --git a/solution/1700-1799/1755.Closest Subsequence Sum/Solution.java b/solution/1700-1799/1755.Closest Subsequence Sum/Solution.java index f1e4b7310b67b..eb9d82c537731 100644 --- a/solution/1700-1799/1755.Closest Subsequence Sum/Solution.java +++ b/solution/1700-1799/1755.Closest Subsequence Sum/Solution.java @@ -40,4 +40,4 @@ private void dfs(int[] nums, List sum, int i, int n, int cur) { dfs(nums, sum, i + 1, n, cur); dfs(nums, sum, i + 1, n, cur + nums[i]); } -} +} \ No newline at end of file diff --git a/solution/1700-1799/1755.Closest Subsequence Sum/Solution2.cpp b/solution/1700-1799/1755.Closest Subsequence Sum/Solution2.cpp new file mode 100644 index 0000000000000..33addf7c34cf9 --- /dev/null +++ b/solution/1700-1799/1755.Closest Subsequence Sum/Solution2.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int minAbsDifference(vector& nums, int goal) { + int n = nums.size(); + vector left; + vector right; + dfs(nums, left, 0, n >> 1, 0); + dfs(nums, right, n >> 1, n, 0); + sort(right.begin(), right.end()); + int ans = INT_MAX; + for (int x : left) { + int y = goal - x; + int idx = lower_bound(right.begin(), right.end(), y) - right.begin(); + if (idx < right.size()) ans = min(ans, abs(y - right[idx])); + if (idx) ans = min(ans, abs(y - right[idx - 1])); + } + return ans; + } + +private: + void dfs(vector& arr, vector& res, int i, int n, int s) { + if (i == n) { + res.emplace_back(s); + return; + } + dfs(arr, res, i + 1, n, s); + dfs(arr, res, i + 1, n, s + arr[i]); + } +}; \ No newline at end of file diff --git a/solution/1700-1799/1755.Closest Subsequence Sum/Solution2.go b/solution/1700-1799/1755.Closest Subsequence Sum/Solution2.go new file mode 100644 index 0000000000000..f3cfb0ff752d6 --- /dev/null +++ b/solution/1700-1799/1755.Closest Subsequence Sum/Solution2.go @@ -0,0 +1,44 @@ +func minAbsDifference(nums []int, goal int) int { + n := len(nums) + left := []int{} + right := []int{} + dfs(nums[:n>>1], &left, 0, 0) + dfs(nums[n>>1:], &right, 0, 0) + sort.Ints(right) + ans := math.MaxInt32 + for _, x := range left { + y := goal - x + l, r := 0, len(right) + for l < r { + mid := (l + r) >> 1 + if right[mid] >= y { + r = mid + } else { + l = mid + 1 + } + } + if l < len(right) { + ans = min(ans, abs(y-right[l])) + } + if l > 0 { + ans = min(ans, abs(y-right[l-1])) + } + } + return ans +} + +func dfs(arr []int, res *[]int, i, s int) { + if i == len(arr) { + *res = append(*res, s) + return + } + dfs(arr, res, i+1, s) + dfs(arr, res, i+1, s+arr[i]) +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} \ No newline at end of file diff --git a/solution/1700-1799/1755.Closest Subsequence Sum/Solution2.java b/solution/1700-1799/1755.Closest Subsequence Sum/Solution2.java new file mode 100644 index 0000000000000..404ea471626a4 --- /dev/null +++ b/solution/1700-1799/1755.Closest Subsequence Sum/Solution2.java @@ -0,0 +1,40 @@ +class Solution { + public int minAbsDifference(int[] nums, int goal) { + int n = nums.length; + Set left = new HashSet<>(); + Set right = new HashSet<>(); + dfs(nums, 0, n >> 1, 0, left); + dfs(nums, n >> 1, n, 0, right); + List rs = new ArrayList<>(right); + Collections.sort(rs); + int ans = Integer.MAX_VALUE; + for (int x : left) { + int y = goal - x; + int l = 0, r = rs.size(); + while (l < r) { + int mid = (l + r) >> 1; + if (rs.get(mid) >= y) { + r = mid; + } else { + l = mid + 1; + } + } + if (l < rs.size()) { + ans = Math.min(ans, Math.abs(y - rs.get(l))); + } + if (l > 0) { + ans = Math.min(ans, Math.abs(y - rs.get(l - 1))); + } + } + return ans; + } + + private void dfs(int[] arr, int i, int n, int s, Set res) { + if (i == n) { + res.add(s); + return; + } + dfs(arr, i + 1, n, s, res); + dfs(arr, i + 1, n, s + arr[i], res); + } +} \ No newline at end of file diff --git a/solution/1700-1799/1755.Closest Subsequence Sum/Solution2.py b/solution/1700-1799/1755.Closest Subsequence Sum/Solution2.py new file mode 100644 index 0000000000000..f18d16c43daec --- /dev/null +++ b/solution/1700-1799/1755.Closest Subsequence Sum/Solution2.py @@ -0,0 +1,23 @@ +class Solution: + def minAbsDifference(self, nums: List[int], goal: int) -> int: + def dfs(arr, res, i, s): + if i == len(arr): + res.add(s) + return + dfs(arr, res, i + 1, s) + dfs(arr, res, i + 1, s + arr[i]) + + n = len(nums) + left, right = set(), set() + dfs(nums[: n >> 1], left, 0, 0) + dfs(nums[n >> 1 :], right, 0, 0) + right = sorted(right) + ans = inf + for l in left: + x = goal - l + i = bisect_left(right, x) + if i < len(right): + ans = min(ans, abs(x - right[i])) + if i: + ans = min(ans, abs(x - right[i - 1])) + return ans diff --git a/solution/1700-1799/1756.Design Most Recently Used Queue/Solution.py b/solution/1700-1799/1756.Design Most Recently Used Queue/Solution.py index 15aa891afb592..e41d54d702f4c 100644 --- a/solution/1700-1799/1756.Design Most Recently Used Queue/Solution.py +++ b/solution/1700-1799/1756.Design Most Recently Used Queue/Solution.py @@ -1,38 +1,12 @@ -class BinaryIndexedTree: - def __init__(self, n: int): - self.n = n - self.c = [0] * (n + 1) - - def update(self, x: int, v: int): - while x <= self.n: - self.c[x] += v - x += x & -x - - def query(self, x: int) -> int: - s = 0 - while x: - s += self.c[x] - x -= x & -x - return s - - class MRUQueue: def __init__(self, n: int): - self.q = list(range(n + 1)) - self.tree = BinaryIndexedTree(n + 2010) + self.q = list(range(1, n + 1)) def fetch(self, k: int) -> int: - l, r = 1, len(self.q) - while l < r: - mid = (l + r) >> 1 - if mid - self.tree.query(mid) >= k: - r = mid - else: - l = mid + 1 - x = self.q[l] - self.q.append(x) - self.tree.update(l, 1) - return x + ans = self.q[k - 1] + self.q[k - 1 : k] = [] + self.q.append(ans) + return ans # Your MRUQueue object will be instantiated and called as such: diff --git a/solution/1700-1799/1756.Design Most Recently Used Queue/Solution2.py b/solution/1700-1799/1756.Design Most Recently Used Queue/Solution2.py new file mode 100644 index 0000000000000..15aa891afb592 --- /dev/null +++ b/solution/1700-1799/1756.Design Most Recently Used Queue/Solution2.py @@ -0,0 +1,40 @@ +class BinaryIndexedTree: + def __init__(self, n: int): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x: int, v: int): + while x <= self.n: + self.c[x] += v + x += x & -x + + def query(self, x: int) -> int: + s = 0 + while x: + s += self.c[x] + x -= x & -x + return s + + +class MRUQueue: + def __init__(self, n: int): + self.q = list(range(n + 1)) + self.tree = BinaryIndexedTree(n + 2010) + + def fetch(self, k: int) -> int: + l, r = 1, len(self.q) + while l < r: + mid = (l + r) >> 1 + if mid - self.tree.query(mid) >= k: + r = mid + else: + l = mid + 1 + x = self.q[l] + self.q.append(x) + self.tree.update(l, 1) + return x + + +# Your MRUQueue object will be instantiated and called as such: +# obj = MRUQueue(n) +# param_1 = obj.fetch(k) diff --git a/solution/1700-1799/1758.Minimum Changes To Make Alternating Binary String/Solution.c b/solution/1700-1799/1758.Minimum Changes To Make Alternating Binary String/Solution.c index af61516dedf26..0e7bb1a1458e4 100644 --- a/solution/1700-1799/1758.Minimum Changes To Make Alternating Binary String/Solution.c +++ b/solution/1700-1799/1758.Minimum Changes To Make Alternating Binary String/Solution.c @@ -7,4 +7,4 @@ int minOperations(char* s) { count += s[i] != ('0' + (i & 1)) ? 0 : 1; } return min(count, n - count); -} +} \ No newline at end of file diff --git a/solution/1700-1799/1759.Count Number of Homogenous Substrings/Solution.c b/solution/1700-1799/1759.Count Number of Homogenous Substrings/Solution.c index d6e0fa1e3c3bf..6bee5b6c43977 100644 --- a/solution/1700-1799/1759.Count Number of Homogenous Substrings/Solution.c +++ b/solution/1700-1799/1759.Count Number of Homogenous Substrings/Solution.c @@ -8,4 +8,4 @@ int countHomogenous(char* s) { ans = (ans + j - i + 1) % MOD; } return ans; -} +} \ No newline at end of file diff --git a/solution/1700-1799/1759.Count Number of Homogenous Substrings/Solution2.cpp b/solution/1700-1799/1759.Count Number of Homogenous Substrings/Solution2.cpp new file mode 100644 index 0000000000000..4c100db76d9af --- /dev/null +++ b/solution/1700-1799/1759.Count Number of Homogenous Substrings/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + const int mod = 1e9 + 7; + + int countHomogenous(string s) { + int n = s.size(); + int ans = 1, cnt = 1; + for (int i = 1; i < n; ++i) { + cnt = s[i] == s[i - 1] ? cnt + 1 : 1; + ans = (ans + cnt) % mod; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1700-1799/1759.Count Number of Homogenous Substrings/Solution2.go b/solution/1700-1799/1759.Count Number of Homogenous Substrings/Solution2.go new file mode 100644 index 0000000000000..f8f2eb924f6dc --- /dev/null +++ b/solution/1700-1799/1759.Count Number of Homogenous Substrings/Solution2.go @@ -0,0 +1,14 @@ +func countHomogenous(s string) int { + n := len(s) + const mod int = 1e9 + 7 + ans, cnt := 1, 1 + for i := 1; i < n; i++ { + if s[i] == s[i-1] { + cnt++ + } else { + cnt = 1 + } + ans = (ans + cnt) % mod + } + return ans +} \ No newline at end of file diff --git a/solution/1700-1799/1759.Count Number of Homogenous Substrings/Solution2.java b/solution/1700-1799/1759.Count Number of Homogenous Substrings/Solution2.java new file mode 100644 index 0000000000000..93c6168ee3b39 --- /dev/null +++ b/solution/1700-1799/1759.Count Number of Homogenous Substrings/Solution2.java @@ -0,0 +1,13 @@ +class Solution { + private static final int MOD = (int) 1e9 + 7; + + public int countHomogenous(String s) { + int n = s.length(); + int ans = 1, cnt = 1; + for (int i = 1; i < n; ++i) { + cnt = s.charAt(i) == s.charAt(i - 1) ? cnt + 1 : 1; + ans = (ans + cnt) % MOD; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1700-1799/1759.Count Number of Homogenous Substrings/Solution2.py b/solution/1700-1799/1759.Count Number of Homogenous Substrings/Solution2.py new file mode 100644 index 0000000000000..119b05662320d --- /dev/null +++ b/solution/1700-1799/1759.Count Number of Homogenous Substrings/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def countHomogenous(self, s: str) -> int: + mod = 10**9 + 7 + ans = cnt = 1 + for a, b in pairwise(s): + cnt = cnt + 1 if a == b else 1 + ans = (ans + cnt) % mod + return ans diff --git a/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/Solution.cpp b/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/Solution.cpp index 3d432bef77897..6423c68ddfa77 100644 --- a/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/Solution.cpp +++ b/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/Solution.cpp @@ -1,19 +1,19 @@ -class Solution { -public: - int minimumSize(vector& nums, int maxOperations) { - int left = 1, right = *max_element(nums.begin(), nums.end()); - while (left < right) { - int mid = (left + right) >> 1; - long long cnt = 0; - for (int x : nums) { - cnt += (x - 1) / mid; - } - if (cnt <= maxOperations) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - } +class Solution { +public: + int minimumSize(vector& nums, int maxOperations) { + int left = 1, right = *max_element(nums.begin(), nums.end()); + while (left < right) { + int mid = (left + right) >> 1; + long long cnt = 0; + for (int x : nums) { + cnt += (x - 1) / mid; + } + if (cnt <= maxOperations) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } }; \ No newline at end of file diff --git a/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/Solution.java b/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/Solution.java index 73a8917b68136..48aca93edbf71 100644 --- a/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/Solution.java +++ b/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/Solution.java @@ -1,21 +1,21 @@ -class Solution { - public int minimumSize(int[] nums, int maxOperations) { - int left = 1, right = 0; - for (int x : nums) { - right = Math.max(right, x); - } - while (left < right) { - int mid = (left + right) >> 1; - long cnt = 0; - for (int x : nums) { - cnt += (x - 1) / mid; - } - if (cnt <= maxOperations) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - } +class Solution { + public int minimumSize(int[] nums, int maxOperations) { + int left = 1, right = 0; + for (int x : nums) { + right = Math.max(right, x); + } + while (left < right) { + int mid = (left + right) >> 1; + long cnt = 0; + for (int x : nums) { + cnt += (x - 1) / mid; + } + if (cnt <= maxOperations) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } } \ No newline at end of file diff --git a/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/Solution.py b/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/Solution.py index 2fa605a331a4d..41c1224361eea 100644 --- a/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/Solution.py +++ b/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/Solution.py @@ -1,6 +1,6 @@ -class Solution: - def minimumSize(self, nums: List[int], maxOperations: int) -> int: - def check(mx: int) -> bool: - return sum((x - 1) // mx for x in nums) <= maxOperations - - return bisect_left(range(1, max(nums)), True, key=check) + 1 +class Solution: + def minimumSize(self, nums: List[int], maxOperations: int) -> int: + def check(mx: int) -> bool: + return sum((x - 1) // mx for x in nums) <= maxOperations + + return bisect_left(range(1, max(nums)), True, key=check) + 1 diff --git a/solution/1700-1799/1762.Buildings With an Ocean View/Solution.cpp b/solution/1700-1799/1762.Buildings With an Ocean View/Solution.cpp index bea5f6c9e632b..23af680e70190 100644 --- a/solution/1700-1799/1762.Buildings With an Ocean View/Solution.cpp +++ b/solution/1700-1799/1762.Buildings With an Ocean View/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - vector findBuildings(vector& heights) { - vector ans; - int mx = 0; - for (int i = heights.size() - 1; ~i; --i) { - if (heights[i] > mx) { - ans.push_back(i); - mx = heights[i]; - } - } - reverse(ans.begin(), ans.end()); - return ans; - } +class Solution { +public: + vector findBuildings(vector& heights) { + vector ans; + int mx = 0; + for (int i = heights.size() - 1; ~i; --i) { + if (heights[i] > mx) { + ans.push_back(i); + mx = heights[i]; + } + } + reverse(ans.begin(), ans.end()); + return ans; + } }; \ No newline at end of file diff --git a/solution/1700-1799/1762.Buildings With an Ocean View/Solution.java b/solution/1700-1799/1762.Buildings With an Ocean View/Solution.java index 245d6237a2bc7..c6977ca671b82 100644 --- a/solution/1700-1799/1762.Buildings With an Ocean View/Solution.java +++ b/solution/1700-1799/1762.Buildings With an Ocean View/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public int[] findBuildings(int[] heights) { - int n = heights.length; - List ans = new ArrayList<>(); - int mx = 0; - for (int i = heights.length - 1; i >= 0; --i) { - if (heights[i] > mx) { - ans.add(i); - mx = heights[i]; - } - } - Collections.reverse(ans); - return ans.stream().mapToInt(Integer::intValue).toArray(); - } +class Solution { + public int[] findBuildings(int[] heights) { + int n = heights.length; + List ans = new ArrayList<>(); + int mx = 0; + for (int i = heights.length - 1; i >= 0; --i) { + if (heights[i] > mx) { + ans.add(i); + mx = heights[i]; + } + } + Collections.reverse(ans); + return ans.stream().mapToInt(Integer::intValue).toArray(); + } } \ No newline at end of file diff --git a/solution/1700-1799/1762.Buildings With an Ocean View/Solution.py b/solution/1700-1799/1762.Buildings With an Ocean View/Solution.py index 2c0ed5aec0375..a1012e0752998 100644 --- a/solution/1700-1799/1762.Buildings With an Ocean View/Solution.py +++ b/solution/1700-1799/1762.Buildings With an Ocean View/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def findBuildings(self, heights: List[int]) -> List[int]: - ans = [] - mx = 0 - for i in range(len(heights) - 1, -1, -1): - if heights[i] > mx: - ans.append(i) - mx = heights[i] - return ans[::-1] +class Solution: + def findBuildings(self, heights: List[int]) -> List[int]: + ans = [] + mx = 0 + for i in range(len(heights) - 1, -1, -1): + if heights[i] > mx: + ans.append(i) + mx = heights[i] + return ans[::-1] diff --git a/solution/1700-1799/1763.Longest Nice Substring/Solution.cpp b/solution/1700-1799/1763.Longest Nice Substring/Solution.cpp index 7b344252441b6..4db111c562f3c 100644 --- a/solution/1700-1799/1763.Longest Nice Substring/Solution.cpp +++ b/solution/1700-1799/1763.Longest Nice Substring/Solution.cpp @@ -4,14 +4,18 @@ class Solution { int n = s.size(); int k = -1, mx = 0; for (int i = 0; i < n; ++i) { - int lower = 0, upper = 0; + unordered_set ss; for (int j = i; j < n; ++j) { - char c = s[j]; - if (islower(c)) - lower |= 1 << (c - 'a'); - else - upper |= 1 << (c - 'A'); - if (lower == upper && mx < j - i + 1) { + ss.insert(s[j]); + bool ok = true; + for (auto& a : ss) { + char b = a ^ 32; + if (!(ss.count(a) && ss.count(b))) { + ok = false; + break; + } + } + if (ok && mx < j - i + 1) { mx = j - i + 1; k = i; } diff --git a/solution/1700-1799/1763.Longest Nice Substring/Solution.go b/solution/1700-1799/1763.Longest Nice Substring/Solution.go index 7c47280a0249e..ffbea9569569e 100644 --- a/solution/1700-1799/1763.Longest Nice Substring/Solution.go +++ b/solution/1700-1799/1763.Longest Nice Substring/Solution.go @@ -2,14 +2,18 @@ func longestNiceSubstring(s string) string { n := len(s) k, mx := -1, 0 for i := 0; i < n; i++ { - var lower, upper int + ss := map[byte]bool{} for j := i; j < n; j++ { - if unicode.IsLower(rune(s[j])) { - lower |= 1 << (s[j] - 'a') - } else { - upper |= 1 << (s[j] - 'A') + ss[s[j]] = true + ok := true + for a := range ss { + b := a ^ 32 + if !(ss[a] && ss[b]) { + ok = false + break + } } - if lower == upper && mx < j-i+1 { + if ok && mx < j-i+1 { mx = j - i + 1 k = i } diff --git a/solution/1700-1799/1763.Longest Nice Substring/Solution.java b/solution/1700-1799/1763.Longest Nice Substring/Solution.java index 9e7460e2f1601..b4905008c6606 100644 --- a/solution/1700-1799/1763.Longest Nice Substring/Solution.java +++ b/solution/1700-1799/1763.Longest Nice Substring/Solution.java @@ -4,15 +4,18 @@ public String longestNiceSubstring(String s) { int k = -1; int mx = 0; for (int i = 0; i < n; ++i) { - int lower = 0, upper = 0; + Set ss = new HashSet<>(); for (int j = i; j < n; ++j) { - char c = s.charAt(j); - if (Character.isLowerCase(c)) { - lower |= 1 << (c - 'a'); - } else { - upper |= 1 << (c - 'A'); + ss.add(s.charAt(j)); + boolean ok = true; + for (char a : ss) { + char b = (char) (a ^ 32); + if (!(ss.contains(a) && ss.contains(b))) { + ok = false; + break; + } } - if (lower == upper && mx < j - i + 1) { + if (ok && mx < j - i + 1) { mx = j - i + 1; k = i; } diff --git a/solution/1700-1799/1763.Longest Nice Substring/Solution.py b/solution/1700-1799/1763.Longest Nice Substring/Solution.py index 165ae774e3015..df5c70131e79b 100644 --- a/solution/1700-1799/1763.Longest Nice Substring/Solution.py +++ b/solution/1700-1799/1763.Longest Nice Substring/Solution.py @@ -3,12 +3,12 @@ def longestNiceSubstring(self, s: str) -> str: n = len(s) ans = '' for i in range(n): - lower = upper = 0 + ss = set() for j in range(i, n): - if s[j].islower(): - lower |= 1 << (ord(s[j]) - ord('a')) - else: - upper |= 1 << (ord(s[j]) - ord('A')) - if lower == upper and len(ans) < j - i + 1: + ss.add(s[j]) + if ( + all(c.lower() in ss and c.upper() in ss for c in ss) + and len(ans) < j - i + 1 + ): ans = s[i : j + 1] return ans diff --git a/solution/1700-1799/1763.Longest Nice Substring/Solution2.cpp b/solution/1700-1799/1763.Longest Nice Substring/Solution2.cpp new file mode 100644 index 0000000000000..7b344252441b6 --- /dev/null +++ b/solution/1700-1799/1763.Longest Nice Substring/Solution2.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + string longestNiceSubstring(string s) { + int n = s.size(); + int k = -1, mx = 0; + for (int i = 0; i < n; ++i) { + int lower = 0, upper = 0; + for (int j = i; j < n; ++j) { + char c = s[j]; + if (islower(c)) + lower |= 1 << (c - 'a'); + else + upper |= 1 << (c - 'A'); + if (lower == upper && mx < j - i + 1) { + mx = j - i + 1; + k = i; + } + } + } + return k == -1 ? "" : s.substr(k, mx); + } +}; \ No newline at end of file diff --git a/solution/1700-1799/1763.Longest Nice Substring/Solution2.go b/solution/1700-1799/1763.Longest Nice Substring/Solution2.go new file mode 100644 index 0000000000000..7c47280a0249e --- /dev/null +++ b/solution/1700-1799/1763.Longest Nice Substring/Solution2.go @@ -0,0 +1,22 @@ +func longestNiceSubstring(s string) string { + n := len(s) + k, mx := -1, 0 + for i := 0; i < n; i++ { + var lower, upper int + for j := i; j < n; j++ { + if unicode.IsLower(rune(s[j])) { + lower |= 1 << (s[j] - 'a') + } else { + upper |= 1 << (s[j] - 'A') + } + if lower == upper && mx < j-i+1 { + mx = j - i + 1 + k = i + } + } + } + if k < 0 { + return "" + } + return s[k : k+mx] +} \ No newline at end of file diff --git a/solution/1700-1799/1763.Longest Nice Substring/Solution2.java b/solution/1700-1799/1763.Longest Nice Substring/Solution2.java new file mode 100644 index 0000000000000..9e7460e2f1601 --- /dev/null +++ b/solution/1700-1799/1763.Longest Nice Substring/Solution2.java @@ -0,0 +1,23 @@ +class Solution { + public String longestNiceSubstring(String s) { + int n = s.length(); + int k = -1; + int mx = 0; + for (int i = 0; i < n; ++i) { + int lower = 0, upper = 0; + for (int j = i; j < n; ++j) { + char c = s.charAt(j); + if (Character.isLowerCase(c)) { + lower |= 1 << (c - 'a'); + } else { + upper |= 1 << (c - 'A'); + } + if (lower == upper && mx < j - i + 1) { + mx = j - i + 1; + k = i; + } + } + } + return k == -1 ? "" : s.substring(k, k + mx); + } +} \ No newline at end of file diff --git a/solution/1700-1799/1763.Longest Nice Substring/Solution2.py b/solution/1700-1799/1763.Longest Nice Substring/Solution2.py new file mode 100644 index 0000000000000..165ae774e3015 --- /dev/null +++ b/solution/1700-1799/1763.Longest Nice Substring/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def longestNiceSubstring(self, s: str) -> str: + n = len(s) + ans = '' + for i in range(n): + lower = upper = 0 + for j in range(i, n): + if s[j].islower(): + lower |= 1 << (ord(s[j]) - ord('a')) + else: + upper |= 1 << (ord(s[j]) - ord('A')) + if lower == upper and len(ans) < j - i + 1: + ans = s[i : j + 1] + return ans diff --git a/solution/1700-1799/1765.Map of Highest Peak/Solution2.cpp b/solution/1700-1799/1765.Map of Highest Peak/Solution2.cpp new file mode 100644 index 0000000000000..c3b514c60b530 --- /dev/null +++ b/solution/1700-1799/1765.Map of Highest Peak/Solution2.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + const int dirs[5] = {-1, 0, 1, 0, -1}; + + vector> highestPeak(vector>& isWater) { + int m = isWater.size(), n = isWater[0].size(); + vector> ans(m, vector(n)); + queue> q; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans[i][j] = isWater[i][j] - 1; + if (ans[i][j] == 0) { + q.emplace(i, j); + } + } + } + while (!q.empty()) { + for (int t = q.size(); t; --t) { + auto [i, j] = q.front(); + q.pop(); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1) { + ans[x][y] = ans[i][j] + 1; + q.emplace(x, y); + } + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1700-1799/1765.Map of Highest Peak/Solution2.go b/solution/1700-1799/1765.Map of Highest Peak/Solution2.go new file mode 100644 index 0000000000000..66b55a0f90adc --- /dev/null +++ b/solution/1700-1799/1765.Map of Highest Peak/Solution2.go @@ -0,0 +1,31 @@ +func highestPeak(isWater [][]int) [][]int { + m, n := len(isWater), len(isWater[0]) + ans := make([][]int, m) + type pair struct{ i, j int } + q := []pair{} + for i, row := range isWater { + ans[i] = make([]int, n) + for j, v := range row { + ans[i][j] = v - 1 + if v == 1 { + q = append(q, pair{i, j}) + } + } + } + dirs := []int{-1, 0, 1, 0, -1} + for len(q) > 0 { + for t := len(q); t > 0; t-- { + p := q[0] + q = q[1:] + i, j := p.i, p.j + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1 { + ans[x][y] = ans[i][j] + 1 + q = append(q, pair{x, y}) + } + } + } + } + return ans +} \ No newline at end of file diff --git a/solution/1700-1799/1765.Map of Highest Peak/Solution2.java b/solution/1700-1799/1765.Map of Highest Peak/Solution2.java new file mode 100644 index 0000000000000..56e8a2140cad7 --- /dev/null +++ b/solution/1700-1799/1765.Map of Highest Peak/Solution2.java @@ -0,0 +1,30 @@ +class Solution { + public int[][] highestPeak(int[][] isWater) { + int m = isWater.length, n = isWater[0].length; + int[][] ans = new int[m][n]; + Deque q = new ArrayDeque<>(); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans[i][j] = isWater[i][j] - 1; + if (ans[i][j] == 0) { + q.offer(new int[] {i, j}); + } + } + } + int[] dirs = {-1, 0, 1, 0, -1}; + while (!q.isEmpty()) { + for (int t = q.size(); t > 0; --t) { + var p = q.poll(); + int i = p[0], j = p[1]; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1) { + ans[x][y] = ans[i][j] + 1; + q.offer(new int[] {x, y}); + } + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1700-1799/1765.Map of Highest Peak/Solution2.py b/solution/1700-1799/1765.Map of Highest Peak/Solution2.py new file mode 100644 index 0000000000000..ffb1c102cb0fc --- /dev/null +++ b/solution/1700-1799/1765.Map of Highest Peak/Solution2.py @@ -0,0 +1,19 @@ +class Solution: + def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: + m, n = len(isWater), len(isWater[0]) + ans = [[-1] * n for _ in range(m)] + q = deque() + for i, row in enumerate(isWater): + for j, v in enumerate(row): + if v: + q.append((i, j)) + ans[i][j] = 0 + while q: + for _ in range(len(q)): + i, j = q.popleft() + for a, b in pairwise((-1, 0, 1, 0, -1)): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n and ans[x][y] == -1: + ans[x][y] = ans[i][j] + 1 + q.append((x, y)) + return ans diff --git a/solution/1700-1799/1768.Merge Strings Alternately/Solution.c b/solution/1700-1799/1768.Merge Strings Alternately/Solution.c index b1b1e77a880e7..1d308d48b2b56 100644 --- a/solution/1700-1799/1768.Merge Strings Alternately/Solution.c +++ b/solution/1700-1799/1768.Merge Strings Alternately/Solution.c @@ -16,4 +16,4 @@ char* mergeAlternately(char* word1, char* word2) { } ans[n + m] = '\0'; return ans; -} +} \ No newline at end of file diff --git a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.c b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.c index 9c7f847fb2ed5..a5faea1ef88e3 100644 --- a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.c +++ b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.c @@ -3,21 +3,28 @@ */ int* minOperations(char* boxes, int* returnSize) { int n = strlen(boxes); - int* ans = malloc(sizeof(int) * n); - memset(ans, 0, sizeof(int) * n); + int* left = malloc(sizeof(int) * n); + int* right = malloc(sizeof(int) * n); + memset(left, 0, sizeof(int) * n); + memset(right, 0, sizeof(int) * n); for (int i = 1, count = 0; i < n; i++) { if (boxes[i - 1] == '1') { count++; } - ans[i] = ans[i - 1] + count; + left[i] = left[i - 1] + count; } - for (int i = n - 2, count = 0, sum = 0; i >= 0; i--) { + for (int i = n - 2, count = 0; i >= 0; i--) { if (boxes[i + 1] == '1') { count++; } - sum += count; - ans[i] += sum; + right[i] = right[i + 1] + count; + } + int* ans = malloc(sizeof(int) * n); + for (int i = 0; i < n; i++) { + ans[i] = left[i] + right[i]; } + free(left); + free(right); *returnSize = n; return ans; -} +} \ No newline at end of file diff --git a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.cpp b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.cpp index aa3a8658a4bd2..a7fdf3a10b137 100644 --- a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.cpp +++ b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.cpp @@ -2,16 +2,20 @@ class Solution { public: vector minOperations(string boxes) { int n = boxes.size(); - vector ans(n); + int left[n]; + int right[n]; + memset(left, 0, sizeof left); + memset(right, 0, sizeof right); for (int i = 1, cnt = 0; i < n; ++i) { cnt += boxes[i - 1] == '1'; - ans[i] = ans[i - 1] + cnt; + left[i] = left[i - 1] + cnt; } - for (int i = n - 2, cnt = 0, s = 0; ~i; --i) { + for (int i = n - 2, cnt = 0; ~i; --i) { cnt += boxes[i + 1] == '1'; - s += cnt; - ans[i] += s; + right[i] = right[i + 1] + cnt; } + vector ans(n); + for (int i = 0; i < n; ++i) ans[i] = left[i] + right[i]; return ans; } }; \ No newline at end of file diff --git a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.go b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.go index 59a2b01b021e5..6607456e1ed2c 100644 --- a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.go +++ b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.go @@ -1,18 +1,22 @@ func minOperations(boxes string) []int { n := len(boxes) - ans := make([]int, n) + left := make([]int, n) + right := make([]int, n) for i, cnt := 1, 0; i < n; i++ { if boxes[i-1] == '1' { cnt++ } - ans[i] = ans[i-1] + cnt + left[i] = left[i-1] + cnt } - for i, cnt, s := n-2, 0, 0; i >= 0; i-- { + for i, cnt := n-2, 0; i >= 0; i-- { if boxes[i+1] == '1' { cnt++ } - s += cnt - ans[i] += s + right[i] = right[i+1] + cnt + } + ans := make([]int, n) + for i := range ans { + ans[i] = left[i] + right[i] } return ans } \ No newline at end of file diff --git a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.java b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.java index be685e82f04df..faeff8552bb05 100644 --- a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.java +++ b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.java @@ -1,19 +1,23 @@ class Solution { public int[] minOperations(String boxes) { int n = boxes.length(); - int[] ans = new int[n]; + int[] left = new int[n]; + int[] right = new int[n]; for (int i = 1, cnt = 0; i < n; ++i) { if (boxes.charAt(i - 1) == '1') { ++cnt; } - ans[i] = ans[i - 1] + cnt; + left[i] = left[i - 1] + cnt; } - for (int i = n - 2, cnt = 0, s = 0; i >= 0; --i) { + for (int i = n - 2, cnt = 0; i >= 0; --i) { if (boxes.charAt(i + 1) == '1') { ++cnt; } - s += cnt; - ans[i] += s; + right[i] = right[i + 1] + cnt; + } + int[] ans = new int[n]; + for (int i = 0; i < n; ++i) { + ans[i] = left[i] + right[i]; } return ans; } diff --git a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.py b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.py index 0421cd991637c..1bf6018c27076 100644 --- a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.py +++ b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.py @@ -1,16 +1,16 @@ class Solution: def minOperations(self, boxes: str) -> List[int]: n = len(boxes) - ans = [0] * n + left = [0] * n + right = [0] * n cnt = 0 for i in range(1, n): if boxes[i - 1] == '1': cnt += 1 - ans[i] = ans[i - 1] + cnt - cnt = s = 0 + left[i] = left[i - 1] + cnt + cnt = 0 for i in range(n - 2, -1, -1): if boxes[i + 1] == '1': cnt += 1 - s += cnt - ans[i] += s - return ans + right[i] = right[i + 1] + cnt + return [a + b for a, b in zip(left, right)] diff --git a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.rs b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.rs index dcfc3c5d3ae6a..93df3b2e2f96e 100644 --- a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.rs +++ b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.rs @@ -2,23 +2,25 @@ impl Solution { pub fn min_operations(boxes: String) -> Vec { let s = boxes.as_bytes(); let n = s.len(); - let mut ans = vec![0; n]; + let mut left = vec![0; n]; + let mut right = vec![0; n]; let mut count = 0; for i in 1..n { if s[i - 1] == b'1' { count += 1; } - ans[i] = ans[i - 1] + count; + left[i] = left[i - 1] + count; } - let mut sum = 0; count = 0; for i in (0..n - 1).rev() { if s[i + 1] == b'1' { count += 1; } - sum += count; - ans[i] += sum; + right[i] = right[i + 1] + count; } - ans + (0..n) + .into_iter() + .map(|i| left[i] + right[i]) + .collect() } } diff --git a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.ts b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.ts index 4cf2fca4075fe..7da00488fe562 100644 --- a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.ts +++ b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution.ts @@ -1,18 +1,18 @@ function minOperations(boxes: string): number[] { const n = boxes.length; - const ans = new Array(n).fill(0); + const left = new Array(n).fill(0); + const right = new Array(n).fill(0); for (let i = 1, count = 0; i < n; i++) { - if (boxes[i - 1] === '1') { + if (boxes[i - 1] == '1') { count++; } - ans[i] = ans[i - 1] + count; + left[i] = left[i - 1] + count; } - for (let i = n - 2, count = 0, sum = 0; i >= 0; i--) { - if (boxes[i + 1] === '1') { + for (let i = n - 2, count = 0; i >= 0; i--) { + if (boxes[i + 1] == '1') { count++; } - sum += count; - ans[i] += sum; + right[i] = right[i + 1] + count; } - return ans; + return left.map((v, i) => v + right[i]); } diff --git a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.c b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.c new file mode 100644 index 0000000000000..6fbc17658d79a --- /dev/null +++ b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.c @@ -0,0 +1,23 @@ +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +int* minOperations(char* boxes, int* returnSize) { + int n = strlen(boxes); + int* ans = malloc(sizeof(int) * n); + memset(ans, 0, sizeof(int) * n); + for (int i = 1, count = 0; i < n; i++) { + if (boxes[i - 1] == '1') { + count++; + } + ans[i] = ans[i - 1] + count; + } + for (int i = n - 2, count = 0, sum = 0; i >= 0; i--) { + if (boxes[i + 1] == '1') { + count++; + } + sum += count; + ans[i] += sum; + } + *returnSize = n; + return ans; +} \ No newline at end of file diff --git a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.cpp b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.cpp new file mode 100644 index 0000000000000..aa3a8658a4bd2 --- /dev/null +++ b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector minOperations(string boxes) { + int n = boxes.size(); + vector ans(n); + for (int i = 1, cnt = 0; i < n; ++i) { + cnt += boxes[i - 1] == '1'; + ans[i] = ans[i - 1] + cnt; + } + for (int i = n - 2, cnt = 0, s = 0; ~i; --i) { + cnt += boxes[i + 1] == '1'; + s += cnt; + ans[i] += s; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.go b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.go new file mode 100644 index 0000000000000..59a2b01b021e5 --- /dev/null +++ b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.go @@ -0,0 +1,18 @@ +func minOperations(boxes string) []int { + n := len(boxes) + ans := make([]int, n) + for i, cnt := 1, 0; i < n; i++ { + if boxes[i-1] == '1' { + cnt++ + } + ans[i] = ans[i-1] + cnt + } + for i, cnt, s := n-2, 0, 0; i >= 0; i-- { + if boxes[i+1] == '1' { + cnt++ + } + s += cnt + ans[i] += s + } + return ans +} \ No newline at end of file diff --git a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.java b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.java new file mode 100644 index 0000000000000..be685e82f04df --- /dev/null +++ b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.java @@ -0,0 +1,20 @@ +class Solution { + public int[] minOperations(String boxes) { + int n = boxes.length(); + int[] ans = new int[n]; + for (int i = 1, cnt = 0; i < n; ++i) { + if (boxes.charAt(i - 1) == '1') { + ++cnt; + } + ans[i] = ans[i - 1] + cnt; + } + for (int i = n - 2, cnt = 0, s = 0; i >= 0; --i) { + if (boxes.charAt(i + 1) == '1') { + ++cnt; + } + s += cnt; + ans[i] += s; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.py b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.py new file mode 100644 index 0000000000000..0421cd991637c --- /dev/null +++ b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.py @@ -0,0 +1,16 @@ +class Solution: + def minOperations(self, boxes: str) -> List[int]: + n = len(boxes) + ans = [0] * n + cnt = 0 + for i in range(1, n): + if boxes[i - 1] == '1': + cnt += 1 + ans[i] = ans[i - 1] + cnt + cnt = s = 0 + for i in range(n - 2, -1, -1): + if boxes[i + 1] == '1': + cnt += 1 + s += cnt + ans[i] += s + return ans diff --git a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.rs b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.rs new file mode 100644 index 0000000000000..dcfc3c5d3ae6a --- /dev/null +++ b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn min_operations(boxes: String) -> Vec { + let s = boxes.as_bytes(); + let n = s.len(); + let mut ans = vec![0; n]; + let mut count = 0; + for i in 1..n { + if s[i - 1] == b'1' { + count += 1; + } + ans[i] = ans[i - 1] + count; + } + let mut sum = 0; + count = 0; + for i in (0..n - 1).rev() { + if s[i + 1] == b'1' { + count += 1; + } + sum += count; + ans[i] += sum; + } + ans + } +} diff --git a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.ts b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.ts new file mode 100644 index 0000000000000..4cf2fca4075fe --- /dev/null +++ b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.ts @@ -0,0 +1,18 @@ +function minOperations(boxes: string): number[] { + const n = boxes.length; + const ans = new Array(n).fill(0); + for (let i = 1, count = 0; i < n; i++) { + if (boxes[i - 1] === '1') { + count++; + } + ans[i] = ans[i - 1] + count; + } + for (let i = n - 2, count = 0, sum = 0; i >= 0; i--) { + if (boxes[i + 1] === '1') { + count++; + } + sum += count; + ans[i] += sum; + } + return ans; +} diff --git a/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution.cpp b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution.cpp index 257b1138a143a..3a37df7740423 100644 --- a/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution.cpp +++ b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution.cpp @@ -1,25 +1,17 @@ class Solution { public: int maximumScore(vector& nums, vector& multipliers) { - const int inf = 1 << 30; int n = nums.size(), m = multipliers.size(); - vector> f(m + 1, vector(m + 1, -inf)); - f[0][0] = 0; - int ans = -inf; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= m - i; ++j) { - int k = i + j - 1; - if (i > 0) { - f[i][j] = max(f[i][j], f[i - 1][j] + multipliers[k] * nums[i - 1]); - } - if (j > 0) { - f[i][j] = max(f[i][j], f[i][j - 1] + multipliers[k] * nums[n - j]); - } - if (i + j == m) { - ans = max(ans, f[i][j]); - } - } - } - return ans; + int f[m][m]; + memset(f, 0x3f, sizeof f); + function dfs = [&](int i, int j) -> int { + if (i >= m || j >= m || (i + j) >= m) return 0; + if (f[i][j] != 0x3f3f3f3f) return f[i][j]; + int k = i + j; + int a = dfs(i + 1, j) + nums[i] * multipliers[k]; + int b = dfs(i, j + 1) + nums[n - j - 1] * multipliers[k]; + return f[i][j] = max(a, b); + }; + return dfs(0, 0); } }; \ No newline at end of file diff --git a/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution.go b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution.go index 26b09829f439f..928dbb0ec97c1 100644 --- a/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution.go +++ b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution.go @@ -1,28 +1,25 @@ func maximumScore(nums []int, multipliers []int) int { - const inf int = 1 << 30 n, m := len(nums), len(multipliers) - f := make([][]int, m+1) + f := make([][]int, m) for i := range f { - f[i] = make([]int, m+1) - for j := range f { - f[i][j] = -inf + f[i] = make([]int, m) + for j := range f[i] { + f[i][j] = 1 << 30 } } - f[0][0] = 0 - ans := -inf - for i := 0; i <= m; i++ { - for j := 0; j <= m-i; j++ { - k := i + j - 1 - if i > 0 { - f[i][j] = max(f[i][j], f[i-1][j]+multipliers[k]*nums[i-1]) - } - if j > 0 { - f[i][j] = max(f[i][j], f[i][j-1]+multipliers[k]*nums[n-j]) - } - if i+j == m { - ans = max(ans, f[i][j]) - } + var dfs func(i, j int) int + dfs = func(i, j int) int { + if i >= m || j >= m || i+j >= m { + return 0 } + if f[i][j] != 1<<30 { + return f[i][j] + } + k := i + j + a := dfs(i+1, j) + nums[i]*multipliers[k] + b := dfs(i, j+1) + nums[n-j-1]*multipliers[k] + f[i][j] = max(a, b) + return f[i][j] } - return ans + return dfs(0, 0) } \ No newline at end of file diff --git a/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution.java b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution.java index aa8f84feb50b0..33f1046e3b855 100644 --- a/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution.java +++ b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution.java @@ -1,27 +1,30 @@ class Solution { + private Integer[][] f; + private int[] multipliers; + private int[] nums; + private int n; + private int m; + public int maximumScore(int[] nums, int[] multipliers) { - final int inf = 1 << 30; - int n = nums.length, m = multipliers.length; - int[][] f = new int[m + 1][m + 1]; - for (int i = 0; i <= m; i++) { - Arrays.fill(f[i], -inf); + n = nums.length; + m = multipliers.length; + f = new Integer[m][m]; + this.nums = nums; + this.multipliers = multipliers; + return dfs(0, 0); + } + + private int dfs(int i, int j) { + if (i >= m || j >= m || (i + j) >= m) { + return 0; } - f[0][0] = 0; - int ans = -inf; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= m - i; ++j) { - int k = i + j - 1; - if (i > 0) { - f[i][j] = Math.max(f[i][j], f[i - 1][j] + multipliers[k] * nums[i - 1]); - } - if (j > 0) { - f[i][j] = Math.max(f[i][j], f[i][j - 1] + multipliers[k] * nums[n - j]); - } - if (i + j == m) { - ans = Math.max(ans, f[i][j]); - } - } + if (f[i][j] != null) { + return f[i][j]; } - return ans; + int k = i + j; + int a = dfs(i + 1, j) + nums[i] * multipliers[k]; + int b = dfs(i, j + 1) + nums[n - 1 - j] * multipliers[k]; + f[i][j] = Math.max(a, b); + return f[i][j]; } } \ No newline at end of file diff --git a/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution.py b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution.py index 3e392c5779f46..f66032fefc060 100644 --- a/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution.py +++ b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution.py @@ -1,16 +1,13 @@ class Solution: def maximumScore(self, nums: List[int], multipliers: List[int]) -> int: - n, m = len(nums), len(multipliers) - f = [[-inf] * (m + 1) for _ in range(m + 1)] - f[0][0] = 0 - ans = -inf - for i in range(m + 1): - for j in range(m - i + 1): - k = i + j - 1 - if i > 0: - f[i][j] = max(f[i][j], f[i - 1][j] + multipliers[k] * nums[i - 1]) - if j > 0: - f[i][j] = max(f[i][j], f[i][j - 1] + multipliers[k] * nums[n - j]) - if i + j == m: - ans = max(ans, f[i][j]) - return ans + @cache + def f(i, j, k): + if k >= m or i >= n or j < 0: + return 0 + a = f(i + 1, j, k + 1) + nums[i] * multipliers[k] + b = f(i, j - 1, k + 1) + nums[j] * multipliers[k] + return max(a, b) + + n = len(nums) + m = len(multipliers) + return f(0, n - 1, 0) diff --git a/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution2.cpp b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution2.cpp new file mode 100644 index 0000000000000..257b1138a143a --- /dev/null +++ b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution2.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int maximumScore(vector& nums, vector& multipliers) { + const int inf = 1 << 30; + int n = nums.size(), m = multipliers.size(); + vector> f(m + 1, vector(m + 1, -inf)); + f[0][0] = 0; + int ans = -inf; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= m - i; ++j) { + int k = i + j - 1; + if (i > 0) { + f[i][j] = max(f[i][j], f[i - 1][j] + multipliers[k] * nums[i - 1]); + } + if (j > 0) { + f[i][j] = max(f[i][j], f[i][j - 1] + multipliers[k] * nums[n - j]); + } + if (i + j == m) { + ans = max(ans, f[i][j]); + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution2.go b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution2.go new file mode 100644 index 0000000000000..26b09829f439f --- /dev/null +++ b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution2.go @@ -0,0 +1,28 @@ +func maximumScore(nums []int, multipliers []int) int { + const inf int = 1 << 30 + n, m := len(nums), len(multipliers) + f := make([][]int, m+1) + for i := range f { + f[i] = make([]int, m+1) + for j := range f { + f[i][j] = -inf + } + } + f[0][0] = 0 + ans := -inf + for i := 0; i <= m; i++ { + for j := 0; j <= m-i; j++ { + k := i + j - 1 + if i > 0 { + f[i][j] = max(f[i][j], f[i-1][j]+multipliers[k]*nums[i-1]) + } + if j > 0 { + f[i][j] = max(f[i][j], f[i][j-1]+multipliers[k]*nums[n-j]) + } + if i+j == m { + ans = max(ans, f[i][j]) + } + } + } + return ans +} \ No newline at end of file diff --git a/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution2.java b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution2.java new file mode 100644 index 0000000000000..aa8f84feb50b0 --- /dev/null +++ b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution2.java @@ -0,0 +1,27 @@ +class Solution { + public int maximumScore(int[] nums, int[] multipliers) { + final int inf = 1 << 30; + int n = nums.length, m = multipliers.length; + int[][] f = new int[m + 1][m + 1]; + for (int i = 0; i <= m; i++) { + Arrays.fill(f[i], -inf); + } + f[0][0] = 0; + int ans = -inf; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= m - i; ++j) { + int k = i + j - 1; + if (i > 0) { + f[i][j] = Math.max(f[i][j], f[i - 1][j] + multipliers[k] * nums[i - 1]); + } + if (j > 0) { + f[i][j] = Math.max(f[i][j], f[i][j - 1] + multipliers[k] * nums[n - j]); + } + if (i + j == m) { + ans = Math.max(ans, f[i][j]); + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution2.py b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution2.py new file mode 100644 index 0000000000000..3e392c5779f46 --- /dev/null +++ b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/Solution2.py @@ -0,0 +1,16 @@ +class Solution: + def maximumScore(self, nums: List[int], multipliers: List[int]) -> int: + n, m = len(nums), len(multipliers) + f = [[-inf] * (m + 1) for _ in range(m + 1)] + f[0][0] = 0 + ans = -inf + for i in range(m + 1): + for j in range(m - i + 1): + k = i + j - 1 + if i > 0: + f[i][j] = max(f[i][j], f[i - 1][j] + multipliers[k] * nums[i - 1]) + if j > 0: + f[i][j] = max(f[i][j], f[i][j - 1] + multipliers[k] * nums[n - j]) + if i + j == m: + ans = max(ans, f[i][j]) + return ans diff --git a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.py b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.py index 9980153e69e14..a60463b258c17 100644 --- a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.py +++ b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.py @@ -1,17 +1,17 @@ -class Solution: - def longestPalindrome(self, word1: str, word2: str) -> int: - s = word1 + word2 - n = len(s) - f = [[0] * n for _ in range(n)] - for i in range(n): - f[i][i] = 1 - ans = 0 - for i in range(n - 2, -1, -1): - for j in range(i + 1, n): - if s[i] == s[j]: - f[i][j] = f[i + 1][j - 1] + 2 - if i < len(word1) <= j: - ans = max(ans, f[i][j]) - else: - f[i][j] = max(f[i + 1][j], f[i][j - 1]) - return ans +class Solution: + def longestPalindrome(self, word1: str, word2: str) -> int: + s = word1 + word2 + n = len(s) + f = [[0] * n for _ in range(n)] + for i in range(n): + f[i][i] = 1 + ans = 0 + for i in range(n - 2, -1, -1): + for j in range(i + 1, n): + if s[i] == s[j]: + f[i][j] = f[i + 1][j - 1] + 2 + if i < len(word1) <= j: + ans = max(ans, f[i][j]) + else: + f[i][j] = max(f[i + 1][j], f[i][j - 1]) + return ans diff --git a/solution/1700-1799/1772.Sort Features by Popularity/Solution.cpp b/solution/1700-1799/1772.Sort Features by Popularity/Solution.cpp index dba4a4c39152e..acd088a171aa7 100644 --- a/solution/1700-1799/1772.Sort Features by Popularity/Solution.cpp +++ b/solution/1700-1799/1772.Sort Features by Popularity/Solution.cpp @@ -1,29 +1,29 @@ -class Solution { -public: - vector sortFeatures(vector& features, vector& responses) { - unordered_map cnt; - for (auto& s : responses) { - istringstream iss(s); - string w; - unordered_set st; - while (iss >> w) { - st.insert(w); - } - for (auto& w : st) { - ++cnt[w]; - } - } - int n = features.size(); - vector idx(n); - iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) { - int x = cnt[features[i]], y = cnt[features[j]]; - return x == y ? i < j : x > y; - }); - vector ans(n); - for (int i = 0; i < n; ++i) { - ans[i] = features[idx[i]]; - } - return ans; - } +class Solution { +public: + vector sortFeatures(vector& features, vector& responses) { + unordered_map cnt; + for (auto& s : responses) { + istringstream iss(s); + string w; + unordered_set st; + while (iss >> w) { + st.insert(w); + } + for (auto& w : st) { + ++cnt[w]; + } + } + int n = features.size(); + vector idx(n); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { + int x = cnt[features[i]], y = cnt[features[j]]; + return x == y ? i < j : x > y; + }); + vector ans(n); + for (int i = 0; i < n; ++i) { + ans[i] = features[idx[i]]; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1700-1799/1772.Sort Features by Popularity/Solution.java b/solution/1700-1799/1772.Sort Features by Popularity/Solution.java index 702a7979d845f..c1cb8ba43410b 100644 --- a/solution/1700-1799/1772.Sort Features by Popularity/Solution.java +++ b/solution/1700-1799/1772.Sort Features by Popularity/Solution.java @@ -1,28 +1,28 @@ -class Solution { - public String[] sortFeatures(String[] features, String[] responses) { - Map cnt = new HashMap<>(); - for (String s : responses) { - Set vis = new HashSet<>(); - for (String w : s.split(" ")) { - if (vis.add(w)) { - cnt.merge(w, 1, Integer::sum); - } - } - } - int n = features.length; - Integer[] idx = new Integer[n]; - for (int i = 0; i < n; i++) { - idx[i] = i; - } - Arrays.sort(idx, (i, j) -> { - int x = cnt.getOrDefault(features[i], 0); - int y = cnt.getOrDefault(features[j], 0); - return x == y ? i - j : y - x; - }); - String[] ans = new String[n]; - for (int i = 0; i < n; i++) { - ans[i] = features[idx[i]]; - } - return ans; - } +class Solution { + public String[] sortFeatures(String[] features, String[] responses) { + Map cnt = new HashMap<>(); + for (String s : responses) { + Set vis = new HashSet<>(); + for (String w : s.split(" ")) { + if (vis.add(w)) { + cnt.merge(w, 1, Integer::sum); + } + } + } + int n = features.length; + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; i++) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> { + int x = cnt.getOrDefault(features[i], 0); + int y = cnt.getOrDefault(features[j], 0); + return x == y ? i - j : y - x; + }); + String[] ans = new String[n]; + for (int i = 0; i < n; i++) { + ans[i] = features[idx[i]]; + } + return ans; + } } \ No newline at end of file diff --git a/solution/1700-1799/1772.Sort Features by Popularity/Solution.py b/solution/1700-1799/1772.Sort Features by Popularity/Solution.py index 5250bc917eb10..a7609f61a416a 100644 --- a/solution/1700-1799/1772.Sort Features by Popularity/Solution.py +++ b/solution/1700-1799/1772.Sort Features by Popularity/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def sortFeatures(self, features: List[str], responses: List[str]) -> List[str]: - cnt = Counter() - for s in responses: - for w in set(s.split()): - cnt[w] += 1 - return sorted(features, key=lambda w: -cnt[w]) +class Solution: + def sortFeatures(self, features: List[str], responses: List[str]) -> List[str]: + cnt = Counter() + for s in responses: + for w in set(s.split()): + cnt[w] += 1 + return sorted(features, key=lambda w: -cnt[w]) diff --git a/solution/1700-1799/1773.Count Items Matching a Rule/Solution.c b/solution/1700-1799/1773.Count Items Matching a Rule/Solution.c index a795862f97c65..12558f223467d 100644 --- a/solution/1700-1799/1773.Count Items Matching a Rule/Solution.c +++ b/solution/1700-1799/1773.Count Items Matching a Rule/Solution.c @@ -8,4 +8,4 @@ int countMatches(char*** items, int itemsSize, int* itemsColSize, char* ruleKey, } } return res; -} +} \ No newline at end of file diff --git a/solution/1700-1799/1774.Closest Dessert Cost/Solution.cpp b/solution/1700-1799/1774.Closest Dessert Cost/Solution.cpp index 73771a21b4dbd..40dd64f1813d5 100644 --- a/solution/1700-1799/1774.Closest Dessert Cost/Solution.cpp +++ b/solution/1700-1799/1774.Closest Dessert Cost/Solution.cpp @@ -14,8 +14,11 @@ class Solution { dfs(0, 0); sort(arr.begin(), arr.end()); int d = inf, ans = inf; + // 选择一种冰激淋基料 for (int x : baseCosts) { + // 枚举子集和 for (int y : arr) { + // 二分查找 int i = lower_bound(arr.begin(), arr.end(), target - x - y) - arr.begin(); for (int j = i - 1; j < i + 1; ++j) { if (j >= 0 && j < arr.size()) { diff --git a/solution/1700-1799/1774.Closest Dessert Cost/Solution.go b/solution/1700-1799/1774.Closest Dessert Cost/Solution.go index 401beba47c221..54f926bbf42aa 100644 --- a/solution/1700-1799/1774.Closest Dessert Cost/Solution.go +++ b/solution/1700-1799/1774.Closest Dessert Cost/Solution.go @@ -13,8 +13,11 @@ func closestCost(baseCosts []int, toppingCosts []int, target int) int { sort.Ints(arr) const inf = 1 << 30 ans, d := inf, inf + // 选择一种冰激淋基料 for _, x := range baseCosts { + // 枚举子集和 for _, y := range arr { + // 二分查找 i := sort.SearchInts(arr, target-x-y) for j := i - 1; j < i+1; j++ { if j >= 0 && j < len(arr) { diff --git a/solution/1700-1799/1774.Closest Dessert Cost/Solution.java b/solution/1700-1799/1774.Closest Dessert Cost/Solution.java index 874ff39f4c375..4689f1ad552a0 100644 --- a/solution/1700-1799/1774.Closest Dessert Cost/Solution.java +++ b/solution/1700-1799/1774.Closest Dessert Cost/Solution.java @@ -8,8 +8,12 @@ public int closestCost(int[] baseCosts, int[] toppingCosts, int target) { dfs(0, 0); Collections.sort(arr); int d = inf, ans = inf; + + // 选择一种冰激淋基料 for (int x : baseCosts) { + // 枚举子集和 for (int y : arr) { + // 二分查找 int i = search(target - x - y); for (int j : new int[] {i, i - 1}) { if (j >= 0 && j < arr.size()) { diff --git a/solution/1700-1799/1774.Closest Dessert Cost/Solution.py b/solution/1700-1799/1774.Closest Dessert Cost/Solution.py index 036f368be92a4..436f4860d58e8 100644 --- a/solution/1700-1799/1774.Closest Dessert Cost/Solution.py +++ b/solution/1700-1799/1774.Closest Dessert Cost/Solution.py @@ -13,8 +13,12 @@ def dfs(i, t): dfs(0, 0) arr.sort() d = ans = inf + + # 选择一种冰激淋基料 for x in baseCosts: + # 枚举子集和 for y in arr: + # 二分查找 i = bisect_left(arr, target - x - y) for j in (i, i - 1): if 0 <= j < len(arr): diff --git a/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution.go b/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution.go index 5f77a920cf984..d5197969a1276 100644 --- a/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution.go +++ b/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution.go @@ -1,4 +1,4 @@ -func minOperations(nums1 []int, nums2 []int) (ans int) { +func minOperations(nums1 []int, nums2 []int) int { s1, s2 := sum(nums1), sum(nums2) if s1 == s2 { return 0 @@ -7,23 +7,20 @@ func minOperations(nums1 []int, nums2 []int) (ans int) { return minOperations(nums2, nums1) } d := s2 - s1 - cnt := [6]int{} + arr := []int{} for _, v := range nums1 { - cnt[6-v]++ + arr = append(arr, 6-v) } for _, v := range nums2 { - cnt[v-1]++ + arr = append(arr, v-1) } - for i := 5; i > 0; i-- { - for cnt[i] > 0 && d > 0 { - d -= i - cnt[i]-- - ans++ + sort.Sort(sort.Reverse(sort.IntSlice(arr))) + for i, v := range arr { + d -= v + if d <= 0 { + return i + 1 } } - if d <= 0 { - return - } return -1 } diff --git a/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution.java b/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution.java index 83da5d820e34c..0b6353d43ee89 100644 --- a/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution.java +++ b/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution.java @@ -9,21 +9,21 @@ public int minOperations(int[] nums1, int[] nums2) { return minOperations(nums2, nums1); } int d = s2 - s1; - int[] cnt = new int[6]; + int[] arr = new int[nums1.length + nums2.length]; + int k = 0; for (int v : nums1) { - ++cnt[6 - v]; + arr[k++] = 6 - v; } for (int v : nums2) { - ++cnt[v - 1]; + arr[k++] = v - 1; } - int ans = 0; - for (int i = 5; i > 0; --i) { - while (cnt[i] > 0 && d > 0) { - d -= i; - --cnt[i]; - ++ans; + Arrays.sort(arr); + for (int i = 1, j = arr.length - 1; j >= 0; ++i, --j) { + d -= arr[j]; + if (d <= 0) { + return i; } } - return d <= 0 ? ans : -1; + return -1; } } \ No newline at end of file diff --git a/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution2.cpp b/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution2.cpp new file mode 100644 index 0000000000000..2be917be017b5 --- /dev/null +++ b/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution2.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int minOperations(vector& nums1, vector& nums2) { + int s1 = accumulate(nums1.begin(), nums1.end(), 0); + int s2 = accumulate(nums2.begin(), nums2.end(), 0); + if (s1 == s2) return 0; + if (s1 > s2) return minOperations(nums2, nums1); + int d = s2 - s1; + int cnt[6] = {0}; + for (int& v : nums1) ++cnt[6 - v]; + for (int& v : nums2) ++cnt[v - 1]; + int ans = 0; + for (int i = 5; i; --i) { + while (cnt[i] && d > 0) { + d -= i; + --cnt[i]; + ++ans; + } + } + return d <= 0 ? ans : -1; + } +}; \ No newline at end of file diff --git a/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution2.go b/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution2.go new file mode 100644 index 0000000000000..5f77a920cf984 --- /dev/null +++ b/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution2.go @@ -0,0 +1,35 @@ +func minOperations(nums1 []int, nums2 []int) (ans int) { + s1, s2 := sum(nums1), sum(nums2) + if s1 == s2 { + return 0 + } + if s1 > s2 { + return minOperations(nums2, nums1) + } + d := s2 - s1 + cnt := [6]int{} + for _, v := range nums1 { + cnt[6-v]++ + } + for _, v := range nums2 { + cnt[v-1]++ + } + for i := 5; i > 0; i-- { + for cnt[i] > 0 && d > 0 { + d -= i + cnt[i]-- + ans++ + } + } + if d <= 0 { + return + } + return -1 +} + +func sum(nums []int) (s int) { + for _, v := range nums { + s += v + } + return +} \ No newline at end of file diff --git a/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution2.java b/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution2.java new file mode 100644 index 0000000000000..83da5d820e34c --- /dev/null +++ b/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution2.java @@ -0,0 +1,29 @@ +class Solution { + public int minOperations(int[] nums1, int[] nums2) { + int s1 = Arrays.stream(nums1).sum(); + int s2 = Arrays.stream(nums2).sum(); + if (s1 == s2) { + return 0; + } + if (s1 > s2) { + return minOperations(nums2, nums1); + } + int d = s2 - s1; + int[] cnt = new int[6]; + for (int v : nums1) { + ++cnt[6 - v]; + } + for (int v : nums2) { + ++cnt[v - 1]; + } + int ans = 0; + for (int i = 5; i > 0; --i) { + while (cnt[i] > 0 && d > 0) { + d -= i; + --cnt[i]; + ++ans; + } + } + return d <= 0 ? ans : -1; + } +} \ No newline at end of file diff --git a/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution2.py b/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution2.py new file mode 100644 index 0000000000000..6f585b765bcdf --- /dev/null +++ b/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution2.py @@ -0,0 +1,16 @@ +class Solution: + def minOperations(self, nums1: List[int], nums2: List[int]) -> int: + s1, s2 = sum(nums1), sum(nums2) + if s1 == s2: + return 0 + if s1 > s2: + return self.minOperations(nums2, nums1) + cnt = Counter([6 - v for v in nums1] + [v - 1 for v in nums2]) + d = s2 - s1 + ans = 0 + for i in range(5, 0, -1): + while cnt[i] and d > 0: + d -= i + cnt[i] -= 1 + ans += 1 + return ans if d <= 0 else -1 diff --git a/solution/1700-1799/1778.Shortest Path in a Hidden Grid/Solution.cpp b/solution/1700-1799/1778.Shortest Path in a Hidden Grid/Solution.cpp index ea414076852a2..e7cfce6096739 100644 --- a/solution/1700-1799/1778.Shortest Path in a Hidden Grid/Solution.cpp +++ b/solution/1700-1799/1778.Shortest Path in a Hidden Grid/Solution.cpp @@ -1,64 +1,64 @@ -/** - * // This is the GridMaster's API interface. - * // You should not implement it, or speculate about its implementation - * class GridMaster { - * public: - * bool canMove(char direction); - * void move(char direction); - * boolean isTarget(); - * }; - */ - -class Solution { -private: - const int n = 2010; - int dirs[5] = {-1, 0, 1, 0, -1}; - string s = "URDL"; - int target; - unordered_set vis; - -public: - int findShortestPath(GridMaster& master) { - target = n * n; - vis.insert(0); - dfs(0, 0, master); - if (target == n * n) { - return -1; - } - vis.erase(0); - queue> q; - q.emplace(0, 0); - for (int ans = 0; q.size(); ++ans) { - for (int m = q.size(); m; --m) { - auto [i, j] = q.front(); - q.pop(); - if (i * n + j == target) { - return ans; - } - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (vis.count(x * n + y)) { - vis.erase(x * n + y); - q.emplace(x, y); - } - } - } - } - return -1; - } - - void dfs(int i, int j, GridMaster& master) { - if (master.isTarget()) { - target = i * n + j; - } - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (master.canMove(s[k]) && !vis.count(x * n + y)) { - vis.insert(x * n + y); - master.move(s[k]); - dfs(x, y, master); - master.move(s[(k + 2) % 4]); - } - } - } +/** + * // This is the GridMaster's API interface. + * // You should not implement it, or speculate about its implementation + * class GridMaster { + * public: + * bool canMove(char direction); + * void move(char direction); + * boolean isTarget(); + * }; + */ + +class Solution { +private: + const int n = 2010; + int dirs[5] = {-1, 0, 1, 0, -1}; + string s = "URDL"; + int target; + unordered_set vis; + +public: + int findShortestPath(GridMaster& master) { + target = n * n; + vis.insert(0); + dfs(0, 0, master); + if (target == n * n) { + return -1; + } + vis.erase(0); + queue> q; + q.emplace(0, 0); + for (int ans = 0; q.size(); ++ans) { + for (int m = q.size(); m; --m) { + auto [i, j] = q.front(); + q.pop(); + if (i * n + j == target) { + return ans; + } + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (vis.count(x * n + y)) { + vis.erase(x * n + y); + q.emplace(x, y); + } + } + } + } + return -1; + } + + void dfs(int i, int j, GridMaster& master) { + if (master.isTarget()) { + target = i * n + j; + } + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (master.canMove(s[k]) && !vis.count(x * n + y)) { + vis.insert(x * n + y); + master.move(s[k]); + dfs(x, y, master); + master.move(s[(k + 2) % 4]); + } + } + } }; \ No newline at end of file diff --git a/solution/1700-1799/1778.Shortest Path in a Hidden Grid/Solution.java b/solution/1700-1799/1778.Shortest Path in a Hidden Grid/Solution.java index 9d2568d1e80d9..383ab97ca5494 100644 --- a/solution/1700-1799/1778.Shortest Path in a Hidden Grid/Solution.java +++ b/solution/1700-1799/1778.Shortest Path in a Hidden Grid/Solution.java @@ -1,59 +1,59 @@ -/** - * // This is the GridMaster's API interface. - * // You should not implement it, or speculate about its implementation - * class GridMaster { - * boolean canMove(char direction); - * void move(char direction); - * boolean isTarget(); - * } - */ - -class Solution { - private int[] target; - private GridMaster master; - private final int n = 2010; - private final String s = "URDL"; - private final int[] dirs = {-1, 0, 1, 0, -1}; - private final Set vis = new HashSet<>(); - - public int findShortestPath(GridMaster master) { - this.master = master; - dfs(0, 0); - if (target == null) { - return -1; - } - vis.remove(0); - Deque q = new ArrayDeque<>(); - q.offer(new int[] {0, 0}); - for (int ans = 0; !q.isEmpty(); ++ans) { - for (int m = q.size(); m > 0; --m) { - var p = q.poll(); - if (p[0] == target[0] && p[1] == target[1]) { - return ans; - } - for (int k = 0; k < 4; ++k) { - int x = p[0] + dirs[k], y = p[1] + dirs[k + 1]; - if (vis.remove(x * n + y)) { - q.offer(new int[] {x, y}); - } - } - } - } - return -1; - } - - private void dfs(int i, int j) { - if (master.isTarget()) { - target = new int[] {i, j}; - return; - } - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (master.canMove(s.charAt(k)) && vis.add(x * n + y)) { - master.move(s.charAt(k)); - dfs(x, y); - master.move(s.charAt((k + 2) % 4)); - } - } - } +/** + * // This is the GridMaster's API interface. + * // You should not implement it, or speculate about its implementation + * class GridMaster { + * boolean canMove(char direction); + * void move(char direction); + * boolean isTarget(); + * } + */ + +class Solution { + private int[] target; + private GridMaster master; + private final int n = 2010; + private final String s = "URDL"; + private final int[] dirs = {-1, 0, 1, 0, -1}; + private final Set vis = new HashSet<>(); + + public int findShortestPath(GridMaster master) { + this.master = master; + dfs(0, 0); + if (target == null) { + return -1; + } + vis.remove(0); + Deque q = new ArrayDeque<>(); + q.offer(new int[] {0, 0}); + for (int ans = 0; !q.isEmpty(); ++ans) { + for (int m = q.size(); m > 0; --m) { + var p = q.poll(); + if (p[0] == target[0] && p[1] == target[1]) { + return ans; + } + for (int k = 0; k < 4; ++k) { + int x = p[0] + dirs[k], y = p[1] + dirs[k + 1]; + if (vis.remove(x * n + y)) { + q.offer(new int[] {x, y}); + } + } + } + } + return -1; + } + + private void dfs(int i, int j) { + if (master.isTarget()) { + target = new int[] {i, j}; + return; + } + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (master.canMove(s.charAt(k)) && vis.add(x * n + y)) { + master.move(s.charAt(k)); + dfs(x, y); + master.move(s.charAt((k + 2) % 4)); + } + } + } } \ No newline at end of file diff --git a/solution/1700-1799/1778.Shortest Path in a Hidden Grid/Solution.py b/solution/1700-1799/1778.Shortest Path in a Hidden Grid/Solution.py index 0b307b9aafbd7..bdd4606ac8fe4 100644 --- a/solution/1700-1799/1778.Shortest Path in a Hidden Grid/Solution.py +++ b/solution/1700-1799/1778.Shortest Path in a Hidden Grid/Solution.py @@ -1,53 +1,53 @@ -# """ -# This is GridMaster's API interface. -# You should not implement it, or speculate about its implementation -# """ -# class GridMaster(object): -# def canMove(self, direction: str) -> bool: -# -# -# def move(self, direction: str) -> bool: -# -# -# def isTarget(self) -> None: -# -# - - -class Solution(object): - def findShortestPath(self, master: "GridMaster") -> int: - def dfs(i: int, j: int): - if master.isTarget(): - nonlocal target - target = (i, j) - return - for k, c in enumerate(s): - x, y = i + dirs[k], j + dirs[k + 1] - if master.canMove(c) and (x, y) not in vis: - vis.add((x, y)) - master.move(c) - dfs(x, y) - master.move(s[(k + 2) % 4]) - - s = "URDL" - dirs = (-1, 0, 1, 0, -1) - target = None - vis = set() - dfs(0, 0) - if target is None: - return -1 - vis.discard((0, 0)) - q = deque([(0, 0)]) - ans = -1 - while q: - ans += 1 - for _ in range(len(q)): - i, j = q.popleft() - if (i, j) == target: - return ans - for a, b in pairwise(dirs): - x, y = i + a, j + b - if (x, y) in vis: - vis.remove((x, y)) - q.append((x, y)) - return -1 +# """ +# This is GridMaster's API interface. +# You should not implement it, or speculate about its implementation +# """ +# class GridMaster(object): +# def canMove(self, direction: str) -> bool: +# +# +# def move(self, direction: str) -> bool: +# +# +# def isTarget(self) -> None: +# +# + + +class Solution(object): + def findShortestPath(self, master: "GridMaster") -> int: + def dfs(i: int, j: int): + if master.isTarget(): + nonlocal target + target = (i, j) + return + for k, c in enumerate(s): + x, y = i + dirs[k], j + dirs[k + 1] + if master.canMove(c) and (x, y) not in vis: + vis.add((x, y)) + master.move(c) + dfs(x, y) + master.move(s[(k + 2) % 4]) + + s = "URDL" + dirs = (-1, 0, 1, 0, -1) + target = None + vis = set() + dfs(0, 0) + if target is None: + return -1 + vis.discard((0, 0)) + q = deque([(0, 0)]) + ans = -1 + while q: + ans += 1 + for _ in range(len(q)): + i, j = q.popleft() + if (i, j) == target: + return ans + for a, b in pairwise(dirs): + x, y = i + a, j + b + if (x, y) in vis: + vis.remove((x, y)) + q.append((x, y)) + return -1 diff --git a/solution/1700-1799/1779.Find Nearest Point That Has the Same X or Y Coordinate/Solution.c b/solution/1700-1799/1779.Find Nearest Point That Has the Same X or Y Coordinate/Solution.c index 2e6a7aa136573..6dd5707918479 100644 --- a/solution/1700-1799/1779.Find Nearest Point That Has the Same X or Y Coordinate/Solution.c +++ b/solution/1700-1799/1779.Find Nearest Point That Has the Same X or Y Coordinate/Solution.c @@ -13,4 +13,4 @@ int nearestValidPoint(int x, int y, int** points, int pointsSize, int* pointsCol } } return ans; -} +} \ No newline at end of file diff --git a/solution/1700-1799/1781.Sum of Beauty of All Substrings/Solution2.cpp b/solution/1700-1799/1781.Sum of Beauty of All Substrings/Solution2.cpp new file mode 100644 index 0000000000000..6b05ba9251a94 --- /dev/null +++ b/solution/1700-1799/1781.Sum of Beauty of All Substrings/Solution2.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int beautySum(string s) { + int n = s.size(); + int ans = 0; + for (int i = 0; i < n; ++i) { + int cnt[26]{}; + unordered_map freq; + int mi = 1, mx = 1; + for (int j = i; j < n; ++j) { + int k = s[j] - 'a'; + --freq[cnt[k]]; + ++cnt[k]; + ++freq[cnt[k]]; + + if (cnt[k] == 1) { + mi = 1; + } + if (freq[mi] == 0) { + ++mi; + } + if (cnt[k] > mx) { + mx = cnt[k]; + } + ans += mx - mi; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1700-1799/1781.Sum of Beauty of All Substrings/Solution2.go b/solution/1700-1799/1781.Sum of Beauty of All Substrings/Solution2.go new file mode 100644 index 0000000000000..285023898fce9 --- /dev/null +++ b/solution/1700-1799/1781.Sum of Beauty of All Substrings/Solution2.go @@ -0,0 +1,26 @@ +func beautySum(s string) (ans int) { + n := len(s) + for i := 0; i < n; i++ { + cnt := [26]int{} + freq := map[int]int{} + mi, mx := 1, 1 + for j := i; j < n; j++ { + k := int(s[j] - 'a') + freq[cnt[k]]-- + cnt[k]++ + freq[cnt[k]]++ + + if cnt[k] == 1 { + mi = 1 + } + if freq[mi] == 0 { + mi++ + } + if cnt[k] > mx { + mx = cnt[k] + } + ans += mx - mi + } + } + return +} \ No newline at end of file diff --git a/solution/1700-1799/1781.Sum of Beauty of All Substrings/Solution2.java b/solution/1700-1799/1781.Sum of Beauty of All Substrings/Solution2.java new file mode 100644 index 0000000000000..335444f17fb1e --- /dev/null +++ b/solution/1700-1799/1781.Sum of Beauty of All Substrings/Solution2.java @@ -0,0 +1,29 @@ +class Solution { + public int beautySum(String s) { + int n = s.length(); + int ans = 0; + for (int i = 0; i < n; ++i) { + int[] cnt = new int[26]; + Map freq = new HashMap<>(); + int mi = 1, mx = 1; + for (int j = i; j < n; ++j) { + int k = s.charAt(j) - 'a'; + freq.merge(cnt[k], -1, Integer::sum); + ++cnt[k]; + freq.merge(cnt[k], 1, Integer::sum); + + if (cnt[k] == 1) { + mi = 1; + } + if (freq.getOrDefault(mi, 0) == 0) { + ++mi; + } + if (cnt[k] > mx) { + mx = cnt[k]; + } + ans += mx - mi; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1700-1799/1781.Sum of Beauty of All Substrings/Solution2.js b/solution/1700-1799/1781.Sum of Beauty of All Substrings/Solution2.js new file mode 100644 index 0000000000000..fe6391a5dedd9 --- /dev/null +++ b/solution/1700-1799/1781.Sum of Beauty of All Substrings/Solution2.js @@ -0,0 +1,30 @@ +/** + * @param {string} s + * @return {number} + */ +var beautySum = function (s) { + const n = s.length; + let ans = 0; + for (let i = 0; i < n; ++i) { + const cnt = Array(26).fill(0); + const freq = new Map(); + let [mi, mx] = [1, 1]; + for (let j = i; j < n; ++j) { + const k = s[j].charCodeAt() - 97; + freq.set(cnt[k], (freq.get(cnt[k]) || 0) - 1); + ++cnt[k]; + freq.set(cnt[k], (freq.get(cnt[k]) || 0) + 1); + if (cnt[k] === 1) { + mi = 1; + } + if (freq.get(mi) === 0) { + ++mi; + } + if (cnt[k] > mx) { + mx = cnt[k]; + } + ans += mx - mi; + } + } + return ans; +}; diff --git a/solution/1700-1799/1781.Sum of Beauty of All Substrings/Solution2.py b/solution/1700-1799/1781.Sum of Beauty of All Substrings/Solution2.py new file mode 100644 index 0000000000000..0d5745c1028ed --- /dev/null +++ b/solution/1700-1799/1781.Sum of Beauty of All Substrings/Solution2.py @@ -0,0 +1,21 @@ +class Solution: + def beautySum(self, s: str) -> int: + ans, n = 0, len(s) + for i in range(n): + cnt = Counter() + freq = Counter() + mi = mx = 1 + for j in range(i, n): + freq[cnt[s[j]]] -= 1 + cnt[s[j]] += 1 + freq[cnt[s[j]]] += 1 + + if cnt[s[j]] == 1: + mi = 1 + if freq[mi] == 0: + mi += 1 + if cnt[s[j]] > mx: + mx = cnt[s[j]] + + ans += mx - mi + return ans diff --git a/solution/1700-1799/1782.Count Pairs Of Nodes/Solution.java b/solution/1700-1799/1782.Count Pairs Of Nodes/Solution.java index 0e0144ceb3eac..70ec1655f60a5 100644 --- a/solution/1700-1799/1782.Count Pairs Of Nodes/Solution.java +++ b/solution/1700-1799/1782.Count Pairs Of Nodes/Solution.java @@ -1,45 +1,45 @@ -class Solution { - public int[] countPairs(int n, int[][] edges, int[] queries) { - int[] cnt = new int[n]; - Map g = new HashMap<>(); - for (var e : edges) { - int a = e[0] - 1, b = e[1] - 1; - ++cnt[a]; - ++cnt[b]; - int k = Math.min(a, b) * n + Math.max(a, b); - g.merge(k, 1, Integer::sum); - } - int[] s = cnt.clone(); - Arrays.sort(s); - int[] ans = new int[queries.length]; - for (int i = 0; i < queries.length; ++i) { - int t = queries[i]; - for (int j = 0; j < n; ++j) { - int x = s[j]; - int k = search(s, t - x, j + 1); - ans[i] += n - k; - } - for (var e : g.entrySet()) { - int a = e.getKey() / n, b = e.getKey() % n; - int v = e.getValue(); - if (cnt[a] + cnt[b] > t && cnt[a] + cnt[b] - v <= t) { - --ans[i]; - } - } - } - return ans; - } - - private int search(int[] arr, int x, int i) { - int left = i, right = arr.length; - while (left < right) { - int mid = (left + right) >> 1; - if (arr[mid] > x) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - } +class Solution { + public int[] countPairs(int n, int[][] edges, int[] queries) { + int[] cnt = new int[n]; + Map g = new HashMap<>(); + for (var e : edges) { + int a = e[0] - 1, b = e[1] - 1; + ++cnt[a]; + ++cnt[b]; + int k = Math.min(a, b) * n + Math.max(a, b); + g.merge(k, 1, Integer::sum); + } + int[] s = cnt.clone(); + Arrays.sort(s); + int[] ans = new int[queries.length]; + for (int i = 0; i < queries.length; ++i) { + int t = queries[i]; + for (int j = 0; j < n; ++j) { + int x = s[j]; + int k = search(s, t - x, j + 1); + ans[i] += n - k; + } + for (var e : g.entrySet()) { + int a = e.getKey() / n, b = e.getKey() % n; + int v = e.getValue(); + if (cnt[a] + cnt[b] > t && cnt[a] + cnt[b] - v <= t) { + --ans[i]; + } + } + } + return ans; + } + + private int search(int[] arr, int x, int i) { + int left = i, right = arr.length; + while (left < right) { + int mid = (left + right) >> 1; + if (arr[mid] > x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } } \ No newline at end of file diff --git a/solution/1700-1799/1782.Count Pairs Of Nodes/Solution.py b/solution/1700-1799/1782.Count Pairs Of Nodes/Solution.py index 9abc335481ecb..95651dbb23fab 100644 --- a/solution/1700-1799/1782.Count Pairs Of Nodes/Solution.py +++ b/solution/1700-1799/1782.Count Pairs Of Nodes/Solution.py @@ -1,23 +1,23 @@ -class Solution: - def countPairs( - self, n: int, edges: List[List[int]], queries: List[int] - ) -> List[int]: - cnt = [0] * n - g = defaultdict(int) - for a, b in edges: - a, b = a - 1, b - 1 - a, b = min(a, b), max(a, b) - cnt[a] += 1 - cnt[b] += 1 - g[(a, b)] += 1 - - s = sorted(cnt) - ans = [0] * len(queries) - for i, t in enumerate(queries): - for j, x in enumerate(s): - k = bisect_right(s, t - x, lo=j + 1) - ans[i] += n - k - for (a, b), v in g.items(): - if cnt[a] + cnt[b] > t and cnt[a] + cnt[b] - v <= t: - ans[i] -= 1 - return ans +class Solution: + def countPairs( + self, n: int, edges: List[List[int]], queries: List[int] + ) -> List[int]: + cnt = [0] * n + g = defaultdict(int) + for a, b in edges: + a, b = a - 1, b - 1 + a, b = min(a, b), max(a, b) + cnt[a] += 1 + cnt[b] += 1 + g[(a, b)] += 1 + + s = sorted(cnt) + ans = [0] * len(queries) + for i, t in enumerate(queries): + for j, x in enumerate(s): + k = bisect_right(s, t - x, lo=j + 1) + ans[i] += n - k + for (a, b), v in g.items(): + if cnt[a] + cnt[b] > t and cnt[a] + cnt[b] - v <= t: + ans[i] -= 1 + return ans diff --git a/solution/1700-1799/1783.Grand Slam Titles/Solution2.sql b/solution/1700-1799/1783.Grand Slam Titles/Solution2.sql new file mode 100644 index 0000000000000..0083d66e6218c --- /dev/null +++ b/solution/1700-1799/1783.Grand Slam Titles/Solution2.sql @@ -0,0 +1,32 @@ +# Write your MySQL query statement below +SELECT + player_id, + player_name, + SUM( + ( + CASE + WHEN Wimbledon = player_id THEN 1 + ELSE 0 + END + ) + ( + CASE + WHEN Fr_open = player_id THEN 1 + ELSE 0 + END + ) + ( + CASE + WHEN US_open = player_id THEN 1 + ELSE 0 + END + ) + ( + CASE + WHEN Au_open = player_id THEN 1 + ELSE 0 + END + ) + ) AS grand_slams_count +FROM + Championships + CROSS JOIN Players +GROUP BY player_id +HAVING grand_slams_count > 0; diff --git a/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/Solution.ts b/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/Solution.ts index 718812525ff9b..d3cf717b043f9 100644 --- a/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/Solution.ts +++ b/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/Solution.ts @@ -1,3 +1,10 @@ function checkOnesSegment(s: string): boolean { - return !s.includes('01'); + let pre = s[0]; + for (const c of s) { + if (pre !== c && c === '1') { + return false; + } + pre = c; + } + return true; } diff --git a/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/Solution2.ts b/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/Solution2.ts new file mode 100644 index 0000000000000..718812525ff9b --- /dev/null +++ b/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/Solution2.ts @@ -0,0 +1,3 @@ +function checkOnesSegment(s: string): boolean { + return !s.includes('01'); +} diff --git a/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/Solution.c b/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/Solution.c index baff308313746..8e2203bdbc94c 100644 --- a/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/Solution.c +++ b/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/Solution.c @@ -5,4 +5,4 @@ int minElements(int* nums, int numsSize, int limit, int goal) { } long long diff = labs(goal - sum); return (diff + limit - 1) / limit; -} +} \ No newline at end of file diff --git a/solution/1700-1799/1786.Number of Restricted Paths From First to Last Node/Solution2.java b/solution/1700-1799/1786.Number of Restricted Paths From First to Last Node/Solution2.java new file mode 100644 index 0000000000000..3cae92bb2ee0a --- /dev/null +++ b/solution/1700-1799/1786.Number of Restricted Paths From First to Last Node/Solution2.java @@ -0,0 +1,46 @@ +class Solution { + private static final int INF = Integer.MAX_VALUE; + private static final int MOD = (int) 1e9 + 7; + + public int countRestrictedPaths(int n, int[][] edges) { + List[] g = new List[n + 1]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (int[] e : edges) { + int u = e[0], v = e[1], w = e[2]; + g[u].add(new int[] {v, w}); + g[v].add(new int[] {u, w}); + } + PriorityQueue q = new PriorityQueue<>((a, b) -> a[0] - b[0]); + q.offer(new int[] {0, n}); + int[] dist = new int[n + 1]; + Arrays.fill(dist, INF); + dist[n] = 0; + while (!q.isEmpty()) { + int[] p = q.poll(); + int u = p[1]; + for (int[] ne : g[u]) { + int v = ne[0], w = ne[1]; + if (dist[v] > dist[u] + w) { + dist[v] = dist[u] + w; + q.offer(new int[] {dist[v], v}); + } + } + } + int[] f = new int[n + 1]; + f[n] = 1; + Integer[] arr = new Integer[n]; + for (int i = 0; i < n; ++i) { + arr[i] = i + 1; + } + Arrays.sort(arr, (i, j) -> dist[i] - dist[j]); + for (int i : arr) { + for (int[] ne : g[i]) { + int j = ne[0]; + if (dist[i] > dist[j]) { + f[i] = (f[i] + f[j]) % MOD; + } + } + } + return f[1]; + } +} \ No newline at end of file diff --git a/solution/1700-1799/1786.Number of Restricted Paths From First to Last Node/Solution2.py b/solution/1700-1799/1786.Number of Restricted Paths From First to Last Node/Solution2.py new file mode 100644 index 0000000000000..1c192afe07e20 --- /dev/null +++ b/solution/1700-1799/1786.Number of Restricted Paths From First to Last Node/Solution2.py @@ -0,0 +1,25 @@ +class Solution: + def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int: + g = defaultdict(list) + for u, v, w in edges: + g[u].append((v, w)) + g[v].append((u, w)) + dist = [inf] * (n + 1) + dist[n] = 0 + q = [(0, n)] + mod = 10**9 + 7 + while q: + _, u = heappop(q) + for v, w in g[u]: + if dist[v] > dist[u] + w: + dist[v] = dist[u] + w + heappush(q, (dist[v], v)) + arr = list(range(1, n + 1)) + arr.sort(key=lambda i: dist[i]) + f = [0] * (n + 1) + f[n] = 1 + for i in arr: + for j, _ in g[i]: + if dist[i] > dist[j]: + f[i] = (f[i] + f[j]) % mod + return f[1] diff --git a/solution/1700-1799/1787.Make the XOR of All Segments Equal to Zero/Solution.cpp b/solution/1700-1799/1787.Make the XOR of All Segments Equal to Zero/Solution.cpp index 7c64695afe09f..4d432e7c45915 100644 --- a/solution/1700-1799/1787.Make the XOR of All Segments Equal to Zero/Solution.cpp +++ b/solution/1700-1799/1787.Make the XOR of All Segments Equal to Zero/Solution.cpp @@ -1,25 +1,25 @@ -class Solution { -public: - int minChanges(vector& nums, int k) { - int n = 1 << 10; - unordered_map cnt[k]; - vector size(k); - for (int i = 0; i < nums.size(); ++i) { - cnt[i % k][nums[i]]++; - size[i % k]++; - } - vector f(n, 1 << 30); - f[0] = 0; - for (int i = 0; i < k; ++i) { - int mi = *min_element(f.begin(), f.end()); - vector g(n, mi + size[i]); - for (int j = 0; j < n; ++j) { - for (auto& [v, c] : cnt[i]) { - g[j] = min(g[j], f[j ^ v] + size[i] - c); - } - } - f = move(g); - } - return f[0]; - } +class Solution { +public: + int minChanges(vector& nums, int k) { + int n = 1 << 10; + unordered_map cnt[k]; + vector size(k); + for (int i = 0; i < nums.size(); ++i) { + cnt[i % k][nums[i]]++; + size[i % k]++; + } + vector f(n, 1 << 30); + f[0] = 0; + for (int i = 0; i < k; ++i) { + int mi = *min_element(f.begin(), f.end()); + vector g(n, mi + size[i]); + for (int j = 0; j < n; ++j) { + for (auto& [v, c] : cnt[i]) { + g[j] = min(g[j], f[j ^ v] + size[i] - c); + } + } + f = move(g); + } + return f[0]; + } }; \ No newline at end of file diff --git a/solution/1700-1799/1787.Make the XOR of All Segments Equal to Zero/Solution.java b/solution/1700-1799/1787.Make the XOR of All Segments Equal to Zero/Solution.java index b8b899da38d63..f04df92112137 100644 --- a/solution/1700-1799/1787.Make the XOR of All Segments Equal to Zero/Solution.java +++ b/solution/1700-1799/1787.Make the XOR of All Segments Equal to Zero/Solution.java @@ -1,37 +1,37 @@ -class Solution { - public int minChanges(int[] nums, int k) { - int n = 1 << 10; - Map[] cnt = new Map[k]; - Arrays.setAll(cnt, i -> new HashMap<>()); - int[] size = new int[k]; - for (int i = 0; i < nums.length; ++i) { - int j = i % k; - cnt[j].merge(nums[i], 1, Integer::sum); - size[j]++; - } - int[] f = new int[n]; - final int inf = 1 << 30; - Arrays.fill(f, inf); - f[0] = 0; - for (int i = 0; i < k; ++i) { - int[] g = new int[n]; - Arrays.fill(g, min(f) + size[i]); - for (int j = 0; j < n; ++j) { - for (var e : cnt[i].entrySet()) { - int v = e.getKey(), c = e.getValue(); - g[j] = Math.min(g[j], f[j ^ v] + size[i] - c); - } - } - f = g; - } - return f[0]; - } - - private int min(int[] arr) { - int mi = arr[0]; - for (int v : arr) { - mi = Math.min(mi, v); - } - return mi; - } +class Solution { + public int minChanges(int[] nums, int k) { + int n = 1 << 10; + Map[] cnt = new Map[k]; + Arrays.setAll(cnt, i -> new HashMap<>()); + int[] size = new int[k]; + for (int i = 0; i < nums.length; ++i) { + int j = i % k; + cnt[j].merge(nums[i], 1, Integer::sum); + size[j]++; + } + int[] f = new int[n]; + final int inf = 1 << 30; + Arrays.fill(f, inf); + f[0] = 0; + for (int i = 0; i < k; ++i) { + int[] g = new int[n]; + Arrays.fill(g, min(f) + size[i]); + for (int j = 0; j < n; ++j) { + for (var e : cnt[i].entrySet()) { + int v = e.getKey(), c = e.getValue(); + g[j] = Math.min(g[j], f[j ^ v] + size[i] - c); + } + } + f = g; + } + return f[0]; + } + + private int min(int[] arr) { + int mi = arr[0]; + for (int v : arr) { + mi = Math.min(mi, v); + } + return mi; + } } \ No newline at end of file diff --git a/solution/1700-1799/1788.Maximize the Beauty of the Garden/Solution.java b/solution/1700-1799/1788.Maximize the Beauty of the Garden/Solution.java index 3b46759c59a66..89ecd392c7cbb 100644 --- a/solution/1700-1799/1788.Maximize the Beauty of the Garden/Solution.java +++ b/solution/1700-1799/1788.Maximize the Beauty of the Garden/Solution.java @@ -1,18 +1,18 @@ -class Solution { - public int maximumBeauty(int[] flowers) { - int n = flowers.length; - int[] s = new int[n + 1]; - Map d = new HashMap<>(); - int ans = Integer.MIN_VALUE; - for (int i = 0; i < n; ++i) { - int v = flowers[i]; - if (d.containsKey(v)) { - ans = Math.max(ans, s[i] - s[d.get(v) + 1] + v * 2); - } else { - d.put(v, i); - } - s[i + 1] = s[i] + Math.max(v, 0); - } - return ans; - } +class Solution { + public int maximumBeauty(int[] flowers) { + int n = flowers.length; + int[] s = new int[n + 1]; + Map d = new HashMap<>(); + int ans = Integer.MIN_VALUE; + for (int i = 0; i < n; ++i) { + int v = flowers[i]; + if (d.containsKey(v)) { + ans = Math.max(ans, s[i] - s[d.get(v) + 1] + v * 2); + } else { + d.put(v, i); + } + s[i + 1] = s[i] + Math.max(v, 0); + } + return ans; + } } \ No newline at end of file diff --git a/solution/1700-1799/1788.Maximize the Beauty of the Garden/Solution.py b/solution/1700-1799/1788.Maximize the Beauty of the Garden/Solution.py index 37a006ae5b305..7ffcfc339da2a 100644 --- a/solution/1700-1799/1788.Maximize the Beauty of the Garden/Solution.py +++ b/solution/1700-1799/1788.Maximize the Beauty of the Garden/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def maximumBeauty(self, flowers: List[int]) -> int: - s = [0] * (len(flowers) + 1) - d = {} - ans = -inf - for i, v in enumerate(flowers): - if v in d: - ans = max(ans, s[i] - s[d[v] + 1] + v * 2) - else: - d[v] = i - s[i + 1] = s[i] + max(v, 0) - return ans +class Solution: + def maximumBeauty(self, flowers: List[int]) -> int: + s = [0] * (len(flowers) + 1) + d = {} + ans = -inf + for i, v in enumerate(flowers): + if v in d: + ans = max(ans, s[i] - s[d[v] + 1] + v * 2) + else: + d[v] = i + s[i + 1] = s[i] + max(v, 0) + return ans diff --git a/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/Solution.c b/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/Solution.c index 06f4078dc427e..d0c09052a8f16 100644 --- a/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/Solution.c +++ b/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/Solution.c @@ -20,4 +20,4 @@ bool areAlmostEqual(char* s1, char* s2) { return 0; } return s1[i1] == s2[i2] && s1[i2] == s2[i1]; -} +} \ No newline at end of file diff --git a/solution/1700-1799/1796.Second Largest Digit in a String/Solution.c b/solution/1700-1799/1796.Second Largest Digit in a String/Solution.c index 888ac544fa9b5..0c0eab19f71f3 100644 --- a/solution/1700-1799/1796.Second Largest Digit in a String/Solution.c +++ b/solution/1700-1799/1796.Second Largest Digit in a String/Solution.c @@ -13,4 +13,4 @@ int secondHighest(char* s) { } } return second; -} +} \ No newline at end of file diff --git a/solution/1700-1799/1796.Second Largest Digit in a String/Solution2.cpp b/solution/1700-1799/1796.Second Largest Digit in a String/Solution2.cpp new file mode 100644 index 0000000000000..c441b89e8f81e --- /dev/null +++ b/solution/1700-1799/1796.Second Largest Digit in a String/Solution2.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int secondHighest(string s) { + int mask = 0; + for (char& c : s) + if (isdigit(c)) mask |= 1 << c - '0'; + for (int i = 9, cnt = 0; ~i; --i) + if (mask >> i & 1 && ++cnt == 2) return i; + return -1; + } +}; \ No newline at end of file diff --git a/solution/1700-1799/1796.Second Largest Digit in a String/Solution2.go b/solution/1700-1799/1796.Second Largest Digit in a String/Solution2.go new file mode 100644 index 0000000000000..2c20464048835 --- /dev/null +++ b/solution/1700-1799/1796.Second Largest Digit in a String/Solution2.go @@ -0,0 +1,17 @@ +func secondHighest(s string) int { + mask := 0 + for _, c := range s { + if c >= '0' && c <= '9' { + mask |= 1 << int(c-'0') + } + } + for i, cnt := 9, 0; i >= 0; i-- { + if mask>>i&1 == 1 { + cnt++ + if cnt == 2 { + return i + } + } + } + return -1 +} \ No newline at end of file diff --git a/solution/1700-1799/1796.Second Largest Digit in a String/Solution2.java b/solution/1700-1799/1796.Second Largest Digit in a String/Solution2.java new file mode 100644 index 0000000000000..1068acbe267fd --- /dev/null +++ b/solution/1700-1799/1796.Second Largest Digit in a String/Solution2.java @@ -0,0 +1,17 @@ +class Solution { + public int secondHighest(String s) { + int mask = 0; + for (int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if (Character.isDigit(c)) { + mask |= 1 << (c - '0'); + } + } + for (int i = 9, cnt = 0; i >= 0; --i) { + if (((mask >> i) & 1) == 1 && ++cnt == 2) { + return i; + } + } + return -1; + } +} \ No newline at end of file diff --git a/solution/1700-1799/1796.Second Largest Digit in a String/Solution2.py b/solution/1700-1799/1796.Second Largest Digit in a String/Solution2.py new file mode 100644 index 0000000000000..5a2a9a28a0a0d --- /dev/null +++ b/solution/1700-1799/1796.Second Largest Digit in a String/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def secondHighest(self, s: str) -> int: + mask = reduce(or_, (1 << int(c) for c in s if c.isdigit()), 0) + cnt = 0 + for i in range(9, -1, -1): + if (mask >> i) & 1: + cnt += 1 + if cnt == 2: + return i + return -1 diff --git a/solution/1800-1899/1800.Maximum Ascending Subarray Sum/Solution.c b/solution/1800-1899/1800.Maximum Ascending Subarray Sum/Solution.c index 657a95f739e03..1bc33f4d04288 100644 --- a/solution/1800-1899/1800.Maximum Ascending Subarray Sum/Solution.c +++ b/solution/1800-1899/1800.Maximum Ascending Subarray Sum/Solution.c @@ -11,4 +11,4 @@ int maxAscendingSum(int* nums, int numsSize) { sum += nums[i]; } return max(res, sum); -} +} \ No newline at end of file diff --git a/solution/1800-1899/1808.Maximize Number of Nice Divisors/Solution.cpp b/solution/1800-1899/1808.Maximize Number of Nice Divisors/Solution.cpp index 4bb603ceb2174..f88a161b83e9e 100644 --- a/solution/1800-1899/1808.Maximize Number of Nice Divisors/Solution.cpp +++ b/solution/1800-1899/1808.Maximize Number of Nice Divisors/Solution.cpp @@ -1,26 +1,26 @@ -class Solution { -public: - int maxNiceDivisors(int primeFactors) { - if (primeFactors < 4) { - return primeFactors; - } - const int mod = 1e9 + 7; - auto qpow = [&](long long a, long long n) { - long long ans = 1; - for (; n; n >>= 1) { - if (n & 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return (int) ans; - }; - if (primeFactors % 3 == 0) { - return qpow(3, primeFactors / 3); - } - if (primeFactors % 3 == 1) { - return qpow(3, primeFactors / 3 - 1) * 4L % mod; - } - return qpow(3, primeFactors / 3) * 2 % mod; - } +class Solution { +public: + int maxNiceDivisors(int primeFactors) { + if (primeFactors < 4) { + return primeFactors; + } + const int mod = 1e9 + 7; + auto qpow = [&](long long a, long long n) { + long long ans = 1; + for (; n; n >>= 1) { + if (n & 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return (int) ans; + }; + if (primeFactors % 3 == 0) { + return qpow(3, primeFactors / 3); + } + if (primeFactors % 3 == 1) { + return qpow(3, primeFactors / 3 - 1) * 4L % mod; + } + return qpow(3, primeFactors / 3) * 2 % mod; + } }; \ No newline at end of file diff --git a/solution/1800-1899/1808.Maximize Number of Nice Divisors/Solution.java b/solution/1800-1899/1808.Maximize Number of Nice Divisors/Solution.java index 49c391e8477a4..cb55f4f933f6a 100644 --- a/solution/1800-1899/1808.Maximize Number of Nice Divisors/Solution.java +++ b/solution/1800-1899/1808.Maximize Number of Nice Divisors/Solution.java @@ -1,27 +1,27 @@ -class Solution { - private final int mod = (int) 1e9 + 7; - - public int maxNiceDivisors(int primeFactors) { - if (primeFactors < 4) { - return primeFactors; - } - if (primeFactors % 3 == 0) { - return qpow(3, primeFactors / 3); - } - if (primeFactors % 3 == 1) { - return (int) (4L * qpow(3, primeFactors / 3 - 1) % mod); - } - return 2 * qpow(3, primeFactors / 3) % mod; - } - - private int qpow(long a, long n) { - long ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return (int) ans; - } +class Solution { + private final int mod = (int) 1e9 + 7; + + public int maxNiceDivisors(int primeFactors) { + if (primeFactors < 4) { + return primeFactors; + } + if (primeFactors % 3 == 0) { + return qpow(3, primeFactors / 3); + } + if (primeFactors % 3 == 1) { + return (int) (4L * qpow(3, primeFactors / 3 - 1) % mod); + } + return 2 * qpow(3, primeFactors / 3) % mod; + } + + private int qpow(long a, long n) { + long ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return (int) ans; + } } \ No newline at end of file diff --git a/solution/1800-1899/1812.Determine Color of a Chessboard Square/Solution.c b/solution/1800-1899/1812.Determine Color of a Chessboard Square/Solution.c index 6d573e2fd1b04..9a3748250cfa8 100644 --- a/solution/1800-1899/1812.Determine Color of a Chessboard Square/Solution.c +++ b/solution/1800-1899/1812.Determine Color of a Chessboard Square/Solution.c @@ -1,3 +1,3 @@ bool squareIsWhite(char* coordinates) { return (coordinates[0] + coordinates[1]) & 1; -} +} \ No newline at end of file diff --git a/solution/1800-1899/1814.Count Nice Pairs in an Array/Solution2.cpp b/solution/1800-1899/1814.Count Nice Pairs in an Array/Solution2.cpp new file mode 100644 index 0000000000000..759959dc3ef90 --- /dev/null +++ b/solution/1800-1899/1814.Count Nice Pairs in an Array/Solution2.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int countNicePairs(vector& nums) { + auto rev = [](int x) { + int y = 0; + for (; x > 0; x /= 10) { + y = y * 10 + x % 10; + } + return y; + }; + unordered_map cnt; + int ans = 0; + const int mod = 1e9 + 7; + for (int& x : nums) { + int y = x - rev(x); + ans = (ans + cnt[y]++) % mod; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1800-1899/1814.Count Nice Pairs in an Array/Solution2.go b/solution/1800-1899/1814.Count Nice Pairs in an Array/Solution2.go new file mode 100644 index 0000000000000..982a2b9c3ac64 --- /dev/null +++ b/solution/1800-1899/1814.Count Nice Pairs in an Array/Solution2.go @@ -0,0 +1,16 @@ +func countNicePairs(nums []int) (ans int) { + rev := func(x int) (y int) { + for ; x > 0; x /= 10 { + y = y*10 + x%10 + } + return + } + cnt := map[int]int{} + const mod int = 1e9 + 7 + for _, x := range nums { + y := x - rev(x) + ans = (ans + cnt[y]) % mod + cnt[y]++ + } + return +} \ No newline at end of file diff --git a/solution/1800-1899/1814.Count Nice Pairs in an Array/Solution2.java b/solution/1800-1899/1814.Count Nice Pairs in an Array/Solution2.java new file mode 100644 index 0000000000000..4885a99178998 --- /dev/null +++ b/solution/1800-1899/1814.Count Nice Pairs in an Array/Solution2.java @@ -0,0 +1,21 @@ +class Solution { + public int countNicePairs(int[] nums) { + Map cnt = new HashMap<>(); + final int mod = (int) 1e9 + 7; + int ans = 0; + for (int x : nums) { + int y = x - rev(x); + ans = (ans + cnt.getOrDefault(y, 0)) % mod; + cnt.merge(y, 1, Integer::sum); + } + return ans; + } + + private int rev(int x) { + int y = 0; + for (; x > 0; x /= 10) { + y = y * 10 + x % 10; + } + return y; + } +} \ No newline at end of file diff --git a/solution/1800-1899/1814.Count Nice Pairs in an Array/Solution2.js b/solution/1800-1899/1814.Count Nice Pairs in an Array/Solution2.js new file mode 100644 index 0000000000000..c21e23d3804d7 --- /dev/null +++ b/solution/1800-1899/1814.Count Nice Pairs in an Array/Solution2.js @@ -0,0 +1,23 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var countNicePairs = function (nums) { + const rev = x => { + let y = 0; + for (; x > 0; x = Math.floor(x / 10)) { + y = y * 10 + (x % 10); + } + return y; + }; + let ans = 0; + const mod = 1e9 + 7; + const cnt = new Map(); + for (const x of nums) { + const y = x - rev(x); + const v = cnt.get(y) | 0; + ans = (ans + v) % mod; + cnt.set(y, v + 1); + } + return ans; +}; diff --git a/solution/1800-1899/1814.Count Nice Pairs in an Array/Solution2.py b/solution/1800-1899/1814.Count Nice Pairs in an Array/Solution2.py new file mode 100644 index 0000000000000..12b79bc552999 --- /dev/null +++ b/solution/1800-1899/1814.Count Nice Pairs in an Array/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def countNicePairs(self, nums: List[int]) -> int: + def rev(x): + y = 0 + while x: + y = y * 10 + x % 10 + x //= 10 + return y + + ans = 0 + mod = 10**9 + 7 + cnt = Counter() + for x in nums: + y = x - rev(x) + ans += cnt[y] + cnt[y] += 1 + return ans % mod diff --git a/solution/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/Solution2.py b/solution/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/Solution2.py new file mode 100644 index 0000000000000..65adc96b7b39d --- /dev/null +++ b/solution/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def maxHappyGroups(self, batchSize: int, groups: List[int]) -> int: + @cache + def dfs(state, x): + if state == mask: + return 0 + vis = [False] * batchSize + res = 0 + for i, v in enumerate(g): + if state >> i & 1 == 0 and not vis[v]: + vis[v] = True + y = (x + v) % batchSize + res = max(res, dfs(state | 1 << i, y)) + return res + (x == 0) + + g = [v % batchSize for v in groups if v % batchSize] + mask = (1 << len(g)) - 1 + return len(groups) - len(g) + dfs(0, 0) diff --git a/solution/1800-1899/1816.Truncate Sentence/Solution.py b/solution/1800-1899/1816.Truncate Sentence/Solution.py index d09754481cf19..9bdc18808b7e6 100644 --- a/solution/1800-1899/1816.Truncate Sentence/Solution.py +++ b/solution/1800-1899/1816.Truncate Sentence/Solution.py @@ -1,7 +1,3 @@ class Solution: def truncateSentence(self, s: str, k: int) -> str: - for i, c in enumerate(s): - k -= c == ' ' - if k == 0: - return s[:i] - return s + return ' '.join(s.split()[:k]) diff --git a/solution/1800-1899/1816.Truncate Sentence/Solution2.py b/solution/1800-1899/1816.Truncate Sentence/Solution2.py new file mode 100644 index 0000000000000..d09754481cf19 --- /dev/null +++ b/solution/1800-1899/1816.Truncate Sentence/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def truncateSentence(self, s: str, k: int) -> str: + for i, c in enumerate(s): + k -= c == ' ' + if k == 0: + return s[:i] + return s diff --git a/solution/1800-1899/1818.Minimum Absolute Sum Difference/Solution.cpp b/solution/1800-1899/1818.Minimum Absolute Sum Difference/Solution.cpp index e884fb6e44e97..b204759972644 100644 --- a/solution/1800-1899/1818.Minimum Absolute Sum Difference/Solution.cpp +++ b/solution/1800-1899/1818.Minimum Absolute Sum Difference/Solution.cpp @@ -1,26 +1,26 @@ -class Solution { -public: - int minAbsoluteSumDiff(vector& nums1, vector& nums2) { - const int mod = 1e9 + 7; - vector nums(nums1); - sort(nums.begin(), nums.end()); - int s = 0, n = nums.size(); - for (int i = 0; i < n; ++i) { - s = (s + abs(nums1[i] - nums2[i])) % mod; - } - int mx = 0; - for (int i = 0; i < n; ++i) { - int d1 = abs(nums1[i] - nums2[i]); - int d2 = 1 << 30; - int j = lower_bound(nums.begin(), nums.end(), nums2[i]) - nums.begin(); - if (j < n) { - d2 = min(d2, abs(nums[j] - nums2[i])); - } - if (j) { - d2 = min(d2, abs(nums[j - 1] - nums2[i])); - } - mx = max(mx, d1 - d2); - } - return (s - mx + mod) % mod; - } +class Solution { +public: + int minAbsoluteSumDiff(vector& nums1, vector& nums2) { + const int mod = 1e9 + 7; + vector nums(nums1); + sort(nums.begin(), nums.end()); + int s = 0, n = nums.size(); + for (int i = 0; i < n; ++i) { + s = (s + abs(nums1[i] - nums2[i])) % mod; + } + int mx = 0; + for (int i = 0; i < n; ++i) { + int d1 = abs(nums1[i] - nums2[i]); + int d2 = 1 << 30; + int j = lower_bound(nums.begin(), nums.end(), nums2[i]) - nums.begin(); + if (j < n) { + d2 = min(d2, abs(nums[j] - nums2[i])); + } + if (j) { + d2 = min(d2, abs(nums[j - 1] - nums2[i])); + } + mx = max(mx, d1 - d2); + } + return (s - mx + mod) % mod; + } }; \ No newline at end of file diff --git a/solution/1800-1899/1818.Minimum Absolute Sum Difference/Solution.java b/solution/1800-1899/1818.Minimum Absolute Sum Difference/Solution.java index 3ab70c2f232a8..0ca964e63c0a6 100644 --- a/solution/1800-1899/1818.Minimum Absolute Sum Difference/Solution.java +++ b/solution/1800-1899/1818.Minimum Absolute Sum Difference/Solution.java @@ -1,38 +1,38 @@ -class Solution { - public int minAbsoluteSumDiff(int[] nums1, int[] nums2) { - final int mod = (int) 1e9 + 7; - int[] nums = nums1.clone(); - Arrays.sort(nums); - int s = 0, n = nums.length; - for (int i = 0; i < n; ++i) { - s = (s + Math.abs(nums1[i] - nums2[i])) % mod; - } - int mx = 0; - for (int i = 0; i < n; ++i) { - int d1 = Math.abs(nums1[i] - nums2[i]); - int d2 = 1 << 30; - int j = search(nums, nums2[i]); - if (j < n) { - d2 = Math.min(d2, Math.abs(nums[j] - nums2[i])); - } - if (j > 0) { - d2 = Math.min(d2, Math.abs(nums[j - 1] - nums2[i])); - } - mx = Math.max(mx, d1 - d2); - } - return (s - mx + mod) % mod; - } - - private int search(int[] nums, int x) { - int left = 0, right = nums.length; - while (left < right) { - int mid = (left + right) >>> 1; - if (nums[mid] >= x) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - } +class Solution { + public int minAbsoluteSumDiff(int[] nums1, int[] nums2) { + final int mod = (int) 1e9 + 7; + int[] nums = nums1.clone(); + Arrays.sort(nums); + int s = 0, n = nums.length; + for (int i = 0; i < n; ++i) { + s = (s + Math.abs(nums1[i] - nums2[i])) % mod; + } + int mx = 0; + for (int i = 0; i < n; ++i) { + int d1 = Math.abs(nums1[i] - nums2[i]); + int d2 = 1 << 30; + int j = search(nums, nums2[i]); + if (j < n) { + d2 = Math.min(d2, Math.abs(nums[j] - nums2[i])); + } + if (j > 0) { + d2 = Math.min(d2, Math.abs(nums[j - 1] - nums2[i])); + } + mx = Math.max(mx, d1 - d2); + } + return (s - mx + mod) % mod; + } + + private int search(int[] nums, int x) { + int left = 0, right = nums.length; + while (left < right) { + int mid = (left + right) >>> 1; + if (nums[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } } \ No newline at end of file diff --git a/solution/1800-1899/1818.Minimum Absolute Sum Difference/Solution.py b/solution/1800-1899/1818.Minimum Absolute Sum Difference/Solution.py index 84eea52769157..bbb2a221d46fb 100644 --- a/solution/1800-1899/1818.Minimum Absolute Sum Difference/Solution.py +++ b/solution/1800-1899/1818.Minimum Absolute Sum Difference/Solution.py @@ -1,15 +1,15 @@ -class Solution: - def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int: - mod = 10**9 + 7 - nums = sorted(nums1) - s = sum(abs(a - b) for a, b in zip(nums1, nums2)) % mod - mx = 0 - for a, b in zip(nums1, nums2): - d1, d2 = abs(a - b), inf - i = bisect_left(nums, b) - if i < len(nums): - d2 = min(d2, abs(nums[i] - b)) - if i: - d2 = min(d2, abs(nums[i - 1] - b)) - mx = max(mx, d1 - d2) - return (s - mx + mod) % mod +class Solution: + def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int: + mod = 10**9 + 7 + nums = sorted(nums1) + s = sum(abs(a - b) for a, b in zip(nums1, nums2)) % mod + mx = 0 + for a, b in zip(nums1, nums2): + d1, d2 = abs(a - b), inf + i = bisect_left(nums, b) + if i < len(nums): + d2 = min(d2, abs(nums[i] - b)) + if i: + d2 = min(d2, abs(nums[i - 1] - b)) + mx = max(mx, d1 - d2) + return (s - mx + mod) % mod diff --git a/solution/1800-1899/1822.Sign of the Product of an Array/Solution.c b/solution/1800-1899/1822.Sign of the Product of an Array/Solution.c index 782e3cea909e6..a738c77c96550 100644 --- a/solution/1800-1899/1822.Sign of the Product of an Array/Solution.c +++ b/solution/1800-1899/1822.Sign of the Product of an Array/Solution.c @@ -9,4 +9,4 @@ int arraySign(int* nums, int numsSize) { } } return ans; -} +} \ No newline at end of file diff --git a/solution/1800-1899/1825.Finding MK Average/Solution2.py b/solution/1800-1899/1825.Finding MK Average/Solution2.py new file mode 100644 index 0000000000000..da39efcc0edff --- /dev/null +++ b/solution/1800-1899/1825.Finding MK Average/Solution2.py @@ -0,0 +1,44 @@ +from sortedcontainers import SortedList + + +class MKAverage: + def __init__(self, m: int, k: int): + self.m = m + self.k = k + self.sl = SortedList() + self.q = deque() + self.s = 0 + + def addElement(self, num: int) -> None: + self.q.append(num) + if len(self.q) == self.m: + self.sl = SortedList(self.q) + self.s = sum(self.sl[self.k : -self.k]) + elif len(self.q) > self.m: + i = self.sl.bisect_left(num) + if i < self.k: + self.s += self.sl[self.k - 1] + elif self.k <= i <= self.m - self.k: + self.s += num + else: + self.s += self.sl[self.m - self.k] + self.sl.add(num) + + x = self.q.popleft() + i = self.sl.bisect_left(x) + if i < self.k: + self.s -= self.sl[self.k] + elif self.k <= i <= self.m - self.k: + self.s -= x + else: + self.s -= self.sl[self.m - self.k] + self.sl.remove(x) + + def calculateMKAverage(self) -> int: + return -1 if len(self.sl) < self.m else self.s // (self.m - self.k * 2) + + +# Your MKAverage object will be instantiated and called as such: +# obj = MKAverage(m, k) +# obj.addElement(num) +# param_2 = obj.calculateMKAverage() diff --git a/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/Solution.c b/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/Solution.c index 803bfc19be1c0..f63e3cec454c8 100644 --- a/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/Solution.c +++ b/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/Solution.c @@ -8,4 +8,4 @@ int minOperations(int* nums, int numsSize) { mx = max(mx + 1, nums[i]); } return ans; -} +} \ No newline at end of file diff --git a/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/Solution.cs b/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/Solution.cs index f589ad76fd04d..735fc4934d124 100644 --- a/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/Solution.cs +++ b/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/Solution.cs @@ -7,4 +7,4 @@ public int MinOperations(int[] nums) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/1800-1899/1828.Queries on Number of Points Inside a Circle/Solution.c b/solution/1800-1899/1828.Queries on Number of Points Inside a Circle/Solution.c index 4fb03900f64e6..6d62df599b5a9 100644 --- a/solution/1800-1899/1828.Queries on Number of Points Inside a Circle/Solution.c +++ b/solution/1800-1899/1828.Queries on Number of Points Inside a Circle/Solution.c @@ -18,4 +18,4 @@ int* countPoints(int** points, int pointsSize, int* pointsColSize, int** queries } *returnSize = queriesSize; return ans; -} +} \ No newline at end of file diff --git a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.cpp b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.cpp index 119dd94f5b477..5cf37187658fd 100644 --- a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.cpp +++ b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.cpp @@ -5,12 +5,16 @@ class Solution { for (int& x : nums) { xs ^= x; } - int mask = (1 << maximumBit) - 1; int n = nums.size(); vector ans(n); for (int i = 0; i < n; ++i) { int x = nums[n - i - 1]; - int k = xs ^ mask; + int k = 0; + for (int j = maximumBit - 1; ~j; --j) { + if ((xs >> j & 1) == 0) { + k |= 1 << j; + } + } ans[i] = k; xs ^= x; } diff --git a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.cs b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.cs index 8d64c7bdf98ff..095798ecad109 100644 --- a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.cs +++ b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.cs @@ -4,15 +4,19 @@ public int[] GetMaximumXor(int[] nums, int maximumBit) { foreach (int x in nums) { xs ^= x; } - int mask = (1 << maximumBit) - 1; int n = nums.Length; int[] ans = new int[n]; for (int i = 0; i < n; ++i) { int x = nums[n - i - 1]; - int k = xs ^ mask; + int k = 0; + for (int j = maximumBit - 1; j >= 0; --j) { + if ((xs >> j & 1) == 0) { + k |= 1 << j; + } + } ans[i] = k; xs ^= x; } return ans; } -} \ No newline at end of file +} diff --git a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.go b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.go index f98ff96aa20e2..2191f30df2f03 100644 --- a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.go +++ b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.go @@ -3,10 +3,14 @@ func getMaximumXor(nums []int, maximumBit int) (ans []int) { for _, x := range nums { xs ^= x } - mask := (1 << maximumBit) - 1 for i := range nums { x := nums[len(nums)-i-1] - k := xs ^ mask + k := 0 + for j := maximumBit - 1; j >= 0; j-- { + if xs>>j&1 == 0 { + k |= 1 << j + } + } ans = append(ans, k) xs ^= x } diff --git a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.java b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.java index d67c579b56770..70a57127a927b 100644 --- a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.java +++ b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.java @@ -1,15 +1,19 @@ class Solution { public int[] getMaximumXor(int[] nums, int maximumBit) { + int n = nums.length; int xs = 0; for (int x : nums) { xs ^= x; } - int mask = (1 << maximumBit) - 1; - int n = nums.length; int[] ans = new int[n]; for (int i = 0; i < n; ++i) { int x = nums[n - i - 1]; - int k = xs ^ mask; + int k = 0; + for (int j = maximumBit - 1; j >= 0; --j) { + if (((xs >> j) & 1) == 0) { + k |= 1 << j; + } + } ans[i] = k; xs ^= x; } diff --git a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.js b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.js index a90a3329449e3..5d33d693dfd82 100644 --- a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.js +++ b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.js @@ -8,12 +8,16 @@ var getMaximumXor = function (nums, maximumBit) { for (const x of nums) { xs ^= x; } - const mask = (1 << maximumBit) - 1; const n = nums.length; const ans = new Array(n); for (let i = 0; i < n; ++i) { const x = nums[n - i - 1]; - let k = xs ^ mask; + let k = 0; + for (let j = maximumBit - 1; j >= 0; --j) { + if (((xs >> j) & 1) == 0) { + k |= 1 << j; + } + } ans[i] = k; xs ^= x; } diff --git a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.py b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.py index 54479e2d6b6d6..4388dd883bc09 100644 --- a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.py +++ b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.py @@ -2,9 +2,11 @@ class Solution: def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]: ans = [] xs = reduce(xor, nums) - mask = (1 << maximumBit) - 1 for x in nums[::-1]: - k = xs ^ mask + k = 0 + for i in range(maximumBit - 1, -1, -1): + if (xs >> i & 1) == 0: + k |= 1 << i ans.append(k) xs ^= x return ans diff --git a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.ts b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.ts index f0c02f1ecdf40..41712f660778c 100644 --- a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.ts +++ b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution.ts @@ -3,12 +3,16 @@ function getMaximumXor(nums: number[], maximumBit: number): number[] { for (const x of nums) { xs ^= x; } - const mask = (1 << maximumBit) - 1; const n = nums.length; const ans = new Array(n); for (let i = 0; i < n; ++i) { const x = nums[n - i - 1]; - let k = xs ^ mask; + let k = 0; + for (let j = maximumBit - 1; j >= 0; --j) { + if (((xs >> j) & 1) == 0) { + k |= 1 << j; + } + } ans[i] = k; xs ^= x; } diff --git a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.cpp b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.cpp new file mode 100644 index 0000000000000..119dd94f5b477 --- /dev/null +++ b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + vector getMaximumXor(vector& nums, int maximumBit) { + int xs = 0; + for (int& x : nums) { + xs ^= x; + } + int mask = (1 << maximumBit) - 1; + int n = nums.size(); + vector ans(n); + for (int i = 0; i < n; ++i) { + int x = nums[n - i - 1]; + int k = xs ^ mask; + ans[i] = k; + xs ^= x; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.cs b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.cs new file mode 100644 index 0000000000000..7941e1cc4922b --- /dev/null +++ b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.cs @@ -0,0 +1,18 @@ +public class Solution { + public int[] GetMaximumXor(int[] nums, int maximumBit) { + int xs = 0; + foreach (int x in nums) { + xs ^= x; + } + int mask = (1 << maximumBit) - 1; + int n = nums.Length; + int[] ans = new int[n]; + for (int i = 0; i < n; ++i) { + int x = nums[n - i - 1]; + int k = xs ^ mask; + ans[i] = k; + xs ^= x; + } + return ans; + } +} diff --git a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.go b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.go new file mode 100644 index 0000000000000..f98ff96aa20e2 --- /dev/null +++ b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.go @@ -0,0 +1,14 @@ +func getMaximumXor(nums []int, maximumBit int) (ans []int) { + xs := 0 + for _, x := range nums { + xs ^= x + } + mask := (1 << maximumBit) - 1 + for i := range nums { + x := nums[len(nums)-i-1] + k := xs ^ mask + ans = append(ans, k) + xs ^= x + } + return +} \ No newline at end of file diff --git a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.java b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.java new file mode 100644 index 0000000000000..d67c579b56770 --- /dev/null +++ b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.java @@ -0,0 +1,18 @@ +class Solution { + public int[] getMaximumXor(int[] nums, int maximumBit) { + int xs = 0; + for (int x : nums) { + xs ^= x; + } + int mask = (1 << maximumBit) - 1; + int n = nums.length; + int[] ans = new int[n]; + for (int i = 0; i < n; ++i) { + int x = nums[n - i - 1]; + int k = xs ^ mask; + ans[i] = k; + xs ^= x; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.js b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.js new file mode 100644 index 0000000000000..a90a3329449e3 --- /dev/null +++ b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.js @@ -0,0 +1,21 @@ +/** + * @param {number[]} nums + * @param {number} maximumBit + * @return {number[]} + */ +var getMaximumXor = function (nums, maximumBit) { + let xs = 0; + for (const x of nums) { + xs ^= x; + } + const mask = (1 << maximumBit) - 1; + const n = nums.length; + const ans = new Array(n); + for (let i = 0; i < n; ++i) { + const x = nums[n - i - 1]; + let k = xs ^ mask; + ans[i] = k; + xs ^= x; + } + return ans; +}; diff --git a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.py b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.py new file mode 100644 index 0000000000000..54479e2d6b6d6 --- /dev/null +++ b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]: + ans = [] + xs = reduce(xor, nums) + mask = (1 << maximumBit) - 1 + for x in nums[::-1]: + k = xs ^ mask + ans.append(k) + xs ^= x + return ans diff --git a/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.ts b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.ts new file mode 100644 index 0000000000000..f0c02f1ecdf40 --- /dev/null +++ b/solution/1800-1899/1829.Maximum XOR for Each Query/Solution2.ts @@ -0,0 +1,16 @@ +function getMaximumXor(nums: number[], maximumBit: number): number[] { + let xs = 0; + for (const x of nums) { + xs ^= x; + } + const mask = (1 << maximumBit) - 1; + const n = nums.length; + const ans = new Array(n); + for (let i = 0; i < n; ++i) { + const x = nums[n - i - 1]; + let k = xs ^ mask; + ans[i] = k; + xs ^= x; + } + return ans; +} diff --git a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.c b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.c index c7287aee419a2..f5f434ec768d6 100644 --- a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.c +++ b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.c @@ -1,7 +1,12 @@ bool checkIfPangram(char* sentence) { - int mark = 0; + int vis[26] = {0}; for (int i = 0; sentence[i]; i++) { - mark |= 1 << (sentence[i] - 'a'); + vis[sentence[i] - 'a'] = 1; } - return mark == (1 << 26) - 1; -} + for (int i = 0; i < 26; i++) { + if (!vis[i]) { + return 0; + } + } + return 1; +} \ No newline at end of file diff --git a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.cpp b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.cpp index 196b129c7394c..01a555a4171dd 100644 --- a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.cpp +++ b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.cpp @@ -1,8 +1,10 @@ class Solution { public: bool checkIfPangram(string sentence) { - int mask = 0; - for (char& c : sentence) mask |= 1 << (c - 'a'); - return mask == (1 << 26) - 1; + int vis[26] = {0}; + for (char& c : sentence) vis[c - 'a'] = 1; + for (int& v : vis) + if (!v) return false; + return true; } }; \ No newline at end of file diff --git a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.go b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.go index 79a8f1511d53f..293acd11239a4 100644 --- a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.go +++ b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.go @@ -1,7 +1,12 @@ func checkIfPangram(sentence string) bool { - mask := 0 + vis := [26]bool{} for _, c := range sentence { - mask |= 1 << int(c-'a') + vis[c-'a'] = true } - return mask == 1<<26-1 + for _, v := range vis { + if !v { + return false + } + } + return true } \ No newline at end of file diff --git a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.java b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.java index e669632eb76fa..f05c57389c693 100644 --- a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.java +++ b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.java @@ -1,9 +1,14 @@ class Solution { public boolean checkIfPangram(String sentence) { - int mask = 0; + boolean[] vis = new boolean[26]; for (int i = 0; i < sentence.length(); ++i) { - mask |= 1 << (sentence.charAt(i) - 'a'); + vis[sentence.charAt(i) - 'a'] = true; } - return mask == (1 << 26) - 1; + for (boolean v : vis) { + if (!v) { + return false; + } + } + return true; } } \ No newline at end of file diff --git a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.rs b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.rs index 3017c642b8163..0f536e04c7132 100644 --- a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.rs +++ b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.rs @@ -1,9 +1,9 @@ impl Solution { pub fn check_if_pangram(sentence: String) -> bool { - let mut mark = 0; + let mut vis = [false; 26]; for c in sentence.as_bytes() { - mark |= 1 << (*c - b'a'); + vis[(*c - b'a') as usize] = true; } - mark == (1 << 26) - 1 + vis.iter().all(|v| *v) } } diff --git a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.ts b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.ts index 79536d7fd7b89..b9f8d584fb4be 100644 --- a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.ts +++ b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution.ts @@ -1,7 +1,7 @@ function checkIfPangram(sentence: string): boolean { - let mark = 0; + const vis = new Array(26).fill(false); for (const c of sentence) { - mark |= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0)); + vis[c.charCodeAt(0) - 'a'.charCodeAt(0)] = true; } - return mark === (1 << 26) - 1; + return vis.every(v => v); } diff --git a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.c b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.c new file mode 100644 index 0000000000000..219e72333ba23 --- /dev/null +++ b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.c @@ -0,0 +1,7 @@ +bool checkIfPangram(char* sentence) { + int mark = 0; + for (int i = 0; sentence[i]; i++) { + mark |= 1 << (sentence[i] - 'a'); + } + return mark == (1 << 26) - 1; +} \ No newline at end of file diff --git a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.cpp b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.cpp new file mode 100644 index 0000000000000..196b129c7394c --- /dev/null +++ b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.cpp @@ -0,0 +1,8 @@ +class Solution { +public: + bool checkIfPangram(string sentence) { + int mask = 0; + for (char& c : sentence) mask |= 1 << (c - 'a'); + return mask == (1 << 26) - 1; + } +}; \ No newline at end of file diff --git a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.go b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.go new file mode 100644 index 0000000000000..79a8f1511d53f --- /dev/null +++ b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.go @@ -0,0 +1,7 @@ +func checkIfPangram(sentence string) bool { + mask := 0 + for _, c := range sentence { + mask |= 1 << int(c-'a') + } + return mask == 1<<26-1 +} \ No newline at end of file diff --git a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.java b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.java new file mode 100644 index 0000000000000..e669632eb76fa --- /dev/null +++ b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.java @@ -0,0 +1,9 @@ +class Solution { + public boolean checkIfPangram(String sentence) { + int mask = 0; + for (int i = 0; i < sentence.length(); ++i) { + mask |= 1 << (sentence.charAt(i) - 'a'); + } + return mask == (1 << 26) - 1; + } +} \ No newline at end of file diff --git a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.py b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.py new file mode 100644 index 0000000000000..6f16ab6446884 --- /dev/null +++ b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.py @@ -0,0 +1,6 @@ +class Solution: + def checkIfPangram(self, sentence: str) -> bool: + mask = 0 + for c in sentence: + mask |= 1 << (ord(c) - ord('a')) + return mask == (1 << 26) - 1 diff --git a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.rs b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.rs new file mode 100644 index 0000000000000..3017c642b8163 --- /dev/null +++ b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.rs @@ -0,0 +1,9 @@ +impl Solution { + pub fn check_if_pangram(sentence: String) -> bool { + let mut mark = 0; + for c in sentence.as_bytes() { + mark |= 1 << (*c - b'a'); + } + mark == (1 << 26) - 1 + } +} diff --git a/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.ts b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.ts new file mode 100644 index 0000000000000..79536d7fd7b89 --- /dev/null +++ b/solution/1800-1899/1832.Check if the Sentence Is Pangram/Solution2.ts @@ -0,0 +1,7 @@ +function checkIfPangram(sentence: string): boolean { + let mark = 0; + for (const c of sentence) { + mark |= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0)); + } + return mark === (1 << 26) - 1; +} diff --git a/solution/1800-1899/1837.Sum of Digits in Base K/Solution.c b/solution/1800-1899/1837.Sum of Digits in Base K/Solution.c index f7360f291f4a4..199dbe924d56e 100644 --- a/solution/1800-1899/1837.Sum of Digits in Base K/Solution.c +++ b/solution/1800-1899/1837.Sum of Digits in Base K/Solution.c @@ -5,4 +5,4 @@ int sumBase(int n, int k) { n /= k; } return ans; -} +} \ No newline at end of file diff --git a/solution/1800-1899/1838.Frequency of the Most Frequent Element/Solution2.cpp b/solution/1800-1899/1838.Frequency of the Most Frequent Element/Solution2.cpp new file mode 100644 index 0000000000000..2d915717b51e7 --- /dev/null +++ b/solution/1800-1899/1838.Frequency of the Most Frequent Element/Solution2.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int maxFrequency(vector& nums, int k) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + long long s[n + 1]; + s[0] = 0; + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + int left = 1, right = n; + auto check = [&](int cnt) { + for (int i = 0; i < n + 1 - cnt; ++i) { + int j = i + cnt - 1; + if (1LL * nums[j] * cnt - (s[j + 1] - s[i]) <= k) { + return true; + } + } + return false; + }; + while (left < right) { + int mid = (left + right + 1) >> 1; + if (check(mid)) { + left = mid; + } else { + right = mid - 1; + } + } + return left; + } +}; \ No newline at end of file diff --git a/solution/1800-1899/1838.Frequency of the Most Frequent Element/Solution2.go b/solution/1800-1899/1838.Frequency of the Most Frequent Element/Solution2.go new file mode 100644 index 0000000000000..007b156cddcb7 --- /dev/null +++ b/solution/1800-1899/1838.Frequency of the Most Frequent Element/Solution2.go @@ -0,0 +1,27 @@ +func maxFrequency(nums []int, k int) int { + sort.Ints(nums) + n := len(nums) + s := make([]int, n+1) + for i, x := range nums { + s[i+1] = s[i] + x + } + left, right := 1, n + check := func(cnt int) bool { + for i := 0; i < n+1-cnt; i++ { + j := i + cnt - 1 + if nums[j]*cnt-(s[j+1]-s[i]) <= k { + return true + } + } + return false + } + for left < right { + mid := (left + right + 1) >> 1 + if check(mid) { + left = mid + } else { + right = mid - 1 + } + } + return left +} \ No newline at end of file diff --git a/solution/1800-1899/1838.Frequency of the Most Frequent Element/Solution2.java b/solution/1800-1899/1838.Frequency of the Most Frequent Element/Solution2.java new file mode 100644 index 0000000000000..5d3273e3c152a --- /dev/null +++ b/solution/1800-1899/1838.Frequency of the Most Frequent Element/Solution2.java @@ -0,0 +1,37 @@ +class Solution { + private long[] s; + private int[] nums; + private int n; + private int k; + + public int maxFrequency(int[] nums, int k) { + n = nums.length; + Arrays.sort(nums); + this.nums = nums; + this.s = new long[n + 1]; + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + this.k = k; + int left = 1, right = n; + while (left < right) { + int mid = (left + right + 1) >>> 1; + if (check(mid)) { + left = mid; + } else { + right = mid - 1; + } + } + return left; + } + + private boolean check(int cnt) { + for (int i = 0; i < n + 1 - cnt; ++i) { + int j = i + cnt - 1; + if (1L * nums[j] * cnt - (s[j + 1] - s[i]) <= k) { + return true; + } + } + return false; + } +} \ No newline at end of file diff --git a/solution/1800-1899/1838.Frequency of the Most Frequent Element/Solution2.js b/solution/1800-1899/1838.Frequency of the Most Frequent Element/Solution2.js new file mode 100644 index 0000000000000..3184ad9c3472e --- /dev/null +++ b/solution/1800-1899/1838.Frequency of the Most Frequent Element/Solution2.js @@ -0,0 +1,33 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var maxFrequency = function (nums, k) { + nums.sort((a, b) => a - b); + const n = nums.length; + const s = new Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + const check = cnt => { + for (let i = 0; i < n + 1 - cnt; ++i) { + const j = i + cnt - 1; + if (nums[j] * cnt - (s[j + 1] - s[i]) <= k) { + return true; + } + } + return false; + }; + let left = 1; + let right = n; + while (left < right) { + const mid = (left + right + 1) >> 1; + if (check(mid)) { + left = mid; + } else { + right = mid - 1; + } + } + return left; +}; diff --git a/solution/1800-1899/1838.Frequency of the Most Frequent Element/Solution2.py b/solution/1800-1899/1838.Frequency of the Most Frequent Element/Solution2.py new file mode 100644 index 0000000000000..5346f7e29e959 --- /dev/null +++ b/solution/1800-1899/1838.Frequency of the Most Frequent Element/Solution2.py @@ -0,0 +1,20 @@ +class Solution: + def maxFrequency(self, nums: List[int], k: int) -> int: + def check(cnt): + for i in range(n + 1 - cnt): + j = i + cnt - 1 + if nums[j] * cnt - (s[j + 1] - s[i]) <= k: + return True + return False + + nums.sort() + s = list(accumulate(nums, initial=0)) + n = len(nums) + left, right = 1, n + while left < right: + mid = (left + right + 1) >> 1 + if check(mid): + left = mid + else: + right = mid - 1 + return left diff --git a/solution/1800-1899/1838.Frequency of the Most Frequent Element/Solution2.ts b/solution/1800-1899/1838.Frequency of the Most Frequent Element/Solution2.ts new file mode 100644 index 0000000000000..29d50892147be --- /dev/null +++ b/solution/1800-1899/1838.Frequency of the Most Frequent Element/Solution2.ts @@ -0,0 +1,28 @@ +function maxFrequency(nums: number[], k: number): number { + nums.sort((a, b) => a - b); + const n = nums.length; + const s = new Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + const check = (cnt: number) => { + for (let i = 0; i < n + 1 - cnt; ++i) { + const j = i + cnt - 1; + if (nums[j] * cnt - (s[j + 1] - s[i]) <= k) { + return true; + } + } + return false; + }; + let left = 1; + let right = n; + while (left < right) { + const mid = (left + right + 1) >> 1; + if (check(mid)) { + left = mid; + } else { + right = mid - 1; + } + } + return left; +} diff --git a/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.cpp b/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.cpp index 90cd4d6a6c389..8b1413425a2d0 100644 --- a/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.cpp +++ b/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - string nextPalindrome(string num) { - int n = num.size(); - string nums = num.substr(0, n / 2); - if (!next_permutation(begin(nums), end(nums))) { - return ""; - } - for (int i = 0; i < n / 2; ++i) { - num[i] = nums[i]; - num[n - i - 1] = nums[i]; - } - return num; - } +class Solution { +public: + string nextPalindrome(string num) { + int n = num.size(); + string nums = num.substr(0, n / 2); + if (!next_permutation(begin(nums), end(nums))) { + return ""; + } + for (int i = 0; i < n / 2; ++i) { + num[i] = nums[i]; + num[n - i - 1] = nums[i]; + } + return num; + } }; \ No newline at end of file diff --git a/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.java b/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.java index b2abe6bbff2e3..0bcfc7afc995a 100644 --- a/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.java +++ b/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.java @@ -1,39 +1,39 @@ -class Solution { - public String nextPalindrome(String num) { - char[] nums = num.toCharArray(); - if (!nextPermutation(nums)) { - return ""; - } - int n = nums.length; - for (int i = 0; i < n / 2; ++i) { - nums[n - 1 - i] = nums[i]; - } - return String.valueOf(nums); - } - - private boolean nextPermutation(char[] nums) { - int n = nums.length / 2; - int i = n - 2; - while (i >= 0 && nums[i] >= nums[i + 1]) { - --i; - } - if (i < 0) { - return false; - } - int j = n - 1; - while (j >= 0 && nums[i] >= nums[j]) { - --j; - } - swap(nums, i++, j); - for (j = n - 1; i < j; ++i, --j) { - swap(nums, i, j); - } - return true; - } - - private void swap(char[] nums, int i, int j) { - char t = nums[i]; - nums[i] = nums[j]; - nums[j] = t; - } +class Solution { + public String nextPalindrome(String num) { + char[] nums = num.toCharArray(); + if (!nextPermutation(nums)) { + return ""; + } + int n = nums.length; + for (int i = 0; i < n / 2; ++i) { + nums[n - 1 - i] = nums[i]; + } + return String.valueOf(nums); + } + + private boolean nextPermutation(char[] nums) { + int n = nums.length / 2; + int i = n - 2; + while (i >= 0 && nums[i] >= nums[i + 1]) { + --i; + } + if (i < 0) { + return false; + } + int j = n - 1; + while (j >= 0 && nums[i] >= nums[j]) { + --j; + } + swap(nums, i++, j); + for (j = n - 1; i < j; ++i, --j) { + swap(nums, i, j); + } + return true; + } + + private void swap(char[] nums, int i, int j) { + char t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } } \ No newline at end of file diff --git a/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.py b/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.py index a555ffdf7a0e9..07923bd3994ed 100644 --- a/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.py +++ b/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.py @@ -1,23 +1,23 @@ -class Solution: - def nextPalindrome(self, num: str) -> str: - def next_permutation(nums: List[str]) -> bool: - n = len(nums) // 2 - i = n - 2 - while i >= 0 and nums[i] >= nums[i + 1]: - i -= 1 - if i < 0: - return False - j = n - 1 - while j >= 0 and nums[j] <= nums[i]: - j -= 1 - nums[i], nums[j] = nums[j], nums[i] - nums[i + 1 : n] = nums[i + 1 : n][::-1] - return True - - nums = list(num) - if not next_permutation(nums): - return "" - n = len(nums) - for i in range(n // 2): - nums[n - i - 1] = nums[i] - return "".join(nums) +class Solution: + def nextPalindrome(self, num: str) -> str: + def next_permutation(nums: List[str]) -> bool: + n = len(nums) // 2 + i = n - 2 + while i >= 0 and nums[i] >= nums[i + 1]: + i -= 1 + if i < 0: + return False + j = n - 1 + while j >= 0 and nums[j] <= nums[i]: + j -= 1 + nums[i], nums[j] = nums[j], nums[i] + nums[i + 1 : n] = nums[i + 1 : n][::-1] + return True + + nums = list(num) + if not next_permutation(nums): + return "" + n = len(nums) + for i in range(n // 2): + nums[n - i - 1] = nums[i] + return "".join(nums) diff --git a/solution/1800-1899/1843.Suspicious Bank Accounts/Solution.sql b/solution/1800-1899/1843.Suspicious Bank Accounts/Solution.sql index 263f1256b7fee..bc7348ce599cd 100644 --- a/solution/1800-1899/1843.Suspicious Bank Accounts/Solution.sql +++ b/solution/1800-1899/1843.Suspicious Bank Accounts/Solution.sql @@ -1,18 +1,21 @@ # Write your MySQL query statement below WITH S AS ( - SELECT - account_id, - DATE_FORMAT(day, '%Y%m') AS yearmonth, - transaction_id AS tx + SELECT DISTINCT + t.account_id, + DATE_FORMAT(day, '%Y-%m-01') AS day, + transaction_id AS tx, + SUM(amount) OVER ( + PARTITION BY account_id, DATE_FORMAT(day, '%Y-%m-01') + ) > max_income AS marked FROM - Transactions - JOIN Accounts USING (account_id) + Transactions AS t + LEFT JOIN Accounts AS a ON t.account_id = a.account_id WHERE type = 'Creditor' - GROUP BY account_id, yearmonth - HAVING SUM(amount) > AVG(max_income) ) -SELECT DISTINCT account_id -FROM S -WHERE (account_id, PERIOD_ADD(yearmonth, 1)) IN (SELECT account_id, yearmonth FROM S) -ORDER BY tx; +SELECT DISTINCT s1.account_id +FROM + S AS s1 + LEFT JOIN S AS s2 ON s1.account_id = s2.account_id AND TIMESTAMPDIFF(Month, s1.day, s2.day) = 1 +WHERE s1.marked = 1 AND s2.marked = 1 +ORDER BY s1.tx; diff --git a/solution/1800-1899/1843.Suspicious Bank Accounts/Solution2.sql b/solution/1800-1899/1843.Suspicious Bank Accounts/Solution2.sql new file mode 100644 index 0000000000000..263f1256b7fee --- /dev/null +++ b/solution/1800-1899/1843.Suspicious Bank Accounts/Solution2.sql @@ -0,0 +1,18 @@ +# Write your MySQL query statement below +WITH + S AS ( + SELECT + account_id, + DATE_FORMAT(day, '%Y%m') AS yearmonth, + transaction_id AS tx + FROM + Transactions + JOIN Accounts USING (account_id) + WHERE type = 'Creditor' + GROUP BY account_id, yearmonth + HAVING SUM(amount) > AVG(max_income) + ) +SELECT DISTINCT account_id +FROM S +WHERE (account_id, PERIOD_ADD(yearmonth, 1)) IN (SELECT account_id, yearmonth FROM S) +ORDER BY tx; diff --git a/solution/1800-1899/1844.Replace All Digits with Characters/Solution.c b/solution/1800-1899/1844.Replace All Digits with Characters/Solution.c index ae78e45aad8d1..0d5c93bb95333 100644 --- a/solution/1800-1899/1844.Replace All Digits with Characters/Solution.c +++ b/solution/1800-1899/1844.Replace All Digits with Characters/Solution.c @@ -4,4 +4,4 @@ char* replaceDigits(char* s) { s[i] = s[i - 1] + s[i] - '0'; } return s; -} +} \ No newline at end of file diff --git a/solution/1800-1899/1845.Seat Reservation Manager/Solution.cs b/solution/1800-1899/1845.Seat Reservation Manager/Solution.cs index b8afc56d3bcba..8beea1cdb2c44 100644 --- a/solution/1800-1899/1845.Seat Reservation Manager/Solution.cs +++ b/solution/1800-1899/1845.Seat Reservation Manager/Solution.cs @@ -7,13 +7,13 @@ public SeatManager(int n) { availableSeats.Add(i); } } - + public int Reserve() { int reservedSeat = availableSeats.Min; availableSeats.Remove(reservedSeat); return reservedSeat; } - + public void Unreserve(int seatNumber) { availableSeats.Add(seatNumber); } diff --git a/solution/1800-1899/1847.Closest Room/Solution.cpp b/solution/1800-1899/1847.Closest Room/Solution.cpp index de082720e8687..f5760453c152b 100644 --- a/solution/1800-1899/1847.Closest Room/Solution.cpp +++ b/solution/1800-1899/1847.Closest Room/Solution.cpp @@ -1,42 +1,42 @@ -class Solution { -public: - vector closestRoom(vector>& rooms, vector>& queries) { - int n = rooms.size(); - int k = queries.size(); - sort(rooms.begin(), rooms.end(), [](const vector& a, const vector& b) { - return a[1] < b[1]; - }); - vector idx(k); - iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) { - return queries[i][1] < queries[j][1]; - }); - vector ans(k, -1); - int i = 0; - multiset s; - for (auto& room : rooms) { - s.insert(room[0]); - } - for (int j : idx) { - int prefer = queries[j][0], minSize = queries[j][1]; - while (i < n && rooms[i][1] < minSize) { - s.erase(s.find(rooms[i][0])); - ++i; - } - if (i == n) { - break; - } - auto it = s.lower_bound(prefer); - if (it != s.end()) { - ans[j] = *it; - } - if (it != s.begin()) { - --it; - if (ans[j] == -1 || abs(*it - prefer) <= abs(ans[j] - prefer)) { - ans[j] = *it; - } - } - } - return ans; - } +class Solution { +public: + vector closestRoom(vector>& rooms, vector>& queries) { + int n = rooms.size(); + int k = queries.size(); + sort(rooms.begin(), rooms.end(), [](const vector& a, const vector& b) { + return a[1] < b[1]; + }); + vector idx(k); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { + return queries[i][1] < queries[j][1]; + }); + vector ans(k, -1); + int i = 0; + multiset s; + for (auto& room : rooms) { + s.insert(room[0]); + } + for (int j : idx) { + int prefer = queries[j][0], minSize = queries[j][1]; + while (i < n && rooms[i][1] < minSize) { + s.erase(s.find(rooms[i][0])); + ++i; + } + if (i == n) { + break; + } + auto it = s.lower_bound(prefer); + if (it != s.end()) { + ans[j] = *it; + } + if (it != s.begin()) { + --it; + if (ans[j] == -1 || abs(*it - prefer) <= abs(ans[j] - prefer)) { + ans[j] = *it; + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1800-1899/1847.Closest Room/Solution.java b/solution/1800-1899/1847.Closest Room/Solution.java index c647e70b3cf90..899e1110b2fac 100644 --- a/solution/1800-1899/1847.Closest Room/Solution.java +++ b/solution/1800-1899/1847.Closest Room/Solution.java @@ -1,40 +1,40 @@ -class Solution { - public int[] closestRoom(int[][] rooms, int[][] queries) { - int n = rooms.length; - int k = queries.length; - Arrays.sort(rooms, (a, b) -> a[1] - b[1]); - Integer[] idx = new Integer[k]; - for (int i = 0; i < k; i++) { - idx[i] = i; - } - Arrays.sort(idx, (i, j) -> queries[i][1] - queries[j][1]); - int i = 0; - TreeMap tm = new TreeMap<>(); - for (int[] room : rooms) { - tm.merge(room[0], 1, Integer::sum); - } - int[] ans = new int[k]; - Arrays.fill(ans, -1); - for (int j : idx) { - int prefer = queries[j][0], minSize = queries[j][1]; - while (i < n && rooms[i][1] < minSize) { - if (tm.merge(rooms[i][0], -1, Integer::sum) == 0) { - tm.remove(rooms[i][0]); - } - ++i; - } - if (i == n) { - break; - } - Integer p = tm.ceilingKey(prefer); - if (p != null) { - ans[j] = p; - } - p = tm.floorKey(prefer); - if (p != null && (ans[j] == -1 || ans[j] - prefer >= prefer - p)) { - ans[j] = p; - } - } - return ans; - } +class Solution { + public int[] closestRoom(int[][] rooms, int[][] queries) { + int n = rooms.length; + int k = queries.length; + Arrays.sort(rooms, (a, b) -> a[1] - b[1]); + Integer[] idx = new Integer[k]; + for (int i = 0; i < k; i++) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> queries[i][1] - queries[j][1]); + int i = 0; + TreeMap tm = new TreeMap<>(); + for (int[] room : rooms) { + tm.merge(room[0], 1, Integer::sum); + } + int[] ans = new int[k]; + Arrays.fill(ans, -1); + for (int j : idx) { + int prefer = queries[j][0], minSize = queries[j][1]; + while (i < n && rooms[i][1] < minSize) { + if (tm.merge(rooms[i][0], -1, Integer::sum) == 0) { + tm.remove(rooms[i][0]); + } + ++i; + } + if (i == n) { + break; + } + Integer p = tm.ceilingKey(prefer); + if (p != null) { + ans[j] = p; + } + p = tm.floorKey(prefer); + if (p != null && (ans[j] == -1 || ans[j] - prefer >= prefer - p)) { + ans[j] = p; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1800-1899/1847.Closest Room/Solution.py b/solution/1800-1899/1847.Closest Room/Solution.py index 8923766e34777..b7d0408462410 100644 --- a/solution/1800-1899/1847.Closest Room/Solution.py +++ b/solution/1800-1899/1847.Closest Room/Solution.py @@ -1,26 +1,26 @@ -from sortedcontainers import SortedList - - -class Solution: - def closestRoom( - self, rooms: List[List[int]], queries: List[List[int]] - ) -> List[int]: - rooms.sort(key=lambda x: x[1]) - k = len(queries) - idx = sorted(range(k), key=lambda i: queries[i][1]) - ans = [-1] * k - i, n = 0, len(rooms) - sl = SortedList(x[0] for x in rooms) - for j in idx: - prefer, minSize = queries[j] - while i < n and rooms[i][1] < minSize: - sl.remove(rooms[i][0]) - i += 1 - if i == n: - break - p = sl.bisect_left(prefer) - if p < len(sl): - ans[j] = sl[p] - if p and (ans[j] == -1 or ans[j] - prefer >= prefer - sl[p - 1]): - ans[j] = sl[p - 1] - return ans +from sortedcontainers import SortedList + + +class Solution: + def closestRoom( + self, rooms: List[List[int]], queries: List[List[int]] + ) -> List[int]: + rooms.sort(key=lambda x: x[1]) + k = len(queries) + idx = sorted(range(k), key=lambda i: queries[i][1]) + ans = [-1] * k + i, n = 0, len(rooms) + sl = SortedList(x[0] for x in rooms) + for j in idx: + prefer, minSize = queries[j] + while i < n and rooms[i][1] < minSize: + sl.remove(rooms[i][0]) + i += 1 + if i == n: + break + p = sl.bisect_left(prefer) + if p < len(sl): + ans[j] = sl[p] + if p and (ans[j] == -1 or ans[j] - prefer >= prefer - sl[p - 1]): + ans[j] = sl[p - 1] + return ans diff --git a/solution/1800-1899/1848.Minimum Distance to the Target Element/Solution.py b/solution/1800-1899/1848.Minimum Distance to the Target Element/Solution.py index 0c96bae76f56a..0ca545ad609ad 100644 --- a/solution/1800-1899/1848.Minimum Distance to the Target Element/Solution.py +++ b/solution/1800-1899/1848.Minimum Distance to the Target Element/Solution.py @@ -1,3 +1,3 @@ -class Solution: - def getMinDistance(self, nums: List[int], target: int, start: int) -> int: - return min(abs(i - start) for i, x in enumerate(nums) if x == target) +class Solution: + def getMinDistance(self, nums: List[int], target: int, start: int) -> int: + return min(abs(i - start) for i, x in enumerate(nums) if x == target) diff --git a/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/Solution.cpp b/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/Solution.cpp index 25c90b2ec34f7..3181c06c2deb2 100644 --- a/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/Solution.cpp +++ b/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/Solution.cpp @@ -1,28 +1,28 @@ -class Solution { -public: - int getMinSwaps(string num, int k) { - string s = num; - for (int i = 0; i < k; ++i) { - next_permutation(begin(s), end(num)); - } - vector d[10]; - int n = num.size(); - for (int i = 0; i < n; ++i) { - d[num[i] - '0'].push_back(i); - } - int idx[10]{}; - vector arr(n); - for (int i = 0; i < n; ++i) { - arr[i] = d[s[i] - '0'][idx[s[i] - '0']++]; - } - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (arr[j] > arr[i]) { - ++ans; - } - } - } - return ans; - } +class Solution { +public: + int getMinSwaps(string num, int k) { + string s = num; + for (int i = 0; i < k; ++i) { + next_permutation(begin(s), end(num)); + } + vector d[10]; + int n = num.size(); + for (int i = 0; i < n; ++i) { + d[num[i] - '0'].push_back(i); + } + int idx[10]{}; + vector arr(n); + for (int i = 0; i < n; ++i) { + arr[i] = d[s[i] - '0'][idx[s[i] - '0']++]; + } + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (arr[j] > arr[i]) { + ++ans; + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/Solution.java b/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/Solution.java index fbec106f34d7e..66c12396b5398 100644 --- a/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/Solution.java +++ b/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/Solution.java @@ -1,54 +1,54 @@ -class Solution { - public int getMinSwaps(String num, int k) { - char[] s = num.toCharArray(); - for (int i = 0; i < k; ++i) { - nextPermutation(s); - } - List[] d = new List[10]; - Arrays.setAll(d, i -> new ArrayList<>()); - int n = s.length; - for (int i = 0; i < n; ++i) { - d[num.charAt(i) - '0'].add(i); - } - int[] idx = new int[10]; - int[] arr = new int[n]; - for (int i = 0; i < n; ++i) { - arr[i] = d[s[i] - '0'].get(idx[s[i] - '0']++); - } - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (arr[j] > arr[i]) { - ++ans; - } - } - } - return ans; - } - - private boolean nextPermutation(char[] nums) { - int n = nums.length; - int i = n - 2; - while (i >= 0 && nums[i] >= nums[i + 1]) { - --i; - } - if (i < 0) { - return false; - } - int j = n - 1; - while (j >= 0 && nums[i] >= nums[j]) { - --j; - } - swap(nums, i++, j); - for (j = n - 1; i < j; ++i, --j) { - swap(nums, i, j); - } - return true; - } - - private void swap(char[] nums, int i, int j) { - char t = nums[i]; - nums[i] = nums[j]; - nums[j] = t; - } +class Solution { + public int getMinSwaps(String num, int k) { + char[] s = num.toCharArray(); + for (int i = 0; i < k; ++i) { + nextPermutation(s); + } + List[] d = new List[10]; + Arrays.setAll(d, i -> new ArrayList<>()); + int n = s.length; + for (int i = 0; i < n; ++i) { + d[num.charAt(i) - '0'].add(i); + } + int[] idx = new int[10]; + int[] arr = new int[n]; + for (int i = 0; i < n; ++i) { + arr[i] = d[s[i] - '0'].get(idx[s[i] - '0']++); + } + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (arr[j] > arr[i]) { + ++ans; + } + } + } + return ans; + } + + private boolean nextPermutation(char[] nums) { + int n = nums.length; + int i = n - 2; + while (i >= 0 && nums[i] >= nums[i + 1]) { + --i; + } + if (i < 0) { + return false; + } + int j = n - 1; + while (j >= 0 && nums[i] >= nums[j]) { + --j; + } + swap(nums, i++, j); + for (j = n - 1; i < j; ++i, --j) { + swap(nums, i, j); + } + return true; + } + + private void swap(char[] nums, int i, int j) { + char t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } } \ No newline at end of file diff --git a/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/Solution.py b/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/Solution.py index ac0c38688734a..87859e20e1d9b 100644 --- a/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/Solution.py +++ b/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/Solution.py @@ -1,31 +1,31 @@ -class Solution: - def getMinSwaps(self, num: str, k: int) -> int: - def next_permutation(nums: List[str]) -> bool: - n = len(nums) - i = n - 2 - while i >= 0 and nums[i] >= nums[i + 1]: - i -= 1 - if i < 0: - return False - j = n - 1 - while j >= 0 and nums[j] <= nums[i]: - j -= 1 - nums[i], nums[j] = nums[j], nums[i] - nums[i + 1 : n] = nums[i + 1 : n][::-1] - return True - - s = list(num) - for _ in range(k): - next_permutation(s) - d = [[] for _ in range(10)] - idx = [0] * 10 - n = len(s) - for i, c in enumerate(num): - j = ord(c) - ord("0") - d[j].append(i) - arr = [0] * n - for i, c in enumerate(s): - j = ord(c) - ord("0") - arr[i] = d[j][idx[j]] - idx[j] += 1 - return sum(arr[j] > arr[i] for i in range(n) for j in range(i)) +class Solution: + def getMinSwaps(self, num: str, k: int) -> int: + def next_permutation(nums: List[str]) -> bool: + n = len(nums) + i = n - 2 + while i >= 0 and nums[i] >= nums[i + 1]: + i -= 1 + if i < 0: + return False + j = n - 1 + while j >= 0 and nums[j] <= nums[i]: + j -= 1 + nums[i], nums[j] = nums[j], nums[i] + nums[i + 1 : n] = nums[i + 1 : n][::-1] + return True + + s = list(num) + for _ in range(k): + next_permutation(s) + d = [[] for _ in range(10)] + idx = [0] * 10 + n = len(s) + for i, c in enumerate(num): + j = ord(c) - ord("0") + d[j].append(i) + arr = [0] * n + for i, c in enumerate(s): + j = ord(c) - ord("0") + arr[i] = d[j][idx[j]] + idx[j] += 1 + return sum(arr[j] > arr[i] for i in range(n) for j in range(i)) diff --git a/solution/1800-1899/1851.Minimum Interval to Include Each Query/Solution.cpp b/solution/1800-1899/1851.Minimum Interval to Include Each Query/Solution.cpp index 2fac1f269796b..1e659c8834bba 100644 --- a/solution/1800-1899/1851.Minimum Interval to Include Each Query/Solution.cpp +++ b/solution/1800-1899/1851.Minimum Interval to Include Each Query/Solution.cpp @@ -1,30 +1,30 @@ -class Solution { -public: - vector minInterval(vector>& intervals, vector& queries) { - int n = intervals.size(), m = queries.size(); - sort(intervals.begin(), intervals.end()); - using pii = pair; - vector qs; - for (int i = 0; i < m; ++i) { - qs.emplace_back(queries[i], i); - } - sort(qs.begin(), qs.end()); - vector ans(m, -1); - priority_queue, greater> pq; - int i = 0; - for (auto& [x, j] : qs) { - while (i < n && intervals[i][0] <= x) { - int a = intervals[i][0], b = intervals[i][1]; - pq.emplace(b - a + 1, b); - ++i; - } - while (!pq.empty() && pq.top().second < x) { - pq.pop(); - } - if (!pq.empty()) { - ans[j] = pq.top().first; - } - } - return ans; - } +class Solution { +public: + vector minInterval(vector>& intervals, vector& queries) { + int n = intervals.size(), m = queries.size(); + sort(intervals.begin(), intervals.end()); + using pii = pair; + vector qs; + for (int i = 0; i < m; ++i) { + qs.emplace_back(queries[i], i); + } + sort(qs.begin(), qs.end()); + vector ans(m, -1); + priority_queue, greater> pq; + int i = 0; + for (auto& [x, j] : qs) { + while (i < n && intervals[i][0] <= x) { + int a = intervals[i][0], b = intervals[i][1]; + pq.emplace(b - a + 1, b); + ++i; + } + while (!pq.empty() && pq.top().second < x) { + pq.pop(); + } + if (!pq.empty()) { + ans[j] = pq.top().first; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1800-1899/1851.Minimum Interval to Include Each Query/Solution.java b/solution/1800-1899/1851.Minimum Interval to Include Each Query/Solution.java index ac55d32ba3ec6..534b54475d33a 100644 --- a/solution/1800-1899/1851.Minimum Interval to Include Each Query/Solution.java +++ b/solution/1800-1899/1851.Minimum Interval to Include Each Query/Solution.java @@ -1,29 +1,29 @@ -class Solution { - public int[] minInterval(int[][] intervals, int[] queries) { - int n = intervals.length, m = queries.length; - Arrays.sort(intervals, (a, b) -> a[0] - b[0]); - int[][] qs = new int[m][0]; - for (int i = 0; i < m; ++i) { - qs[i] = new int[] {queries[i], i}; - } - Arrays.sort(qs, (a, b) -> a[0] - b[0]); - int[] ans = new int[m]; - Arrays.fill(ans, -1); - PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); - int i = 0; - for (int[] q : qs) { - while (i < n && intervals[i][0] <= q[0]) { - int a = intervals[i][0], b = intervals[i][1]; - pq.offer(new int[] {b - a + 1, b}); - ++i; - } - while (!pq.isEmpty() && pq.peek()[1] < q[0]) { - pq.poll(); - } - if (!pq.isEmpty()) { - ans[q[1]] = pq.peek()[0]; - } - } - return ans; - } +class Solution { + public int[] minInterval(int[][] intervals, int[] queries) { + int n = intervals.length, m = queries.length; + Arrays.sort(intervals, (a, b) -> a[0] - b[0]); + int[][] qs = new int[m][0]; + for (int i = 0; i < m; ++i) { + qs[i] = new int[] {queries[i], i}; + } + Arrays.sort(qs, (a, b) -> a[0] - b[0]); + int[] ans = new int[m]; + Arrays.fill(ans, -1); + PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); + int i = 0; + for (int[] q : qs) { + while (i < n && intervals[i][0] <= q[0]) { + int a = intervals[i][0], b = intervals[i][1]; + pq.offer(new int[] {b - a + 1, b}); + ++i; + } + while (!pq.isEmpty() && pq.peek()[1] < q[0]) { + pq.poll(); + } + if (!pq.isEmpty()) { + ans[q[1]] = pq.peek()[0]; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1800-1899/1851.Minimum Interval to Include Each Query/Solution.py b/solution/1800-1899/1851.Minimum Interval to Include Each Query/Solution.py index 4faf61c1ab5c1..565d3f1a8d802 100644 --- a/solution/1800-1899/1851.Minimum Interval to Include Each Query/Solution.py +++ b/solution/1800-1899/1851.Minimum Interval to Include Each Query/Solution.py @@ -1,18 +1,18 @@ -class Solution: - def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]: - n, m = len(intervals), len(queries) - intervals.sort() - queries = sorted((x, i) for i, x in enumerate(queries)) - ans = [-1] * m - pq = [] - i = 0 - for x, j in queries: - while i < n and intervals[i][0] <= x: - a, b = intervals[i] - heappush(pq, (b - a + 1, b)) - i += 1 - while pq and pq[0][1] < x: - heappop(pq) - if pq: - ans[j] = pq[0][0] - return ans +class Solution: + def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]: + n, m = len(intervals), len(queries) + intervals.sort() + queries = sorted((x, i) for i, x in enumerate(queries)) + ans = [-1] * m + pq = [] + i = 0 + for x, j in queries: + while i < n and intervals[i][0] <= x: + a, b = intervals[i] + heappush(pq, (b - a + 1, b)) + i += 1 + while pq and pq[0][1] < x: + heappop(pq) + if pq: + ans[j] = pq[0][0] + return ans diff --git a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.cpp b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.cpp index abb47432a0b45..d173e042b9686 100644 --- a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.cpp +++ b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.cpp @@ -1,27 +1,20 @@ -class Solution { -public: - vector distinctNumbers(vector& nums, int k) { - int m = *max_element(begin(nums), end(nums)); - int cnt[m + 1]; - memset(cnt, 0, sizeof(cnt)); - int n = nums.size(); - int v = 0; - vector ans(n - k + 1); - for (int i = 0; i < k; ++i) { - if (++cnt[nums[i]] == 1) { - ++v; - } - } - ans[0] = v; - for (int i = k; i < n; ++i) { - if (++cnt[nums[i]] == 1) { - ++v; - } - if (--cnt[nums[i - k]] == 0) { - --v; - } - ans[i - k + 1] = v; - } - return ans; - } +class Solution { +public: + vector distinctNumbers(vector& nums, int k) { + unordered_map cnt; + for (int i = 0; i < k; ++i) { + ++cnt[nums[i]]; + } + int n = nums.size(); + vector ans; + ans.push_back(cnt.size()); + for (int i = k; i < n; ++i) { + ++cnt[nums[i]]; + if (--cnt[nums[i - k]] == 0) { + cnt.erase(nums[i - k]); + } + ans.push_back(cnt.size()); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.go b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.go index dd58d837b077c..7b207ac98ff2c 100644 --- a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.go +++ b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.go @@ -1,24 +1,16 @@ -func distinctNumbers(nums []int, k int) (ans []int) { - m := slices.Max(nums) - cnt := make([]int, m+1) - v := 0 +func distinctNumbers(nums []int, k int) []int { + cnt := map[int]int{} for _, x := range nums[:k] { cnt[x]++ - if cnt[x] == 1 { - v++ - } } - ans = append(ans, v) + ans := []int{len(cnt)} for i := k; i < len(nums); i++ { cnt[nums[i]]++ - if cnt[nums[i]] == 1 { - v++ - } cnt[nums[i-k]]-- if cnt[nums[i-k]] == 0 { - v-- + delete(cnt, nums[i-k]) } - ans = append(ans, v) + ans = append(ans, len(cnt)) } - return + return ans } \ No newline at end of file diff --git a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.java b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.java index 34642caa3a27f..f91876996f08b 100644 --- a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.java +++ b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.java @@ -1,28 +1,19 @@ -class Solution { - public int[] distinctNumbers(int[] nums, int k) { - int m = 0; - for (int x : nums) { - m = Math.max(m, x); - } - int[] cnt = new int[m + 1]; - int v = 0; - for (int i = 0; i < k; ++i) { - if (++cnt[nums[i]] == 1) { - ++v; - } - } - int n = nums.length; - int[] ans = new int[n - k + 1]; - ans[0] = v; - for (int i = k; i < n; ++i) { - if (++cnt[nums[i]] == 1) { - ++v; - } - if (--cnt[nums[i - k]] == 0) { - --v; - } - ans[i - k + 1] = v; - } - return ans; - } +class Solution { + public int[] distinctNumbers(int[] nums, int k) { + Map cnt = new HashMap<>(); + for (int i = 0; i < k; ++i) { + cnt.merge(nums[i], 1, Integer::sum); + } + int n = nums.length; + int[] ans = new int[n - k + 1]; + ans[0] = cnt.size(); + for (int i = k; i < n; ++i) { + cnt.merge(nums[i], 1, Integer::sum); + if (cnt.merge(nums[i - k], -1, Integer::sum) == 0) { + cnt.remove(nums[i - k]); + } + ans[i - k + 1] = cnt.size(); + } + return ans; + } } \ No newline at end of file diff --git a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.py b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.py index 9c56a07792e00..e2bc90489afb9 100644 --- a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.py +++ b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def distinctNumbers(self, nums: List[int], k: int) -> List[int]: - cnt = Counter(nums[:k]) - ans = [len(cnt)] - for i in range(k, len(nums)): - cnt[nums[i]] += 1 - cnt[nums[i - k]] -= 1 - if cnt[nums[i - k]] == 0: - cnt.pop(nums[i - k]) - ans.append(len(cnt)) - return ans +class Solution: + def distinctNumbers(self, nums: List[int], k: int) -> List[int]: + cnt = Counter(nums[:k]) + ans = [len(cnt)] + for i in range(k, len(nums)): + cnt[nums[i]] += 1 + cnt[nums[i - k]] -= 1 + if cnt[nums[i - k]] == 0: + cnt.pop(nums[i - k]) + ans.append(len(cnt)) + return ans diff --git a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.ts b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.ts index 39bfb2ac0594e..c53868da0d453 100644 --- a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.ts +++ b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution.ts @@ -1,21 +1,16 @@ function distinctNumbers(nums: number[], k: number): number[] { - const m = Math.max(...nums); - const cnt: number[] = Array(m + 1).fill(0); - let v: number = 0; + const cnt: Map = new Map(); for (let i = 0; i < k; ++i) { - if (++cnt[nums[i]] === 1) { - v++; - } + cnt.set(nums[i], (cnt.get(nums[i]) ?? 0) + 1); } - const ans: number[] = [v]; + const ans: number[] = [cnt.size]; for (let i = k; i < nums.length; ++i) { - if (++cnt[nums[i]] === 1) { - v++; - } - if (--cnt[nums[i - k]] === 0) { - v--; + cnt.set(nums[i], (cnt.get(nums[i]) ?? 0) + 1); + cnt.set(nums[i - k], cnt.get(nums[i - k])! - 1); + if (cnt.get(nums[i - k]) === 0) { + cnt.delete(nums[i - k]); } - ans.push(v); + ans.push(cnt.size); } return ans; } diff --git a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution2.cpp b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution2.cpp new file mode 100644 index 0000000000000..94cb62d73c282 --- /dev/null +++ b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution2.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector distinctNumbers(vector& nums, int k) { + int m = *max_element(begin(nums), end(nums)); + int cnt[m + 1]; + memset(cnt, 0, sizeof(cnt)); + int n = nums.size(); + int v = 0; + vector ans(n - k + 1); + for (int i = 0; i < k; ++i) { + if (++cnt[nums[i]] == 1) { + ++v; + } + } + ans[0] = v; + for (int i = k; i < n; ++i) { + if (++cnt[nums[i]] == 1) { + ++v; + } + if (--cnt[nums[i - k]] == 0) { + --v; + } + ans[i - k + 1] = v; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution2.go b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution2.go new file mode 100644 index 0000000000000..dd58d837b077c --- /dev/null +++ b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution2.go @@ -0,0 +1,24 @@ +func distinctNumbers(nums []int, k int) (ans []int) { + m := slices.Max(nums) + cnt := make([]int, m+1) + v := 0 + for _, x := range nums[:k] { + cnt[x]++ + if cnt[x] == 1 { + v++ + } + } + ans = append(ans, v) + for i := k; i < len(nums); i++ { + cnt[nums[i]]++ + if cnt[nums[i]] == 1 { + v++ + } + cnt[nums[i-k]]-- + if cnt[nums[i-k]] == 0 { + v-- + } + ans = append(ans, v) + } + return +} \ No newline at end of file diff --git a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution2.java b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution2.java new file mode 100644 index 0000000000000..345cc6f845a50 --- /dev/null +++ b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution2.java @@ -0,0 +1,28 @@ +class Solution { + public int[] distinctNumbers(int[] nums, int k) { + int m = 0; + for (int x : nums) { + m = Math.max(m, x); + } + int[] cnt = new int[m + 1]; + int v = 0; + for (int i = 0; i < k; ++i) { + if (++cnt[nums[i]] == 1) { + ++v; + } + } + int n = nums.length; + int[] ans = new int[n - k + 1]; + ans[0] = v; + for (int i = k; i < n; ++i) { + if (++cnt[nums[i]] == 1) { + ++v; + } + if (--cnt[nums[i - k]] == 0) { + --v; + } + ans[i - k + 1] = v; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution2.ts b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution2.ts new file mode 100644 index 0000000000000..39bfb2ac0594e --- /dev/null +++ b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/Solution2.ts @@ -0,0 +1,21 @@ +function distinctNumbers(nums: number[], k: number): number[] { + const m = Math.max(...nums); + const cnt: number[] = Array(m + 1).fill(0); + let v: number = 0; + for (let i = 0; i < k; ++i) { + if (++cnt[nums[i]] === 1) { + v++; + } + } + const ans: number[] = [v]; + for (let i = k; i < nums.length; ++i) { + if (++cnt[nums[i]] === 1) { + v++; + } + if (--cnt[nums[i - k]] === 0) { + v--; + } + ans.push(v); + } + return ans; +} diff --git a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.cpp b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.cpp index 6fb1662d9699c..cd960589f35d0 100644 --- a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.cpp +++ b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.cpp @@ -1,14 +1,12 @@ -class Solution { -public: - int maxDistance(vector& nums1, vector& nums2) { - int m = nums1.size(), n = nums2.size(); - int ans = 0; - for (int i = 0, j = 0; i < m; ++i) { - while (j < n && nums1[i] <= nums2[j]) { - ++j; - } - ans = max(ans, j - i - 1); - } - return ans; - } +class Solution { +public: + int maxDistance(vector& nums1, vector& nums2) { + int ans = 0; + reverse(nums2.begin(), nums2.end()); + for (int i = 0; i < nums1.size(); ++i) { + int j = nums2.size() - (lower_bound(nums2.begin(), nums2.end(), nums1[i]) - nums2.begin()) - 1; + ans = max(ans, j - i); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.go b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.go index 1a831daedcfc2..41de5286ede9e 100644 --- a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.go +++ b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.go @@ -1,12 +1,17 @@ func maxDistance(nums1 []int, nums2 []int) int { - m, n := len(nums1), len(nums2) - ans := 0 - for i, j := 0, 0; i < m; i++ { - for j < n && nums1[i] <= nums2[j] { - j++ + ans, n := 0, len(nums2) + for i, num := range nums1 { + left, right := i, n-1 + for left < right { + mid := (left + right + 1) >> 1 + if nums2[mid] >= num { + left = mid + } else { + right = mid - 1 + } } - if ans < j-i-1 { - ans = j - i - 1 + if ans < left-i { + ans = left - i } } return ans diff --git a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.java b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.java index 8fd4e8ee31507..e9ae9eb318f22 100644 --- a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.java +++ b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.java @@ -1,13 +1,19 @@ -class Solution { - public int maxDistance(int[] nums1, int[] nums2) { - int m = nums1.length, n = nums2.length; - int ans = 0; - for (int i = 0, j = 0; i < m; ++i) { - while (j < n && nums1[i] <= nums2[j]) { - ++j; - } - ans = Math.max(ans, j - i - 1); - } - return ans; - } +class Solution { + public int maxDistance(int[] nums1, int[] nums2) { + int ans = 0; + int m = nums1.length, n = nums2.length; + for (int i = 0; i < m; ++i) { + int left = i, right = n - 1; + while (left < right) { + int mid = (left + right + 1) >> 1; + if (nums2[mid] >= nums1[i]) { + left = mid; + } else { + right = mid - 1; + } + } + ans = Math.max(ans, left - i); + } + return ans; + } } \ No newline at end of file diff --git a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.js b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.js index 49649513c6d1f..278cf95da4784 100644 --- a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.js +++ b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.js @@ -5,13 +5,20 @@ */ var maxDistance = function (nums1, nums2) { let ans = 0; - const m = nums1.length; - const n = nums2.length; - for (let i = 0, j = 0; i < m; ++i) { - while (j < n && nums1[i] <= nums2[j]) { - j++; + let m = nums1.length; + let n = nums2.length; + for (let i = 0; i < m; ++i) { + let left = i; + let right = n - 1; + while (left < right) { + const mid = (left + right + 1) >> 1; + if (nums2[mid] >= nums1[i]) { + left = mid; + } else { + right = mid - 1; + } } - ans = Math.max(ans, j - i - 1); + ans = Math.max(ans, left - i); } return ans; }; diff --git a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.py b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.py index 87ac14052d04c..4576038a0c68e 100644 --- a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.py +++ b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.py @@ -1,10 +1,8 @@ -class Solution: - def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: - m, n = len(nums1), len(nums2) - ans = i = j = 0 - while i < m: - while j < n and nums1[i] <= nums2[j]: - j += 1 - ans = max(ans, j - i - 1) - i += 1 - return ans +class Solution: + def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: + ans = 0 + nums2 = nums2[::-1] + for i, v in enumerate(nums1): + j = len(nums2) - bisect_left(nums2, v) - 1 + ans = max(ans, j - i) + return ans diff --git a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.rs b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.rs index 6b35b53665f32..33c9a6eb1e750 100644 --- a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.rs +++ b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.rs @@ -3,12 +3,18 @@ impl Solution { let m = nums1.len(); let n = nums2.len(); let mut res = 0; - let mut j = 0; for i in 0..m { - while j < n && nums1[i] <= nums2[j] { - j += 1; + let mut left = i; + let mut right = n; + while left < right { + let mid = left + (right - left) / 2; + if nums2[mid] >= nums1[i] { + left = mid + 1; + } else { + right = mid; + } } - res = res.max((j - i - 1) as i32); + res = res.max((left - i - 1) as i32); } res } diff --git a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.ts b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.ts index 42d0f4c3b8a39..6c3531accc87e 100644 --- a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.ts +++ b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution.ts @@ -1,12 +1,19 @@ function maxDistance(nums1: number[], nums2: number[]): number { let ans = 0; - const m = nums1.length; - const n = nums2.length; - for (let i = 0, j = 0; i < m; ++i) { - while (j < n && nums1[i] <= nums2[j]) { - j++; + let m = nums1.length; + let n = nums2.length; + for (let i = 0; i < m; ++i) { + let left = i; + let right = n - 1; + while (left < right) { + const mid = (left + right + 1) >> 1; + if (nums2[mid] >= nums1[i]) { + left = mid; + } else { + right = mid - 1; + } } - ans = Math.max(ans, j - i - 1); + ans = Math.max(ans, left - i); } return ans; } diff --git a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.cpp b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.cpp new file mode 100644 index 0000000000000..e98705e23d479 --- /dev/null +++ b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int maxDistance(vector& nums1, vector& nums2) { + int m = nums1.size(), n = nums2.size(); + int ans = 0; + for (int i = 0, j = 0; i < m; ++i) { + while (j < n && nums1[i] <= nums2[j]) { + ++j; + } + ans = max(ans, j - i - 1); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.go b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.go new file mode 100644 index 0000000000000..1a831daedcfc2 --- /dev/null +++ b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.go @@ -0,0 +1,13 @@ +func maxDistance(nums1 []int, nums2 []int) int { + m, n := len(nums1), len(nums2) + ans := 0 + for i, j := 0, 0; i < m; i++ { + for j < n && nums1[i] <= nums2[j] { + j++ + } + if ans < j-i-1 { + ans = j - i - 1 + } + } + return ans +} \ No newline at end of file diff --git a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.java b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.java new file mode 100644 index 0000000000000..16ca11158ff08 --- /dev/null +++ b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.java @@ -0,0 +1,13 @@ +class Solution { + public int maxDistance(int[] nums1, int[] nums2) { + int m = nums1.length, n = nums2.length; + int ans = 0; + for (int i = 0, j = 0; i < m; ++i) { + while (j < n && nums1[i] <= nums2[j]) { + ++j; + } + ans = Math.max(ans, j - i - 1); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.js b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.js new file mode 100644 index 0000000000000..49649513c6d1f --- /dev/null +++ b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.js @@ -0,0 +1,17 @@ +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var maxDistance = function (nums1, nums2) { + let ans = 0; + const m = nums1.length; + const n = nums2.length; + for (let i = 0, j = 0; i < m; ++i) { + while (j < n && nums1[i] <= nums2[j]) { + j++; + } + ans = Math.max(ans, j - i - 1); + } + return ans; +}; diff --git a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.py b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.py new file mode 100644 index 0000000000000..28550a5c84f73 --- /dev/null +++ b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: + m, n = len(nums1), len(nums2) + ans = i = j = 0 + while i < m: + while j < n and nums1[i] <= nums2[j]: + j += 1 + ans = max(ans, j - i - 1) + i += 1 + return ans diff --git a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.rs b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.rs new file mode 100644 index 0000000000000..6b35b53665f32 --- /dev/null +++ b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn max_distance(nums1: Vec, nums2: Vec) -> i32 { + let m = nums1.len(); + let n = nums2.len(); + let mut res = 0; + let mut j = 0; + for i in 0..m { + while j < n && nums1[i] <= nums2[j] { + j += 1; + } + res = res.max((j - i - 1) as i32); + } + res + } +} diff --git a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.ts b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.ts new file mode 100644 index 0000000000000..42d0f4c3b8a39 --- /dev/null +++ b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.ts @@ -0,0 +1,12 @@ +function maxDistance(nums1: number[], nums2: number[]): number { + let ans = 0; + const m = nums1.length; + const n = nums2.length; + for (let i = 0, j = 0; i < m; ++i) { + while (j < n && nums1[i] <= nums2[j]) { + j++; + } + ans = Math.max(ans, j - i - 1); + } + return ans; +} diff --git a/solution/1800-1899/1858.Longest Word With All Prefixes/Solution.cpp b/solution/1800-1899/1858.Longest Word With All Prefixes/Solution.cpp index db89304be2c06..c61ce04818c60 100644 --- a/solution/1800-1899/1858.Longest Word With All Prefixes/Solution.cpp +++ b/solution/1800-1899/1858.Longest Word With All Prefixes/Solution.cpp @@ -1,51 +1,51 @@ -class Trie { -private: - Trie* children[26]; - bool isEnd = false; - -public: - Trie() { - fill(begin(children), end(children), nullptr); - } - - void insert(const string& w) { - Trie* node = this; - for (char c : w) { - int idx = c - 'a'; - if (!node->children[idx]) { - node->children[idx] = new Trie(); - } - node = node->children[idx]; - } - node->isEnd = true; - } - - bool search(const string& w) { - Trie* node = this; - for (char c : w) { - int idx = c - 'a'; - node = node->children[idx]; - if (!node->isEnd) { - return false; - } - } - return true; - } -}; - -class Solution { -public: - string longestWord(vector& words) { - Trie trie; - for (const string& w : words) { - trie.insert(w); - } - string ans = ""; - for (const string& w : words) { - if ((w.size() > ans.size() || (w.size() == ans.size() && w < ans)) && trie.search(w)) { - ans = w; - } - } - return ans; - } +class Trie { +private: + Trie* children[26]; + bool isEnd = false; + +public: + Trie() { + fill(begin(children), end(children), nullptr); + } + + void insert(const string& w) { + Trie* node = this; + for (char c : w) { + int idx = c - 'a'; + if (!node->children[idx]) { + node->children[idx] = new Trie(); + } + node = node->children[idx]; + } + node->isEnd = true; + } + + bool search(const string& w) { + Trie* node = this; + for (char c : w) { + int idx = c - 'a'; + node = node->children[idx]; + if (!node->isEnd) { + return false; + } + } + return true; + } +}; + +class Solution { +public: + string longestWord(vector& words) { + Trie trie; + for (const string& w : words) { + trie.insert(w); + } + string ans = ""; + for (const string& w : words) { + if ((w.size() > ans.size() || (w.size() == ans.size() && w < ans)) && trie.search(w)) { + ans = w; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1800-1899/1858.Longest Word With All Prefixes/Solution.cs b/solution/1800-1899/1858.Longest Word With All Prefixes/Solution.cs index 2bb78ce9d49ed..49e8878ba9f4e 100644 --- a/solution/1800-1899/1858.Longest Word With All Prefixes/Solution.cs +++ b/solution/1800-1899/1858.Longest Word With All Prefixes/Solution.cs @@ -1,47 +1,47 @@ -public class Trie { - private Trie[] children = new Trie[26]; - private bool isEnd; - - public Trie() { } - - public void Insert(string w) { - Trie node = this; - foreach (char c in w.ToCharArray()) { - int idx = c - 'a'; - if (node.children[idx] == null) { - node.children[idx] = new Trie(); - } - node = node.children[idx]; - } - node.isEnd = true; - } - - public bool Search(string w) { - Trie node = this; - foreach (char c in w.ToCharArray()) { - int idx = c - 'a'; - node = node.children[idx]; - if (!node.isEnd) { - return false; - } - } - return true; - } -} - -public class Solution { - public string LongestWord(string[] words) { - Trie trie = new Trie(); - foreach (string w in words) { - trie.Insert(w); - } - - string ans = ""; - foreach (string w in words) { - if ((w.Length > ans.Length || (w.Length == ans.Length && string.Compare(w, ans) < 0)) && trie.Search(w)) { - ans = w; - } - } - return ans; - } -} \ No newline at end of file +public class Trie { + private Trie[] children = new Trie[26]; + private bool isEnd; + + public Trie() { } + + public void Insert(string w) { + Trie node = this; + foreach (char c in w.ToCharArray()) { + int idx = c - 'a'; + if (node.children[idx] == null) { + node.children[idx] = new Trie(); + } + node = node.children[idx]; + } + node.isEnd = true; + } + + public bool Search(string w) { + Trie node = this; + foreach (char c in w.ToCharArray()) { + int idx = c - 'a'; + node = node.children[idx]; + if (!node.isEnd) { + return false; + } + } + return true; + } +} + +public class Solution { + public string LongestWord(string[] words) { + Trie trie = new Trie(); + foreach (string w in words) { + trie.Insert(w); + } + + string ans = ""; + foreach (string w in words) { + if ((w.Length > ans.Length || (w.Length == ans.Length && string.Compare(w, ans) < 0)) && trie.Search(w)) { + ans = w; + } + } + return ans; + } +} diff --git a/solution/1800-1899/1858.Longest Word With All Prefixes/Solution.java b/solution/1800-1899/1858.Longest Word With All Prefixes/Solution.java index f4f145597e88c..18f04908febcb 100644 --- a/solution/1800-1899/1858.Longest Word With All Prefixes/Solution.java +++ b/solution/1800-1899/1858.Longest Word With All Prefixes/Solution.java @@ -1,48 +1,48 @@ -class Trie { - private Trie[] children = new Trie[26]; - private boolean isEnd; - - public Trie() { - } - - public void insert(String w) { - Trie node = this; - for (char c : w.toCharArray()) { - int idx = c - 'a'; - if (node.children[idx] == null) { - node.children[idx] = new Trie(); - } - node = node.children[idx]; - } - node.isEnd = true; - } - - public boolean search(String w) { - Trie node = this; - for (char c : w.toCharArray()) { - int idx = c - 'a'; - node = node.children[idx]; - if (!node.isEnd) { - return false; - } - } - return true; - } -} - -class Solution { - public String longestWord(String[] words) { - Trie trie = new Trie(); - for (String w : words) { - trie.insert(w); - } - String ans = ""; - for (String w : words) { - if ((w.length() > ans.length() || (w.length() == ans.length() && w.compareTo(ans) < 0)) - && trie.search(w)) { - ans = w; - } - } - return ans; - } +class Trie { + private Trie[] children = new Trie[26]; + private boolean isEnd; + + public Trie() { + } + + public void insert(String w) { + Trie node = this; + for (char c : w.toCharArray()) { + int idx = c - 'a'; + if (node.children[idx] == null) { + node.children[idx] = new Trie(); + } + node = node.children[idx]; + } + node.isEnd = true; + } + + public boolean search(String w) { + Trie node = this; + for (char c : w.toCharArray()) { + int idx = c - 'a'; + node = node.children[idx]; + if (!node.isEnd) { + return false; + } + } + return true; + } +} + +class Solution { + public String longestWord(String[] words) { + Trie trie = new Trie(); + for (String w : words) { + trie.insert(w); + } + String ans = ""; + for (String w : words) { + if ((w.length() > ans.length() || (w.length() == ans.length() && w.compareTo(ans) < 0)) + && trie.search(w)) { + ans = w; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/1800-1899/1858.Longest Word With All Prefixes/Solution.py b/solution/1800-1899/1858.Longest Word With All Prefixes/Solution.py index 0c542511f8692..948377f480742 100644 --- a/solution/1800-1899/1858.Longest Word With All Prefixes/Solution.py +++ b/solution/1800-1899/1858.Longest Word With All Prefixes/Solution.py @@ -1,36 +1,36 @@ -class Trie: - __slots__ = ["children", "is_end"] - - def __init__(self): - self.children: List[Trie | None] = [None] * 26 - self.is_end: bool = False - - def insert(self, w: str) -> None: - node = self - for c in w: - idx = ord(c) - ord("a") - if not node.children[idx]: - node.children[idx] = Trie() - node = node.children[idx] - node.is_end = True - - def search(self, w: str) -> bool: - node = self - for c in w: - idx = ord(c) - ord("a") - node = node.children[idx] - if not node.is_end: - return False - return True - - -class Solution: - def longestWord(self, words: List[str]) -> str: - trie = Trie() - for w in words: - trie.insert(w) - ans = "" - for w in words: - if (len(w) > len(ans) or len(w) == len(ans) and w < ans) and trie.search(w): - ans = w - return ans +class Trie: + __slots__ = ["children", "is_end"] + + def __init__(self): + self.children: List[Trie | None] = [None] * 26 + self.is_end: bool = False + + def insert(self, w: str) -> None: + node = self + for c in w: + idx = ord(c) - ord("a") + if not node.children[idx]: + node.children[idx] = Trie() + node = node.children[idx] + node.is_end = True + + def search(self, w: str) -> bool: + node = self + for c in w: + idx = ord(c) - ord("a") + node = node.children[idx] + if not node.is_end: + return False + return True + + +class Solution: + def longestWord(self, words: List[str]) -> str: + trie = Trie() + for w in words: + trie.insert(w) + ans = "" + for w in words: + if (len(w) > len(ans) or len(w) == len(ans) and w < ans) and trie.search(w): + ans = w + return ans diff --git a/solution/1800-1899/1859.Sorting the Sentence/Solution.cpp b/solution/1800-1899/1859.Sorting the Sentence/Solution.cpp index 01a8e1017d68e..6f28f77021809 100644 --- a/solution/1800-1899/1859.Sorting the Sentence/Solution.cpp +++ b/solution/1800-1899/1859.Sorting the Sentence/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - string sortSentence(string s) { - istringstream iss(s); - string w; - vector ws; - while (iss >> w) { - ws.push_back(w); - } - vector ss(ws.size()); - for (auto& w : ws) { - ss[w.back() - '1'] = w.substr(0, w.size() - 1); - } - string ans; - for (auto& w : ss) { - ans += w + " "; - } - ans.pop_back(); - return ans; - } +class Solution { +public: + string sortSentence(string s) { + istringstream iss(s); + string w; + vector ws; + while (iss >> w) { + ws.push_back(w); + } + vector ss(ws.size()); + for (auto& w : ws) { + ss[w.back() - '1'] = w.substr(0, w.size() - 1); + } + string ans; + for (auto& w : ss) { + ans += w + " "; + } + ans.pop_back(); + return ans; + } }; \ No newline at end of file diff --git a/solution/1800-1899/1859.Sorting the Sentence/Solution.java b/solution/1800-1899/1859.Sorting the Sentence/Solution.java index cea8b91864566..3dfffcc5a6be0 100644 --- a/solution/1800-1899/1859.Sorting the Sentence/Solution.java +++ b/solution/1800-1899/1859.Sorting the Sentence/Solution.java @@ -1,12 +1,12 @@ -class Solution { - public String sortSentence(String s) { - String[] ws = s.split(" "); - int n = ws.length; - String[] ans = new String[n]; - for (int i = 0; i < n; ++i) { - String w = ws[i]; - ans[w.charAt(w.length() - 1) - '1'] = w.substring(0, w.length() - 1); - } - return String.join(" ", ans); - } +class Solution { + public String sortSentence(String s) { + String[] ws = s.split(" "); + int n = ws.length; + String[] ans = new String[n]; + for (int i = 0; i < n; ++i) { + String w = ws[i]; + ans[w.charAt(w.length() - 1) - '1'] = w.substring(0, w.length() - 1); + } + return String.join(" ", ans); + } } \ No newline at end of file diff --git a/solution/1800-1899/1859.Sorting the Sentence/Solution.py b/solution/1800-1899/1859.Sorting the Sentence/Solution.py index bac4af524fec8..23d0851aca4c6 100644 --- a/solution/1800-1899/1859.Sorting the Sentence/Solution.py +++ b/solution/1800-1899/1859.Sorting the Sentence/Solution.py @@ -1,7 +1,5 @@ -class Solution: - def sortSentence(self, s: str) -> str: - ws = s.split() - ans = [None] * len(ws) - for w in ws: - ans[int(w[-1]) - 1] = w[:-1] - return " ".join(ans) +class Solution: + def sortSentence(self, s: str) -> str: + ws = [(w[:-1], int(w[-1])) for w in s.split()] + ws.sort(key=lambda x: x[1]) + return ' '.join(w for w, _ in ws) diff --git a/solution/1800-1899/1859.Sorting the Sentence/Solution2.py b/solution/1800-1899/1859.Sorting the Sentence/Solution2.py new file mode 100644 index 0000000000000..749c262928cb2 --- /dev/null +++ b/solution/1800-1899/1859.Sorting the Sentence/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def sortSentence(self, s: str) -> str: + ws = s.split() + ans = [None] * len(ws) + for w in ws: + ans[int(w[-1]) - 1] = w[:-1] + return ' '.join(ans) diff --git a/solution/1800-1899/1862.Sum of Floored Pairs/Solution.cpp b/solution/1800-1899/1862.Sum of Floored Pairs/Solution.cpp index ad1a8610ab500..19ca72f740ce8 100644 --- a/solution/1800-1899/1862.Sum of Floored Pairs/Solution.cpp +++ b/solution/1800-1899/1862.Sum of Floored Pairs/Solution.cpp @@ -1,25 +1,25 @@ -class Solution { -public: - int sumOfFlooredPairs(vector& nums) { - const int mod = 1e9 + 7; - int mx = *max_element(nums.begin(), nums.end()); - vector cnt(mx + 1); - vector s(mx + 1); - for (int x : nums) { - ++cnt[x]; - } - for (int i = 1; i <= mx; ++i) { - s[i] = s[i - 1] + cnt[i]; - } - long long ans = 0; - for (int y = 1; y <= mx; ++y) { - if (cnt[y]) { - for (int d = 1; d * y <= mx; ++d) { - ans += 1LL * cnt[y] * d * (s[min(mx, d * y + y - 1)] - s[d * y - 1]); - ans %= mod; - } - } - } - return ans; - } +class Solution { +public: + int sumOfFlooredPairs(vector& nums) { + const int mod = 1e9 + 7; + int mx = *max_element(nums.begin(), nums.end()); + vector cnt(mx + 1); + vector s(mx + 1); + for (int x : nums) { + ++cnt[x]; + } + for (int i = 1; i <= mx; ++i) { + s[i] = s[i - 1] + cnt[i]; + } + long long ans = 0; + for (int y = 1; y <= mx; ++y) { + if (cnt[y]) { + for (int d = 1; d * y <= mx; ++d) { + ans += 1LL * cnt[y] * d * (s[min(mx, d * y + y - 1)] - s[d * y - 1]); + ans %= mod; + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1800-1899/1862.Sum of Floored Pairs/Solution.java b/solution/1800-1899/1862.Sum of Floored Pairs/Solution.java index 95240a7a5bf89..d36c1a67f7592 100644 --- a/solution/1800-1899/1862.Sum of Floored Pairs/Solution.java +++ b/solution/1800-1899/1862.Sum of Floored Pairs/Solution.java @@ -1,27 +1,27 @@ -class Solution { - public int sumOfFlooredPairs(int[] nums) { - final int mod = (int) 1e9 + 7; - int mx = 0; - for (int x : nums) { - mx = Math.max(mx, x); - } - int[] cnt = new int[mx + 1]; - int[] s = new int[mx + 1]; - for (int x : nums) { - ++cnt[x]; - } - for (int i = 1; i <= mx; ++i) { - s[i] = s[i - 1] + cnt[i]; - } - long ans = 0; - for (int y = 1; y <= mx; ++y) { - if (cnt[y] > 0) { - for (int d = 1; d * y <= mx; ++d) { - ans += 1L * cnt[y] * d * (s[Math.min(mx, d * y + y - 1)] - s[d * y - 1]); - ans %= mod; - } - } - } - return (int) ans; - } +class Solution { + public int sumOfFlooredPairs(int[] nums) { + final int mod = (int) 1e9 + 7; + int mx = 0; + for (int x : nums) { + mx = Math.max(mx, x); + } + int[] cnt = new int[mx + 1]; + int[] s = new int[mx + 1]; + for (int x : nums) { + ++cnt[x]; + } + for (int i = 1; i <= mx; ++i) { + s[i] = s[i - 1] + cnt[i]; + } + long ans = 0; + for (int y = 1; y <= mx; ++y) { + if (cnt[y] > 0) { + for (int d = 1; d * y <= mx; ++d) { + ans += 1L * cnt[y] * d * (s[Math.min(mx, d * y + y - 1)] - s[d * y - 1]); + ans %= mod; + } + } + } + return (int) ans; + } } \ No newline at end of file diff --git a/solution/1800-1899/1862.Sum of Floored Pairs/Solution.py b/solution/1800-1899/1862.Sum of Floored Pairs/Solution.py index 99f49e14f7242..984449b22df32 100644 --- a/solution/1800-1899/1862.Sum of Floored Pairs/Solution.py +++ b/solution/1800-1899/1862.Sum of Floored Pairs/Solution.py @@ -1,17 +1,17 @@ -class Solution: - def sumOfFlooredPairs(self, nums: List[int]) -> int: - mod = 10**9 + 7 - cnt = Counter(nums) - mx = max(nums) - s = [0] * (mx + 1) - for i in range(1, mx + 1): - s[i] = s[i - 1] + cnt[i] - ans = 0 - for y in range(1, mx + 1): - if cnt[y]: - d = 1 - while d * y <= mx: - ans += cnt[y] * d * (s[min(mx, d * y + y - 1)] - s[d * y - 1]) - ans %= mod - d += 1 - return ans +class Solution: + def sumOfFlooredPairs(self, nums: List[int]) -> int: + mod = 10**9 + 7 + cnt = Counter(nums) + mx = max(nums) + s = [0] * (mx + 1) + for i in range(1, mx + 1): + s[i] = s[i - 1] + cnt[i] + ans = 0 + for y in range(1, mx + 1): + if cnt[y]: + d = 1 + while d * y <= mx: + ans += cnt[y] * d * (s[min(mx, d * y + y - 1)] - s[d * y - 1]) + ans %= mod + d += 1 + return ans diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.cpp b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.cpp index 96a107b07cad6..2ac012d612c1a 100644 --- a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.cpp +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.cpp @@ -1,17 +1,17 @@ -class Solution { -public: - int subsetXORSum(vector& nums) { - int n = nums.size(); - int ans = 0; - for (int i = 0; i < 1 << n; ++i) { - int s = 0; - for (int j = 0; j < n; ++j) { - if (i >> j & 1) { - s ^= nums[j]; - } - } - ans += s; - } - return ans; - } +class Solution { +public: + int subsetXORSum(vector& nums) { + int n = nums.size(); + int ans = 0; + for (int i = 0; i < 1 << n; ++i) { + int s = 0; + for (int j = 0; j < n; ++j) { + if (i >> j & 1) { + s ^= nums[j]; + } + } + ans += s; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.go b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.go index 42f4a535d8583..40b81eac5db29 100644 --- a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.go +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.go @@ -1,14 +1,13 @@ func subsetXORSum(nums []int) (ans int) { n := len(nums) - var dfs func(int, int) - dfs = func(i, s int) { - if i >= n { - ans += s - return + for i := 0; i < 1<>j&1 == 1 { + s ^= x + } } - dfs(i+1, s) - dfs(i+1, s^nums[i]) + ans += s } - dfs(0, 0) return } \ No newline at end of file diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.java b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.java index 4bf80cd0de29a..4ecf44d152731 100644 --- a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.java +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.java @@ -1,19 +1,16 @@ -class Solution { - private int ans; - private int[] nums; - - public int subsetXORSum(int[] nums) { - this.nums = nums; - dfs(0, 0); - return ans; - } - - private void dfs(int i, int s) { - if (i >= nums.length) { - ans += s; - return; - } - dfs(i + 1, s); - dfs(i + 1, s ^ nums[i]); - } +class Solution { + public int subsetXORSum(int[] nums) { + int n = nums.length; + int ans = 0; + for (int i = 0; i < 1 << n; ++i) { + int s = 0; + for (int j = 0; j < n; ++j) { + if ((i >> j & 1) == 1) { + s ^= nums[j]; + } + } + ans += s; + } + return ans; + } } \ No newline at end of file diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.js b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.js index ba314b524a976..57ebaeee1a649 100644 --- a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.js +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.js @@ -5,14 +5,14 @@ var subsetXORSum = function (nums) { let ans = 0; const n = nums.length; - const dfs = (i, s) => { - if (i >= n) { - ans += s; - return; + for (let i = 0; i < 1 << n; ++i) { + let s = 0; + for (let j = 0; j < n; ++j) { + if ((i >> j) & 1) { + s ^= nums[j]; + } } - dfs(i + 1, s); - dfs(i + 1, s ^ nums[i]); - }; - dfs(0, 0); + ans += s; + } return ans; }; diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.py b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.py index 2e180076e0817..408e073b8ad73 100644 --- a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.py +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.py @@ -1,13 +1,10 @@ -class Solution: - def subsetXORSum(self, nums: List[int]) -> int: - def dfs(i: int, s: int): - nonlocal ans - if i >= len(nums): - ans += s - return - dfs(i + 1, s) - dfs(i + 1, s ^ nums[i]) - - ans = 0 - dfs(0, 0) - return ans +class Solution: + def subsetXORSum(self, nums: List[int]) -> int: + ans, n = 0, len(nums) + for i in range(1 << n): + s = 0 + for j in range(n): + if i >> j & 1: + s ^= nums[j] + ans += s + return ans diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.ts b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.ts index 8bd8da85b5597..30df9de10ef8b 100644 --- a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.ts +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.ts @@ -1,14 +1,14 @@ function subsetXORSum(nums: number[]): number { let ans = 0; const n = nums.length; - const dfs = (i: number, s: number) => { - if (i >= n) { - ans += s; - return; + for (let i = 0; i < 1 << n; ++i) { + let s = 0; + for (let j = 0; j < n; ++j) { + if ((i >> j) & 1) { + s ^= nums[j]; + } } - dfs(i + 1, s); - dfs(i + 1, s ^ nums[i]); - }; - dfs(0, 0); + ans += s; + } return ans; } diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.cpp b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.cpp new file mode 100644 index 0000000000000..3f311df23a871 --- /dev/null +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int subsetXORSum(vector& nums) { + int n = nums.size(); + int ans = 0; + function dfs = [&](int i, int s) { + if (i >= n) { + ans += s; + return; + } + dfs(i + 1, s); + dfs(i + 1, s ^ nums[i]); + }; + dfs(0, 0); + return ans; + } +}; \ No newline at end of file diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.go b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.go new file mode 100644 index 0000000000000..42f4a535d8583 --- /dev/null +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.go @@ -0,0 +1,14 @@ +func subsetXORSum(nums []int) (ans int) { + n := len(nums) + var dfs func(int, int) + dfs = func(i, s int) { + if i >= n { + ans += s + return + } + dfs(i+1, s) + dfs(i+1, s^nums[i]) + } + dfs(0, 0) + return +} \ No newline at end of file diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.java b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.java new file mode 100644 index 0000000000000..2f0e44d8f1547 --- /dev/null +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.java @@ -0,0 +1,19 @@ +class Solution { + private int ans; + private int[] nums; + + public int subsetXORSum(int[] nums) { + this.nums = nums; + dfs(0, 0); + return ans; + } + + private void dfs(int i, int s) { + if (i >= nums.length) { + ans += s; + return; + } + dfs(i + 1, s); + dfs(i + 1, s ^ nums[i]); + } +} \ No newline at end of file diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.js b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.js new file mode 100644 index 0000000000000..ba314b524a976 --- /dev/null +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.js @@ -0,0 +1,18 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var subsetXORSum = function (nums) { + let ans = 0; + const n = nums.length; + const dfs = (i, s) => { + if (i >= n) { + ans += s; + return; + } + dfs(i + 1, s); + dfs(i + 1, s ^ nums[i]); + }; + dfs(0, 0); + return ans; +}; diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.py b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.py new file mode 100644 index 0000000000000..a9cb522bf3571 --- /dev/null +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def subsetXORSum(self, nums: List[int]) -> int: + def dfs(i: int, s: int): + nonlocal ans + if i >= len(nums): + ans += s + return + dfs(i + 1, s) + dfs(i + 1, s ^ nums[i]) + + ans = 0 + dfs(0, 0) + return ans diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.ts b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.ts new file mode 100644 index 0000000000000..8bd8da85b5597 --- /dev/null +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.ts @@ -0,0 +1,14 @@ +function subsetXORSum(nums: number[]): number { + let ans = 0; + const n = nums.length; + const dfs = (i: number, s: number) => { + if (i >= n) { + ans += s; + return; + } + dfs(i + 1, s); + dfs(i + 1, s ^ nums[i]); + }; + dfs(0, 0); + return ans; +} diff --git a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.cpp b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.cpp index 96d9eafacc5f5..f290dc2394581 100644 --- a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.cpp +++ b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.cpp @@ -2,15 +2,14 @@ class Solution { public: int rearrangeSticks(int n, int k) { const int mod = 1e9 + 7; - int f[k + 1]; + int f[n + 1][k + 1]; memset(f, 0, sizeof(f)); - f[0] = 1; + f[0][0] = 1; for (int i = 1; i <= n; ++i) { - for (int j = k; j; --j) { - f[j] = (f[j - 1] + f[j] * (i - 1LL)) % mod; + for (int j = 1; j <= k; ++j) { + f[i][j] = (f[i - 1][j - 1] + (i - 1LL) * f[i - 1][j]) % mod; } - f[0] = 0; } - return f[k]; + return f[n][k]; } }; \ No newline at end of file diff --git a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.go b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.go index c38d267742319..e95ef640a0342 100644 --- a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.go +++ b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.go @@ -1,12 +1,14 @@ func rearrangeSticks(n int, k int) int { const mod = 1e9 + 7 - f := make([]int, k+1) - f[0] = 1 + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, k+1) + } + f[0][0] = 1 for i := 1; i <= n; i++ { - for j := k; j > 0; j-- { - f[j] = (f[j-1] + f[j]*(i-1)) % mod + for j := 1; j <= k; j++ { + f[i][j] = (f[i-1][j-1] + (i-1)*f[i-1][j]) % mod } - f[0] = 0 } - return f[k] + return f[n][k] } \ No newline at end of file diff --git a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.java b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.java index ca00628b42efa..b1d146d4e5205 100644 --- a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.java +++ b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.java @@ -1,14 +1,13 @@ class Solution { public int rearrangeSticks(int n, int k) { final int mod = (int) 1e9 + 7; - int[] f = new int[k + 1]; - f[0] = 1; + int[][] f = new int[n + 1][k + 1]; + f[0][0] = 1; for (int i = 1; i <= n; ++i) { - for (int j = k; j > 0; --j) { - f[j] = (int) ((f[j] * (i - 1L) + f[j - 1]) % mod); + for (int j = 1; j <= k; ++j) { + f[i][j] = (int) ((f[i - 1][j - 1] + f[i - 1][j] * (long) (i - 1)) % mod); } - f[0] = 0; } - return f[k]; + return f[n][k]; } } \ No newline at end of file diff --git a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.py b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.py index 36d9ced797804..9f861bdd5c465 100644 --- a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.py +++ b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.py @@ -1,9 +1,9 @@ class Solution: def rearrangeSticks(self, n: int, k: int) -> int: mod = 10**9 + 7 - f = [1] + [0] * k + f = [[0] * (k + 1) for _ in range(n + 1)] + f[0][0] = 1 for i in range(1, n + 1): - for j in range(k, 0, -1): - f[j] = (f[j] * (i - 1) + f[j - 1]) % mod - f[0] = 0 - return f[k] + for j in range(1, k + 1): + f[i][j] = (f[i - 1][j - 1] + f[i - 1][j] * (i - 1)) % mod + return f[n][k] diff --git a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.ts b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.ts index 2ceb5737a78b7..d63b3b9b03929 100644 --- a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.ts +++ b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution.ts @@ -1,12 +1,13 @@ function rearrangeSticks(n: number, k: number): number { const mod = 10 ** 9 + 7; - const f: number[] = Array(n + 1).fill(0); - f[0] = 1; + const f: number[][] = Array.from({ length: n + 1 }, () => + Array.from({ length: k + 1 }, () => 0), + ); + f[0][0] = 1; for (let i = 1; i <= n; ++i) { - for (let j = k; j; --j) { - f[j] = (f[j] * (i - 1) + f[j - 1]) % mod; + for (let j = 1; j <= k; ++j) { + f[i][j] = (f[i - 1][j - 1] + (i - 1) * f[i - 1][j]) % mod; } - f[0] = 0; } - return f[k]; + return f[n][k]; } diff --git a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution2.cpp b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution2.cpp new file mode 100644 index 0000000000000..96d9eafacc5f5 --- /dev/null +++ b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int rearrangeSticks(int n, int k) { + const int mod = 1e9 + 7; + int f[k + 1]; + memset(f, 0, sizeof(f)); + f[0] = 1; + for (int i = 1; i <= n; ++i) { + for (int j = k; j; --j) { + f[j] = (f[j - 1] + f[j] * (i - 1LL)) % mod; + } + f[0] = 0; + } + return f[k]; + } +}; \ No newline at end of file diff --git a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution2.go b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution2.go new file mode 100644 index 0000000000000..c38d267742319 --- /dev/null +++ b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution2.go @@ -0,0 +1,12 @@ +func rearrangeSticks(n int, k int) int { + const mod = 1e9 + 7 + f := make([]int, k+1) + f[0] = 1 + for i := 1; i <= n; i++ { + for j := k; j > 0; j-- { + f[j] = (f[j-1] + f[j]*(i-1)) % mod + } + f[0] = 0 + } + return f[k] +} \ No newline at end of file diff --git a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution2.java b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution2.java new file mode 100644 index 0000000000000..ca00628b42efa --- /dev/null +++ b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public int rearrangeSticks(int n, int k) { + final int mod = (int) 1e9 + 7; + int[] f = new int[k + 1]; + f[0] = 1; + for (int i = 1; i <= n; ++i) { + for (int j = k; j > 0; --j) { + f[j] = (int) ((f[j] * (i - 1L) + f[j - 1]) % mod); + } + f[0] = 0; + } + return f[k]; + } +} \ No newline at end of file diff --git a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution2.py b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution2.py new file mode 100644 index 0000000000000..36d9ced797804 --- /dev/null +++ b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def rearrangeSticks(self, n: int, k: int) -> int: + mod = 10**9 + 7 + f = [1] + [0] * k + for i in range(1, n + 1): + for j in range(k, 0, -1): + f[j] = (f[j] * (i - 1) + f[j - 1]) % mod + f[0] = 0 + return f[k] diff --git a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution2.ts b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution2.ts new file mode 100644 index 0000000000000..2ceb5737a78b7 --- /dev/null +++ b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution2.ts @@ -0,0 +1,12 @@ +function rearrangeSticks(n: number, k: number): number { + const mod = 10 ** 9 + 7; + const f: number[] = Array(n + 1).fill(0); + f[0] = 1; + for (let i = 1; i <= n; ++i) { + for (let j = k; j; --j) { + f[j] = (f[j] * (i - 1) + f[j - 1]) % mod; + } + f[0] = 0; + } + return f[k]; +} diff --git a/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/Solution.cpp b/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/Solution.cpp index 49dc2c4d25759..f193ab6e7c8e9 100644 --- a/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/Solution.cpp +++ b/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/Solution.cpp @@ -1,17 +1,17 @@ -class Solution { -public: - bool checkZeroOnes(string s) { - auto f = [&](char x) { - int cnt = 0, mx = 0; - for (char& c : s) { - if (c == x) { - mx = max(mx, ++cnt); - } else { - cnt = 0; - } - } - return mx; - }; - return f('1') > f('0'); - } +class Solution { +public: + bool checkZeroOnes(string s) { + auto f = [&](char x) { + int cnt = 0, mx = 0; + for (char& c : s) { + if (c == x) { + mx = max(mx, ++cnt); + } else { + cnt = 0; + } + } + return mx; + }; + return f('1') > f('0'); + } }; \ No newline at end of file diff --git a/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/Solution.java b/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/Solution.java index f1522f5a2835b..e36f234a22127 100644 --- a/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/Solution.java +++ b/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public boolean checkZeroOnes(String s) { - return f(s, '1') > f(s, '0'); - } - - private int f(String s, char x) { - int cnt = 0, mx = 0; - for (int i = 0; i < s.length(); ++i) { - if (s.charAt(i) == x) { - mx = Math.max(mx, ++cnt); - } else { - cnt = 0; - } - } - return mx; - } +class Solution { + public boolean checkZeroOnes(String s) { + return f(s, '1') > f(s, '0'); + } + + private int f(String s, char x) { + int cnt = 0, mx = 0; + for (int i = 0; i < s.length(); ++i) { + if (s.charAt(i) == x) { + mx = Math.max(mx, ++cnt); + } else { + cnt = 0; + } + } + return mx; + } } \ No newline at end of file diff --git a/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/Solution.py b/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/Solution.py index c3e16efc89984..61fd334bdc956 100644 --- a/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/Solution.py +++ b/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def checkZeroOnes(self, s: str) -> bool: - def f(x: str) -> int: - cnt = mx = 0 - for c in s: - if c == x: - cnt += 1 - mx = max(mx, cnt) - else: - cnt = 0 - return mx - - return f("1") > f("0") +class Solution: + def checkZeroOnes(self, s: str) -> bool: + def f(x: str) -> int: + cnt = mx = 0 + for c in s: + if c == x: + cnt += 1 + mx = max(mx, cnt) + else: + cnt = 0 + return mx + + return f("1") > f("0") diff --git a/solution/1800-1899/1871.Jump Game VII/Solution.cpp b/solution/1800-1899/1871.Jump Game VII/Solution.cpp index 0bd74357b795f..beb9f1e2940fe 100644 --- a/solution/1800-1899/1871.Jump Game VII/Solution.cpp +++ b/solution/1800-1899/1871.Jump Game VII/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - bool canReach(string s, int minJump, int maxJump) { - int n = s.size(); - int pre[n + 1]; - memset(pre, 0, sizeof(pre)); - pre[1] = 1; - bool f[n]; - memset(f, 0, sizeof(f)); - f[0] = true; - for (int i = 1; i < n; ++i) { - if (s[i] == '0') { - int l = max(0, i - maxJump); - int r = i - minJump; - f[i] = l <= r && pre[r + 1] - pre[l]; - } - pre[i + 1] = pre[i] + f[i]; - } - return f[n - 1]; - } +class Solution { +public: + bool canReach(string s, int minJump, int maxJump) { + int n = s.size(); + int pre[n + 1]; + memset(pre, 0, sizeof(pre)); + pre[1] = 1; + bool f[n]; + memset(f, 0, sizeof(f)); + f[0] = true; + for (int i = 1; i < n; ++i) { + if (s[i] == '0') { + int l = max(0, i - maxJump); + int r = i - minJump; + f[i] = l <= r && pre[r + 1] - pre[l]; + } + pre[i + 1] = pre[i] + f[i]; + } + return f[n - 1]; + } }; \ No newline at end of file diff --git a/solution/1800-1899/1871.Jump Game VII/Solution.java b/solution/1800-1899/1871.Jump Game VII/Solution.java index a8d7a20f63336..1afa48a99de86 100644 --- a/solution/1800-1899/1871.Jump Game VII/Solution.java +++ b/solution/1800-1899/1871.Jump Game VII/Solution.java @@ -1,18 +1,18 @@ -class Solution { - public boolean canReach(String s, int minJump, int maxJump) { - int n = s.length(); - int[] pre = new int[n + 1]; - pre[1] = 1; - boolean[] f = new boolean[n]; - f[0] = true; - for (int i = 1; i < n; ++i) { - if (s.charAt(i) == '0') { - int l = Math.max(0, i - maxJump); - int r = i - minJump; - f[i] = l <= r && pre[r + 1] - pre[l] > 0; - } - pre[i + 1] = pre[i] + (f[i] ? 1 : 0); - } - return f[n - 1]; - } +class Solution { + public boolean canReach(String s, int minJump, int maxJump) { + int n = s.length(); + int[] pre = new int[n + 1]; + pre[1] = 1; + boolean[] f = new boolean[n]; + f[0] = true; + for (int i = 1; i < n; ++i) { + if (s.charAt(i) == '0') { + int l = Math.max(0, i - maxJump); + int r = i - minJump; + f[i] = l <= r && pre[r + 1] - pre[l] > 0; + } + pre[i + 1] = pre[i] + (f[i] ? 1 : 0); + } + return f[n - 1]; + } } \ No newline at end of file diff --git a/solution/1800-1899/1871.Jump Game VII/Solution.py b/solution/1800-1899/1871.Jump Game VII/Solution.py index 6befd03ede034..403aaaa812063 100644 --- a/solution/1800-1899/1871.Jump Game VII/Solution.py +++ b/solution/1800-1899/1871.Jump Game VII/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def canReach(self, s: str, minJump: int, maxJump: int) -> bool: - n = len(s) - pre = [0] * (n + 1) - pre[1] = 1 - f = [True] + [False] * (n - 1) - for i in range(1, n): - if s[i] == "0": - l, r = max(0, i - maxJump), i - minJump - f[i] = l <= r and pre[r + 1] - pre[l] > 0 - pre[i + 1] = pre[i] + f[i] - return f[-1] +class Solution: + def canReach(self, s: str, minJump: int, maxJump: int) -> bool: + n = len(s) + pre = [0] * (n + 1) + pre[1] = 1 + f = [True] + [False] * (n - 1) + for i in range(1, n): + if s[i] == "0": + l, r = max(0, i - maxJump), i - minJump + f[i] = l <= r and pre[r + 1] - pre[l] > 0 + pre[i + 1] = pre[i] + f[i] + return f[-1] diff --git a/solution/1800-1899/1872.Stone Game VIII/Solution.cpp b/solution/1800-1899/1872.Stone Game VIII/Solution.cpp index be7503b9a2eb1..edd95bfe6eac5 100644 --- a/solution/1800-1899/1872.Stone Game VIII/Solution.cpp +++ b/solution/1800-1899/1872.Stone Game VIII/Solution.cpp @@ -1,14 +1,21 @@ -class Solution { -public: - int stoneGameVIII(vector& stones) { - int n = stones.size(); - for (int i = 1; i < n; ++i) { - stones[i] += stones[i - 1]; - } - int f = stones.back(); - for (int i = n - 2; i; --i) { - f = max(f, stones[i] - f); - } - return f; - } +class Solution { +public: + int stoneGameVIII(vector& stones) { + int n = stones.size(); + for (int i = 1; i < n; ++i) { + stones[i] += stones[i - 1]; + } + int f[n]; + memset(f, -1, sizeof(f)); + function dfs = [&](int i) -> int { + if (i >= n - 1) { + return stones[i]; + } + if (f[i] == -1) { + f[i] = max(dfs(i + 1), stones[i] - dfs(i + 1)); + } + return f[i]; + }; + return dfs(1); + } }; \ No newline at end of file diff --git a/solution/1800-1899/1872.Stone Game VIII/Solution.go b/solution/1800-1899/1872.Stone Game VIII/Solution.go index 60c1522f312fb..eda5e98d8bef8 100644 --- a/solution/1800-1899/1872.Stone Game VIII/Solution.go +++ b/solution/1800-1899/1872.Stone Game VIII/Solution.go @@ -1,11 +1,21 @@ func stoneGameVIII(stones []int) int { n := len(stones) + f := make([]int, n) + for i := range f { + f[i] = -1 + } for i := 1; i < n; i++ { stones[i] += stones[i-1] } - f := stones[n-1] - for i := n - 2; i > 0; i-- { - f = max(f, stones[i]-f) + var dfs func(int) int + dfs = func(i int) int { + if i >= n-1 { + return stones[i] + } + if f[i] == -1 { + f[i] = max(dfs(i+1), stones[i]-dfs(i+1)) + } + return f[i] } - return f + return dfs(1) } \ No newline at end of file diff --git a/solution/1800-1899/1872.Stone Game VIII/Solution.java b/solution/1800-1899/1872.Stone Game VIII/Solution.java index 8cf95b08cc207..6f6dc70c6f8a1 100644 --- a/solution/1800-1899/1872.Stone Game VIII/Solution.java +++ b/solution/1800-1899/1872.Stone Game VIII/Solution.java @@ -1,13 +1,25 @@ -class Solution { - public int stoneGameVIII(int[] stones) { - int n = stones.length; - for (int i = 1; i < n; ++i) { - stones[i] += stones[i - 1]; - } - int f = stones[n - 1]; - for (int i = n - 2; i > 0; --i) { - f = Math.max(f, stones[i] - f); - } - return f; - } +class Solution { + private Integer[] f; + private int[] s; + private int n; + + public int stoneGameVIII(int[] stones) { + n = stones.length; + f = new Integer[n]; + for (int i = 1; i < n; ++i) { + stones[i] += stones[i - 1]; + } + s = stones; + return dfs(1); + } + + private int dfs(int i) { + if (i >= n - 1) { + return s[i]; + } + if (f[i] == null) { + f[i] = Math.max(dfs(i + 1), s[i] - dfs(i + 1)); + } + return f[i]; + } } \ No newline at end of file diff --git a/solution/1800-1899/1872.Stone Game VIII/Solution.py b/solution/1800-1899/1872.Stone Game VIII/Solution.py index 4908c82f52153..d910a1346044c 100644 --- a/solution/1800-1899/1872.Stone Game VIII/Solution.py +++ b/solution/1800-1899/1872.Stone Game VIII/Solution.py @@ -1,7 +1,10 @@ -class Solution: - def stoneGameVIII(self, stones: List[int]) -> int: - s = list(accumulate(stones)) - f = s[-1] - for i in range(len(s) - 2, 0, -1): - f = max(f, s[i] - f) - return f +class Solution: + def stoneGameVIII(self, stones: List[int]) -> int: + @cache + def dfs(i: int) -> int: + if i >= len(stones) - 1: + return s[-1] + return max(dfs(i + 1), s[i] - dfs(i + 1)) + + s = list(accumulate(stones)) + return dfs(1) diff --git a/solution/1800-1899/1872.Stone Game VIII/Solution.ts b/solution/1800-1899/1872.Stone Game VIII/Solution.ts index af66461297686..77a810e1dd2e0 100644 --- a/solution/1800-1899/1872.Stone Game VIII/Solution.ts +++ b/solution/1800-1899/1872.Stone Game VIII/Solution.ts @@ -1,11 +1,17 @@ function stoneGameVIII(stones: number[]): number { const n = stones.length; + const f: number[] = Array(n).fill(-1); for (let i = 1; i < n; ++i) { stones[i] += stones[i - 1]; } - let f = stones[n - 1]; - for (let i = n - 2; i; --i) { - f = Math.max(f, stones[i] - f); - } - return f; + const dfs = (i: number): number => { + if (i >= n - 1) { + return stones[i]; + } + if (f[i] === -1) { + f[i] = Math.max(dfs(i + 1), stones[i] - dfs(i + 1)); + } + return f[i]; + }; + return dfs(1); } diff --git a/solution/1800-1899/1872.Stone Game VIII/Solution2.cpp b/solution/1800-1899/1872.Stone Game VIII/Solution2.cpp new file mode 100644 index 0000000000000..dc77dcb65f4d9 --- /dev/null +++ b/solution/1800-1899/1872.Stone Game VIII/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int stoneGameVIII(vector& stones) { + int n = stones.size(); + for (int i = 1; i < n; ++i) { + stones[i] += stones[i - 1]; + } + int f = stones.back(); + for (int i = n - 2; i; --i) { + f = max(f, stones[i] - f); + } + return f; + } +}; \ No newline at end of file diff --git a/solution/1800-1899/1872.Stone Game VIII/Solution2.java b/solution/1800-1899/1872.Stone Game VIII/Solution2.java new file mode 100644 index 0000000000000..a83b461a1c338 --- /dev/null +++ b/solution/1800-1899/1872.Stone Game VIII/Solution2.java @@ -0,0 +1,13 @@ +class Solution { + public int stoneGameVIII(int[] stones) { + int n = stones.length; + for (int i = 1; i < n; ++i) { + stones[i] += stones[i - 1]; + } + int f = stones[n - 1]; + for (int i = n - 2; i > 0; --i) { + f = Math.max(f, stones[i] - f); + } + return f; + } +} \ No newline at end of file diff --git a/solution/1800-1899/1872.Stone Game VIII/Solution2.py b/solution/1800-1899/1872.Stone Game VIII/Solution2.py new file mode 100644 index 0000000000000..2ea257211c02a --- /dev/null +++ b/solution/1800-1899/1872.Stone Game VIII/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def stoneGameVIII(self, stones: List[int]) -> int: + s = list(accumulate(stones)) + f = s[-1] + for i in range(len(s) - 2, 0, -1): + f = max(f, s[i] - f) + return f diff --git a/solution/1800-1899/1872.Stone Game VIII/Solution2.ts b/solution/1800-1899/1872.Stone Game VIII/Solution2.ts new file mode 100644 index 0000000000000..af66461297686 --- /dev/null +++ b/solution/1800-1899/1872.Stone Game VIII/Solution2.ts @@ -0,0 +1,11 @@ +function stoneGameVIII(stones: number[]): number { + const n = stones.length; + for (let i = 1; i < n; ++i) { + stones[i] += stones[i - 1]; + } + let f = stones[n - 1]; + for (let i = n - 2; i; --i) { + f = Math.max(f, stones[i] - f); + } + return f; +} diff --git a/solution/1800-1899/1876.Substrings of Size Three with Distinct Characters/Solution.php b/solution/1800-1899/1876.Substrings of Size Three with Distinct Characters/Solution.php index a6cfa9b724911..4677592fedbcf 100644 --- a/solution/1800-1899/1876.Substrings of Size Three with Distinct Characters/Solution.php +++ b/solution/1800-1899/1876.Substrings of Size Three with Distinct Characters/Solution.php @@ -12,4 +12,4 @@ function countGoodSubstrings($s) { } return $cnt++; } -} \ No newline at end of file +} diff --git a/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/Solution.cpp b/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/Solution.cpp index 71326eb68c0fb..0c49afde68c4b 100644 --- a/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/Solution.cpp +++ b/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/Solution.cpp @@ -1,32 +1,32 @@ -class Solution { -public: - vector getBiggestThree(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - vector> s1(m + 1, vector(n + 2)); - vector> s2(m + 1, vector(n + 2)); - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - s1[i][j] = s1[i - 1][j - 1] + grid[i - 1][j - 1]; - s2[i][j] = s2[i - 1][j + 1] + grid[i - 1][j - 1]; - } - } - set ss; - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - int l = min({i - 1, m - i, j - 1, n - j}); - ss.insert(grid[i - 1][j - 1]); - for (int k = 1; k <= l; ++k) { - int a = s1[i + k][j] - s1[i][j - k]; - int b = s1[i][j + k] - s1[i - k][j]; - int c = s2[i][j - k] - s2[i - k][j]; - int d = s2[i + k][j] - s2[i][j + k]; - ss.insert(a + b + c + d - grid[i + k - 1][j - 1] + grid[i - k - 1][j - 1]); - } - while (ss.size() > 3) { - ss.erase(ss.begin()); - } - } - } - return vector(ss.rbegin(), ss.rend()); - } +class Solution { +public: + vector getBiggestThree(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + vector> s1(m + 1, vector(n + 2)); + vector> s2(m + 1, vector(n + 2)); + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + s1[i][j] = s1[i - 1][j - 1] + grid[i - 1][j - 1]; + s2[i][j] = s2[i - 1][j + 1] + grid[i - 1][j - 1]; + } + } + set ss; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + int l = min({i - 1, m - i, j - 1, n - j}); + ss.insert(grid[i - 1][j - 1]); + for (int k = 1; k <= l; ++k) { + int a = s1[i + k][j] - s1[i][j - k]; + int b = s1[i][j + k] - s1[i - k][j]; + int c = s2[i][j - k] - s2[i - k][j]; + int d = s2[i + k][j] - s2[i][j + k]; + ss.insert(a + b + c + d - grid[i + k - 1][j - 1] + grid[i - k - 1][j - 1]); + } + while (ss.size() > 3) { + ss.erase(ss.begin()); + } + } + } + return vector(ss.rbegin(), ss.rend()); + } }; \ No newline at end of file diff --git a/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/Solution.java b/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/Solution.java index 1972d94481fd8..31278f7201dc1 100644 --- a/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/Solution.java +++ b/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/Solution.java @@ -1,35 +1,35 @@ -class Solution { - public int[] getBiggestThree(int[][] grid) { - int m = grid.length, n = grid[0].length; - int[][] s1 = new int[m + 1][n + 2]; - int[][] s2 = new int[m + 1][n + 2]; - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - s1[i][j] = s1[i - 1][j - 1] + grid[i - 1][j - 1]; - s2[i][j] = s2[i - 1][j + 1] + grid[i - 1][j - 1]; - } - } - TreeSet ss = new TreeSet<>(); - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - int l = Math.min(Math.min(i - 1, m - i), Math.min(j - 1, n - j)); - ss.add(grid[i - 1][j - 1]); - for (int k = 1; k <= l; ++k) { - int a = s1[i + k][j] - s1[i][j - k]; - int b = s1[i][j + k] - s1[i - k][j]; - int c = s2[i][j - k] - s2[i - k][j]; - int d = s2[i + k][j] - s2[i][j + k]; - ss.add(a + b + c + d - grid[i + k - 1][j - 1] + grid[i - k - 1][j - 1]); - } - while (ss.size() > 3) { - ss.pollFirst(); - } - } - } - int[] ans = new int[ss.size()]; - for (int i = 0; i < ans.length; ++i) { - ans[i] = ss.pollLast(); - } - return ans; - } +class Solution { + public int[] getBiggestThree(int[][] grid) { + int m = grid.length, n = grid[0].length; + int[][] s1 = new int[m + 1][n + 2]; + int[][] s2 = new int[m + 1][n + 2]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + s1[i][j] = s1[i - 1][j - 1] + grid[i - 1][j - 1]; + s2[i][j] = s2[i - 1][j + 1] + grid[i - 1][j - 1]; + } + } + TreeSet ss = new TreeSet<>(); + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + int l = Math.min(Math.min(i - 1, m - i), Math.min(j - 1, n - j)); + ss.add(grid[i - 1][j - 1]); + for (int k = 1; k <= l; ++k) { + int a = s1[i + k][j] - s1[i][j - k]; + int b = s1[i][j + k] - s1[i - k][j]; + int c = s2[i][j - k] - s2[i - k][j]; + int d = s2[i + k][j] - s2[i][j + k]; + ss.add(a + b + c + d - grid[i + k - 1][j - 1] + grid[i - k - 1][j - 1]); + } + while (ss.size() > 3) { + ss.pollFirst(); + } + } + } + int[] ans = new int[ss.size()]; + for (int i = 0; i < ans.length; ++i) { + ans[i] = ss.pollLast(); + } + return ans; + } } \ No newline at end of file diff --git a/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/Solution.py b/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/Solution.py index 35a2fcf55a34f..ba5346da4d19a 100644 --- a/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/Solution.py +++ b/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/Solution.py @@ -1,28 +1,28 @@ -from sortedcontainers import SortedSet - - -class Solution: - def getBiggestThree(self, grid: List[List[int]]) -> List[int]: - m, n = len(grid), len(grid[0]) - s1 = [[0] * (n + 2) for _ in range(m + 1)] - s2 = [[0] * (n + 2) for _ in range(m + 1)] - for i, row in enumerate(grid, 1): - for j, x in enumerate(row, 1): - s1[i][j] = s1[i - 1][j - 1] + x - s2[i][j] = s2[i - 1][j + 1] + x - ss = SortedSet() - for i, row in enumerate(grid, 1): - for j, x in enumerate(row, 1): - l = min(i - 1, m - i, j - 1, n - j) - ss.add(x) - for k in range(1, l + 1): - a = s1[i + k][j] - s1[i][j - k] - b = s1[i][j + k] - s1[i - k][j] - c = s2[i][j - k] - s2[i - k][j] - d = s2[i + k][j] - s2[i][j + k] - ss.add( - a + b + c + d - grid[i + k - 1][j - 1] + grid[i - k - 1][j - 1] - ) - while len(ss) > 3: - ss.remove(ss[0]) - return list(ss)[::-1] +from sortedcontainers import SortedSet + + +class Solution: + def getBiggestThree(self, grid: List[List[int]]) -> List[int]: + m, n = len(grid), len(grid[0]) + s1 = [[0] * (n + 2) for _ in range(m + 1)] + s2 = [[0] * (n + 2) for _ in range(m + 1)] + for i, row in enumerate(grid, 1): + for j, x in enumerate(row, 1): + s1[i][j] = s1[i - 1][j - 1] + x + s2[i][j] = s2[i - 1][j + 1] + x + ss = SortedSet() + for i, row in enumerate(grid, 1): + for j, x in enumerate(row, 1): + l = min(i - 1, m - i, j - 1, n - j) + ss.add(x) + for k in range(1, l + 1): + a = s1[i + k][j] - s1[i][j - k] + b = s1[i][j + k] - s1[i - k][j] + c = s2[i][j - k] - s2[i - k][j] + d = s2[i + k][j] - s2[i][j + k] + ss.add( + a + b + c + d - grid[i + k - 1][j - 1] + grid[i - k - 1][j - 1] + ) + while len(ss) > 3: + ss.remove(ss[0]) + return list(ss)[::-1] diff --git a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution.cpp b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution.cpp index f653e3b49b126..240b324a84f75 100644 --- a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution.cpp +++ b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution.cpp @@ -1,18 +1,19 @@ -class Solution { -public: - int minimumXORSum(vector& nums1, vector& nums2) { - int n = nums1.size(); - int f[1 << n]; - memset(f, 0x3f, sizeof(f)); - f[0] = 0; - for (int i = 0; i < 1 << n; ++i) { - int k = __builtin_popcount(i) - 1; - for (int j = 0; j < n; ++j) { - if (i >> j & 1) { - f[i] = min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])); - } - } - } - return f[(1 << n) - 1]; - } +class Solution { +public: + int minimumXORSum(vector& nums1, vector& nums2) { + int n = nums1.size(); + int f[n + 1][1 << n]; + memset(f, 0x3f, sizeof(f)); + f[0][0] = 0; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < 1 << n; ++j) { + for (int k = 0; k < n; ++k) { + if (j >> k & 1) { + f[i][j] = min(f[i][j], f[i - 1][j ^ (1 << k)] + (nums1[i - 1] ^ nums2[k])); + } + } + } + } + return f[n][(1 << n) - 1]; + } }; \ No newline at end of file diff --git a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution.go b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution.go index ca590d06d0b58..495fa0642068a 100644 --- a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution.go +++ b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution.go @@ -1,17 +1,21 @@ func minimumXORSum(nums1 []int, nums2 []int) int { n := len(nums1) - f := make([]int, 1<>j&1 == 1 { - f[i] = min(f[i], f[i^1<>k&1 == 1 { + f[i][j] = min(f[i][j], f[i-1][j^(1<> j & 1) == 1) { - f[i] = Math.min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])); - } - } - } - return f[(1 << n) - 1]; - } +class Solution { + public int minimumXORSum(int[] nums1, int[] nums2) { + int n = nums1.length; + int[][] f = new int[n + 1][1 << n]; + for (var g : f) { + Arrays.fill(g, 1 << 30); + } + f[0][0] = 0; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < 1 << n; ++j) { + for (int k = 0; k < n; ++k) { + if ((j >> k & 1) == 1) { + f[i][j] + = Math.min(f[i][j], f[i - 1][j ^ (1 << k)] + (nums1[i - 1] ^ nums2[k])); + } + } + } + } + return f[n][(1 << n) - 1]; + } } \ No newline at end of file diff --git a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution.py b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution.py index 5a2b7670dc6bd..dd8d9b2c285c3 100644 --- a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution.py +++ b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int: - n = len(nums2) - f = [inf] * (1 << n) - f[0] = 0 - for i in range(1, 1 << n): - k = i.bit_count() - 1 - for j in range(n): - if i >> j & 1: - f[i] = min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])) - return f[-1] +class Solution: + def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int: + n = len(nums2) + f = [[inf] * (1 << n) for _ in range(n + 1)] + f[0][0] = 0 + for i, x in enumerate(nums1, 1): + for j in range(1 << n): + for k in range(n): + if j >> k & 1: + f[i][j] = min(f[i][j], f[i - 1][j ^ (1 << k)] + (x ^ nums2[k])) + return f[-1][-1] diff --git a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution.ts b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution.ts index 1bd9fddf27eb8..1b4c0200f25b1 100644 --- a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution.ts +++ b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution.ts @@ -1,23 +1,17 @@ function minimumXORSum(nums1: number[], nums2: number[]): number { const n = nums1.length; - const f: number[] = Array(1 << n).fill(1 << 30); - f[0] = 0; - for (let i = 0; i < 1 << n; ++i) { - const k = bitCount(i) - 1; - for (let j = 0; j < n; ++j) { - if (((i >> j) & 1) === 1) { - f[i] = Math.min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])); + const f: number[][] = Array(n + 1) + .fill(0) + .map(() => Array(1 << n).fill(1 << 30)); + f[0][0] = 0; + for (let i = 1; i <= n; ++i) { + for (let j = 0; j < 1 << n; ++j) { + for (let k = 0; k < n; ++k) { + if (((j >> k) & 1) === 1) { + f[i][j] = Math.min(f[i][j], f[i - 1][j ^ (1 << k)] + (nums1[i - 1] ^ nums2[k])); + } } } } - return f[(1 << n) - 1]; -} - -function bitCount(i: number): number { - i = i - ((i >>> 1) & 0x55555555); - i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); - i = (i + (i >>> 4)) & 0x0f0f0f0f; - i = i + (i >>> 8); - i = i + (i >>> 16); - return i & 0x3f; + return f[n][(1 << n) - 1]; } diff --git a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution2.cpp b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution2.cpp new file mode 100644 index 0000000000000..1c252909bab98 --- /dev/null +++ b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int minimumXORSum(vector& nums1, vector& nums2) { + int n = nums1.size(); + int f[1 << n]; + memset(f, 0x3f, sizeof(f)); + f[0] = 0; + for (int x : nums1) { + for (int j = (1 << n) - 1; ~j; --j) { + for (int k = 0; k < n; ++k) { + if (j >> k & 1) { + f[j] = min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])); + } + } + } + } + return f[(1 << n) - 1]; + } +}; \ No newline at end of file diff --git a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution2.go b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution2.go new file mode 100644 index 0000000000000..a906ccafc74bc --- /dev/null +++ b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution2.go @@ -0,0 +1,18 @@ +func minimumXORSum(nums1 []int, nums2 []int) int { + n := len(nums1) + f := make([]int, 1<= 0; j-- { + for k := 0; k < n; k++ { + if j>>k&1 == 1 { + f[j] = min(f[j], f[j^(1<= 0; --j) { + for (int k = 0; k < n; ++k) { + if ((j >> k & 1) == 1) { + f[j] = Math.min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])); + } + } + } + } + return f[(1 << n) - 1]; + } +} \ No newline at end of file diff --git a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution2.py b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution2.py new file mode 100644 index 0000000000000..c7870902845f7 --- /dev/null +++ b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int: + n = len(nums2) + f = [inf] * (1 << n) + f[0] = 0 + for x in nums1: + for j in range((1 << n) - 1, -1, -1): + for k in range(n): + if j >> k & 1: + f[j] = min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])) + return f[-1] diff --git a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution2.ts b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution2.ts new file mode 100644 index 0000000000000..a71fa3b3fb610 --- /dev/null +++ b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution2.ts @@ -0,0 +1,15 @@ +function minimumXORSum(nums1: number[], nums2: number[]): number { + const n = nums1.length; + const f: number[] = Array(1 << n).fill(1 << 30); + f[0] = 0; + for (const x of nums1) { + for (let j = (1 << n) - 1; ~j; --j) { + for (let k = 0; k < n; ++k) { + if (((j >> k) & 1) === 1) { + f[j] = Math.min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])); + } + } + } + } + return f[(1 << n) - 1]; +} diff --git a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution3.cpp b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution3.cpp new file mode 100644 index 0000000000000..9dac16e320f22 --- /dev/null +++ b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution3.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int minimumXORSum(vector& nums1, vector& nums2) { + int n = nums1.size(); + int f[1 << n]; + memset(f, 0x3f, sizeof(f)); + f[0] = 0; + for (int i = 0; i < 1 << n; ++i) { + int k = __builtin_popcount(i) - 1; + for (int j = 0; j < n; ++j) { + if (i >> j & 1) { + f[i] = min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])); + } + } + } + return f[(1 << n) - 1]; + } +}; \ No newline at end of file diff --git a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution3.go b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution3.go new file mode 100644 index 0000000000000..ca590d06d0b58 --- /dev/null +++ b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution3.go @@ -0,0 +1,17 @@ +func minimumXORSum(nums1 []int, nums2 []int) int { + n := len(nums1) + f := make([]int, 1<>j&1 == 1 { + f[i] = min(f[i], f[i^1<> j & 1) == 1) { + f[i] = Math.min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])); + } + } + } + return f[(1 << n) - 1]; + } +} \ No newline at end of file diff --git a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution3.py b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution3.py new file mode 100644 index 0000000000000..bb512438540d0 --- /dev/null +++ b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution3.py @@ -0,0 +1,11 @@ +class Solution: + def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int: + n = len(nums2) + f = [inf] * (1 << n) + f[0] = 0 + for i in range(1, 1 << n): + k = i.bit_count() - 1 + for j in range(n): + if i >> j & 1: + f[i] = min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])) + return f[-1] diff --git a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution3.ts b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution3.ts new file mode 100644 index 0000000000000..1bd9fddf27eb8 --- /dev/null +++ b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution3.ts @@ -0,0 +1,23 @@ +function minimumXORSum(nums1: number[], nums2: number[]): number { + const n = nums1.length; + const f: number[] = Array(1 << n).fill(1 << 30); + f[0] = 0; + for (let i = 0; i < 1 << n; ++i) { + const k = bitCount(i) - 1; + for (let j = 0; j < n; ++j) { + if (((i >> j) & 1) === 1) { + f[i] = Math.min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])); + } + } + } + return f[(1 << n) - 1]; +} + +function bitCount(i: number): number { + i = i - ((i >>> 1) & 0x55555555); + i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); + i = (i + (i >>> 4)) & 0x0f0f0f0f; + i = i + (i >>> 8); + i = i + (i >>> 16); + return i & 0x3f; +} diff --git a/solution/1800-1899/1880.Check if Word Equals Summation of Two Words/Solution.c b/solution/1800-1899/1880.Check if Word Equals Summation of Two Words/Solution.c index 6e78c4fd2f276..a1bb00e6737c4 100644 --- a/solution/1800-1899/1880.Check if Word Equals Summation of Two Words/Solution.c +++ b/solution/1800-1899/1880.Check if Word Equals Summation of Two Words/Solution.c @@ -8,4 +8,4 @@ int calc(char* s) { bool isSumEqual(char* firstWord, char* secondWord, char* targetWord) { return calc(firstWord) + calc(secondWord) == calc(targetWord); -} +} \ No newline at end of file diff --git a/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/Solution.cpp b/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/Solution.cpp index cbf06e4caf5b8..1c474ec73dd71 100644 --- a/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/Solution.cpp +++ b/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/Solution.cpp @@ -1,25 +1,25 @@ -class Solution { -public: - int minSkips(vector& dist, int speed, int hoursBefore) { - int n = dist.size(); - vector> f(n + 1, vector(n + 1, 1e20)); - f[0][0] = 0; - double eps = 1e-8; - for (int i = 1; i <= n; ++i) { - for (int j = 0; j <= i; ++j) { - if (j < i) { - f[i][j] = min(f[i][j], ceil(f[i - 1][j] + dist[i - 1] * 1.0 / speed - eps)); - } - if (j) { - f[i][j] = min(f[i][j], f[i - 1][j - 1] + dist[i - 1] * 1.0 / speed); - } - } - } - for (int j = 0; j <= n; ++j) { - if (f[n][j] <= hoursBefore + eps) { - return j; - } - } - return -1; - } +class Solution { +public: + int minSkips(vector& dist, int speed, int hoursBefore) { + int n = dist.size(); + vector> f(n + 1, vector(n + 1, 1e20)); + f[0][0] = 0; + double eps = 1e-8; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j <= i; ++j) { + if (j < i) { + f[i][j] = min(f[i][j], ceil(f[i - 1][j] + dist[i - 1] * 1.0 / speed - eps)); + } + if (j) { + f[i][j] = min(f[i][j], f[i - 1][j - 1] + dist[i - 1] * 1.0 / speed); + } + } + } + for (int j = 0; j <= n; ++j) { + if (f[n][j] <= hoursBefore + eps) { + return j; + } + } + return -1; + } }; \ No newline at end of file diff --git a/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/Solution.java b/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/Solution.java index d0d306bba83de..209eef1e31e68 100644 --- a/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/Solution.java +++ b/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/Solution.java @@ -1,28 +1,28 @@ -class Solution { - public int minSkips(int[] dist, int speed, int hoursBefore) { - int n = dist.length; - double[][] f = new double[n + 1][n + 1]; - for (int i = 0; i <= n; i++) { - Arrays.fill(f[i], 1e20); - } - f[0][0] = 0; - double eps = 1e-8; - for (int i = 1; i <= n; ++i) { - for (int j = 0; j <= i; ++j) { - if (j < i) { - f[i][j] = Math.min( - f[i][j], Math.ceil(f[i - 1][j]) + 1.0 * dist[i - 1] / speed - eps); - } - if (j > 0) { - f[i][j] = Math.min(f[i][j], f[i - 1][j - 1] + 1.0 * dist[i - 1] / speed); - } - } - } - for (int j = 0; j <= n; ++j) { - if (f[n][j] <= hoursBefore + eps) { - return j; - } - } - return -1; - } +class Solution { + public int minSkips(int[] dist, int speed, int hoursBefore) { + int n = dist.length; + double[][] f = new double[n + 1][n + 1]; + for (int i = 0; i <= n; i++) { + Arrays.fill(f[i], 1e20); + } + f[0][0] = 0; + double eps = 1e-8; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j <= i; ++j) { + if (j < i) { + f[i][j] = Math.min( + f[i][j], Math.ceil(f[i - 1][j]) + 1.0 * dist[i - 1] / speed - eps); + } + if (j > 0) { + f[i][j] = Math.min(f[i][j], f[i - 1][j - 1] + 1.0 * dist[i - 1] / speed); + } + } + } + for (int j = 0; j <= n; ++j) { + if (f[n][j] <= hoursBefore + eps) { + return j; + } + } + return -1; + } } \ No newline at end of file diff --git a/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/Solution.py b/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/Solution.py index f1f48413b884e..4d49d3db329be 100644 --- a/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/Solution.py +++ b/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/Solution.py @@ -1,16 +1,16 @@ -class Solution: - def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int: - n = len(dist) - f = [[inf] * (n + 1) for _ in range(n + 1)] - f[0][0] = 0 - eps = 1e-8 - for i, x in enumerate(dist, 1): - for j in range(i + 1): - if j < i: - f[i][j] = min(f[i][j], ceil(f[i - 1][j] + x / speed - eps)) - if j: - f[i][j] = min(f[i][j], f[i - 1][j - 1] + x / speed) - for j in range(n + 1): - if f[n][j] <= hoursBefore + eps: - return j - return -1 +class Solution: + def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int: + n = len(dist) + f = [[inf] * (n + 1) for _ in range(n + 1)] + f[0][0] = 0 + eps = 1e-8 + for i, x in enumerate(dist, 1): + for j in range(i + 1): + if j < i: + f[i][j] = min(f[i][j], ceil(f[i - 1][j] + x / speed - eps)) + if j: + f[i][j] = min(f[i][j], f[i - 1][j - 1] + x / speed) + for j in range(n + 1): + if f[n][j] <= hoursBefore + eps: + return j + return -1 diff --git a/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/Solution2.py b/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/Solution2.py new file mode 100644 index 0000000000000..06610ad5f6901 --- /dev/null +++ b/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/Solution2.py @@ -0,0 +1,15 @@ +class Solution: + def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int: + n = len(dist) + f = [[inf] * (n + 1) for _ in range(n + 1)] + f[0][0] = 0 + for i, x in enumerate(dist, 1): + for j in range(i + 1): + if j < i: + f[i][j] = min(f[i][j], ((f[i - 1][j] + x - 1) // speed + 1) * speed) + if j: + f[i][j] = min(f[i][j], f[i - 1][j - 1] + x) + for j in range(n + 1): + if f[n][j] <= hoursBefore * speed: + return j + return -1 diff --git a/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/Solution.java b/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/Solution.java index 83fe8fbc2e831..d7d5b35f44fab 100644 --- a/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/Solution.java +++ b/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/Solution.java @@ -1,26 +1,33 @@ class Solution { public boolean findRotation(int[][] mat, int[][] target) { - int n = mat.length; - for (int k = 0; k < 4; ++k) { - int[][] g = new int[n][n]; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - g[i][j] = mat[j][n - i - 1]; - } - } - if (equals(g, target)) { + int times = 4; + while (times-- > 0) { + if (equals(mat, target)) { return true; } - mat = g; + rotate(mat); } return false; } - private boolean equals(int[][] a, int[][] b) { - int n = a.length; + private void rotate(int[][] matrix) { + int n = matrix.length; + for (int i = 0; i < n / 2; ++i) { + for (int j = i; j < n - 1 - i; ++j) { + int t = matrix[i][j]; + matrix[i][j] = matrix[n - j - 1][i]; + matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1]; + matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1]; + matrix[j][n - i - 1] = t; + } + } + } + + private boolean equals(int[][] nums1, int[][] nums2) { + int n = nums1.length; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { - if (a[i][j] != b[i][j]) { + if (nums1[i][j] != nums2[i][j]) { return false; } } diff --git a/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/Solution.py b/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/Solution.py index b9279906c51cc..8e5dc26a6cf22 100644 --- a/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/Solution.py +++ b/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/Solution.py @@ -1,7 +1,17 @@ class Solution: def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool: + def rotate(matrix): + n = len(matrix) + for i in range(n // 2): + for j in range(i, n - 1 - i): + t = matrix[i][j] + matrix[i][j] = matrix[n - j - 1][i] + matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1] + matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1] + matrix[j][n - i - 1] = t + for _ in range(4): - mat = [list(col) for col in zip(*mat[::-1])] if mat == target: return True + rotate(mat) return False diff --git a/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/Solution2.java b/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/Solution2.java new file mode 100644 index 0000000000000..83fe8fbc2e831 --- /dev/null +++ b/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/Solution2.java @@ -0,0 +1,30 @@ +class Solution { + public boolean findRotation(int[][] mat, int[][] target) { + int n = mat.length; + for (int k = 0; k < 4; ++k) { + int[][] g = new int[n][n]; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + g[i][j] = mat[j][n - i - 1]; + } + } + if (equals(g, target)) { + return true; + } + mat = g; + } + return false; + } + + private boolean equals(int[][] a, int[][] b) { + int n = a.length; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (a[i][j] != b[i][j]) { + return false; + } + } + } + return true; + } +} \ No newline at end of file diff --git a/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/Solution2.py b/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/Solution2.py new file mode 100644 index 0000000000000..b9279906c51cc --- /dev/null +++ b/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool: + for _ in range(4): + mat = [list(col) for col in zip(*mat[::-1])] + if mat == target: + return True + return False diff --git a/solution/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/Solution2.cpp b/solution/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/Solution2.cpp new file mode 100644 index 0000000000000..ee9781512c8e6 --- /dev/null +++ b/solution/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/Solution2.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int reductionOperations(vector& nums) { + map m; + for (int v : nums) ++m[v]; + int ans = 0, cnt = 0; + for (auto [_, v] : m) { + ans += cnt * v; + ++cnt; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/Solution2.java b/solution/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/Solution2.java new file mode 100644 index 0000000000000..499de94037710 --- /dev/null +++ b/solution/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public int reductionOperations(int[] nums) { + Map tm = new TreeMap<>(); + for (int v : nums) { + tm.put(v, tm.getOrDefault(v, 0) + 1); + } + int ans = 0, cnt = 0; + for (int v : tm.values()) { + ans += cnt * v; + ++cnt; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/Solution2.py b/solution/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/Solution2.py new file mode 100644 index 0000000000000..a2cdc091e5bc3 --- /dev/null +++ b/solution/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def reductionOperations(self, nums: List[int]) -> int: + ans = cnt = 0 + for _, v in sorted(Counter(nums).items()): + ans += cnt * v + cnt += 1 + return ans diff --git a/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/Solution.cpp b/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/Solution.cpp index 77e169e0273aa..3059a8395ed24 100644 --- a/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/Solution.cpp +++ b/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/Solution.cpp @@ -1,24 +1,24 @@ -class Solution { -public: - int minFlips(string s) { - int n = s.size(); - string target = "01"; - int cnt = 0; - for (int i = 0; i < n; ++i) { - if (s[i] != target[i & 1]) { - ++cnt; - } - } - int ans = min(cnt, n - cnt); - for (int i = 0; i < n; ++i) { - if (s[i] != target[i & 1]) { - --cnt; - } - if (s[i] != target[(i + n) & 1]) { - ++cnt; - } - ans = min({ans, cnt, n - cnt}); - } - return ans; - } +class Solution { +public: + int minFlips(string s) { + int n = s.size(); + string target = "01"; + int cnt = 0; + for (int i = 0; i < n; ++i) { + if (s[i] != target[i & 1]) { + ++cnt; + } + } + int ans = min(cnt, n - cnt); + for (int i = 0; i < n; ++i) { + if (s[i] != target[i & 1]) { + --cnt; + } + if (s[i] != target[(i + n) & 1]) { + ++cnt; + } + ans = min({ans, cnt, n - cnt}); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/Solution.java b/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/Solution.java index 8c46f36d359ae..ac10d1d293189 100644 --- a/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/Solution.java +++ b/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/Solution.java @@ -1,23 +1,23 @@ -class Solution { - public int minFlips(String s) { - int n = s.length(); - String target = "01"; - int cnt = 0; - for (int i = 0; i < n; ++i) { - if (s.charAt(i) != target.charAt(i & 1)) { - ++cnt; - } - } - int ans = Math.min(cnt, n - cnt); - for (int i = 0; i < n; ++i) { - if (s.charAt(i) != target.charAt(i & 1)) { - --cnt; - } - if (s.charAt(i) != target.charAt((i + n) & 1)) { - ++cnt; - } - ans = Math.min(ans, Math.min(cnt, n - cnt)); - } - return ans; - } +class Solution { + public int minFlips(String s) { + int n = s.length(); + String target = "01"; + int cnt = 0; + for (int i = 0; i < n; ++i) { + if (s.charAt(i) != target.charAt(i & 1)) { + ++cnt; + } + } + int ans = Math.min(cnt, n - cnt); + for (int i = 0; i < n; ++i) { + if (s.charAt(i) != target.charAt(i & 1)) { + --cnt; + } + if (s.charAt(i) != target.charAt((i + n) & 1)) { + ++cnt; + } + ans = Math.min(ans, Math.min(cnt, n - cnt)); + } + return ans; + } } \ No newline at end of file diff --git a/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/Solution.py b/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/Solution.py index 7f7b3898cd986..4c10eb6895745 100644 --- a/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/Solution.py +++ b/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def minFlips(self, s: str) -> int: - n = len(s) - target = "01" - cnt = sum(c != target[i & 1] for i, c in enumerate(s)) - ans = min(cnt, n - cnt) - for i in range(n): - cnt -= s[i] != target[i & 1] - cnt += s[i] != target[(i + n) & 1] - ans = min(ans, cnt, n - cnt) - return ans +class Solution: + def minFlips(self, s: str) -> int: + n = len(s) + target = "01" + cnt = sum(c != target[i & 1] for i, c in enumerate(s)) + ans = min(cnt, n - cnt) + for i in range(n): + cnt -= s[i] != target[i & 1] + cnt += s[i] != target[(i + n) & 1] + ans = min(ans, cnt, n - cnt) + return ans diff --git a/solution/1800-1899/1889.Minimum Space Wasted From Packaging/Solution.cpp b/solution/1800-1899/1889.Minimum Space Wasted From Packaging/Solution.cpp index 358934748a1cb..f3fbfebb4165a 100644 --- a/solution/1800-1899/1889.Minimum Space Wasted From Packaging/Solution.cpp +++ b/solution/1800-1899/1889.Minimum Space Wasted From Packaging/Solution.cpp @@ -1,25 +1,25 @@ -class Solution { -public: - int minWastedSpace(vector& packages, vector>& boxes) { - int n = packages.size(), m = boxes.size(); - sort(packages.begin(), packages.end()); - const int mod = 1e9 + 7; - const long long inf = 1LL << 62; - long long ans = inf; - for (auto& box : boxes) { - sort(box.begin(), box.end()); - if (packages.back() > box.back()) { - continue; - } - int i = 0; - long long s = 0; - for (auto& b : box) { - int j = upper_bound(packages.begin() + i, packages.end(), b) - packages.begin(); - s += 1LL * (j - i) * b; - i = j; - } - ans = min(ans, s); - } - return ans == inf ? -1 : (ans - accumulate(packages.begin(), packages.end(), 0LL)) % mod; - } +class Solution { +public: + int minWastedSpace(vector& packages, vector>& boxes) { + int n = packages.size(), m = boxes.size(); + sort(packages.begin(), packages.end()); + const int mod = 1e9 + 7; + const long long inf = 1LL << 62; + long long ans = inf; + for (auto& box : boxes) { + sort(box.begin(), box.end()); + if (packages.back() > box.back()) { + continue; + } + int i = 0; + long long s = 0; + for (auto& b : box) { + int j = upper_bound(packages.begin() + i, packages.end(), b) - packages.begin(); + s += 1LL * (j - i) * b; + i = j; + } + ans = min(ans, s); + } + return ans == inf ? -1 : (ans - accumulate(packages.begin(), packages.end(), 0LL)) % mod; + } }; \ No newline at end of file diff --git a/solution/1800-1899/1889.Minimum Space Wasted From Packaging/Solution.java b/solution/1800-1899/1889.Minimum Space Wasted From Packaging/Solution.java index 541cacc7db378..c70d4b389353f 100644 --- a/solution/1800-1899/1889.Minimum Space Wasted From Packaging/Solution.java +++ b/solution/1800-1899/1889.Minimum Space Wasted From Packaging/Solution.java @@ -1,44 +1,44 @@ -class Solution { - public int minWastedSpace(int[] packages, int[][] boxes) { - int n = packages.length; - final long inf = 1L << 62; - Arrays.sort(packages); - long ans = inf; - for (var box : boxes) { - Arrays.sort(box); - if (packages[n - 1] > box[box.length - 1]) { - continue; - } - long s = 0; - int i = 0; - for (int b : box) { - int j = search(packages, b, i); - s += 1L * (j - i) * b; - i = j; - } - ans = Math.min(ans, s); - } - if (ans == inf) { - return -1; - } - long s = 0; - for (int p : packages) { - s += p; - } - final int mod = (int) 1e9 + 7; - return (int) ((ans - s) % mod); - } - - private int search(int[] nums, int x, int l) { - int r = nums.length; - while (l < r) { - int mid = (l + r) >> 1; - if (nums[mid] > x) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } +class Solution { + public int minWastedSpace(int[] packages, int[][] boxes) { + int n = packages.length; + final long inf = 1L << 62; + Arrays.sort(packages); + long ans = inf; + for (var box : boxes) { + Arrays.sort(box); + if (packages[n - 1] > box[box.length - 1]) { + continue; + } + long s = 0; + int i = 0; + for (int b : box) { + int j = search(packages, b, i); + s += 1L * (j - i) * b; + i = j; + } + ans = Math.min(ans, s); + } + if (ans == inf) { + return -1; + } + long s = 0; + for (int p : packages) { + s += p; + } + final int mod = (int) 1e9 + 7; + return (int) ((ans - s) % mod); + } + + private int search(int[] nums, int x, int l) { + int r = nums.length; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid] > x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } } \ No newline at end of file diff --git a/solution/1800-1899/1889.Minimum Space Wasted From Packaging/Solution.py b/solution/1800-1899/1889.Minimum Space Wasted From Packaging/Solution.py index 972d4059a3ad9..c2767d8b50e68 100644 --- a/solution/1800-1899/1889.Minimum Space Wasted From Packaging/Solution.py +++ b/solution/1800-1899/1889.Minimum Space Wasted From Packaging/Solution.py @@ -1,18 +1,18 @@ -class Solution: - def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int: - mod = 10**9 + 7 - ans = inf - packages.sort() - for box in boxes: - box.sort() - if packages[-1] > box[-1]: - continue - s = i = 0 - for b in box: - j = bisect_right(packages, b, lo=i) - s += (j - i) * b - i = j - ans = min(ans, s) - if ans == inf: - return -1 - return (ans - sum(packages)) % mod +class Solution: + def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int: + mod = 10**9 + 7 + ans = inf + packages.sort() + for box in boxes: + box.sort() + if packages[-1] > box[-1]: + continue + s = i = 0 + for b in box: + j = bisect_right(packages, b, lo=i) + s += (j - i) * b + i = j + ans = min(ans, s) + if ans == inf: + return -1 + return (ans - sum(packages)) % mod diff --git a/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/Solution.cpp b/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/Solution.cpp index 3448711b14fb8..8cab806f57cbe 100644 --- a/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/Solution.cpp +++ b/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/Solution.cpp @@ -1,13 +1,13 @@ -class Solution { -public: - int chalkReplacer(vector& chalk, int k) { - long long s = accumulate(chalk.begin(), chalk.end(), 0LL); - k %= s; - for (int i = 0;; ++i) { - if (k < chalk[i]) { - return i; - } - k -= chalk[i]; - } - } +class Solution { +public: + int chalkReplacer(vector& chalk, int k) { + long long s = accumulate(chalk.begin(), chalk.end(), 0LL); + k %= s; + for (int i = 0;; ++i) { + if (k < chalk[i]) { + return i; + } + k -= chalk[i]; + } + } }; \ No newline at end of file diff --git a/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/Solution.java b/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/Solution.java index 6fec2a84f3602..b836d9ea82596 100644 --- a/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/Solution.java +++ b/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public int chalkReplacer(int[] chalk, int k) { - long s = 0; - for (int x : chalk) { - s += x; - } - k %= s; - for (int i = 0;; ++i) { - if (k < chalk[i]) { - return i; - } - k -= chalk[i]; - } - } +class Solution { + public int chalkReplacer(int[] chalk, int k) { + long s = 0; + for (int x : chalk) { + s += x; + } + k %= s; + for (int i = 0;; ++i) { + if (k < chalk[i]) { + return i; + } + k -= chalk[i]; + } + } } \ No newline at end of file diff --git a/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/Solution.py b/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/Solution.py index e68cc368b5845..8fefccdbf600a 100644 --- a/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/Solution.py +++ b/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/Solution.py @@ -1,8 +1,8 @@ -class Solution: - def chalkReplacer(self, chalk: List[int], k: int) -> int: - s = sum(chalk) - k %= s - for i, x in enumerate(chalk): - if k < x: - return i - k -= x +class Solution: + def chalkReplacer(self, chalk: List[int], k: int) -> int: + s = sum(chalk) + k %= s + for i, x in enumerate(chalk): + if k < x: + return i + k -= x diff --git a/solution/1900-1999/1901.Find a Peak Element II/Solution.cpp b/solution/1900-1999/1901.Find a Peak Element II/Solution.cpp index 4d6ba81b29814..cbfc8c818d4d2 100644 --- a/solution/1900-1999/1901.Find a Peak Element II/Solution.cpp +++ b/solution/1900-1999/1901.Find a Peak Element II/Solution.cpp @@ -1,17 +1,17 @@ -class Solution { -public: - vector findPeakGrid(vector>& mat) { - int l = 0, r = mat.size() - 1; - while (l < r) { - int mid = (l + r) >> 1; - int j = distance(mat[mid].begin(), max_element(mat[mid].begin(), mat[mid].end())); - if (mat[mid][j] > mat[mid + 1][j]) { - r = mid; - } else { - l = mid + 1; - } - } - int j = distance(mat[l].begin(), max_element(mat[l].begin(), mat[l].end())); - return {l, j}; - } +class Solution { +public: + vector findPeakGrid(vector>& mat) { + int l = 0, r = mat.size() - 1; + while (l < r) { + int mid = (l + r) >> 1; + int j = distance(mat[mid].begin(), max_element(mat[mid].begin(), mat[mid].end())); + if (mat[mid][j] > mat[mid + 1][j]) { + r = mid; + } else { + l = mid + 1; + } + } + int j = distance(mat[l].begin(), max_element(mat[l].begin(), mat[l].end())); + return {l, j}; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1901.Find a Peak Element II/Solution.java b/solution/1900-1999/1901.Find a Peak Element II/Solution.java index 17b72a4b27882..f01f621124798 100644 --- a/solution/1900-1999/1901.Find a Peak Element II/Solution.java +++ b/solution/1900-1999/1901.Find a Peak Element II/Solution.java @@ -1,26 +1,26 @@ -class Solution { - public int[] findPeakGrid(int[][] mat) { - int l = 0, r = mat.length - 1; - int n = mat[0].length; - while (l < r) { - int mid = (l + r) >> 1; - int j = maxPos(mat[mid]); - if (mat[mid][j] > mat[mid + 1][j]) { - r = mid; - } else { - l = mid + 1; - } - } - return new int[] {l, maxPos(mat[l])}; - } - - private int maxPos(int[] arr) { - int j = 0; - for (int i = 1; i < arr.length; ++i) { - if (arr[j] < arr[i]) { - j = i; - } - } - return j; - } +class Solution { + public int[] findPeakGrid(int[][] mat) { + int l = 0, r = mat.length - 1; + int n = mat[0].length; + while (l < r) { + int mid = (l + r) >> 1; + int j = maxPos(mat[mid]); + if (mat[mid][j] > mat[mid + 1][j]) { + r = mid; + } else { + l = mid + 1; + } + } + return new int[] {l, maxPos(mat[l])}; + } + + private int maxPos(int[] arr) { + int j = 0; + for (int i = 1; i < arr.length; ++i) { + if (arr[j] < arr[i]) { + j = i; + } + } + return j; + } } \ No newline at end of file diff --git a/solution/1900-1999/1901.Find a Peak Element II/Solution.py b/solution/1900-1999/1901.Find a Peak Element II/Solution.py index cd85b3a0e093a..b76fb9ed55af7 100644 --- a/solution/1900-1999/1901.Find a Peak Element II/Solution.py +++ b/solution/1900-1999/1901.Find a Peak Element II/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def findPeakGrid(self, mat: List[List[int]]) -> List[int]: - l, r = 0, len(mat) - 1 - while l < r: - mid = (l + r) >> 1 - j = mat[mid].index(max(mat[mid])) - if mat[mid][j] > mat[mid + 1][j]: - r = mid - else: - l = mid + 1 - return [l, mat[l].index(max(mat[l]))] +class Solution: + def findPeakGrid(self, mat: List[List[int]]) -> List[int]: + l, r = 0, len(mat) - 1 + while l < r: + mid = (l + r) >> 1 + j = mat[mid].index(max(mat[mid])) + if mat[mid][j] > mat[mid + 1][j]: + r = mid + else: + l = mid + 1 + return [l, mat[l].index(max(mat[l]))] diff --git a/solution/1900-1999/1904.The Number of Full Rounds You Have Played/Solution.cpp b/solution/1900-1999/1904.The Number of Full Rounds You Have Played/Solution.cpp index cd138fa92911b..f621e013a4dfc 100644 --- a/solution/1900-1999/1904.The Number of Full Rounds You Have Played/Solution.cpp +++ b/solution/1900-1999/1904.The Number of Full Rounds You Have Played/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - int numberOfRounds(string loginTime, string logoutTime) { - auto f = [](string& s) { - int h, m; - sscanf(s.c_str(), "%d:%d", &h, &m); - return h * 60 + m; - }; - int a = f(loginTime), b = f(logoutTime); - if (a > b) { - b += 1440; - } - return max(0, b / 15 - (a + 14) / 15); - } +class Solution { +public: + int numberOfRounds(string loginTime, string logoutTime) { + auto f = [](string& s) { + int h, m; + sscanf(s.c_str(), "%d:%d", &h, &m); + return h * 60 + m; + }; + int a = f(loginTime), b = f(logoutTime); + if (a > b) { + b += 1440; + } + return max(0, b / 15 - (a + 14) / 15); + } }; \ No newline at end of file diff --git a/solution/1900-1999/1904.The Number of Full Rounds You Have Played/Solution.java b/solution/1900-1999/1904.The Number of Full Rounds You Have Played/Solution.java index 7fa77e82cb30a..1434fe5c6b569 100644 --- a/solution/1900-1999/1904.The Number of Full Rounds You Have Played/Solution.java +++ b/solution/1900-1999/1904.The Number of Full Rounds You Have Played/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public int numberOfRounds(String loginTime, String logoutTime) { - int a = f(loginTime), b = f(logoutTime); - if (a > b) { - b += 1440; - } - return Math.max(0, b / 15 - (a + 14) / 15); - } - - private int f(String s) { - int h = Integer.parseInt(s.substring(0, 2)); - int m = Integer.parseInt(s.substring(3, 5)); - return h * 60 + m; - } +class Solution { + public int numberOfRounds(String loginTime, String logoutTime) { + int a = f(loginTime), b = f(logoutTime); + if (a > b) { + b += 1440; + } + return Math.max(0, b / 15 - (a + 14) / 15); + } + + private int f(String s) { + int h = Integer.parseInt(s.substring(0, 2)); + int m = Integer.parseInt(s.substring(3, 5)); + return h * 60 + m; + } } \ No newline at end of file diff --git a/solution/1900-1999/1904.The Number of Full Rounds You Have Played/Solution.py b/solution/1900-1999/1904.The Number of Full Rounds You Have Played/Solution.py index c95b4b987d3c5..80afee09f8909 100644 --- a/solution/1900-1999/1904.The Number of Full Rounds You Have Played/Solution.py +++ b/solution/1900-1999/1904.The Number of Full Rounds You Have Played/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def numberOfRounds(self, loginTime: str, logoutTime: str) -> int: - def f(s: str) -> int: - return int(s[:2]) * 60 + int(s[3:]) - - a, b = f(loginTime), f(logoutTime) - if a > b: - b += 1440 - a, b = (a + 14) // 15, b // 15 - return max(0, b - a) +class Solution: + def numberOfRounds(self, loginTime: str, logoutTime: str) -> int: + def f(s: str) -> int: + return int(s[:2]) * 60 + int(s[3:]) + + a, b = f(loginTime), f(logoutTime) + if a > b: + b += 1440 + a, b = (a + 14) // 15, b // 15 + return max(0, b - a) diff --git a/solution/1900-1999/1905.Count Sub Islands/Solution.cpp b/solution/1900-1999/1905.Count Sub Islands/Solution.cpp index b32c5a6278f8e..24228c3a5b088 100644 --- a/solution/1900-1999/1905.Count Sub Islands/Solution.cpp +++ b/solution/1900-1999/1905.Count Sub Islands/Solution.cpp @@ -1,27 +1,27 @@ -class Solution { -public: - int countSubIslands(vector>& grid1, vector>& grid2) { - int m = grid1.size(), n = grid1[0].size(); - int ans = 0; - int dirs[5] = {-1, 0, 1, 0, -1}; - function dfs = [&](int i, int j) { - int ok = grid1[i][j]; - grid2[i][j] = 0; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y]) { - ok &= dfs(x, y); - } - } - return ok; - }; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid2[i][j]) { - ans += dfs(i, j); - } - } - } - return ans; - } +class Solution { +public: + int countSubIslands(vector>& grid1, vector>& grid2) { + int m = grid1.size(), n = grid1[0].size(); + int ans = 0; + int dirs[5] = {-1, 0, 1, 0, -1}; + function dfs = [&](int i, int j) { + int ok = grid1[i][j]; + grid2[i][j] = 0; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y]) { + ok &= dfs(x, y); + } + } + return ok; + }; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid2[i][j]) { + ans += dfs(i, j); + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1905.Count Sub Islands/Solution.java b/solution/1900-1999/1905.Count Sub Islands/Solution.java index 350826143a009..fe64b0008da9a 100644 --- a/solution/1900-1999/1905.Count Sub Islands/Solution.java +++ b/solution/1900-1999/1905.Count Sub Islands/Solution.java @@ -1,35 +1,35 @@ -class Solution { - private final int[] dirs = {-1, 0, 1, 0, -1}; - private int[][] grid1; - private int[][] grid2; - private int m; - private int n; - - public int countSubIslands(int[][] grid1, int[][] grid2) { - m = grid1.length; - n = grid1[0].length; - this.grid1 = grid1; - this.grid2 = grid2; - int ans = 0; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid2[i][j] == 1) { - ans += dfs(i, j); - } - } - } - return ans; - } - - private int dfs(int i, int j) { - int ok = grid1[i][j]; - grid2[i][j] = 0; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y] == 1) { - ok &= dfs(x, y); - } - } - return ok; - } +class Solution { + private final int[] dirs = {-1, 0, 1, 0, -1}; + private int[][] grid1; + private int[][] grid2; + private int m; + private int n; + + public int countSubIslands(int[][] grid1, int[][] grid2) { + m = grid1.length; + n = grid1[0].length; + this.grid1 = grid1; + this.grid2 = grid2; + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid2[i][j] == 1) { + ans += dfs(i, j); + } + } + } + return ans; + } + + private int dfs(int i, int j) { + int ok = grid1[i][j]; + grid2[i][j] = 0; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y] == 1) { + ok &= dfs(x, y); + } + } + return ok; + } } \ No newline at end of file diff --git a/solution/1900-1999/1905.Count Sub Islands/Solution.py b/solution/1900-1999/1905.Count Sub Islands/Solution.py index cbc621f66b9c6..8e0e9ea71811e 100644 --- a/solution/1900-1999/1905.Count Sub Islands/Solution.py +++ b/solution/1900-1999/1905.Count Sub Islands/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: - def dfs(i: int, j: int) -> int: - ok = grid1[i][j] - grid2[i][j] = 0 - for a, b in pairwise(dirs): - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n and grid2[x][y] and not dfs(x, y): - ok = 0 - return ok - - m, n = len(grid1), len(grid1[0]) - dirs = (-1, 0, 1, 0, -1) - return sum(dfs(i, j) for i in range(m) for j in range(n) if grid2[i][j]) +class Solution: + def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: + def dfs(i: int, j: int) -> int: + ok = grid1[i][j] + grid2[i][j] = 0 + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n and grid2[x][y] and not dfs(x, y): + ok = 0 + return ok + + m, n = len(grid1), len(grid1[0]) + dirs = (-1, 0, 1, 0, -1) + return sum(dfs(i, j) for i in range(m) for j in range(n) if grid2[i][j]) diff --git a/solution/1900-1999/1905.Count Sub Islands/Solution2.py b/solution/1900-1999/1905.Count Sub Islands/Solution2.py new file mode 100644 index 0000000000000..4123ca8d42e83 --- /dev/null +++ b/solution/1900-1999/1905.Count Sub Islands/Solution2.py @@ -0,0 +1,19 @@ +class Solution: + def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: + def bfs(i: int, j: int) -> int: + ok = grid1[i][j] + q = deque([(i, j)]) + grid2[i][j] = 0 + while q: + i, j = q.popleft() + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n and grid2[x][y]: + q.append((x, y)) + ok = ok & grid1[x][y] + grid2[x][y] = 0 + return ok + + m, n = len(grid1), len(grid1[0]) + dirs = (-1, 0, 1, 0, -1) + return sum(bfs(i, j) for i in range(m) for j in range(n) if grid2[i][j]) diff --git a/solution/1900-1999/1907.Count Salary Categories/Solution2.sql b/solution/1900-1999/1907.Count Salary Categories/Solution2.sql new file mode 100644 index 0000000000000..a45fa311fd848 --- /dev/null +++ b/solution/1900-1999/1907.Count Salary Categories/Solution2.sql @@ -0,0 +1,9 @@ +# Write your MySQL query statement below +SELECT 'Low Salary' AS category, IFNULL(SUM(income < 20000), 0) AS accounts_count FROM Accounts +UNION +SELECT + 'Average Salary' AS category, + IFNULL(SUM(income BETWEEN 20000 AND 50000), 0) AS accounts_count +FROM Accounts +UNION +SELECT 'High Salary' AS category, IFNULL(SUM(income > 50000), 0) AS accounts_count FROM Accounts; diff --git a/solution/1900-1999/1908.Game of Nim/Solution.cpp b/solution/1900-1999/1908.Game of Nim/Solution.cpp index 73515a5390af2..15a58348179bf 100644 --- a/solution/1900-1999/1908.Game of Nim/Solution.cpp +++ b/solution/1900-1999/1908.Game of Nim/Solution.cpp @@ -1,35 +1,35 @@ -class Solution { -public: - bool nimGame(vector& piles) { - unordered_map memo; - int p[8] = {1}; - for (int i = 1; i < 8; ++i) { - p[i] = p[i - 1] * 8; - } - auto f = [&](vector& piles) { - int st = 0; - for (int i = 0; i < piles.size(); ++i) { - st += piles[i] * p[i]; - } - return st; - }; - function&)> dfs = [&](vector& piles) { - int st = f(piles); - if (memo.count(st)) { - return memo[st]; - } - for (int i = 0; i < piles.size(); ++i) { - for (int j = 1; j <= piles[i]; ++j) { - piles[i] -= j; - if (!dfs(piles)) { - piles[i] += j; - return memo[st] = true; - } - piles[i] += j; - } - } - return memo[st] = false; - }; - return dfs(piles); - } +class Solution { +public: + bool nimGame(vector& piles) { + unordered_map memo; + int p[8] = {1}; + for (int i = 1; i < 8; ++i) { + p[i] = p[i - 1] * 8; + } + auto f = [&](vector& piles) { + int st = 0; + for (int i = 0; i < piles.size(); ++i) { + st += piles[i] * p[i]; + } + return st; + }; + function&)> dfs = [&](vector& piles) { + int st = f(piles); + if (memo.count(st)) { + return memo[st]; + } + for (int i = 0; i < piles.size(); ++i) { + for (int j = 1; j <= piles[i]; ++j) { + piles[i] -= j; + if (!dfs(piles)) { + piles[i] += j; + return memo[st] = true; + } + piles[i] += j; + } + } + return memo[st] = false; + }; + return dfs(piles); + } }; \ No newline at end of file diff --git a/solution/1900-1999/1908.Game of Nim/Solution.java b/solution/1900-1999/1908.Game of Nim/Solution.java index 995a03c6f6ad4..3ba56f8d0a50f 100644 --- a/solution/1900-1999/1908.Game of Nim/Solution.java +++ b/solution/1900-1999/1908.Game of Nim/Solution.java @@ -1,43 +1,43 @@ -class Solution { - private Map memo = new HashMap<>(); - private int[] p = new int[8]; - - public Solution() { - p[0] = 1; - for (int i = 1; i < 8; ++i) { - p[i] = p[i - 1] * 8; - } - } - - public boolean nimGame(int[] piles) { - return dfs(piles); - } - - private boolean dfs(int[] piles) { - int st = f(piles); - if (memo.containsKey(st)) { - return memo.get(st); - } - for (int i = 0; i < piles.length; ++i) { - for (int j = 1; j <= piles[i]; ++j) { - piles[i] -= j; - if (!dfs(piles)) { - piles[i] += j; - memo.put(st, true); - return true; - } - piles[i] += j; - } - } - memo.put(st, false); - return false; - } - - private int f(int[] piles) { - int st = 0; - for (int i = 0; i < piles.length; ++i) { - st += piles[i] * p[i]; - } - return st; - } +class Solution { + private Map memo = new HashMap<>(); + private int[] p = new int[8]; + + public Solution() { + p[0] = 1; + for (int i = 1; i < 8; ++i) { + p[i] = p[i - 1] * 8; + } + } + + public boolean nimGame(int[] piles) { + return dfs(piles); + } + + private boolean dfs(int[] piles) { + int st = f(piles); + if (memo.containsKey(st)) { + return memo.get(st); + } + for (int i = 0; i < piles.length; ++i) { + for (int j = 1; j <= piles[i]; ++j) { + piles[i] -= j; + if (!dfs(piles)) { + piles[i] += j; + memo.put(st, true); + return true; + } + piles[i] += j; + } + } + memo.put(st, false); + return false; + } + + private int f(int[] piles) { + int st = 0; + for (int i = 0; i < piles.length; ++i) { + st += piles[i] * p[i]; + } + return st; + } } \ No newline at end of file diff --git a/solution/1900-1999/1908.Game of Nim/Solution.py b/solution/1900-1999/1908.Game of Nim/Solution.py index 5d5b3caebb3e2..abea3fe647036 100644 --- a/solution/1900-1999/1908.Game of Nim/Solution.py +++ b/solution/1900-1999/1908.Game of Nim/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def nimGame(self, piles: List[int]) -> bool: - @cache - def dfs(st): - lst = list(st) - for i, x in enumerate(lst): - for j in range(1, x + 1): - lst[i] -= j - if not dfs(tuple(lst)): - return True - lst[i] += j - return False - - return dfs(tuple(piles)) +class Solution: + def nimGame(self, piles: List[int]) -> bool: + @cache + def dfs(st): + lst = list(st) + for i, x in enumerate(lst): + for j in range(1, x + 1): + lst[i] -= j + if not dfs(tuple(lst)): + return True + lst[i] += j + return False + + return dfs(tuple(piles)) diff --git a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.cpp b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.cpp index 3206b6b4c96f2..90c3b161f941b 100644 --- a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.cpp +++ b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.cpp @@ -1,11 +1,12 @@ class Solution { public: long long maxAlternatingSum(vector& nums) { - long long f = 0, g = 0; - for (int& x : nums) { - long ff = max(g - x, f), gg = max(f + x, g); - f = ff, g = gg; + int n = nums.size(); + vector f(n + 1), g(n + 1); + for (int i = 1; i <= n; ++i) { + f[i] = max(g[i - 1] - nums[i - 1], f[i - 1]); + g[i] = max(f[i - 1] + nums[i - 1], g[i - 1]); } - return max(f, g); + return max(f[n], g[n]); } }; \ No newline at end of file diff --git a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.go b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.go index 1489dcc250cb0..5c33451cf2ee8 100644 --- a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.go +++ b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.go @@ -1,7 +1,11 @@ func maxAlternatingSum(nums []int) int64 { - var f, g int - for _, x := range nums { - f, g = max(g-x, f), max(f+x, g) + n := len(nums) + f := make([]int, n+1) + g := make([]int, n+1) + for i, x := range nums { + i++ + f[i] = max(g[i-1]-x, f[i-1]) + g[i] = max(f[i-1]+x, g[i-1]) } - return int64(max(f, g)) + return int64(max(f[n], g[n])) } \ No newline at end of file diff --git a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.java b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.java index cb9fdc3051330..a4ef060e2fd13 100644 --- a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.java +++ b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.java @@ -1,12 +1,12 @@ class Solution { public long maxAlternatingSum(int[] nums) { - long f = 0, g = 0; - for (int x : nums) { - long ff = Math.max(g - x, f); - long gg = Math.max(f + x, g); - f = ff; - g = gg; + int n = nums.length; + long[] f = new long[n + 1]; + long[] g = new long[n + 1]; + for (int i = 1; i <= n; ++i) { + f[i] = Math.max(g[i - 1] - nums[i - 1], f[i - 1]); + g[i] = Math.max(f[i - 1] + nums[i - 1], g[i - 1]); } - return Math.max(f, g); + return Math.max(f[n], g[n]); } } \ No newline at end of file diff --git a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.py b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.py index 624ce15f1cdc8..0613f4f54ab0b 100644 --- a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.py +++ b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.py @@ -1,6 +1,9 @@ class Solution: def maxAlternatingSum(self, nums: List[int]) -> int: - f = g = 0 - for x in nums: - f, g = max(g - x, f), max(f + x, g) - return max(f, g) + n = len(nums) + f = [0] * (n + 1) + g = [0] * (n + 1) + for i, x in enumerate(nums, 1): + f[i] = max(g[i - 1] - x, f[i - 1]) + g[i] = max(f[i - 1] + x, g[i - 1]) + return max(f[n], g[n]) diff --git a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.ts b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.ts index 7dbb1c90a1ce6..40bf8b303ef6e 100644 --- a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.ts +++ b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution.ts @@ -1,7 +1,10 @@ function maxAlternatingSum(nums: number[]): number { - let [f, g] = [0, 0]; - for (const x of nums) { - [f, g] = [Math.max(g - x, f), Math.max(f + x, g)]; + const n = nums.length; + const f: number[] = new Array(n + 1).fill(0); + const g = f.slice(); + for (let i = 1; i <= n; ++i) { + f[i] = Math.max(g[i - 1] + nums[i - 1], f[i - 1]); + g[i] = Math.max(f[i - 1] - nums[i - 1], g[i - 1]); } - return g; + return Math.max(f[n], g[n]); } diff --git a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution2.cpp b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution2.cpp new file mode 100644 index 0000000000000..3206b6b4c96f2 --- /dev/null +++ b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution2.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + long long maxAlternatingSum(vector& nums) { + long long f = 0, g = 0; + for (int& x : nums) { + long ff = max(g - x, f), gg = max(f + x, g); + f = ff, g = gg; + } + return max(f, g); + } +}; \ No newline at end of file diff --git a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution2.go b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution2.go new file mode 100644 index 0000000000000..1489dcc250cb0 --- /dev/null +++ b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution2.go @@ -0,0 +1,7 @@ +func maxAlternatingSum(nums []int) int64 { + var f, g int + for _, x := range nums { + f, g = max(g-x, f), max(f+x, g) + } + return int64(max(f, g)) +} \ No newline at end of file diff --git a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution2.java b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution2.java new file mode 100644 index 0000000000000..cb9fdc3051330 --- /dev/null +++ b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution2.java @@ -0,0 +1,12 @@ +class Solution { + public long maxAlternatingSum(int[] nums) { + long f = 0, g = 0; + for (int x : nums) { + long ff = Math.max(g - x, f); + long gg = Math.max(f + x, g); + f = ff; + g = gg; + } + return Math.max(f, g); + } +} \ No newline at end of file diff --git a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution2.py b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution2.py new file mode 100644 index 0000000000000..624ce15f1cdc8 --- /dev/null +++ b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution2.py @@ -0,0 +1,6 @@ +class Solution: + def maxAlternatingSum(self, nums: List[int]) -> int: + f = g = 0 + for x in nums: + f, g = max(g - x, f), max(f + x, g) + return max(f, g) diff --git a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution2.ts b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution2.ts new file mode 100644 index 0000000000000..7dbb1c90a1ce6 --- /dev/null +++ b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/Solution2.ts @@ -0,0 +1,7 @@ +function maxAlternatingSum(nums: number[]): number { + let [f, g] = [0, 0]; + for (const x of nums) { + [f, g] = [Math.max(g - x, f), Math.max(f + x, g)]; + } + return g; +} diff --git a/solution/1900-1999/1914.Cyclically Rotating a Grid/Solution.cpp b/solution/1900-1999/1914.Cyclically Rotating a Grid/Solution.cpp index 11056e2a49380..2d7eafa0f4e9d 100644 --- a/solution/1900-1999/1914.Cyclically Rotating a Grid/Solution.cpp +++ b/solution/1900-1999/1914.Cyclically Rotating a Grid/Solution.cpp @@ -1,42 +1,42 @@ -class Solution { -public: - vector> rotateGrid(vector>& grid, int k) { - int m = grid.size(), n = grid[0].size(); - auto rotate = [&](int p, int k) { - vector nums; - for (int j = p; j < n - p - 1; ++j) { - nums.push_back(grid[p][j]); - } - for (int i = p; i < m - p - 1; ++i) { - nums.push_back(grid[i][n - p - 1]); - } - for (int j = n - p - 1; j > p; --j) { - nums.push_back(grid[m - p - 1][j]); - } - for (int i = m - p - 1; i > p; --i) { - nums.push_back(grid[i][p]); - } - int l = nums.size(); - k %= l; - if (k == 0) { - return; - } - for (int j = p; j < n - p - 1; ++j) { - grid[p][j] = nums[k++ % l]; - } - for (int i = p; i < m - p - 1; ++i) { - grid[i][n - p - 1] = nums[k++ % l]; - } - for (int j = n - p - 1; j > p; --j) { - grid[m - p - 1][j] = nums[k++ % l]; - } - for (int i = m - p - 1; i > p; --i) { - grid[i][p] = nums[k++ % l]; - } - }; - for (int p = 0; p < min(m, n) / 2; ++p) { - rotate(p, k); - } - return grid; - } +class Solution { +public: + vector> rotateGrid(vector>& grid, int k) { + int m = grid.size(), n = grid[0].size(); + auto rotate = [&](int p, int k) { + vector nums; + for (int j = p; j < n - p - 1; ++j) { + nums.push_back(grid[p][j]); + } + for (int i = p; i < m - p - 1; ++i) { + nums.push_back(grid[i][n - p - 1]); + } + for (int j = n - p - 1; j > p; --j) { + nums.push_back(grid[m - p - 1][j]); + } + for (int i = m - p - 1; i > p; --i) { + nums.push_back(grid[i][p]); + } + int l = nums.size(); + k %= l; + if (k == 0) { + return; + } + for (int j = p; j < n - p - 1; ++j) { + grid[p][j] = nums[k++ % l]; + } + for (int i = p; i < m - p - 1; ++i) { + grid[i][n - p - 1] = nums[k++ % l]; + } + for (int j = n - p - 1; j > p; --j) { + grid[m - p - 1][j] = nums[k++ % l]; + } + for (int i = m - p - 1; i > p; --i) { + grid[i][p] = nums[k++ % l]; + } + }; + for (int p = 0; p < min(m, n) / 2; ++p) { + rotate(p, k); + } + return grid; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1914.Cyclically Rotating a Grid/Solution.java b/solution/1900-1999/1914.Cyclically Rotating a Grid/Solution.java index 5e23a0404c2a8..9a71e46bb1369 100644 --- a/solution/1900-1999/1914.Cyclically Rotating a Grid/Solution.java +++ b/solution/1900-1999/1914.Cyclically Rotating a Grid/Solution.java @@ -1,48 +1,48 @@ -class Solution { - private int m; - private int n; - private int[][] grid; - - public int[][] rotateGrid(int[][] grid, int k) { - m = grid.length; - n = grid[0].length; - this.grid = grid; - for (int p = 0; p < Math.min(m, n) / 2; ++p) { - rotate(p, k); - } - return grid; - } - - private void rotate(int p, int k) { - List nums = new ArrayList<>(); - for (int j = p; j < n - p - 1; ++j) { - nums.add(grid[p][j]); - } - for (int i = p; i < m - p - 1; ++i) { - nums.add(grid[i][n - p - 1]); - } - for (int j = n - p - 1; j > p; --j) { - nums.add(grid[m - p - 1][j]); - } - for (int i = m - p - 1; i > p; --i) { - nums.add(grid[i][p]); - } - int l = nums.size(); - k %= l; - if (k == 0) { - return; - } - for (int j = p; j < n - p - 1; ++j) { - grid[p][j] = nums.get(k++ % l); - } - for (int i = p; i < m - p - 1; ++i) { - grid[i][n - p - 1] = nums.get(k++ % l); - } - for (int j = n - p - 1; j > p; --j) { - grid[m - p - 1][j] = nums.get(k++ % l); - } - for (int i = m - p - 1; i > p; --i) { - grid[i][p] = nums.get(k++ % l); - } - } +class Solution { + private int m; + private int n; + private int[][] grid; + + public int[][] rotateGrid(int[][] grid, int k) { + m = grid.length; + n = grid[0].length; + this.grid = grid; + for (int p = 0; p < Math.min(m, n) / 2; ++p) { + rotate(p, k); + } + return grid; + } + + private void rotate(int p, int k) { + List nums = new ArrayList<>(); + for (int j = p; j < n - p - 1; ++j) { + nums.add(grid[p][j]); + } + for (int i = p; i < m - p - 1; ++i) { + nums.add(grid[i][n - p - 1]); + } + for (int j = n - p - 1; j > p; --j) { + nums.add(grid[m - p - 1][j]); + } + for (int i = m - p - 1; i > p; --i) { + nums.add(grid[i][p]); + } + int l = nums.size(); + k %= l; + if (k == 0) { + return; + } + for (int j = p; j < n - p - 1; ++j) { + grid[p][j] = nums.get(k++ % l); + } + for (int i = p; i < m - p - 1; ++i) { + grid[i][n - p - 1] = nums.get(k++ % l); + } + for (int j = n - p - 1; j > p; --j) { + grid[m - p - 1][j] = nums.get(k++ % l); + } + for (int i = m - p - 1; i > p; --i) { + grid[i][p] = nums.get(k++ % l); + } + } } \ No newline at end of file diff --git a/solution/1900-1999/1914.Cyclically Rotating a Grid/Solution.py b/solution/1900-1999/1914.Cyclically Rotating a Grid/Solution.py index 9531c96379ca5..2adfd5193ee0c 100644 --- a/solution/1900-1999/1914.Cyclically Rotating a Grid/Solution.py +++ b/solution/1900-1999/1914.Cyclically Rotating a Grid/Solution.py @@ -1,34 +1,34 @@ -class Solution: - def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: - def rotate(p: int, k: int): - nums = [] - for j in range(p, n - p - 1): - nums.append(grid[p][j]) - for i in range(p, m - p - 1): - nums.append(grid[i][n - p - 1]) - for j in range(n - p - 1, p, -1): - nums.append(grid[m - p - 1][j]) - for i in range(m - p - 1, p, -1): - nums.append(grid[i][p]) - k %= len(nums) - if k == 0: - return - nums = nums[k:] + nums[:k] - k = 0 - for j in range(p, n - p - 1): - grid[p][j] = nums[k] - k += 1 - for i in range(p, m - p - 1): - grid[i][n - p - 1] = nums[k] - k += 1 - for j in range(n - p - 1, p, -1): - grid[m - p - 1][j] = nums[k] - k += 1 - for i in range(m - p - 1, p, -1): - grid[i][p] = nums[k] - k += 1 - - m, n = len(grid), len(grid[0]) - for p in range(min(m, n) >> 1): - rotate(p, k) - return grid +class Solution: + def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: + def rotate(p: int, k: int): + nums = [] + for j in range(p, n - p - 1): + nums.append(grid[p][j]) + for i in range(p, m - p - 1): + nums.append(grid[i][n - p - 1]) + for j in range(n - p - 1, p, -1): + nums.append(grid[m - p - 1][j]) + for i in range(m - p - 1, p, -1): + nums.append(grid[i][p]) + k %= len(nums) + if k == 0: + return + nums = nums[k:] + nums[:k] + k = 0 + for j in range(p, n - p - 1): + grid[p][j] = nums[k] + k += 1 + for i in range(p, m - p - 1): + grid[i][n - p - 1] = nums[k] + k += 1 + for j in range(n - p - 1, p, -1): + grid[m - p - 1][j] = nums[k] + k += 1 + for i in range(m - p - 1, p, -1): + grid[i][p] = nums[k] + k += 1 + + m, n = len(grid), len(grid[0]) + for p in range(min(m, n) >> 1): + rotate(p, k) + return grid diff --git a/solution/1900-1999/1915.Number of Wonderful Substrings/Solution.cpp b/solution/1900-1999/1915.Number of Wonderful Substrings/Solution.cpp index ba7905ed720ad..04ff597e0b629 100644 --- a/solution/1900-1999/1915.Number of Wonderful Substrings/Solution.cpp +++ b/solution/1900-1999/1915.Number of Wonderful Substrings/Solution.cpp @@ -1,17 +1,17 @@ -class Solution { -public: - long long wonderfulSubstrings(string word) { - int cnt[1024] = {1}; - long long ans = 0; - int st = 0; - for (char c : word) { - st ^= 1 << (c - 'a'); - ans += cnt[st]; - for (int i = 0; i < 10; ++i) { - ans += cnt[st ^ (1 << i)]; - } - ++cnt[st]; - } - return ans; - } +class Solution { +public: + long long wonderfulSubstrings(string word) { + int cnt[1024] = {1}; + long long ans = 0; + int st = 0; + for (char c : word) { + st ^= 1 << (c - 'a'); + ans += cnt[st]; + for (int i = 0; i < 10; ++i) { + ans += cnt[st ^ (1 << i)]; + } + ++cnt[st]; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1915.Number of Wonderful Substrings/Solution.java b/solution/1900-1999/1915.Number of Wonderful Substrings/Solution.java index 914ac9169cf9c..7d4b65ea9c0a3 100644 --- a/solution/1900-1999/1915.Number of Wonderful Substrings/Solution.java +++ b/solution/1900-1999/1915.Number of Wonderful Substrings/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public long wonderfulSubstrings(String word) { - int[] cnt = new int[1 << 10]; - cnt[0] = 1; - long ans = 0; - int st = 0; - for (char c : word.toCharArray()) { - st ^= 1 << (c - 'a'); - ans += cnt[st]; - for (int i = 0; i < 10; ++i) { - ans += cnt[st ^ (1 << i)]; - } - ++cnt[st]; - } - return ans; - } +class Solution { + public long wonderfulSubstrings(String word) { + int[] cnt = new int[1 << 10]; + cnt[0] = 1; + long ans = 0; + int st = 0; + for (char c : word.toCharArray()) { + st ^= 1 << (c - 'a'); + ans += cnt[st]; + for (int i = 0; i < 10; ++i) { + ans += cnt[st ^ (1 << i)]; + } + ++cnt[st]; + } + return ans; + } } \ No newline at end of file diff --git a/solution/1900-1999/1915.Number of Wonderful Substrings/Solution.py b/solution/1900-1999/1915.Number of Wonderful Substrings/Solution.py index b50f9f1a0fb01..ac616e624ec8b 100644 --- a/solution/1900-1999/1915.Number of Wonderful Substrings/Solution.py +++ b/solution/1900-1999/1915.Number of Wonderful Substrings/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def wonderfulSubstrings(self, word: str) -> int: - cnt = Counter({0: 1}) - ans = st = 0 - for c in word: - st ^= 1 << (ord(c) - ord("a")) - ans += cnt[st] - for i in range(10): - ans += cnt[st ^ (1 << i)] - cnt[st] += 1 - return ans +class Solution: + def wonderfulSubstrings(self, word: str) -> int: + cnt = Counter({0: 1}) + ans = st = 0 + for c in word: + st ^= 1 << (ord(c) - ord("a")) + ans += cnt[st] + for i in range(10): + ans += cnt[st ^ (1 << i)] + cnt[st] += 1 + return ans diff --git a/solution/1900-1999/1920.Build Array from Permutation/Solution.c b/solution/1900-1999/1920.Build Array from Permutation/Solution.c index 08899dd07fe3a..b4494ecf4f2b3 100644 --- a/solution/1900-1999/1920.Build Array from Permutation/Solution.c +++ b/solution/1900-1999/1920.Build Array from Permutation/Solution.c @@ -8,4 +8,4 @@ int* buildArray(int* nums, int numsSize, int* returnSize) { } *returnSize = numsSize; return ans; -} +} \ No newline at end of file diff --git a/solution/1900-1999/1926.Nearest Exit from Entrance in Maze/Solution.py b/solution/1900-1999/1926.Nearest Exit from Entrance in Maze/Solution.py index e7c7e24e32e63..8e2d374d8ac1d 100644 --- a/solution/1900-1999/1926.Nearest Exit from Entrance in Maze/Solution.py +++ b/solution/1900-1999/1926.Nearest Exit from Entrance in Maze/Solution.py @@ -1,19 +1,19 @@ -class Solution: - def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: - m, n = len(maze), len(maze[0]) - i, j = entrance - q = deque([(i, j)]) - maze[i][j] = '+' - ans = 0 - while q: - ans += 1 - for _ in range(len(q)): - i, j = q.popleft() - for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n and maze[x][y] == '.': - if x == 0 or x == m - 1 or y == 0 or y == n - 1: - return ans - q.append((x, y)) - maze[x][y] = '+' - return -1 +class Solution: + def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: + m, n = len(maze), len(maze[0]) + i, j = entrance + q = deque([(i, j)]) + maze[i][j] = '+' + ans = 0 + while q: + ans += 1 + for _ in range(len(q)): + i, j = q.popleft() + for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n and maze[x][y] == '.': + if x == 0 or x == m - 1 or y == 0 or y == n - 1: + return ans + q.append((x, y)) + maze[x][y] = '+' + return -1 diff --git a/solution/1900-1999/1927.Sum Game/Solution.cpp b/solution/1900-1999/1927.Sum Game/Solution.cpp index c987b30f2dfbb..32046a40d9105 100644 --- a/solution/1900-1999/1927.Sum Game/Solution.cpp +++ b/solution/1900-1999/1927.Sum Game/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - bool sumGame(string num) { - int n = num.size(); - int cnt1 = 0, cnt2 = 0; - int s1 = 0, s2 = 0; - for (int i = 0; i < n / 2; ++i) { - if (num[i] == '?') { - cnt1++; - } else { - s1 += num[i] - '0'; - } - } - for (int i = n / 2; i < n; ++i) { - if (num[i] == '?') { - cnt2++; - } else { - s2 += num[i] - '0'; - } - } - return (cnt1 + cnt2) % 2 == 1 || (s1 - s2) != 9 * (cnt2 - cnt1) / 2; - } +class Solution { +public: + bool sumGame(string num) { + int n = num.size(); + int cnt1 = 0, cnt2 = 0; + int s1 = 0, s2 = 0; + for (int i = 0; i < n / 2; ++i) { + if (num[i] == '?') { + cnt1++; + } else { + s1 += num[i] - '0'; + } + } + for (int i = n / 2; i < n; ++i) { + if (num[i] == '?') { + cnt2++; + } else { + s2 += num[i] - '0'; + } + } + return (cnt1 + cnt2) % 2 == 1 || (s1 - s2) != 9 * (cnt2 - cnt1) / 2; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1927.Sum Game/Solution.java b/solution/1900-1999/1927.Sum Game/Solution.java index 86104bf359d74..2a66ca84ce6a1 100644 --- a/solution/1900-1999/1927.Sum Game/Solution.java +++ b/solution/1900-1999/1927.Sum Game/Solution.java @@ -1,22 +1,22 @@ -class Solution { - public boolean sumGame(String num) { - int n = num.length(); - int cnt1 = 0, cnt2 = 0; - int s1 = 0, s2 = 0; - for (int i = 0; i < n / 2; ++i) { - if (num.charAt(i) == '?') { - cnt1++; - } else { - s1 += num.charAt(i) - '0'; - } - } - for (int i = n / 2; i < n; ++i) { - if (num.charAt(i) == '?') { - cnt2++; - } else { - s2 += num.charAt(i) - '0'; - } - } - return (cnt1 + cnt2) % 2 == 1 || s1 - s2 != 9 * (cnt2 - cnt1) / 2; - } +class Solution { + public boolean sumGame(String num) { + int n = num.length(); + int cnt1 = 0, cnt2 = 0; + int s1 = 0, s2 = 0; + for (int i = 0; i < n / 2; ++i) { + if (num.charAt(i) == '?') { + cnt1++; + } else { + s1 += num.charAt(i) - '0'; + } + } + for (int i = n / 2; i < n; ++i) { + if (num.charAt(i) == '?') { + cnt2++; + } else { + s2 += num.charAt(i) - '0'; + } + } + return (cnt1 + cnt2) % 2 == 1 || s1 - s2 != 9 * (cnt2 - cnt1) / 2; + } } \ No newline at end of file diff --git a/solution/1900-1999/1927.Sum Game/Solution.py b/solution/1900-1999/1927.Sum Game/Solution.py index 4832d1ba733f5..199a9de85020a 100644 --- a/solution/1900-1999/1927.Sum Game/Solution.py +++ b/solution/1900-1999/1927.Sum Game/Solution.py @@ -1,8 +1,8 @@ -class Solution: - def sumGame(self, num: str) -> bool: - n = len(num) - cnt1 = num[: n // 2].count("?") - cnt2 = num[n // 2 :].count("?") - s1 = sum(int(x) for x in num[: n // 2] if x != "?") - s2 = sum(int(x) for x in num[n // 2 :] if x != "?") - return (cnt1 + cnt2) % 2 == 1 or s1 - s2 != 9 * (cnt2 - cnt1) // 2 +class Solution: + def sumGame(self, num: str) -> bool: + n = len(num) + cnt1 = num[: n // 2].count("?") + cnt2 = num[n // 2 :].count("?") + s1 = sum(int(x) for x in num[: n // 2] if x != "?") + s2 = sum(int(x) for x in num[n // 2 :] if x != "?") + return (cnt1 + cnt2) % 2 == 1 or s1 - s2 != 9 * (cnt2 - cnt1) // 2 diff --git a/solution/1900-1999/1929.Concatenation of Array/Solution.c b/solution/1900-1999/1929.Concatenation of Array/Solution.c index 8db6f17cea15e..6f96e290c32f3 100644 --- a/solution/1900-1999/1929.Concatenation of Array/Solution.c +++ b/solution/1900-1999/1929.Concatenation of Array/Solution.c @@ -8,4 +8,4 @@ int* getConcatenation(int* nums, int numsSize, int* returnSize) { } *returnSize = numsSize * 2; return ans; -} +} \ No newline at end of file diff --git a/solution/1900-1999/1931.Painting a Grid With Three Different Colors/Solution.cpp b/solution/1900-1999/1931.Painting a Grid With Three Different Colors/Solution.cpp index 64987328a2b99..f2b2fa0b0cd4c 100644 --- a/solution/1900-1999/1931.Painting a Grid With Three Different Colors/Solution.cpp +++ b/solution/1900-1999/1931.Painting a Grid With Three Different Colors/Solution.cpp @@ -1,59 +1,59 @@ -class Solution { -public: - int colorTheGrid(int m, int n) { - auto f1 = [&](int x) { - int last = -1; - for (int i = 0; i < m; ++i) { - if (x % 3 == last) { - return false; - } - last = x % 3; - x /= 3; - } - return true; - }; - auto f2 = [&](int x, int y) { - for (int i = 0; i < m; ++i) { - if (x % 3 == y % 3) { - return false; - } - x /= 3; - y /= 3; - } - return true; - }; - - const int mod = 1e9 + 7; - int mx = pow(3, m); - unordered_set valid; - vector f(mx); - for (int i = 0; i < mx; ++i) { - if (f1(i)) { - valid.insert(i); - f[i] = 1; - } - } - unordered_map> d; - for (int i : valid) { - for (int j : valid) { - if (f2(i, j)) { - d[i].push_back(j); - } - } - } - for (int k = 1; k < n; ++k) { - vector g(mx); - for (int i : valid) { - for (int j : d[i]) { - g[i] = (g[i] + f[j]) % mod; - } - } - f = move(g); - } - int ans = 0; - for (int x : f) { - ans = (ans + x) % mod; - } - return ans; - } +class Solution { +public: + int colorTheGrid(int m, int n) { + auto f1 = [&](int x) { + int last = -1; + for (int i = 0; i < m; ++i) { + if (x % 3 == last) { + return false; + } + last = x % 3; + x /= 3; + } + return true; + }; + auto f2 = [&](int x, int y) { + for (int i = 0; i < m; ++i) { + if (x % 3 == y % 3) { + return false; + } + x /= 3; + y /= 3; + } + return true; + }; + + const int mod = 1e9 + 7; + int mx = pow(3, m); + unordered_set valid; + vector f(mx); + for (int i = 0; i < mx; ++i) { + if (f1(i)) { + valid.insert(i); + f[i] = 1; + } + } + unordered_map> d; + for (int i : valid) { + for (int j : valid) { + if (f2(i, j)) { + d[i].push_back(j); + } + } + } + for (int k = 1; k < n; ++k) { + vector g(mx); + for (int i : valid) { + for (int j : d[i]) { + g[i] = (g[i] + f[j]) % mod; + } + } + f = move(g); + } + int ans = 0; + for (int x : f) { + ans = (ans + x) % mod; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1931.Painting a Grid With Three Different Colors/Solution.java b/solution/1900-1999/1931.Painting a Grid With Three Different Colors/Solution.java index 1aa965cd8c09a..b9ccee7b71e39 100644 --- a/solution/1900-1999/1931.Painting a Grid With Three Different Colors/Solution.java +++ b/solution/1900-1999/1931.Painting a Grid With Three Different Colors/Solution.java @@ -1,62 +1,62 @@ -class Solution { - private int m; - - public int colorTheGrid(int m, int n) { - this.m = m; - final int mod = (int) 1e9 + 7; - int mx = (int) Math.pow(3, m); - Set valid = new HashSet<>(); - int[] f = new int[mx]; - for (int i = 0; i < mx; ++i) { - if (f1(i)) { - valid.add(i); - f[i] = 1; - } - } - Map> d = new HashMap<>(); - for (int i : valid) { - for (int j : valid) { - if (f2(i, j)) { - d.computeIfAbsent(i, k -> new ArrayList<>()).add(j); - } - } - } - for (int k = 1; k < n; ++k) { - int[] g = new int[mx]; - for (int i : valid) { - for (int j : d.getOrDefault(i, List.of())) { - g[i] = (g[i] + f[j]) % mod; - } - } - f = g; - } - int ans = 0; - for (int x : f) { - ans = (ans + x) % mod; - } - return ans; - } - - private boolean f1(int x) { - int last = -1; - for (int i = 0; i < m; ++i) { - if (x % 3 == last) { - return false; - } - last = x % 3; - x /= 3; - } - return true; - } - - private boolean f2(int x, int y) { - for (int i = 0; i < m; ++i) { - if (x % 3 == y % 3) { - return false; - } - x /= 3; - y /= 3; - } - return true; - } +class Solution { + private int m; + + public int colorTheGrid(int m, int n) { + this.m = m; + final int mod = (int) 1e9 + 7; + int mx = (int) Math.pow(3, m); + Set valid = new HashSet<>(); + int[] f = new int[mx]; + for (int i = 0; i < mx; ++i) { + if (f1(i)) { + valid.add(i); + f[i] = 1; + } + } + Map> d = new HashMap<>(); + for (int i : valid) { + for (int j : valid) { + if (f2(i, j)) { + d.computeIfAbsent(i, k -> new ArrayList<>()).add(j); + } + } + } + for (int k = 1; k < n; ++k) { + int[] g = new int[mx]; + for (int i : valid) { + for (int j : d.getOrDefault(i, List.of())) { + g[i] = (g[i] + f[j]) % mod; + } + } + f = g; + } + int ans = 0; + for (int x : f) { + ans = (ans + x) % mod; + } + return ans; + } + + private boolean f1(int x) { + int last = -1; + for (int i = 0; i < m; ++i) { + if (x % 3 == last) { + return false; + } + last = x % 3; + x /= 3; + } + return true; + } + + private boolean f2(int x, int y) { + for (int i = 0; i < m; ++i) { + if (x % 3 == y % 3) { + return false; + } + x /= 3; + y /= 3; + } + return true; + } } \ No newline at end of file diff --git a/solution/1900-1999/1931.Painting a Grid With Three Different Colors/Solution.py b/solution/1900-1999/1931.Painting a Grid With Three Different Colors/Solution.py index a48a7114ac661..72eb52aa9fe13 100644 --- a/solution/1900-1999/1931.Painting a Grid With Three Different Colors/Solution.py +++ b/solution/1900-1999/1931.Painting a Grid With Three Different Colors/Solution.py @@ -1,34 +1,34 @@ -class Solution: - def colorTheGrid(self, m: int, n: int) -> int: - def f1(x: int) -> bool: - last = -1 - for _ in range(m): - if x % 3 == last: - return False - last = x % 3 - x //= 3 - return True - - def f2(x: int, y: int) -> bool: - for _ in range(m): - if x % 3 == y % 3: - return False - x, y = x // 3, y // 3 - return True - - mod = 10**9 + 7 - mx = 3**m - valid = {i for i in range(mx) if f1(i)} - d = defaultdict(list) - for x in valid: - for y in valid: - if f2(x, y): - d[x].append(y) - f = [int(i in valid) for i in range(mx)] - for _ in range(n - 1): - g = [0] * mx - for i in valid: - for j in d[i]: - g[i] = (g[i] + f[j]) % mod - f = g - return sum(f) % mod +class Solution: + def colorTheGrid(self, m: int, n: int) -> int: + def f1(x: int) -> bool: + last = -1 + for _ in range(m): + if x % 3 == last: + return False + last = x % 3 + x //= 3 + return True + + def f2(x: int, y: int) -> bool: + for _ in range(m): + if x % 3 == y % 3: + return False + x, y = x // 3, y // 3 + return True + + mod = 10**9 + 7 + mx = 3**m + valid = {i for i in range(mx) if f1(i)} + d = defaultdict(list) + for x in valid: + for y in valid: + if f2(x, y): + d[x].append(y) + f = [int(i in valid) for i in range(mx)] + for _ in range(n - 1): + g = [0] * mx + for i in valid: + for j in d[i]: + g[i] = (g[i] + f[j]) % mod + f = g + return sum(f) % mod diff --git a/solution/1900-1999/1933.Check if String Is Decomposable Into Value-Equal Substrings/Solution.cpp b/solution/1900-1999/1933.Check if String Is Decomposable Into Value-Equal Substrings/Solution.cpp index 9f160c786fe02..d9ab5044ca470 100644 --- a/solution/1900-1999/1933.Check if String Is Decomposable Into Value-Equal Substrings/Solution.cpp +++ b/solution/1900-1999/1933.Check if String Is Decomposable Into Value-Equal Substrings/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - bool isDecomposable(string s) { - int cnt2 = 0; - for (int i = 0, n = s.size(); i < n;) { - int j = i; - while (j < n && s[j] == s[i]) { - ++j; - } - if ((j - i) % 3 == 1) { - return false; - } - cnt2 += (j - i) % 3 == 2; - if (cnt2 > 1) { - return false; - } - i = j; - } - return cnt2 == 1; - } +class Solution { +public: + bool isDecomposable(string s) { + int cnt2 = 0; + for (int i = 0, n = s.size(); i < n;) { + int j = i; + while (j < n && s[j] == s[i]) { + ++j; + } + if ((j - i) % 3 == 1) { + return false; + } + cnt2 += (j - i) % 3 == 2; + if (cnt2 > 1) { + return false; + } + i = j; + } + return cnt2 == 1; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1933.Check if String Is Decomposable Into Value-Equal Substrings/Solution2.py b/solution/1900-1999/1933.Check if String Is Decomposable Into Value-Equal Substrings/Solution2.py new file mode 100644 index 0000000000000..5b938278d2632 --- /dev/null +++ b/solution/1900-1999/1933.Check if String Is Decomposable Into Value-Equal Substrings/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def isDecomposable(self, s: str) -> bool: + cnt2 = 0 + for _, g in groupby(s): + m = len(list(g)) + if m % 3 == 1: + return False + cnt2 += m % 3 == 2 + if cnt2 > 1: + return False + return cnt2 == 1 diff --git a/solution/1900-1999/1935.Maximum Number of Words You Can Type/Solution.cpp b/solution/1900-1999/1935.Maximum Number of Words You Can Type/Solution.cpp index d356d4f3b3928..d74caeb8f107f 100644 --- a/solution/1900-1999/1935.Maximum Number of Words You Can Type/Solution.cpp +++ b/solution/1900-1999/1935.Maximum Number of Words You Can Type/Solution.cpp @@ -1,35 +1,35 @@ -class Solution { -public: - int canBeTypedWords(string text, string brokenLetters) { - bool s[26]{}; - for (char& c : brokenLetters) { - s[c - 'a'] = true; - } - int ans = 0; - for (auto& w : split(text, ' ')) { - for (char& c : w) { - if (s[c - 'a']) { - --ans; - break; - } - } - ++ans; - } - return ans; - } - - vector split(const string& s, char c) { - vector ans; - string t; - for (char d : s) { - if (d == c) { - ans.push_back(t); - t.clear(); - } else { - t.push_back(d); - } - } - ans.push_back(t); - return ans; - } +class Solution { +public: + int canBeTypedWords(string text, string brokenLetters) { + bool s[26]{}; + for (char& c : brokenLetters) { + s[c - 'a'] = true; + } + int ans = 0; + for (auto& w : split(text, ' ')) { + for (char& c : w) { + if (s[c - 'a']) { + --ans; + break; + } + } + ++ans; + } + return ans; + } + + vector split(const string& s, char c) { + vector ans; + string t; + for (char d : s) { + if (d == c) { + ans.push_back(t); + t.clear(); + } else { + t.push_back(d); + } + } + ans.push_back(t); + return ans; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1935.Maximum Number of Words You Can Type/Solution.java b/solution/1900-1999/1935.Maximum Number of Words You Can Type/Solution.java index 676c0d864678b..c99fd96029dee 100644 --- a/solution/1900-1999/1935.Maximum Number of Words You Can Type/Solution.java +++ b/solution/1900-1999/1935.Maximum Number of Words You Can Type/Solution.java @@ -1,19 +1,19 @@ -class Solution { - public int canBeTypedWords(String text, String brokenLetters) { - boolean[] s = new boolean[26]; - for (char c : brokenLetters.toCharArray()) { - s[c - 'a'] = true; - } - int ans = 0; - for (String w : text.split(" ")) { - for (char c : w.toCharArray()) { - if (s[c - 'a']) { - --ans; - break; - } - } - ++ans; - } - return ans; - } +class Solution { + public int canBeTypedWords(String text, String brokenLetters) { + boolean[] s = new boolean[26]; + for (char c : brokenLetters.toCharArray()) { + s[c - 'a'] = true; + } + int ans = 0; + for (String w : text.split(" ")) { + for (char c : w.toCharArray()) { + if (s[c - 'a']) { + --ans; + break; + } + } + ++ans; + } + return ans; + } } \ No newline at end of file diff --git a/solution/1900-1999/1935.Maximum Number of Words You Can Type/Solution.py b/solution/1900-1999/1935.Maximum Number of Words You Can Type/Solution.py index cbe01ef3cb8a6..ad7b30a197b26 100644 --- a/solution/1900-1999/1935.Maximum Number of Words You Can Type/Solution.py +++ b/solution/1900-1999/1935.Maximum Number of Words You Can Type/Solution.py @@ -1,4 +1,4 @@ -class Solution: - def canBeTypedWords(self, text: str, brokenLetters: str) -> int: - s = set(brokenLetters) - return sum(all(c not in s for c in w) for w in text.split()) +class Solution: + def canBeTypedWords(self, text: str, brokenLetters: str) -> int: + s = set(brokenLetters) + return sum(all(c not in s for c in w) for w in text.split()) diff --git a/solution/1900-1999/1936.Add Minimum Number of Rungs/Solution.cpp b/solution/1900-1999/1936.Add Minimum Number of Rungs/Solution.cpp index 96a7c845d546c..8b0458176f0ea 100644 --- a/solution/1900-1999/1936.Add Minimum Number of Rungs/Solution.cpp +++ b/solution/1900-1999/1936.Add Minimum Number of Rungs/Solution.cpp @@ -1,11 +1,11 @@ -class Solution { -public: - int addRungs(vector& rungs, int dist) { - int ans = 0, prev = 0; - for (int& x : rungs) { - ans += (x - prev - 1) / dist; - prev = x; - } - return ans; - } +class Solution { +public: + int addRungs(vector& rungs, int dist) { + int ans = 0, prev = 0; + for (int& x : rungs) { + ans += (x - prev - 1) / dist; + prev = x; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1936.Add Minimum Number of Rungs/Solution.java b/solution/1900-1999/1936.Add Minimum Number of Rungs/Solution.java index 6569985136d7b..9189dc179f69e 100644 --- a/solution/1900-1999/1936.Add Minimum Number of Rungs/Solution.java +++ b/solution/1900-1999/1936.Add Minimum Number of Rungs/Solution.java @@ -1,10 +1,10 @@ -class Solution { - public int addRungs(int[] rungs, int dist) { - int ans = 0, prev = 0; - for (int x : rungs) { - ans += (x - prev - 1) / dist; - prev = x; - } - return ans; - } +class Solution { + public int addRungs(int[] rungs, int dist) { + int ans = 0, prev = 0; + for (int x : rungs) { + ans += (x - prev - 1) / dist; + prev = x; + } + return ans; + } } \ No newline at end of file diff --git a/solution/1900-1999/1936.Add Minimum Number of Rungs/Solution.py b/solution/1900-1999/1936.Add Minimum Number of Rungs/Solution.py index 4cd5495162839..59ada4580a2af 100644 --- a/solution/1900-1999/1936.Add Minimum Number of Rungs/Solution.py +++ b/solution/1900-1999/1936.Add Minimum Number of Rungs/Solution.py @@ -1,4 +1,4 @@ -class Solution: - def addRungs(self, rungs: List[int], dist: int) -> int: - rungs = [0] + rungs - return sum((b - a - 1) // dist for a, b in pairwise(rungs)) +class Solution: + def addRungs(self, rungs: List[int], dist: int) -> int: + rungs = [0] + rungs + return sum((b - a - 1) // dist for a, b in pairwise(rungs)) diff --git a/solution/1900-1999/1937.Maximum Number of Points with Cost/Solution.cpp b/solution/1900-1999/1937.Maximum Number of Points with Cost/Solution.cpp index 23f876c0f04d0..642c51f3c31f9 100644 --- a/solution/1900-1999/1937.Maximum Number of Points with Cost/Solution.cpp +++ b/solution/1900-1999/1937.Maximum Number of Points with Cost/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - long long maxPoints(vector>& points) { - using ll = long long; - int n = points[0].size(); - vector f(n); - const ll inf = 1e18; - for (auto& p : points) { - vector g(n); - ll lmx = -inf, rmx = -inf; - for (int j = 0; j < n; ++j) { - lmx = max(lmx, f[j] + j); - g[j] = max(g[j], p[j] + lmx - j); - } - for (int j = n - 1; ~j; --j) { - rmx = max(rmx, f[j] - j); - g[j] = max(g[j], p[j] + rmx + j); - } - f = move(g); - } - return *max_element(f.begin(), f.end()); - } +class Solution { +public: + long long maxPoints(vector>& points) { + using ll = long long; + int n = points[0].size(); + vector f(n); + const ll inf = 1e18; + for (auto& p : points) { + vector g(n); + ll lmx = -inf, rmx = -inf; + for (int j = 0; j < n; ++j) { + lmx = max(lmx, f[j] + j); + g[j] = max(g[j], p[j] + lmx - j); + } + for (int j = n - 1; ~j; --j) { + rmx = max(rmx, f[j] - j); + g[j] = max(g[j], p[j] + rmx + j); + } + f = move(g); + } + return *max_element(f.begin(), f.end()); + } }; \ No newline at end of file diff --git a/solution/1900-1999/1937.Maximum Number of Points with Cost/Solution.java b/solution/1900-1999/1937.Maximum Number of Points with Cost/Solution.java index e4dbbddff27c8..ae4fe5914347a 100644 --- a/solution/1900-1999/1937.Maximum Number of Points with Cost/Solution.java +++ b/solution/1900-1999/1937.Maximum Number of Points with Cost/Solution.java @@ -1,25 +1,25 @@ -class Solution { - public long maxPoints(int[][] points) { - int n = points[0].length; - long[] f = new long[n]; - final long inf = 1L << 60; - for (int[] p : points) { - long[] g = new long[n]; - long lmx = -inf, rmx = -inf; - for (int j = 0; j < n; ++j) { - lmx = Math.max(lmx, f[j] + j); - g[j] = Math.max(g[j], p[j] + lmx - j); - } - for (int j = n - 1; j >= 0; --j) { - rmx = Math.max(rmx, f[j] - j); - g[j] = Math.max(g[j], p[j] + rmx + j); - } - f = g; - } - long ans = 0; - for (long x : f) { - ans = Math.max(ans, x); - } - return ans; - } +class Solution { + public long maxPoints(int[][] points) { + int n = points[0].length; + long[] f = new long[n]; + final long inf = 1L << 60; + for (int[] p : points) { + long[] g = new long[n]; + long lmx = -inf, rmx = -inf; + for (int j = 0; j < n; ++j) { + lmx = Math.max(lmx, f[j] + j); + g[j] = Math.max(g[j], p[j] + lmx - j); + } + for (int j = n - 1; j >= 0; --j) { + rmx = Math.max(rmx, f[j] - j); + g[j] = Math.max(g[j], p[j] + rmx + j); + } + f = g; + } + long ans = 0; + for (long x : f) { + ans = Math.max(ans, x); + } + return ans; + } } \ No newline at end of file diff --git a/solution/1900-1999/1937.Maximum Number of Points with Cost/Solution.py b/solution/1900-1999/1937.Maximum Number of Points with Cost/Solution.py index b8044e6ae3eaf..c5a88124b66f0 100644 --- a/solution/1900-1999/1937.Maximum Number of Points with Cost/Solution.py +++ b/solution/1900-1999/1937.Maximum Number of Points with Cost/Solution.py @@ -1,16 +1,16 @@ -class Solution: - def maxPoints(self, points: List[List[int]]) -> int: - n = len(points[0]) - f = points[0][:] - for p in points[1:]: - g = [0] * n - lmx = -inf - for j in range(n): - lmx = max(lmx, f[j] + j) - g[j] = max(g[j], p[j] + lmx - j) - rmx = -inf - for j in range(n - 1, -1, -1): - rmx = max(rmx, f[j] - j) - g[j] = max(g[j], p[j] + rmx + j) - f = g - return max(f) +class Solution: + def maxPoints(self, points: List[List[int]]) -> int: + n = len(points[0]) + f = points[0][:] + for p in points[1:]: + g = [0] * n + lmx = -inf + for j in range(n): + lmx = max(lmx, f[j] + j) + g[j] = max(g[j], p[j] + lmx - j) + rmx = -inf + for j in range(n - 1, -1, -1): + rmx = max(rmx, f[j] - j) + g[j] = max(g[j], p[j] + rmx + j) + f = g + return max(f) diff --git a/solution/1900-1999/1940.Longest Common Subsequence Between Sorted Arrays/Solution.py b/solution/1900-1999/1940.Longest Common Subsequence Between Sorted Arrays/Solution.py new file mode 100644 index 0000000000000..0ad7b9bc17b1b --- /dev/null +++ b/solution/1900-1999/1940.Longest Common Subsequence Between Sorted Arrays/Solution.py @@ -0,0 +1,8 @@ +class Solution: + def longestCommomSubsequence(self, arrays: List[List[int]]) -> List[int]: + n = len(arrays) + counter = defaultdict(int) + for array in arrays: + for e in array: + counter[e] += 1 + return [e for e, count in counter.items() if count == n] diff --git a/solution/1900-1999/1940.Longest Common Subsequence Between Sorted Arrays/Solution2.py b/solution/1900-1999/1940.Longest Common Subsequence Between Sorted Arrays/Solution2.py new file mode 100644 index 0000000000000..944e7249458e2 --- /dev/null +++ b/solution/1900-1999/1940.Longest Common Subsequence Between Sorted Arrays/Solution2.py @@ -0,0 +1,20 @@ +class Solution: + def longestCommomSubsequence(self, arrays: List[List[int]]) -> List[int]: + def common(l1, l2): + i, j, n1, n2 = 0, 0, len(l1), len(l2) + res = [] + while i < n1 and j < n2: + if l1[i] == l2[j]: + res.append(l1[i]) + i += 1 + j += 1 + elif l1[i] > l2[j]: + j += 1 + else: + i += 1 + return res + + n = len(arrays) + for i in range(1, n): + arrays[i] = common(arrays[i - 1], arrays[i]) + return arrays[n - 1] diff --git a/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/Solution.php b/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/Solution.php index d72ce3bce779c..d07b8026ab486 100644 --- a/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/Solution.php +++ b/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/Solution.php @@ -10,4 +10,4 @@ function areOccurrencesEqual($s) { $rs = array_unique($hashtable); return count($rs) === 1; } -} \ No newline at end of file +} diff --git a/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/Solution.ts b/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/Solution.ts index 678d4756e37bd..09bfeefef72ee 100644 --- a/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/Solution.ts +++ b/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/Solution.ts @@ -3,6 +3,15 @@ function areOccurrencesEqual(s: string): boolean { for (const c of s) { ++cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]; } - const x = cnt.find(v => v); - return cnt.every(v => !v || v === x); + let x = 0; + for (const v of cnt) { + if (v) { + if (!x) { + x = v; + } else if (x !== v) { + return false; + } + } + } + return true; } diff --git a/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/Solution2.ts b/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/Solution2.ts new file mode 100644 index 0000000000000..678d4756e37bd --- /dev/null +++ b/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/Solution2.ts @@ -0,0 +1,8 @@ +function areOccurrencesEqual(s: string): boolean { + const cnt: number[] = new Array(26).fill(0); + for (const c of s) { + ++cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]; + } + const x = cnt.find(v => v); + return cnt.every(v => !v || v === x); +} diff --git a/solution/1900-1999/1944.Number of Visible People in a Queue/Solution.c b/solution/1900-1999/1944.Number of Visible People in a Queue/Solution.c index 0cb593dc532db..4b304a4cf91cc 100644 --- a/solution/1900-1999/1944.Number of Visible People in a Queue/Solution.c +++ b/solution/1900-1999/1944.Number of Visible People in a Queue/Solution.c @@ -18,4 +18,4 @@ int* canSeePersonsCount(int* heights, int heightsSize, int* returnSize) { } *returnSize = heightsSize; return ans; -} +} \ No newline at end of file diff --git a/solution/1900-1999/1944.Number of Visible People in a Queue/Solution.cpp b/solution/1900-1999/1944.Number of Visible People in a Queue/Solution.cpp index 616662c7ddb77..f8afe0f21da6a 100644 --- a/solution/1900-1999/1944.Number of Visible People in a Queue/Solution.cpp +++ b/solution/1900-1999/1944.Number of Visible People in a Queue/Solution.cpp @@ -1,19 +1,19 @@ -class Solution { -public: - vector canSeePersonsCount(vector& heights) { - int n = heights.size(); - vector ans(n); - stack stk; - for (int i = n - 1; ~i; --i) { - while (stk.size() && stk.top() < heights[i]) { - ++ans[i]; - stk.pop(); - } - if (stk.size()) { - ++ans[i]; - } - stk.push(heights[i]); - } - return ans; - } +class Solution { +public: + vector canSeePersonsCount(vector& heights) { + int n = heights.size(); + vector ans(n); + stack stk; + for (int i = n - 1; ~i; --i) { + while (stk.size() && stk.top() < heights[i]) { + ++ans[i]; + stk.pop(); + } + if (stk.size()) { + ++ans[i]; + } + stk.push(heights[i]); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1944.Number of Visible People in a Queue/Solution.java b/solution/1900-1999/1944.Number of Visible People in a Queue/Solution.java index 738c27dad32e2..c0727509e7afa 100644 --- a/solution/1900-1999/1944.Number of Visible People in a Queue/Solution.java +++ b/solution/1900-1999/1944.Number of Visible People in a Queue/Solution.java @@ -1,18 +1,18 @@ -class Solution { - public int[] canSeePersonsCount(int[] heights) { - int n = heights.length; - int[] ans = new int[n]; - Deque stk = new ArrayDeque<>(); - for (int i = n - 1; i >= 0; --i) { - while (!stk.isEmpty() && stk.peek() < heights[i]) { - stk.pop(); - ++ans[i]; - } - if (!stk.isEmpty()) { - ++ans[i]; - } - stk.push(heights[i]); - } - return ans; - } +class Solution { + public int[] canSeePersonsCount(int[] heights) { + int n = heights.length; + int[] ans = new int[n]; + Deque stk = new ArrayDeque<>(); + for (int i = n - 1; i >= 0; --i) { + while (!stk.isEmpty() && stk.peek() < heights[i]) { + stk.pop(); + ++ans[i]; + } + if (!stk.isEmpty()) { + ++ans[i]; + } + stk.push(heights[i]); + } + return ans; + } } \ No newline at end of file diff --git a/solution/1900-1999/1944.Number of Visible People in a Queue/Solution.py b/solution/1900-1999/1944.Number of Visible People in a Queue/Solution.py index 9a47e09118148..00897624aea5e 100644 --- a/solution/1900-1999/1944.Number of Visible People in a Queue/Solution.py +++ b/solution/1900-1999/1944.Number of Visible People in a Queue/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def canSeePersonsCount(self, heights: List[int]) -> List[int]: - n = len(heights) - ans = [0] * n - stk = [] - for i in range(n - 1, -1, -1): - while stk and stk[-1] < heights[i]: - ans[i] += 1 - stk.pop() - if stk: - ans[i] += 1 - stk.append(heights[i]) - return ans +class Solution: + def canSeePersonsCount(self, heights: List[int]) -> List[int]: + n = len(heights) + ans = [0] * n + stk = [] + for i in range(n - 1, -1, -1): + while stk and stk[-1] < heights[i]: + ans[i] += 1 + stk.pop() + if stk: + ans[i] += 1 + stk.append(heights[i]) + return ans diff --git a/solution/1900-1999/1945.Sum of Digits of String After Convert/Solution.php b/solution/1900-1999/1945.Sum of Digits of String After Convert/Solution.php index 5bbadc0fccc82..a52701a9ac171 100644 --- a/solution/1900-1999/1945.Sum of Digits of String After Convert/Solution.php +++ b/solution/1900-1999/1945.Sum of Digits of String After Convert/Solution.php @@ -20,4 +20,4 @@ function getLucky($s, $k) { } return intval($rs); } -} \ No newline at end of file +} diff --git a/solution/1900-1999/1952.Three Divisors/Solution.cpp b/solution/1900-1999/1952.Three Divisors/Solution.cpp index ade1f9263243b..e2438eb0bd7bf 100644 --- a/solution/1900-1999/1952.Three Divisors/Solution.cpp +++ b/solution/1900-1999/1952.Three Divisors/Solution.cpp @@ -2,11 +2,9 @@ class Solution { public: bool isThree(int n) { int cnt = 0; - for (int i = 1; i <= n / i; ++i) { - if (n % i == 0) { - cnt += n / i == i ? 1 : 2; - } + for (int i = 2; i < n; ++i) { + cnt += n % i == 0; } - return cnt == 3; + return cnt == 1; } }; \ No newline at end of file diff --git a/solution/1900-1999/1952.Three Divisors/Solution.go b/solution/1900-1999/1952.Three Divisors/Solution.go index 392a6e963ab80..41b797f6ff012 100644 --- a/solution/1900-1999/1952.Three Divisors/Solution.go +++ b/solution/1900-1999/1952.Three Divisors/Solution.go @@ -1,13 +1,9 @@ func isThree(n int) bool { cnt := 0 - for i := 1; i <= n/i; i++ { + for i := 2; i < n; i++ { if n%i == 0 { - if n/i == i { - cnt++ - } else { - cnt += 2 - } + cnt++ } } - return cnt == 3 + return cnt == 1 } \ No newline at end of file diff --git a/solution/1900-1999/1952.Three Divisors/Solution.java b/solution/1900-1999/1952.Three Divisors/Solution.java index e98eb28398b77..66be363b364d7 100644 --- a/solution/1900-1999/1952.Three Divisors/Solution.java +++ b/solution/1900-1999/1952.Three Divisors/Solution.java @@ -1,11 +1,11 @@ class Solution { public boolean isThree(int n) { int cnt = 0; - for (int i = 1; i <= n / i; ++i) { + for (int i = 2; i < n; i++) { if (n % i == 0) { - cnt += n / i == i ? 1 : 2; + ++cnt; } } - return cnt == 3; + return cnt == 1; } } \ No newline at end of file diff --git a/solution/1900-1999/1952.Three Divisors/Solution.js b/solution/1900-1999/1952.Three Divisors/Solution.js index e43a0437239ff..88fa2283977d5 100644 --- a/solution/1900-1999/1952.Three Divisors/Solution.js +++ b/solution/1900-1999/1952.Three Divisors/Solution.js @@ -4,10 +4,10 @@ */ var isThree = function (n) { let cnt = 0; - for (let i = 1; i <= n / i; ++i) { + for (let i = 2; i < n; ++i) { if (n % i == 0) { - cnt += ~~(n / i) == i ? 1 : 2; + ++cnt; } } - return cnt == 3; + return cnt == 1; }; diff --git a/solution/1900-1999/1952.Three Divisors/Solution.py b/solution/1900-1999/1952.Three Divisors/Solution.py index c939bbaafe3fa..35950bd26eb48 100644 --- a/solution/1900-1999/1952.Three Divisors/Solution.py +++ b/solution/1900-1999/1952.Three Divisors/Solution.py @@ -1,9 +1,3 @@ class Solution: def isThree(self, n: int) -> bool: - cnt = 0 - i = 1 - while i <= n // i: - if n % i == 0: - cnt += 1 if i == n // i else 2 - i += 1 - return cnt == 3 + return sum(n % i == 0 for i in range(2, n)) == 1 diff --git a/solution/1900-1999/1952.Three Divisors/Solution2.cpp b/solution/1900-1999/1952.Three Divisors/Solution2.cpp new file mode 100644 index 0000000000000..ade1f9263243b --- /dev/null +++ b/solution/1900-1999/1952.Three Divisors/Solution2.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + bool isThree(int n) { + int cnt = 0; + for (int i = 1; i <= n / i; ++i) { + if (n % i == 0) { + cnt += n / i == i ? 1 : 2; + } + } + return cnt == 3; + } +}; \ No newline at end of file diff --git a/solution/1900-1999/1952.Three Divisors/Solution2.go b/solution/1900-1999/1952.Three Divisors/Solution2.go new file mode 100644 index 0000000000000..392a6e963ab80 --- /dev/null +++ b/solution/1900-1999/1952.Three Divisors/Solution2.go @@ -0,0 +1,13 @@ +func isThree(n int) bool { + cnt := 0 + for i := 1; i <= n/i; i++ { + if n%i == 0 { + if n/i == i { + cnt++ + } else { + cnt += 2 + } + } + } + return cnt == 3 +} \ No newline at end of file diff --git a/solution/1900-1999/1952.Three Divisors/Solution2.java b/solution/1900-1999/1952.Three Divisors/Solution2.java new file mode 100644 index 0000000000000..e98eb28398b77 --- /dev/null +++ b/solution/1900-1999/1952.Three Divisors/Solution2.java @@ -0,0 +1,11 @@ +class Solution { + public boolean isThree(int n) { + int cnt = 0; + for (int i = 1; i <= n / i; ++i) { + if (n % i == 0) { + cnt += n / i == i ? 1 : 2; + } + } + return cnt == 3; + } +} \ No newline at end of file diff --git a/solution/1900-1999/1952.Three Divisors/Solution2.js b/solution/1900-1999/1952.Three Divisors/Solution2.js new file mode 100644 index 0000000000000..e43a0437239ff --- /dev/null +++ b/solution/1900-1999/1952.Three Divisors/Solution2.js @@ -0,0 +1,13 @@ +/** + * @param {number} n + * @return {boolean} + */ +var isThree = function (n) { + let cnt = 0; + for (let i = 1; i <= n / i; ++i) { + if (n % i == 0) { + cnt += ~~(n / i) == i ? 1 : 2; + } + } + return cnt == 3; +}; diff --git a/solution/1900-1999/1952.Three Divisors/Solution2.py b/solution/1900-1999/1952.Three Divisors/Solution2.py new file mode 100644 index 0000000000000..c939bbaafe3fa --- /dev/null +++ b/solution/1900-1999/1952.Three Divisors/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def isThree(self, n: int) -> bool: + cnt = 0 + i = 1 + while i <= n // i: + if n % i == 0: + cnt += 1 if i == n // i else 2 + i += 1 + return cnt == 3 diff --git a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.cpp b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.cpp index a58f56b0de88c..c0c6f60409d06 100644 --- a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.cpp +++ b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.cpp @@ -1,15 +1,10 @@ -class Solution { -public: - long long minimumPerimeter(long long neededApples) { - long long l = 1, r = 100000; - while (l < r) { - long mid = (l + r) >> 1; - if (2 * mid * (mid + 1) * (2 * mid + 1) >= neededApples) { - r = mid; - } else { - l = mid + 1; - } - } - return l * 8; - } +class Solution { +public: + long long minimumPerimeter(long long neededApples) { + long long x = 1; + while (2 * x * (x + 1) * (2 * x + 1) < neededApples) { + ++x; + } + return 8 * x; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.go b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.go index 2327a7692807a..4cc8e8b994a21 100644 --- a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.go +++ b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.go @@ -1,12 +1,7 @@ func minimumPerimeter(neededApples int64) int64 { - var l, r int64 = 1, 100000 - for l < r { - mid := (l + r) >> 1 - if 2*mid*(mid+1)*(2*mid+1) >= neededApples { - r = mid - } else { - l = mid + 1 - } + var x int64 = 1 + for 2*x*(x+1)*(2*x+1) < neededApples { + x++ } - return l * 8 + return 8 * x } \ No newline at end of file diff --git a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.java b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.java index 63fb4418ba9ad..8641af24ff278 100644 --- a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.java +++ b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.java @@ -1,14 +1,9 @@ -class Solution { - public long minimumPerimeter(long neededApples) { - long l = 1, r = 100000; - while (l < r) { - long mid = (l + r) >> 1; - if (2 * mid * (mid + 1) * (2 * mid + 1) >= neededApples) { - r = mid; - } else { - l = mid + 1; - } - } - return l * 8; - } +class Solution { + public long minimumPerimeter(long neededApples) { + long x = 1; + while (2 * x * (x + 1) * (2 * x + 1) < neededApples) { + ++x; + } + return 8 * x; + } } \ No newline at end of file diff --git a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.py b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.py index ff93aa6576887..3ae80fae5ea4b 100644 --- a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.py +++ b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.py @@ -1,10 +1,6 @@ -class Solution: - def minimumPerimeter(self, neededApples: int) -> int: - l, r = 1, 100000 - while l < r: - mid = (l + r) >> 1 - if 2 * mid * (mid + 1) * (2 * mid + 1) >= neededApples: - r = mid - else: - l = mid + 1 - return l * 8 +class Solution: + def minimumPerimeter(self, neededApples: int) -> int: + x = 1 + while 2 * x * (x + 1) * (2 * x + 1) < neededApples: + x += 1 + return x * 8 diff --git a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.ts b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.ts index cf3df55cf58fb..c4f002b7eee8f 100644 --- a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.ts +++ b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.ts @@ -1,13 +1,7 @@ function minimumPerimeter(neededApples: number): number { - let l = 1; - let r = 100000; - while (l < r) { - const mid = (l + r) >> 1; - if (2 * mid * (mid + 1) * (2 * mid + 1) >= neededApples) { - r = mid; - } else { - l = mid + 1; - } + let x = 1; + while (2 * x * (x + 1) * (2 * x + 1) < neededApples) { + ++x; } - return 8 * l; + return 8 * x; } diff --git a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution2.cpp b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution2.cpp new file mode 100644 index 0000000000000..515db372b463e --- /dev/null +++ b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + long long minimumPerimeter(long long neededApples) { + long long l = 1, r = 100000; + while (l < r) { + long mid = (l + r) >> 1; + if (2 * mid * (mid + 1) * (2 * mid + 1) >= neededApples) { + r = mid; + } else { + l = mid + 1; + } + } + return l * 8; + } +}; \ No newline at end of file diff --git a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution2.go b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution2.go new file mode 100644 index 0000000000000..2327a7692807a --- /dev/null +++ b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution2.go @@ -0,0 +1,12 @@ +func minimumPerimeter(neededApples int64) int64 { + var l, r int64 = 1, 100000 + for l < r { + mid := (l + r) >> 1 + if 2*mid*(mid+1)*(2*mid+1) >= neededApples { + r = mid + } else { + l = mid + 1 + } + } + return l * 8 +} \ No newline at end of file diff --git a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution2.java b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution2.java new file mode 100644 index 0000000000000..d58e0da8ba25c --- /dev/null +++ b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public long minimumPerimeter(long neededApples) { + long l = 1, r = 100000; + while (l < r) { + long mid = (l + r) >> 1; + if (2 * mid * (mid + 1) * (2 * mid + 1) >= neededApples) { + r = mid; + } else { + l = mid + 1; + } + } + return l * 8; + } +} \ No newline at end of file diff --git a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution2.py b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution2.py new file mode 100644 index 0000000000000..07e14df5ce79b --- /dev/null +++ b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def minimumPerimeter(self, neededApples: int) -> int: + l, r = 1, 100000 + while l < r: + mid = (l + r) >> 1 + if 2 * mid * (mid + 1) * (2 * mid + 1) >= neededApples: + r = mid + else: + l = mid + 1 + return l * 8 diff --git a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution2.ts b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution2.ts new file mode 100644 index 0000000000000..cf3df55cf58fb --- /dev/null +++ b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution2.ts @@ -0,0 +1,13 @@ +function minimumPerimeter(neededApples: number): number { + let l = 1; + let r = 100000; + while (l < r) { + const mid = (l + r) >> 1; + if (2 * mid * (mid + 1) * (2 * mid + 1) >= neededApples) { + r = mid; + } else { + l = mid + 1; + } + } + return 8 * l; +} diff --git a/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.cpp b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.cpp index f9fc1da01a0d8..45920ad4703a7 100644 --- a/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.cpp +++ b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.cpp @@ -1,19 +1,26 @@ -class Solution { -public: - int countSpecialSubsequences(vector& nums) { - const int mod = 1e9 + 7; - int n = nums.size(); - int f[3]{0}; - f[0] = nums[0] == 0; - for (int i = 1; i < n; ++i) { - if (nums[i] == 0) { - f[0] = (2 * f[0] % mod + 1) % mod; - } else if (nums[i] == 1) { - f[1] = (f[0] + 2 * f[1] % mod) % mod; - } else { - f[2] = (f[1] + 2 * f[2] % mod) % mod; - } - } - return f[2]; - } +class Solution { +public: + int countSpecialSubsequences(vector& nums) { + const int mod = 1e9 + 7; + int n = nums.size(); + int f[n][3]; + memset(f, 0, sizeof(f)); + f[0][0] = nums[0] == 0; + for (int i = 1; i < n; ++i) { + if (nums[i] == 0) { + f[i][0] = (2 * f[i - 1][0] % mod + 1) % mod; + f[i][1] = f[i - 1][1]; + f[i][2] = f[i - 1][2]; + } else if (nums[i] == 1) { + f[i][0] = f[i - 1][0]; + f[i][1] = (f[i - 1][0] + 2 * f[i - 1][1] % mod) % mod; + f[i][2] = f[i - 1][2]; + } else { + f[i][0] = f[i - 1][0]; + f[i][1] = f[i - 1][1]; + f[i][2] = (f[i - 1][1] + 2 * f[i - 1][2] % mod) % mod; + } + } + return f[n - 1][2]; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.go b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.go index a6496ea856f7f..1e1f318b3db3d 100644 --- a/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.go +++ b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.go @@ -1,18 +1,24 @@ func countSpecialSubsequences(nums []int) int { const mod = 1e9 + 7 n := len(nums) - f := [3]int{} + f := make([][3]int, n) if nums[0] == 0 { - f[0] = 1 + f[0][0] = 1 } for i := 1; i < n; i++ { if nums[i] == 0 { - f[0] = (2*f[0] + 1) % mod + f[i][0] = (2*f[i-1][0] + 1) % mod + f[i][1] = f[i-1][1] + f[i][2] = f[i-1][2] } else if nums[i] == 1 { - f[1] = (f[0] + 2*f[1]) % mod + f[i][0] = f[i-1][0] + f[i][1] = (f[i-1][0] + 2*f[i-1][1]) % mod + f[i][2] = f[i-1][2] } else { - f[2] = (f[1] + 2*f[2]) % mod + f[i][0] = f[i-1][0] + f[i][1] = f[i-1][1] + f[i][2] = (f[i-1][1] + 2*f[i-1][2]) % mod } } - return f[2] + return f[n-1][2] } \ No newline at end of file diff --git a/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.java b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.java index b17198c729b4f..b2498535919b9 100644 --- a/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.java +++ b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.java @@ -1,18 +1,24 @@ -class Solution { - public int countSpecialSubsequences(int[] nums) { - final int mod = (int) 1e9 + 7; - int n = nums.length; - int[] f = new int[3]; - f[0] = nums[0] == 0 ? 1 : 0; - for (int i = 1; i < n; ++i) { - if (nums[i] == 0) { - f[0] = (2 * f[0] % mod + 1) % mod; - } else if (nums[i] == 1) { - f[1] = (f[0] + 2 * f[1] % mod) % mod; - } else { - f[2] = (f[1] + 2 * f[2] % mod) % mod; - } - } - return f[2]; - } +class Solution { + public int countSpecialSubsequences(int[] nums) { + final int mod = (int) 1e9 + 7; + int n = nums.length; + int[][] f = new int[n][3]; + f[0][0] = nums[0] == 0 ? 1 : 0; + for (int i = 1; i < n; ++i) { + if (nums[i] == 0) { + f[i][0] = (2 * f[i - 1][0] % mod + 1) % mod; + f[i][1] = f[i - 1][1]; + f[i][2] = f[i - 1][2]; + } else if (nums[i] == 1) { + f[i][0] = f[i - 1][0]; + f[i][1] = (f[i - 1][0] + 2 * f[i - 1][1] % mod) % mod; + f[i][2] = f[i - 1][2]; + } else { + f[i][0] = f[i - 1][0]; + f[i][1] = f[i - 1][1]; + f[i][2] = (f[i - 1][1] + 2 * f[i - 1][2] % mod) % mod; + } + } + return f[n - 1][2]; + } } \ No newline at end of file diff --git a/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.py b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.py index 828f76af21ead..4e58919f8985e 100644 --- a/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.py +++ b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.py @@ -1,14 +1,20 @@ -class Solution: - def countSpecialSubsequences(self, nums: List[int]) -> int: - mod = 10**9 + 7 - n = len(nums) - f = [0] * 3 - f[0] = nums[0] == 0 - for i in range(1, n): - if nums[i] == 0: - f[0] = (2 * f[0] + 1) % mod - elif nums[i] == 1: - f[1] = (f[0] + 2 * f[1]) % mod - else: - f[2] = (f[1] + 2 * f[2]) % mod - return f[2] +class Solution: + def countSpecialSubsequences(self, nums: List[int]) -> int: + mod = 10**9 + 7 + n = len(nums) + f = [[0] * 3 for _ in range(n)] + f[0][0] = nums[0] == 0 + for i in range(1, n): + if nums[i] == 0: + f[i][0] = (2 * f[i - 1][0] + 1) % mod + f[i][1] = f[i - 1][1] + f[i][2] = f[i - 1][2] + elif nums[i] == 1: + f[i][0] = f[i - 1][0] + f[i][1] = (f[i - 1][0] + 2 * f[i - 1][1]) % mod + f[i][2] = f[i - 1][2] + else: + f[i][0] = f[i - 1][0] + f[i][1] = f[i - 1][1] + f[i][2] = (f[i - 1][1] + 2 * f[i - 1][2]) % mod + return f[n - 1][2] diff --git a/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.ts b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.ts index 9c300957f44b1..d16b062fb9de7 100644 --- a/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.ts +++ b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution.ts @@ -1,22 +1,24 @@ function countSpecialSubsequences(nums: number[]): number { const mod = 1e9 + 7; const n = nums.length; - const f: number[] = [0, 0, 0]; - f[0] = nums[0] === 0 ? 1 : 0; + const f: number[][] = Array(n) + .fill(0) + .map(() => Array(3).fill(0)); + f[0][0] = nums[0] === 0 ? 1 : 0; for (let i = 1; i < n; ++i) { if (nums[i] === 0) { - f[0] = (((2 * f[0]) % mod) + 1) % mod; - f[1] = f[1]; - f[2] = f[2]; + f[i][0] = (((2 * f[i - 1][0]) % mod) + 1) % mod; + f[i][1] = f[i - 1][1]; + f[i][2] = f[i - 1][2]; } else if (nums[i] === 1) { - f[0] = f[0]; - f[1] = (f[0] + ((2 * f[1]) % mod)) % mod; - f[2] = f[2]; + f[i][0] = f[i - 1][0]; + f[i][1] = (f[i - 1][0] + ((2 * f[i - 1][1]) % mod)) % mod; + f[i][2] = f[i - 1][2]; } else { - f[0] = f[0]; - f[1] = f[1]; - f[2] = (f[1] + ((2 * f[2]) % mod)) % mod; + f[i][0] = f[i - 1][0]; + f[i][1] = f[i - 1][1]; + f[i][2] = (f[i - 1][1] + ((2 * f[i - 1][2]) % mod)) % mod; } } - return f[2]; + return f[n - 1][2]; } diff --git a/solution/1900-1999/1955.Count Number of Special Subsequences/Solution2.cpp b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution2.cpp new file mode 100644 index 0000000000000..c6b5991a7b9e7 --- /dev/null +++ b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int countSpecialSubsequences(vector& nums) { + const int mod = 1e9 + 7; + int n = nums.size(); + int f[3]{0}; + f[0] = nums[0] == 0; + for (int i = 1; i < n; ++i) { + if (nums[i] == 0) { + f[0] = (2 * f[0] % mod + 1) % mod; + } else if (nums[i] == 1) { + f[1] = (f[0] + 2 * f[1] % mod) % mod; + } else { + f[2] = (f[1] + 2 * f[2] % mod) % mod; + } + } + return f[2]; + } +}; \ No newline at end of file diff --git a/solution/1900-1999/1955.Count Number of Special Subsequences/Solution2.go b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution2.go new file mode 100644 index 0000000000000..a6496ea856f7f --- /dev/null +++ b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution2.go @@ -0,0 +1,18 @@ +func countSpecialSubsequences(nums []int) int { + const mod = 1e9 + 7 + n := len(nums) + f := [3]int{} + if nums[0] == 0 { + f[0] = 1 + } + for i := 1; i < n; i++ { + if nums[i] == 0 { + f[0] = (2*f[0] + 1) % mod + } else if nums[i] == 1 { + f[1] = (f[0] + 2*f[1]) % mod + } else { + f[2] = (f[1] + 2*f[2]) % mod + } + } + return f[2] +} \ No newline at end of file diff --git a/solution/1900-1999/1955.Count Number of Special Subsequences/Solution2.java b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution2.java new file mode 100644 index 0000000000000..fec4375faf5cb --- /dev/null +++ b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution2.java @@ -0,0 +1,18 @@ +class Solution { + public int countSpecialSubsequences(int[] nums) { + final int mod = (int) 1e9 + 7; + int n = nums.length; + int[] f = new int[3]; + f[0] = nums[0] == 0 ? 1 : 0; + for (int i = 1; i < n; ++i) { + if (nums[i] == 0) { + f[0] = (2 * f[0] % mod + 1) % mod; + } else if (nums[i] == 1) { + f[1] = (f[0] + 2 * f[1] % mod) % mod; + } else { + f[2] = (f[1] + 2 * f[2] % mod) % mod; + } + } + return f[2]; + } +} \ No newline at end of file diff --git a/solution/1900-1999/1955.Count Number of Special Subsequences/Solution2.py b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution2.py new file mode 100644 index 0000000000000..ec95a84a4cfa3 --- /dev/null +++ b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def countSpecialSubsequences(self, nums: List[int]) -> int: + mod = 10**9 + 7 + n = len(nums) + f = [0] * 3 + f[0] = nums[0] == 0 + for i in range(1, n): + if nums[i] == 0: + f[0] = (2 * f[0] + 1) % mod + elif nums[i] == 1: + f[1] = (f[0] + 2 * f[1]) % mod + else: + f[2] = (f[1] + 2 * f[2]) % mod + return f[2] diff --git a/solution/1900-1999/1955.Count Number of Special Subsequences/Solution2.ts b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution2.ts new file mode 100644 index 0000000000000..9c300957f44b1 --- /dev/null +++ b/solution/1900-1999/1955.Count Number of Special Subsequences/Solution2.ts @@ -0,0 +1,22 @@ +function countSpecialSubsequences(nums: number[]): number { + const mod = 1e9 + 7; + const n = nums.length; + const f: number[] = [0, 0, 0]; + f[0] = nums[0] === 0 ? 1 : 0; + for (let i = 1; i < n; ++i) { + if (nums[i] === 0) { + f[0] = (((2 * f[0]) % mod) + 1) % mod; + f[1] = f[1]; + f[2] = f[2]; + } else if (nums[i] === 1) { + f[0] = f[0]; + f[1] = (f[0] + ((2 * f[1]) % mod)) % mod; + f[2] = f[2]; + } else { + f[0] = f[0]; + f[1] = f[1]; + f[2] = (f[1] + ((2 * f[2]) % mod)) % mod; + } + } + return f[2]; +} diff --git a/solution/1900-1999/1957.Delete Characters to Make Fancy String/Solution.php b/solution/1900-1999/1957.Delete Characters to Make Fancy String/Solution.php index 704fd0bc078b3..ad55dfce7a289 100644 --- a/solution/1900-1999/1957.Delete Characters to Make Fancy String/Solution.php +++ b/solution/1900-1999/1957.Delete Characters to Make Fancy String/Solution.php @@ -14,4 +14,4 @@ function makeFancyString($s) { } return $rs; } -} \ No newline at end of file +} diff --git a/solution/1900-1999/1961.Check If String Is a Prefix of Array/Solution.cpp b/solution/1900-1999/1961.Check If String Is a Prefix of Array/Solution.cpp index 5fad3229e75b9..f203d96ba2935 100644 --- a/solution/1900-1999/1961.Check If String Is a Prefix of Array/Solution.cpp +++ b/solution/1900-1999/1961.Check If String Is a Prefix of Array/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - bool isPrefixString(string s, vector& words) { - string t; - for (auto& w : words) { - t += w; - if (t.size() > s.size()) { - return false; - } - if (t.size() == s.size()) { - return t == s; - } - } - return false; - } +class Solution { +public: + bool isPrefixString(string s, vector& words) { + string t; + for (auto& w : words) { + t += w; + if (t.size() > s.size()) { + return false; + } + if (t.size() == s.size()) { + return t == s; + } + } + return false; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1961.Check If String Is a Prefix of Array/Solution.java b/solution/1900-1999/1961.Check If String Is a Prefix of Array/Solution.java index dad513df30dbf..85b5fdec20397 100644 --- a/solution/1900-1999/1961.Check If String Is a Prefix of Array/Solution.java +++ b/solution/1900-1999/1961.Check If String Is a Prefix of Array/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public boolean isPrefixString(String s, String[] words) { - StringBuilder t = new StringBuilder(); - for (var w : words) { - t.append(w); - if (t.length() > s.length()) { - return false; - } - if (t.length() == s.length()) { - return s.equals(t.toString()); - } - } - return false; - } +class Solution { + public boolean isPrefixString(String s, String[] words) { + StringBuilder t = new StringBuilder(); + for (var w : words) { + t.append(w); + if (t.length() > s.length()) { + return false; + } + if (t.length() == s.length()) { + return s.equals(t.toString()); + } + } + return false; + } } \ No newline at end of file diff --git a/solution/1900-1999/1961.Check If String Is a Prefix of Array/Solution.py b/solution/1900-1999/1961.Check If String Is a Prefix of Array/Solution.py index 828d134ec457b..0e8fd5024cbca 100644 --- a/solution/1900-1999/1961.Check If String Is a Prefix of Array/Solution.py +++ b/solution/1900-1999/1961.Check If String Is a Prefix of Array/Solution.py @@ -1,8 +1,8 @@ -class Solution: - def isPrefixString(self, s: str, words: List[str]) -> bool: - n, m = len(s), 0 - for i, w in enumerate(words): - m += len(w) - if m == n: - return "".join(words[: i + 1]) == s - return False +class Solution: + def isPrefixString(self, s: str, words: List[str]) -> bool: + n, m = len(s), 0 + for i, w in enumerate(words): + m += len(w) + if m == n: + return "".join(words[: i + 1]) == s + return False diff --git a/solution/1900-1999/1962.Remove Stones to Minimize the Total/Solution.cpp b/solution/1900-1999/1962.Remove Stones to Minimize the Total/Solution.cpp index eaa06dd347d95..021ea07a5945f 100644 --- a/solution/1900-1999/1962.Remove Stones to Minimize the Total/Solution.cpp +++ b/solution/1900-1999/1962.Remove Stones to Minimize the Total/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - int minStoneSum(vector& piles, int k) { - priority_queue pq; - for (int x : piles) { - pq.push(x); - } - while (k--) { - int x = pq.top(); - pq.pop(); - pq.push(x - x / 2); - } - int ans = 0; - while (!pq.empty()) { - ans += pq.top(); - pq.pop(); - } - return ans; - } +class Solution { +public: + int minStoneSum(vector& piles, int k) { + priority_queue pq; + for (int x : piles) { + pq.push(x); + } + while (k--) { + int x = pq.top(); + pq.pop(); + pq.push(x - x / 2); + } + int ans = 0; + while (!pq.empty()) { + ans += pq.top(); + pq.pop(); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1962.Remove Stones to Minimize the Total/Solution.java b/solution/1900-1999/1962.Remove Stones to Minimize the Total/Solution.java index 5d637cbb93631..0b8ab91424eea 100644 --- a/solution/1900-1999/1962.Remove Stones to Minimize the Total/Solution.java +++ b/solution/1900-1999/1962.Remove Stones to Minimize the Total/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public int minStoneSum(int[] piles, int k) { - PriorityQueue pq = new PriorityQueue<>((a, b) -> b - a); - for (int x : piles) { - pq.offer(x); - } - while (k-- > 0) { - int x = pq.poll(); - pq.offer(x - x / 2); - } - int ans = 0; - while (!pq.isEmpty()) { - ans += pq.poll(); - } - return ans; - } +class Solution { + public int minStoneSum(int[] piles, int k) { + PriorityQueue pq = new PriorityQueue<>((a, b) -> b - a); + for (int x : piles) { + pq.offer(x); + } + while (k-- > 0) { + int x = pq.poll(); + pq.offer(x - x / 2); + } + int ans = 0; + while (!pq.isEmpty()) { + ans += pq.poll(); + } + return ans; + } } \ No newline at end of file diff --git a/solution/1900-1999/1962.Remove Stones to Minimize the Total/Solution.py b/solution/1900-1999/1962.Remove Stones to Minimize the Total/Solution.py index 7cd34c576c9db..65d3ec53b3252 100644 --- a/solution/1900-1999/1962.Remove Stones to Minimize the Total/Solution.py +++ b/solution/1900-1999/1962.Remove Stones to Minimize the Total/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def minStoneSum(self, piles: List[int], k: int) -> int: - pq = [-x for x in piles] - heapify(pq) - for _ in range(k): - heapreplace(pq, pq[0] // 2) - return -sum(pq) +class Solution: + def minStoneSum(self, piles: List[int], k: int) -> int: + pq = [-x for x in piles] + heapify(pq) + for _ in range(k): + heapreplace(pq, pq[0] // 2) + return -sum(pq) diff --git a/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/Solution.cpp b/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/Solution.cpp index f8de4b8bbb52d..6676ea1488a85 100644 --- a/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/Solution.cpp +++ b/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/Solution.cpp @@ -1,14 +1,14 @@ -class Solution { -public: - int minSwaps(string s) { - int x = 0; - for (char& c : s) { - if (c == '[') { - ++x; - } else if (x) { - --x; - } - } - return (x + 1) / 2; - } +class Solution { +public: + int minSwaps(string s) { + int x = 0; + for (char& c : s) { + if (c == '[') { + ++x; + } else if (x) { + --x; + } + } + return (x + 1) / 2; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/Solution.java b/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/Solution.java index 2a7dabaf28d10..aa56627c98cd8 100644 --- a/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/Solution.java +++ b/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/Solution.java @@ -1,14 +1,14 @@ -class Solution { - public int minSwaps(String s) { - int x = 0; - for (int i = 0; i < s.length(); ++i) { - char c = s.charAt(i); - if (c == '[') { - ++x; - } else if (x > 0) { - --x; - } - } - return (x + 1) / 2; - } +class Solution { + public int minSwaps(String s) { + int x = 0; + for (int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if (c == '[') { + ++x; + } else if (x > 0) { + --x; + } + } + return (x + 1) / 2; + } } \ No newline at end of file diff --git a/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/Solution.py b/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/Solution.py index cb578a53e5c77..f5a677cfe381e 100644 --- a/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/Solution.py +++ b/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def minSwaps(self, s: str) -> int: - x = 0 - for c in s: - if c == "[": - x += 1 - elif x: - x -= 1 - return (x + 1) >> 1 +class Solution: + def minSwaps(self, s: str) -> int: + x = 0 + for c in s: + if c == "[": + x += 1 + elif x: + x -= 1 + return (x + 1) >> 1 diff --git a/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/Solution.cpp b/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/Solution.cpp index d380f40ef6b3c..183fbdfd54f0f 100644 --- a/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/Solution.cpp +++ b/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/Solution.cpp @@ -1,46 +1,46 @@ -class BinaryIndexedTree { -private: - int n; - vector c; - -public: - BinaryIndexedTree(int n) { - this->n = n; - c = vector(n + 1); - } - - void update(int x, int v) { - while (x <= n) { - c[x] = max(c[x], v); - x += x & -x; - } - } - - int query(int x) { - int s = 0; - while (x > 0) { - s = max(s, c[x]); - x -= x & -x; - } - return s; - } -}; - -class Solution { -public: - vector longestObstacleCourseAtEachPosition(vector& obstacles) { - vector nums = obstacles; - sort(nums.begin(), nums.end()); - int n = nums.size(); - vector ans(n); - BinaryIndexedTree tree(n); - for (int k = 0; k < n; ++k) { - int x = obstacles[k]; - auto it = lower_bound(nums.begin(), nums.end(), x); - int i = distance(nums.begin(), it) + 1; - ans[k] = tree.query(i) + 1; - tree.update(i, ans[k]); - } - return ans; - } +class BinaryIndexedTree { +private: + int n; + vector c; + +public: + BinaryIndexedTree(int n) { + this->n = n; + c = vector(n + 1); + } + + void update(int x, int v) { + while (x <= n) { + c[x] = max(c[x], v); + x += x & -x; + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s = max(s, c[x]); + x -= x & -x; + } + return s; + } +}; + +class Solution { +public: + vector longestObstacleCourseAtEachPosition(vector& obstacles) { + vector nums = obstacles; + sort(nums.begin(), nums.end()); + int n = nums.size(); + vector ans(n); + BinaryIndexedTree tree(n); + for (int k = 0; k < n; ++k) { + int x = obstacles[k]; + auto it = lower_bound(nums.begin(), nums.end(), x); + int i = distance(nums.begin(), it) + 1; + ans[k] = tree.query(i) + 1; + tree.update(i, ans[k]); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/Solution.java b/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/Solution.java index 831ebe57a7594..cf66ef2f24d56 100644 --- a/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/Solution.java +++ b/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/Solution.java @@ -1,42 +1,42 @@ -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void update(int x, int v) { - while (x <= n) { - c[x] = Math.max(c[x], v); - x += x & -x; - } - } - - public int query(int x) { - int s = 0; - while (x > 0) { - s = Math.max(s, c[x]); - x -= x & -x; - } - return s; - } -} - -class Solution { - public int[] longestObstacleCourseAtEachPosition(int[] obstacles) { - int[] nums = obstacles.clone(); - Arrays.sort(nums); - int n = nums.length; - int[] ans = new int[n]; - BinaryIndexedTree tree = new BinaryIndexedTree(n); - for (int k = 0; k < n; ++k) { - int x = obstacles[k]; - int i = Arrays.binarySearch(nums, x) + 1; - ans[k] = tree.query(i) + 1; - tree.update(i, ans[k]); - } - return ans; - } +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int v) { + while (x <= n) { + c[x] = Math.max(c[x], v); + x += x & -x; + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s = Math.max(s, c[x]); + x -= x & -x; + } + return s; + } +} + +class Solution { + public int[] longestObstacleCourseAtEachPosition(int[] obstacles) { + int[] nums = obstacles.clone(); + Arrays.sort(nums); + int n = nums.length; + int[] ans = new int[n]; + BinaryIndexedTree tree = new BinaryIndexedTree(n); + for (int k = 0; k < n; ++k) { + int x = obstacles[k]; + int i = Arrays.binarySearch(nums, x) + 1; + ans[k] = tree.query(i) + 1; + tree.update(i, ans[k]); + } + return ans; + } } \ No newline at end of file diff --git a/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/Solution.py b/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/Solution.py index 380247ff21ae3..7214d4e2e54a6 100644 --- a/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/Solution.py +++ b/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/Solution.py @@ -1,31 +1,31 @@ -class BinaryIndexedTree: - __slots__ = ["n", "c"] - - def __init__(self, n: int): - self.n = n - self.c = [0] * (n + 1) - - def update(self, x: int, v: int): - while x <= self.n: - self.c[x] = max(self.c[x], v) - x += x & -x - - def query(self, x: int) -> int: - s = 0 - while x: - s = max(s, self.c[x]) - x -= x & -x - return s - - -class Solution: - def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]: - nums = sorted(set(obstacles)) - n = len(nums) - tree = BinaryIndexedTree(n) - ans = [] - for x in obstacles: - i = bisect_left(nums, x) + 1 - ans.append(tree.query(i) + 1) - tree.update(i, ans[-1]) - return ans +class BinaryIndexedTree: + __slots__ = ["n", "c"] + + def __init__(self, n: int): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x: int, v: int): + while x <= self.n: + self.c[x] = max(self.c[x], v) + x += x & -x + + def query(self, x: int) -> int: + s = 0 + while x: + s = max(s, self.c[x]) + x -= x & -x + return s + + +class Solution: + def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]: + nums = sorted(set(obstacles)) + n = len(nums) + tree = BinaryIndexedTree(n) + ans = [] + for x in obstacles: + i = bisect_left(nums, x) + 1 + ans.append(tree.query(i) + 1) + tree.update(i, ans[-1]) + return ans diff --git a/solution/1900-1999/1968.Array With Elements Not Equal to Average of Neighbors/Solution2.go b/solution/1900-1999/1968.Array With Elements Not Equal to Average of Neighbors/Solution2.go new file mode 100644 index 0000000000000..b60065c959639 --- /dev/null +++ b/solution/1900-1999/1968.Array With Elements Not Equal to Average of Neighbors/Solution2.go @@ -0,0 +1,13 @@ +func rearrangeArray(nums []int) []int { + rand.Seed(time.Now().UnixNano()) +outer: + for { + rand.Shuffle(len(nums), func(i, j int) { nums[i], nums[j] = nums[j], nums[i] }) + for i := 1; i < len(nums)-1; i++ { + if nums[i]*2 == nums[i-1]+nums[i+1] { + continue outer + } + } + return nums + } +} \ No newline at end of file diff --git a/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/Solution.cpp b/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/Solution.cpp index f2d3a7573f2c3..c1e9cf4bf25cf 100644 --- a/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/Solution.cpp +++ b/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - int minNonZeroProduct(int p) { - using ll = long long; - const int mod = 1e9 + 7; - auto qpow = [](ll a, ll n) { - ll ans = 1; - for (; n; n >>= 1) { - if (n & 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return ans; - }; - ll a = ((1LL << p) - 1) % mod; - ll b = qpow(((1LL << p) - 2) % mod, (1L << (p - 1)) - 1); - return a * b % mod; - } +class Solution { +public: + int minNonZeroProduct(int p) { + using ll = long long; + const int mod = 1e9 + 7; + auto qpow = [](ll a, ll n) { + ll ans = 1; + for (; n; n >>= 1) { + if (n & 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return ans; + }; + ll a = ((1LL << p) - 1) % mod; + ll b = qpow(((1LL << p) - 2) % mod, (1L << (p - 1)) - 1); + return a * b % mod; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/Solution.java b/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/Solution.java index 45611e20078d5..de09ba5d11acf 100644 --- a/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/Solution.java +++ b/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/Solution.java @@ -1,19 +1,19 @@ -class Solution { - public int minNonZeroProduct(int p) { - final int mod = (int) 1e9 + 7; - long a = ((1L << p) - 1) % mod; - long b = qpow(((1L << p) - 2) % mod, (1L << (p - 1)) - 1, mod); - return (int) (a * b % mod); - } - - private long qpow(long a, long n, int mod) { - long ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return ans; - } +class Solution { + public int minNonZeroProduct(int p) { + final int mod = (int) 1e9 + 7; + long a = ((1L << p) - 1) % mod; + long b = qpow(((1L << p) - 2) % mod, (1L << (p - 1)) - 1, mod); + return (int) (a * b % mod); + } + + private long qpow(long a, long n, int mod) { + long ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return ans; + } } \ No newline at end of file diff --git a/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/Solution.py b/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/Solution.py index c355b3481e2e6..9e29cb55d765c 100644 --- a/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/Solution.py +++ b/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/Solution.py @@ -1,4 +1,4 @@ -class Solution: - def minNonZeroProduct(self, p: int) -> int: - mod = 10**9 + 7 - return (2**p - 1) * pow(2**p - 2, 2 ** (p - 1) - 1, mod) % mod +class Solution: + def minNonZeroProduct(self, p: int) -> int: + mod = 10**9 + 7 + return (2**p - 1) * pow(2**p - 2, 2 ** (p - 1) - 1, mod) % mod diff --git a/solution/1900-1999/1971.Find if Path Exists in Graph/Solution.cpp b/solution/1900-1999/1971.Find if Path Exists in Graph/Solution.cpp index aeac22b853990..df3683cf97ec3 100644 --- a/solution/1900-1999/1971.Find if Path Exists in Graph/Solution.cpp +++ b/solution/1900-1999/1971.Find if Path Exists in Graph/Solution.cpp @@ -1,16 +1,23 @@ -class Solution { -public: - vector p; - - bool validPath(int n, vector>& edges, int source, int destination) { - p.resize(n); - for (int i = 0; i < n; ++i) p[i] = i; - for (auto& e : edges) p[find(e[0])] = find(e[1]); - return find(source) == find(destination); - } - - int find(int x) { - if (p[x] != x) p[x] = find(p[x]); - return p[x]; - } +class Solution { +public: + bool validPath(int n, vector>& edges, int source, int destination) { + vector vis(n); + vector> g(n); + for (auto& e : edges) { + int a = e[0], b = e[1]; + g[a].emplace_back(b); + g[b].emplace_back(a); + } + function dfs = [&](int i) -> bool { + if (i == destination) return true; + vis[i] = true; + for (int& j : g[i]) { + if (!vis[j] && dfs(j)) { + return true; + } + } + return false; + }; + return dfs(source); + } }; \ No newline at end of file diff --git a/solution/1900-1999/1971.Find if Path Exists in Graph/Solution.go b/solution/1900-1999/1971.Find if Path Exists in Graph/Solution.go index dcdedbee8d23f..390abc8e8b690 100644 --- a/solution/1900-1999/1971.Find if Path Exists in Graph/Solution.go +++ b/solution/1900-1999/1971.Find if Path Exists in Graph/Solution.go @@ -1,17 +1,23 @@ func validPath(n int, edges [][]int, source int, destination int) bool { - p := make([]int, n) - for i := range p { - p[i] = i + vis := make([]bool, n) + g := make([][]int, n) + for _, e := range edges { + a, b := e[0], e[1] + g[a] = append(g[a], b) + g[b] = append(g[b], a) } - var find func(x int) int - find = func(x int) int { - if p[x] != x { - p[x] = find(p[x]) + var dfs func(int) bool + dfs = func(i int) bool { + if i == destination { + return true } - return p[x] - } - for _, e := range edges { - p[find(e[0])] = find(e[1]) + vis[i] = true + for _, j := range g[i] { + if !vis[j] && dfs(j) { + return true + } + } + return false } - return find(source) == find(destination) + return dfs(source) } \ No newline at end of file diff --git a/solution/1900-1999/1971.Find if Path Exists in Graph/Solution.java b/solution/1900-1999/1971.Find if Path Exists in Graph/Solution.java index 15d3d7f141094..d17566422e991 100644 --- a/solution/1900-1999/1971.Find if Path Exists in Graph/Solution.java +++ b/solution/1900-1999/1971.Find if Path Exists in Graph/Solution.java @@ -1,21 +1,29 @@ -class Solution { - private int[] p; - - public boolean validPath(int n, int[][] edges, int source, int destination) { - p = new int[n]; - for (int i = 0; i < n; ++i) { - p[i] = i; - } - for (int[] e : edges) { - p[find(e[0])] = find(e[1]); - } - return find(source) == find(destination); - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } +class Solution { + private boolean[] vis; + private List[] g; + + public boolean validPath(int n, int[][] edges, int source, int destination) { + vis = new boolean[n]; + g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (var e : edges) { + int a = e[0], b = e[1]; + g[a].add(b); + g[b].add(a); + } + return dfs(source, destination); + } + + private boolean dfs(int source, int destination) { + if (source == destination) { + return true; + } + vis[source] = true; + for (int nxt : g[source]) { + if (!vis[nxt] && dfs(nxt, destination)) { + return true; + } + } + return false; + } } \ No newline at end of file diff --git a/solution/1900-1999/1971.Find if Path Exists in Graph/Solution.py b/solution/1900-1999/1971.Find if Path Exists in Graph/Solution.py index d57433129dc14..8bc7f3c01056c 100644 --- a/solution/1900-1999/1971.Find if Path Exists in Graph/Solution.py +++ b/solution/1900-1999/1971.Find if Path Exists in Graph/Solution.py @@ -1,13 +1,19 @@ -class Solution: - def validPath( - self, n: int, edges: List[List[int]], source: int, destination: int - ) -> bool: - def find(x): - if p[x] != x: - p[x] = find(p[x]) - return p[x] - - p = list(range(n)) - for u, v in edges: - p[find(u)] = find(v) - return find(source) == find(destination) +class Solution: + def validPath( + self, n: int, edges: List[List[int]], source: int, destination: int + ) -> bool: + def dfs(i): + if i == destination: + return True + vis.add(i) + for j in g[i]: + if j not in vis and dfs(j): + return True + return False + + g = defaultdict(list) + for a, b in edges: + g[a].append(b) + g[b].append(a) + vis = set() + return dfs(source) diff --git a/solution/1900-1999/1971.Find if Path Exists in Graph/Solution2.cpp b/solution/1900-1999/1971.Find if Path Exists in Graph/Solution2.cpp new file mode 100644 index 0000000000000..b8cae57d8318b --- /dev/null +++ b/solution/1900-1999/1971.Find if Path Exists in Graph/Solution2.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + bool validPath(int n, vector>& edges, int source, int destination) { + vector p(n); + iota(p.begin(), p.end(), 0); + function find = [&](int x) -> int { + if (p[x] != x) p[x] = find(p[x]); + return p[x]; + }; + for (auto& e : edges) p[find(e[0])] = find(e[1]); + return find(source) == find(destination); + } +}; \ No newline at end of file diff --git a/solution/1900-1999/1971.Find if Path Exists in Graph/Solution2.go b/solution/1900-1999/1971.Find if Path Exists in Graph/Solution2.go new file mode 100644 index 0000000000000..dcdedbee8d23f --- /dev/null +++ b/solution/1900-1999/1971.Find if Path Exists in Graph/Solution2.go @@ -0,0 +1,17 @@ +func validPath(n int, edges [][]int, source int, destination int) bool { + p := make([]int, n) + for i := range p { + p[i] = i + } + var find func(x int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + for _, e := range edges { + p[find(e[0])] = find(e[1]) + } + return find(source) == find(destination) +} \ No newline at end of file diff --git a/solution/1900-1999/1971.Find if Path Exists in Graph/Solution2.java b/solution/1900-1999/1971.Find if Path Exists in Graph/Solution2.java new file mode 100644 index 0000000000000..6cf85193fe6a3 --- /dev/null +++ b/solution/1900-1999/1971.Find if Path Exists in Graph/Solution2.java @@ -0,0 +1,21 @@ +class Solution { + private int[] p; + + public boolean validPath(int n, int[][] edges, int source, int destination) { + p = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + } + for (int[] e : edges) { + p[find(e[0])] = find(e[1]); + } + return find(source) == find(destination); + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} \ No newline at end of file diff --git a/solution/1900-1999/1971.Find if Path Exists in Graph/Solution2.py b/solution/1900-1999/1971.Find if Path Exists in Graph/Solution2.py new file mode 100644 index 0000000000000..a6d19f52c4fcd --- /dev/null +++ b/solution/1900-1999/1971.Find if Path Exists in Graph/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def validPath( + self, n: int, edges: List[List[int]], source: int, destination: int + ) -> bool: + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + p = list(range(n)) + for u, v in edges: + p[find(u)] = find(v) + return find(source) == find(destination) diff --git a/solution/1900-1999/1976.Number of Ways to Arrive at Destination/Solution.cpp b/solution/1900-1999/1976.Number of Ways to Arrive at Destination/Solution.cpp index 992670d72eec2..756619d01555d 100644 --- a/solution/1900-1999/1976.Number of Ways to Arrive at Destination/Solution.cpp +++ b/solution/1900-1999/1976.Number of Ways to Arrive at Destination/Solution.cpp @@ -1,39 +1,39 @@ -typedef long long ll; - -class Solution { -public: - const ll INF = LLONG_MAX / 2; - const int MOD = 1e9 + 7; - - int countPaths(int n, vector>& roads) { - vector> g(n, vector(n, INF)); - vector dist(n, INF); - vector w(n); - vector vis(n); - for (auto& r : roads) { - int u = r[0], v = r[1], t = r[2]; - g[u][v] = t; - g[v][u] = t; - } - g[0][0] = 0; - dist[0] = 0; - w[0] = 1; - for (int i = 0; i < n; ++i) { - int t = -1; - for (int j = 0; j < n; ++j) { - if (!vis[j] && (t == -1 || dist[t] > dist[j])) t = j; - } - vis[t] = true; - for (int j = 0; j < n; ++j) { - if (t == j) continue; - ll ne = dist[t] + g[t][j]; - if (dist[j] > ne) { - dist[j] = ne; - w[j] = w[t]; - } else if (dist[j] == ne) - w[j] = (w[j] + w[t]) % MOD; - } - } - return w[n - 1]; - } +typedef long long ll; + +class Solution { +public: + const ll INF = LLONG_MAX / 2; + const int MOD = 1e9 + 7; + + int countPaths(int n, vector>& roads) { + vector> g(n, vector(n, INF)); + vector dist(n, INF); + vector w(n); + vector vis(n); + for (auto& r : roads) { + int u = r[0], v = r[1], t = r[2]; + g[u][v] = t; + g[v][u] = t; + } + g[0][0] = 0; + dist[0] = 0; + w[0] = 1; + for (int i = 0; i < n; ++i) { + int t = -1; + for (int j = 0; j < n; ++j) { + if (!vis[j] && (t == -1 || dist[t] > dist[j])) t = j; + } + vis[t] = true; + for (int j = 0; j < n; ++j) { + if (t == j) continue; + ll ne = dist[t] + g[t][j]; + if (dist[j] > ne) { + dist[j] = ne; + w[j] = w[t]; + } else if (dist[j] == ne) + w[j] = (w[j] + w[t]) % MOD; + } + } + return w[n - 1]; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1976.Number of Ways to Arrive at Destination/Solution.java b/solution/1900-1999/1976.Number of Ways to Arrive at Destination/Solution.java index 3463d5ec40df6..d673b81148d3f 100644 --- a/solution/1900-1999/1976.Number of Ways to Arrive at Destination/Solution.java +++ b/solution/1900-1999/1976.Number of Ways to Arrive at Destination/Solution.java @@ -1,45 +1,45 @@ -class Solution { - private static final long INF = Long.MAX_VALUE / 2; - private static final int MOD = (int) 1e9 + 7; - - public int countPaths(int n, int[][] roads) { - long[][] g = new long[n][n]; - long[] dist = new long[n]; - long[] w = new long[n]; - boolean[] vis = new boolean[n]; - for (int i = 0; i < n; ++i) { - Arrays.fill(g[i], INF); - Arrays.fill(dist, INF); - } - for (int[] r : roads) { - int u = r[0], v = r[1], t = r[2]; - g[u][v] = t; - g[v][u] = t; - } - g[0][0] = 0; - dist[0] = 0; - w[0] = 1; - for (int i = 0; i < n; ++i) { - int t = -1; - for (int j = 0; j < n; ++j) { - if (!vis[j] && (t == -1 || dist[j] < dist[t])) { - t = j; - } - } - vis[t] = true; - for (int j = 0; j < n; ++j) { - if (j == t) { - continue; - } - long ne = dist[t] + g[t][j]; - if (dist[j] > ne) { - dist[j] = ne; - w[j] = w[t]; - } else if (dist[j] == ne) { - w[j] = (w[j] + w[t]) % MOD; - } - } - } - return (int) w[n - 1]; - } +class Solution { + private static final long INF = Long.MAX_VALUE / 2; + private static final int MOD = (int) 1e9 + 7; + + public int countPaths(int n, int[][] roads) { + long[][] g = new long[n][n]; + long[] dist = new long[n]; + long[] w = new long[n]; + boolean[] vis = new boolean[n]; + for (int i = 0; i < n; ++i) { + Arrays.fill(g[i], INF); + Arrays.fill(dist, INF); + } + for (int[] r : roads) { + int u = r[0], v = r[1], t = r[2]; + g[u][v] = t; + g[v][u] = t; + } + g[0][0] = 0; + dist[0] = 0; + w[0] = 1; + for (int i = 0; i < n; ++i) { + int t = -1; + for (int j = 0; j < n; ++j) { + if (!vis[j] && (t == -1 || dist[j] < dist[t])) { + t = j; + } + } + vis[t] = true; + for (int j = 0; j < n; ++j) { + if (j == t) { + continue; + } + long ne = dist[t] + g[t][j]; + if (dist[j] > ne) { + dist[j] = ne; + w[j] = w[t]; + } else if (dist[j] == ne) { + w[j] = (w[j] + w[t]) % MOD; + } + } + } + return (int) w[n - 1]; + } } \ No newline at end of file diff --git a/solution/1900-1999/1976.Number of Ways to Arrive at Destination/Solution.py b/solution/1900-1999/1976.Number of Ways to Arrive at Destination/Solution.py index a31c61cd34d8a..f1d670bf61d8c 100644 --- a/solution/1900-1999/1976.Number of Ways to Arrive at Destination/Solution.py +++ b/solution/1900-1999/1976.Number of Ways to Arrive at Destination/Solution.py @@ -1,30 +1,30 @@ -class Solution: - def countPaths(self, n: int, roads: List[List[int]]) -> int: - INF = inf - MOD = 10**9 + 7 - g = [[INF] * n for _ in range(n)] - for u, v, t in roads: - g[u][v] = t - g[v][u] = t - g[0][0] = 0 - dist = [INF] * n - w = [0] * n - dist[0] = 0 - w[0] = 1 - vis = [False] * n - for _ in range(n): - t = -1 - for i in range(n): - if not vis[i] and (t == -1 or dist[i] < dist[t]): - t = i - vis[t] = True - for i in range(n): - if i == t: - continue - ne = dist[t] + g[t][i] - if dist[i] > ne: - dist[i] = ne - w[i] = w[t] - elif dist[i] == ne: - w[i] += w[t] - return w[-1] % MOD +class Solution: + def countPaths(self, n: int, roads: List[List[int]]) -> int: + INF = inf + MOD = 10**9 + 7 + g = [[INF] * n for _ in range(n)] + for u, v, t in roads: + g[u][v] = t + g[v][u] = t + g[0][0] = 0 + dist = [INF] * n + w = [0] * n + dist[0] = 0 + w[0] = 1 + vis = [False] * n + for _ in range(n): + t = -1 + for i in range(n): + if not vis[i] and (t == -1 or dist[i] < dist[t]): + t = i + vis[t] = True + for i in range(n): + if i == t: + continue + ne = dist[t] + g[t][i] + if dist[i] > ne: + dist[i] = ne + w[i] = w[t] + elif dist[i] == ne: + w[i] += w[t] + return w[-1] % MOD diff --git a/solution/1900-1999/1978.Employees Whose Manager Left the Company/Solution2.sql b/solution/1900-1999/1978.Employees Whose Manager Left the Company/Solution2.sql new file mode 100644 index 0000000000000..c46396278f517 --- /dev/null +++ b/solution/1900-1999/1978.Employees Whose Manager Left the Company/Solution2.sql @@ -0,0 +1,5 @@ +# Write your MySQL query statement below +SELECT employee_id +FROM Employees +WHERE salary < 30000 AND manager_id NOT IN (SELECT employee_id FROM Employees) +ORDER BY 1; diff --git a/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/Solution.java b/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/Solution.java index fc8fbf863de36..29a820158575d 100644 --- a/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/Solution.java +++ b/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/Solution.java @@ -1,24 +1,19 @@ class Solution { public int minimizeTheDifference(int[][] mat, int target) { - boolean[] f = {true}; + Set f = new HashSet<>(); + f.add(0); for (var row : mat) { - int mx = 0; - for (int x : row) { - mx = Math.max(mx, x); - } - boolean[] g = new boolean[f.length + mx]; - for (int x : row) { - for (int j = x; j < f.length + x; ++j) { - g[j] |= f[j - x]; + Set g = new HashSet<>(); + for (int a : f) { + for (int b : row) { + g.add(a + b); } } f = g; } int ans = 1 << 30; - for (int j = 0; j < f.length; ++j) { - if (f[j]) { - ans = Math.min(ans, Math.abs(j - target)); - } + for (int v : f) { + ans = Math.min(ans, Math.abs(v - target)); } return ans; } diff --git a/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/Solution2.java b/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/Solution2.java new file mode 100644 index 0000000000000..fc8fbf863de36 --- /dev/null +++ b/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/Solution2.java @@ -0,0 +1,25 @@ +class Solution { + public int minimizeTheDifference(int[][] mat, int target) { + boolean[] f = {true}; + for (var row : mat) { + int mx = 0; + for (int x : row) { + mx = Math.max(mx, x); + } + boolean[] g = new boolean[f.length + mx]; + for (int x : row) { + for (int j = x; j < f.length + x; ++j) { + g[j] |= f[j - x]; + } + } + f = g; + } + int ans = 1 << 30; + for (int j = 0; j < f.length; ++j) { + if (f[j]) { + ans = Math.min(ans, Math.abs(j - target)); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1900-1999/1982.Find Array Given Subset Sums/Solution2.cpp b/solution/1900-1999/1982.Find Array Given Subset Sums/Solution2.cpp new file mode 100644 index 0000000000000..15f57d1312703 --- /dev/null +++ b/solution/1900-1999/1982.Find Array Given Subset Sums/Solution2.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + vector recoverArray(int n, vector& sums) { + sort(sums.begin(), sums.end()); + vector ans(n); + unordered_map cnt; + for (int i = n; i; --i) { + cnt.clear(); + int k = 1 << i; + int d = sums[k - 1] - sums[k - 2]; + for (int j = 0; j < k; ++j) { + cnt[sums[j]]++; + } + vector sums1, sums2; + int sign = 1; + for (int j = 0; j < k; ++j) { + if (cnt[sums[j]] == 0) { + continue; + } + --cnt[sums[j]]; + --cnt[sums[j] + d]; + sums1.push_back(sums[j]); + sums2.push_back(sums[j] + d); + if (sums2.back() == 0) { + sign = -1; + } + } + ans[i - 1] = sign * d; + for (int j = 0; j < k / 2; ++j) { + sums[j] = sign == 1 ? sums1[j] : sums2[j]; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1900-1999/1982.Find Array Given Subset Sums/Solution2.go b/solution/1900-1999/1982.Find Array Given Subset Sums/Solution2.go new file mode 100644 index 0000000000000..014d98155d08b --- /dev/null +++ b/solution/1900-1999/1982.Find Array Given Subset Sums/Solution2.go @@ -0,0 +1,31 @@ +func recoverArray(n int, sums []int) (ans []int) { + sort.Ints(sums) + for i := n; i > 0; i-- { + k := 1 << i + d := sums[k-1] - sums[k-2] + cnt := map[int]int{} + for _, s := range sums[:k] { + cnt[s]++ + } + sums1, sums2 := []int{}, []int{} + sign := 1 + for _, s := range sums[:k] { + if cnt[s] == 0 { + continue + } + cnt[s]-- + cnt[s+d]-- + sums1 = append(sums1, s) + sums2 = append(sums2, s+d) + if s+d == 0 { + sign = -1 + } + } + ans = append(ans, sign*d) + if sign == -1 { + sums1 = sums2 + } + sums = sums1 + } + return +} \ No newline at end of file diff --git a/solution/1900-1999/1982.Find Array Given Subset Sums/Solution2.java b/solution/1900-1999/1982.Find Array Given Subset Sums/Solution2.java new file mode 100644 index 0000000000000..eda766940be68 --- /dev/null +++ b/solution/1900-1999/1982.Find Array Given Subset Sums/Solution2.java @@ -0,0 +1,33 @@ +class Solution { + public int[] recoverArray(int n, int[] sums) { + Arrays.sort(sums); + int[] sums1 = new int[1 << n]; + int[] sums2 = new int[1 << n]; + Map cnt = new HashMap<>(); + int[] ans = new int[n]; + for (int i = n; i > 0; --i) { + int k = 1 << i; + int d = sums[k - 1] - sums[k - 2]; + cnt.clear(); + for (int j = 0; j < k; ++j) { + cnt.merge(sums[j], 1, Integer::sum); + } + int sign = 1; + for (int j = 0, p = 0; j < k; ++j) { + if (cnt.getOrDefault(sums[j], 0) == 0) { + continue; + } + cnt.merge(sums[j], -1, Integer::sum); + cnt.merge(sums[j] + d, -1, Integer::sum); + sums1[p] = sums[j]; + sums2[p++] = sums[j] + d; + if (sums[j] + d == 0) { + sign = -1; + } + } + ans[i - 1] = sign * d; + System.arraycopy(sign == 1 ? sums1 : sums2, 0, sums, 0, k / 2); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1900-1999/1982.Find Array Given Subset Sums/Solution2.py b/solution/1900-1999/1982.Find Array Given Subset Sums/Solution2.py new file mode 100644 index 0000000000000..dcdd70f12cbb3 --- /dev/null +++ b/solution/1900-1999/1982.Find Array Given Subset Sums/Solution2.py @@ -0,0 +1,22 @@ +class Solution: + def recoverArray(self, n: int, sums: List[int]) -> List[int]: + sums.sort() + ans = [] + for i in range(n, 0, -1): + k = 1 << i + d = sums[k - 1] - sums[k - 2] + cnt = Counter(sums[:k]) + sums1, sums2 = [], [] + sign = 1 + for s in sums[:k]: + if not cnt[s]: + continue + cnt[s] -= 1 + cnt[s + d] -= 1 + sums1.append(s) + sums2.append(s + d) + if s + d == 0: + sign = -1 + ans.append(sign * d) + sums = sums1 if sign == 1 else sums2 + return ans diff --git a/solution/1900-1999/1984.Minimum Difference Between Highest and Lowest of K Scores/Solution.php b/solution/1900-1999/1984.Minimum Difference Between Highest and Lowest of K Scores/Solution.php index 07202468b9eb0..adeb394b66538 100644 --- a/solution/1900-1999/1984.Minimum Difference Between Highest and Lowest of K Scores/Solution.php +++ b/solution/1900-1999/1984.Minimum Difference Between Highest and Lowest of K Scores/Solution.php @@ -12,4 +12,4 @@ function minimumDifference($nums, $k) { } return $rs; } -} \ No newline at end of file +} diff --git a/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/Solution.cpp b/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/Solution.cpp index e0b09d5684737..dc6c6517d04b2 100644 --- a/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/Solution.cpp +++ b/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/Solution.cpp @@ -1,28 +1,28 @@ -class Solution { -public: - int minSessions(vector& tasks, int sessionTime) { - int n = tasks.size(); - bool ok[1 << n]; - memset(ok, false, sizeof(ok)); - for (int i = 1; i < 1 << n; ++i) { - int t = 0; - for (int j = 0; j < n; ++j) { - if (i >> j & 1) { - t += tasks[j]; - } - } - ok[i] = t <= sessionTime; - } - int f[1 << n]; - memset(f, 0x3f, sizeof(f)); - f[0] = 0; - for (int i = 1; i < 1 << n; ++i) { - for (int j = i; j; j = (j - 1) & i) { - if (ok[j]) { - f[i] = min(f[i], f[i ^ j] + 1); - } - } - } - return f[(1 << n) - 1]; - } +class Solution { +public: + int minSessions(vector& tasks, int sessionTime) { + int n = tasks.size(); + bool ok[1 << n]; + memset(ok, false, sizeof(ok)); + for (int i = 1; i < 1 << n; ++i) { + int t = 0; + for (int j = 0; j < n; ++j) { + if (i >> j & 1) { + t += tasks[j]; + } + } + ok[i] = t <= sessionTime; + } + int f[1 << n]; + memset(f, 0x3f, sizeof(f)); + f[0] = 0; + for (int i = 1; i < 1 << n; ++i) { + for (int j = i; j; j = (j - 1) & i) { + if (ok[j]) { + f[i] = min(f[i], f[i ^ j] + 1); + } + } + } + return f[(1 << n) - 1]; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/Solution.java b/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/Solution.java index 8704ddc730846..05c8b1de66002 100644 --- a/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/Solution.java +++ b/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/Solution.java @@ -1,26 +1,26 @@ -class Solution { - public int minSessions(int[] tasks, int sessionTime) { - int n = tasks.length; - boolean[] ok = new boolean[1 << n]; - for (int i = 1; i < 1 << n; ++i) { - int t = 0; - for (int j = 0; j < n; ++j) { - if ((i >> j & 1) == 1) { - t += tasks[j]; - } - } - ok[i] = t <= sessionTime; - } - int[] f = new int[1 << n]; - Arrays.fill(f, 1 << 30); - f[0] = 0; - for (int i = 1; i < 1 << n; ++i) { - for (int j = i; j > 0; j = (j - 1) & i) { - if (ok[j]) { - f[i] = Math.min(f[i], f[i ^ j] + 1); - } - } - } - return f[(1 << n) - 1]; - } +class Solution { + public int minSessions(int[] tasks, int sessionTime) { + int n = tasks.length; + boolean[] ok = new boolean[1 << n]; + for (int i = 1; i < 1 << n; ++i) { + int t = 0; + for (int j = 0; j < n; ++j) { + if ((i >> j & 1) == 1) { + t += tasks[j]; + } + } + ok[i] = t <= sessionTime; + } + int[] f = new int[1 << n]; + Arrays.fill(f, 1 << 30); + f[0] = 0; + for (int i = 1; i < 1 << n; ++i) { + for (int j = i; j > 0; j = (j - 1) & i) { + if (ok[j]) { + f[i] = Math.min(f[i], f[i ^ j] + 1); + } + } + } + return f[(1 << n) - 1]; + } } \ No newline at end of file diff --git a/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/Solution.py b/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/Solution.py index bf8b450438248..a13adf9f8523b 100644 --- a/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/Solution.py +++ b/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/Solution.py @@ -1,16 +1,16 @@ -class Solution: - def minSessions(self, tasks: List[int], sessionTime: int) -> int: - n = len(tasks) - ok = [False] * (1 << n) - for i in range(1, 1 << n): - t = sum(tasks[j] for j in range(n) if i >> j & 1) - ok[i] = t <= sessionTime - f = [inf] * (1 << n) - f[0] = 0 - for i in range(1, 1 << n): - j = i - while j: - if ok[j]: - f[i] = min(f[i], f[i ^ j] + 1) - j = (j - 1) & i - return f[-1] +class Solution: + def minSessions(self, tasks: List[int], sessionTime: int) -> int: + n = len(tasks) + ok = [False] * (1 << n) + for i in range(1, 1 << n): + t = sum(tasks[j] for j in range(n) if i >> j & 1) + ok[i] = t <= sessionTime + f = [inf] * (1 << n) + f[0] = 0 + for i in range(1, 1 << n): + j = i + while j: + if ok[j]: + f[i] = min(f[i], f[i ^ j] + 1) + j = (j - 1) & i + return f[-1] diff --git a/solution/1900-1999/1987.Number of Unique Good Subsequences/Solution.cpp b/solution/1900-1999/1987.Number of Unique Good Subsequences/Solution.cpp index 730c6d767ac19..ad8102bdecdcc 100644 --- a/solution/1900-1999/1987.Number of Unique Good Subsequences/Solution.cpp +++ b/solution/1900-1999/1987.Number of Unique Good Subsequences/Solution.cpp @@ -1,18 +1,18 @@ -class Solution { -public: - int numberOfUniqueGoodSubsequences(string binary) { - const int mod = 1e9 + 7; - int f = 0, g = 0; - int ans = 0; - for (char& c : binary) { - if (c == '0') { - g = (g + f) % mod; - ans = 1; - } else { - f = (f + g + 1) % mod; - } - } - ans = (ans + f + g) % mod; - return ans; - } +class Solution { +public: + int numberOfUniqueGoodSubsequences(string binary) { + const int mod = 1e9 + 7; + int f = 0, g = 0; + int ans = 0; + for (char& c : binary) { + if (c == '0') { + g = (g + f) % mod; + ans = 1; + } else { + f = (f + g + 1) % mod; + } + } + ans = (ans + f + g) % mod; + return ans; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1987.Number of Unique Good Subsequences/Solution.java b/solution/1900-1999/1987.Number of Unique Good Subsequences/Solution.java index 6d4f11b81ca9b..5f5c3511a97d3 100644 --- a/solution/1900-1999/1987.Number of Unique Good Subsequences/Solution.java +++ b/solution/1900-1999/1987.Number of Unique Good Subsequences/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public int numberOfUniqueGoodSubsequences(String binary) { - final int mod = (int) 1e9 + 7; - int f = 0, g = 0; - int ans = 0; - for (int i = 0; i < binary.length(); ++i) { - if (binary.charAt(i) == '0') { - g = (g + f) % mod; - ans = 1; - } else { - f = (f + g + 1) % mod; - } - } - ans = (ans + f + g) % mod; - return ans; - } +class Solution { + public int numberOfUniqueGoodSubsequences(String binary) { + final int mod = (int) 1e9 + 7; + int f = 0, g = 0; + int ans = 0; + for (int i = 0; i < binary.length(); ++i) { + if (binary.charAt(i) == '0') { + g = (g + f) % mod; + ans = 1; + } else { + f = (f + g + 1) % mod; + } + } + ans = (ans + f + g) % mod; + return ans; + } } \ No newline at end of file diff --git a/solution/1900-1999/1987.Number of Unique Good Subsequences/Solution.py b/solution/1900-1999/1987.Number of Unique Good Subsequences/Solution.py index 75fd5d5823d4c..cb589010e62a4 100644 --- a/solution/1900-1999/1987.Number of Unique Good Subsequences/Solution.py +++ b/solution/1900-1999/1987.Number of Unique Good Subsequences/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def numberOfUniqueGoodSubsequences(self, binary: str) -> int: - f = g = 0 - ans = 0 - mod = 10**9 + 7 - for c in binary: - if c == "0": - g = (g + f) % mod - ans = 1 - else: - f = (f + g + 1) % mod - ans = (ans + f + g) % mod - return ans +class Solution: + def numberOfUniqueGoodSubsequences(self, binary: str) -> int: + f = g = 0 + ans = 0 + mod = 10**9 + 7 + for c in binary: + if c == "0": + g = (g + f) % mod + ans = 1 + else: + f = (f + g + 1) % mod + ans = (ans + f + g) % mod + return ans diff --git a/solution/1900-1999/1991.Find the Middle Index in Array/Solution.cpp b/solution/1900-1999/1991.Find the Middle Index in Array/Solution.cpp index 320953e6194d7..8c5da028e2197 100644 --- a/solution/1900-1999/1991.Find the Middle Index in Array/Solution.cpp +++ b/solution/1900-1999/1991.Find the Middle Index in Array/Solution.cpp @@ -1,14 +1,14 @@ -class Solution { -public: - int findMiddleIndex(vector& nums) { - int left = 0, right = accumulate(nums.begin(), nums.end(), 0); - for (int i = 0; i < nums.size(); ++i) { - right -= nums[i]; - if (left == right) { - return i; - } - left += nums[i]; - } - return -1; - } +class Solution { +public: + int findMiddleIndex(vector& nums) { + int left = 0, right = accumulate(nums.begin(), nums.end(), 0); + for (int i = 0; i < nums.size(); ++i) { + right -= nums[i]; + if (left == right) { + return i; + } + left += nums[i]; + } + return -1; + } }; \ No newline at end of file diff --git a/solution/1900-1999/1991.Find the Middle Index in Array/Solution.go b/solution/1900-1999/1991.Find the Middle Index in Array/Solution.go index 5f89db45afab1..58068c62e652f 100644 --- a/solution/1900-1999/1991.Find the Middle Index in Array/Solution.go +++ b/solution/1900-1999/1991.Find the Middle Index in Array/Solution.go @@ -1,14 +1,14 @@ func findMiddleIndex(nums []int) int { - var left, right int - for _, x := range nums { - right += x + s := 0 + for _, num := range nums { + s += num } - for i, x := range nums { - right -= x - if left == right { + total := 0 + for i, num := range nums { + total += num + if total-num == s-total { return i } - left += x } return -1 } \ No newline at end of file diff --git a/solution/1900-1999/1993.Operations on Tree/Solution.cpp b/solution/1900-1999/1993.Operations on Tree/Solution.cpp index 42a7ae932e319..58a36f139ded4 100644 --- a/solution/1900-1999/1993.Operations on Tree/Solution.cpp +++ b/solution/1900-1999/1993.Operations on Tree/Solution.cpp @@ -1,67 +1,67 @@ -class LockingTree { -public: - LockingTree(vector& parent) { - int n = parent.size(); - locked = vector(n, -1); - this->parent = parent; - children.resize(n); - for (int i = 1; i < n; ++i) { - children[parent[i]].push_back(i); - } - } - - bool lock(int num, int user) { - if (locked[num] == -1) { - locked[num] = user; - return true; - } - return false; - } - - bool unlock(int num, int user) { - if (locked[num] == user) { - locked[num] = -1; - return true; - } - return false; - } - - bool upgrade(int num, int user) { - int x = num; - while (x != -1) { - if (locked[x] != -1) { - return false; - } - x = parent[x]; - } - bool find = false; - function dfs = [&](int x) { - for (int y : children[x]) { - if (locked[y] != -1) { - find = true; - locked[y] = -1; - } - dfs(y); - } - }; - dfs(num); - if (!find) { - return false; - } - locked[num] = user; - return true; - } - -private: - vector locked; - vector parent; - vector> children; -}; - -/** - * Your LockingTree object will be instantiated and called as such: - * LockingTree* obj = new LockingTree(parent); - * bool param_1 = obj->lock(num,user); - * bool param_2 = obj->unlock(num,user); - * bool param_3 = obj->upgrade(num,user); +class LockingTree { +public: + LockingTree(vector& parent) { + int n = parent.size(); + locked = vector(n, -1); + this->parent = parent; + children.resize(n); + for (int i = 1; i < n; ++i) { + children[parent[i]].push_back(i); + } + } + + bool lock(int num, int user) { + if (locked[num] == -1) { + locked[num] = user; + return true; + } + return false; + } + + bool unlock(int num, int user) { + if (locked[num] == user) { + locked[num] = -1; + return true; + } + return false; + } + + bool upgrade(int num, int user) { + int x = num; + while (x != -1) { + if (locked[x] != -1) { + return false; + } + x = parent[x]; + } + bool find = false; + function dfs = [&](int x) { + for (int y : children[x]) { + if (locked[y] != -1) { + find = true; + locked[y] = -1; + } + dfs(y); + } + }; + dfs(num); + if (!find) { + return false; + } + locked[num] = user; + return true; + } + +private: + vector locked; + vector parent; + vector> children; +}; + +/** + * Your LockingTree object will be instantiated and called as such: + * LockingTree* obj = new LockingTree(parent); + * bool param_1 = obj->lock(num,user); + * bool param_2 = obj->unlock(num,user); + * bool param_3 = obj->upgrade(num,user); */ \ No newline at end of file diff --git a/solution/1900-1999/1993.Operations on Tree/Solution.java b/solution/1900-1999/1993.Operations on Tree/Solution.java index a1a69bed0e3d4..96054acb0c440 100644 --- a/solution/1900-1999/1993.Operations on Tree/Solution.java +++ b/solution/1900-1999/1993.Operations on Tree/Solution.java @@ -1,68 +1,68 @@ -class LockingTree { - private int[] locked; - private int[] parent; - private List[] children; - - public LockingTree(int[] parent) { - int n = parent.length; - locked = new int[n]; - this.parent = parent; - children = new List[n]; - Arrays.fill(locked, -1); - Arrays.setAll(children, i -> new ArrayList<>()); - for (int i = 1; i < n; i++) { - children[parent[i]].add(i); - } - } - - public boolean lock(int num, int user) { - if (locked[num] == -1) { - locked[num] = user; - return true; - } - return false; - } - - public boolean unlock(int num, int user) { - if (locked[num] == user) { - locked[num] = -1; - return true; - } - return false; - } - - public boolean upgrade(int num, int user) { - int x = num; - while (x != -1) { - if (locked[x] != -1) { - return false; - } - x = parent[x]; - } - boolean[] find = new boolean[1]; - dfs(num, find); - if (!find[0]) { - return false; - } - locked[num] = user; - return true; - } - - private void dfs(int x, boolean[] find) { - for (int y : children[x]) { - if (locked[y] != -1) { - locked[y] = -1; - find[0] = true; - } - dfs(y, find); - } - } -} - -/** - * Your LockingTree object will be instantiated and called as such: - * LockingTree obj = new LockingTree(parent); - * boolean param_1 = obj.lock(num,user); - * boolean param_2 = obj.unlock(num,user); - * boolean param_3 = obj.upgrade(num,user); +class LockingTree { + private int[] locked; + private int[] parent; + private List[] children; + + public LockingTree(int[] parent) { + int n = parent.length; + locked = new int[n]; + this.parent = parent; + children = new List[n]; + Arrays.fill(locked, -1); + Arrays.setAll(children, i -> new ArrayList<>()); + for (int i = 1; i < n; i++) { + children[parent[i]].add(i); + } + } + + public boolean lock(int num, int user) { + if (locked[num] == -1) { + locked[num] = user; + return true; + } + return false; + } + + public boolean unlock(int num, int user) { + if (locked[num] == user) { + locked[num] = -1; + return true; + } + return false; + } + + public boolean upgrade(int num, int user) { + int x = num; + while (x != -1) { + if (locked[x] != -1) { + return false; + } + x = parent[x]; + } + boolean[] find = new boolean[1]; + dfs(num, find); + if (!find[0]) { + return false; + } + locked[num] = user; + return true; + } + + private void dfs(int x, boolean[] find) { + for (int y : children[x]) { + if (locked[y] != -1) { + locked[y] = -1; + find[0] = true; + } + dfs(y, find); + } + } +} + +/** + * Your LockingTree object will be instantiated and called as such: + * LockingTree obj = new LockingTree(parent); + * boolean param_1 = obj.lock(num,user); + * boolean param_2 = obj.unlock(num,user); + * boolean param_3 = obj.upgrade(num,user); */ \ No newline at end of file diff --git a/solution/1900-1999/1993.Operations on Tree/Solution.py b/solution/1900-1999/1993.Operations on Tree/Solution.py index 1651edf54ae1b..5b7888d546c7d 100644 --- a/solution/1900-1999/1993.Operations on Tree/Solution.py +++ b/solution/1900-1999/1993.Operations on Tree/Solution.py @@ -1,49 +1,49 @@ -class LockingTree: - def __init__(self, parent: List[int]): - n = len(parent) - self.locked = [-1] * n - self.parent = parent - self.children = [[] for _ in range(n)] - for son, fa in enumerate(parent[1:], 1): - self.children[fa].append(son) - - def lock(self, num: int, user: int) -> bool: - if self.locked[num] == -1: - self.locked[num] = user - return True - return False - - def unlock(self, num: int, user: int) -> bool: - if self.locked[num] == user: - self.locked[num] = -1 - return True - return False - - def upgrade(self, num: int, user: int) -> bool: - def dfs(x: int): - nonlocal find - for y in self.children[x]: - if self.locked[y] != -1: - self.locked[y] = -1 - find = True - dfs(y) - - x = num - while x != -1: - if self.locked[x] != -1: - return False - x = self.parent[x] - - find = False - dfs(num) - if not find: - return False - self.locked[num] = user - return True - - -# Your LockingTree object will be instantiated and called as such: -# obj = LockingTree(parent) -# param_1 = obj.lock(num,user) -# param_2 = obj.unlock(num,user) -# param_3 = obj.upgrade(num,user) +class LockingTree: + def __init__(self, parent: List[int]): + n = len(parent) + self.locked = [-1] * n + self.parent = parent + self.children = [[] for _ in range(n)] + for son, fa in enumerate(parent[1:], 1): + self.children[fa].append(son) + + def lock(self, num: int, user: int) -> bool: + if self.locked[num] == -1: + self.locked[num] = user + return True + return False + + def unlock(self, num: int, user: int) -> bool: + if self.locked[num] == user: + self.locked[num] = -1 + return True + return False + + def upgrade(self, num: int, user: int) -> bool: + def dfs(x: int): + nonlocal find + for y in self.children[x]: + if self.locked[y] != -1: + self.locked[y] = -1 + find = True + dfs(y) + + x = num + while x != -1: + if self.locked[x] != -1: + return False + x = self.parent[x] + + find = False + dfs(num) + if not find: + return False + self.locked[num] = user + return True + + +# Your LockingTree object will be instantiated and called as such: +# obj = LockingTree(parent) +# param_1 = obj.lock(num,user) +# param_2 = obj.unlock(num,user) +# param_3 = obj.upgrade(num,user) diff --git a/solution/1900-1999/1995.Count Special Quadruplets/Solution.cpp b/solution/1900-1999/1995.Count Special Quadruplets/Solution.cpp index 1e682d8fecbd5..82e9c71b1dfbc 100644 --- a/solution/1900-1999/1995.Count Special Quadruplets/Solution.cpp +++ b/solution/1900-1999/1995.Count Special Quadruplets/Solution.cpp @@ -2,18 +2,11 @@ class Solution { public: int countQuadruplets(vector& nums) { int ans = 0, n = nums.size(); - vector counter(310); - for (int b = n - 3; b > 0; --b) { - int c = b + 1; - for (int d = c + 1; d < n; ++d) { - if (nums[d] - nums[c] >= 0) { - ++counter[nums[d] - nums[c]]; - } - } - for (int a = 0; a < b; ++a) { - ans += counter[nums[a] + nums[b]]; - } - } + for (int a = 0; a < n - 3; ++a) + for (int b = a + 1; b < n - 2; ++b) + for (int c = b + 1; c < n - 1; ++c) + for (int d = c + 1; d < n; ++d) + if (nums[a] + nums[b] + nums[c] == nums[d]) ++ans; return ans; } }; \ No newline at end of file diff --git a/solution/1900-1999/1995.Count Special Quadruplets/Solution.go b/solution/1900-1999/1995.Count Special Quadruplets/Solution.go index cae98bf22eae5..dc1d5219d21ef 100644 --- a/solution/1900-1999/1995.Count Special Quadruplets/Solution.go +++ b/solution/1900-1999/1995.Count Special Quadruplets/Solution.go @@ -1,16 +1,15 @@ func countQuadruplets(nums []int) int { ans, n := 0, len(nums) - counter := make([]int, 310) - for b := n - 3; b > 0; b-- { - c := b + 1 - for d := c + 1; d < n; d++ { - if nums[d] >= nums[c] { - counter[nums[d]-nums[c]]++ + for a := 0; a < n-3; a++ { + for b := a + 1; b < n-2; b++ { + for c := b + 1; c < n-1; c++ { + for d := c + 1; d < n; d++ { + if nums[a]+nums[b]+nums[c] == nums[d] { + ans++ + } + } } } - for a := 0; a < b; a++ { - ans += counter[nums[a]+nums[b]] - } } return ans } \ No newline at end of file diff --git a/solution/1900-1999/1995.Count Special Quadruplets/Solution.java b/solution/1900-1999/1995.Count Special Quadruplets/Solution.java index c75cf929630dd..379883e98e9b5 100644 --- a/solution/1900-1999/1995.Count Special Quadruplets/Solution.java +++ b/solution/1900-1999/1995.Count Special Quadruplets/Solution.java @@ -1,17 +1,16 @@ class Solution { public int countQuadruplets(int[] nums) { int ans = 0, n = nums.length; - int[] counter = new int[310]; - for (int b = n - 3; b > 0; --b) { - int c = b + 1; - for (int d = c + 1; d < n; ++d) { - if (nums[d] - nums[c] >= 0) { - ++counter[nums[d] - nums[c]]; + for (int a = 0; a < n - 3; ++a) { + for (int b = a + 1; b < n - 2; ++b) { + for (int c = b + 1; c < n - 1; ++c) { + for (int d = c + 1; d < n; ++d) { + if (nums[a] + nums[b] + nums[c] == nums[d]) { + ++ans; + } + } } } - for (int a = 0; a < b; ++a) { - ans += counter[nums[a] + nums[b]]; - } } return ans; } diff --git a/solution/1900-1999/1995.Count Special Quadruplets/Solution.py b/solution/1900-1999/1995.Count Special Quadruplets/Solution.py index 7028e9b14dd52..3a389e3fb1e67 100644 --- a/solution/1900-1999/1995.Count Special Quadruplets/Solution.py +++ b/solution/1900-1999/1995.Count Special Quadruplets/Solution.py @@ -1,11 +1,10 @@ class Solution: def countQuadruplets(self, nums: List[int]) -> int: ans, n = 0, len(nums) - counter = Counter() - for b in range(n - 3, 0, -1): - c = b + 1 - for d in range(c + 1, n): - counter[nums[d] - nums[c]] += 1 - for a in range(b): - ans += counter[nums[a] + nums[b]] + for a in range(n - 3): + for b in range(a + 1, n - 2): + for c in range(b + 1, n - 1): + for d in range(c + 1, n): + if nums[a] + nums[b] + nums[c] == nums[d]: + ans += 1 return ans diff --git a/solution/1900-1999/1995.Count Special Quadruplets/Solution2.cpp b/solution/1900-1999/1995.Count Special Quadruplets/Solution2.cpp new file mode 100644 index 0000000000000..c1b810b23da3f --- /dev/null +++ b/solution/1900-1999/1995.Count Special Quadruplets/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int countQuadruplets(vector& nums) { + int ans = 0, n = nums.size(); + vector counter(310); + for (int c = n - 2; c > 1; --c) { + ++counter[nums[c + 1]]; + for (int a = 0; a < c - 1; ++a) { + for (int b = a + 1; b < c; ++b) { + ans += counter[nums[a] + nums[b] + nums[c]]; + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1900-1999/1995.Count Special Quadruplets/Solution2.go b/solution/1900-1999/1995.Count Special Quadruplets/Solution2.go new file mode 100644 index 0000000000000..892b1b6d241a7 --- /dev/null +++ b/solution/1900-1999/1995.Count Special Quadruplets/Solution2.go @@ -0,0 +1,13 @@ +func countQuadruplets(nums []int) int { + ans, n := 0, len(nums) + counter := make([]int, 310) + for c := n - 2; c > 1; c-- { + counter[nums[c+1]]++ + for a := 0; a < c-1; a++ { + for b := a + 1; b < c; b++ { + ans += counter[nums[a]+nums[b]+nums[c]] + } + } + } + return ans +} \ No newline at end of file diff --git a/solution/1900-1999/1995.Count Special Quadruplets/Solution2.java b/solution/1900-1999/1995.Count Special Quadruplets/Solution2.java new file mode 100644 index 0000000000000..859a2c70069e5 --- /dev/null +++ b/solution/1900-1999/1995.Count Special Quadruplets/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public int countQuadruplets(int[] nums) { + int ans = 0, n = nums.length; + int[] counter = new int[310]; + for (int c = n - 2; c > 1; --c) { + ++counter[nums[c + 1]]; + for (int a = 0; a < c - 1; ++a) { + for (int b = a + 1; b < c; ++b) { + ans += counter[nums[a] + nums[b] + nums[c]]; + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1900-1999/1995.Count Special Quadruplets/Solution2.py b/solution/1900-1999/1995.Count Special Quadruplets/Solution2.py new file mode 100644 index 0000000000000..8f00a5958bf20 --- /dev/null +++ b/solution/1900-1999/1995.Count Special Quadruplets/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def countQuadruplets(self, nums: List[int]) -> int: + ans, n = 0, len(nums) + counter = Counter() + for c in range(n - 2, 1, -1): + counter[nums[c + 1]] += 1 + for a in range(c - 1): + for b in range(a + 1, c): + ans += counter[nums[a] + nums[b] + nums[c]] + return ans diff --git a/solution/1900-1999/1995.Count Special Quadruplets/Solution3.cpp b/solution/1900-1999/1995.Count Special Quadruplets/Solution3.cpp new file mode 100644 index 0000000000000..1e682d8fecbd5 --- /dev/null +++ b/solution/1900-1999/1995.Count Special Quadruplets/Solution3.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int countQuadruplets(vector& nums) { + int ans = 0, n = nums.size(); + vector counter(310); + for (int b = n - 3; b > 0; --b) { + int c = b + 1; + for (int d = c + 1; d < n; ++d) { + if (nums[d] - nums[c] >= 0) { + ++counter[nums[d] - nums[c]]; + } + } + for (int a = 0; a < b; ++a) { + ans += counter[nums[a] + nums[b]]; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1900-1999/1995.Count Special Quadruplets/Solution3.go b/solution/1900-1999/1995.Count Special Quadruplets/Solution3.go new file mode 100644 index 0000000000000..cae98bf22eae5 --- /dev/null +++ b/solution/1900-1999/1995.Count Special Quadruplets/Solution3.go @@ -0,0 +1,16 @@ +func countQuadruplets(nums []int) int { + ans, n := 0, len(nums) + counter := make([]int, 310) + for b := n - 3; b > 0; b-- { + c := b + 1 + for d := c + 1; d < n; d++ { + if nums[d] >= nums[c] { + counter[nums[d]-nums[c]]++ + } + } + for a := 0; a < b; a++ { + ans += counter[nums[a]+nums[b]] + } + } + return ans +} \ No newline at end of file diff --git a/solution/1900-1999/1995.Count Special Quadruplets/Solution3.java b/solution/1900-1999/1995.Count Special Quadruplets/Solution3.java new file mode 100644 index 0000000000000..c75cf929630dd --- /dev/null +++ b/solution/1900-1999/1995.Count Special Quadruplets/Solution3.java @@ -0,0 +1,18 @@ +class Solution { + public int countQuadruplets(int[] nums) { + int ans = 0, n = nums.length; + int[] counter = new int[310]; + for (int b = n - 3; b > 0; --b) { + int c = b + 1; + for (int d = c + 1; d < n; ++d) { + if (nums[d] - nums[c] >= 0) { + ++counter[nums[d] - nums[c]]; + } + } + for (int a = 0; a < b; ++a) { + ans += counter[nums[a] + nums[b]]; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1900-1999/1995.Count Special Quadruplets/Solution3.py b/solution/1900-1999/1995.Count Special Quadruplets/Solution3.py new file mode 100644 index 0000000000000..7028e9b14dd52 --- /dev/null +++ b/solution/1900-1999/1995.Count Special Quadruplets/Solution3.py @@ -0,0 +1,11 @@ +class Solution: + def countQuadruplets(self, nums: List[int]) -> int: + ans, n = 0, len(nums) + counter = Counter() + for b in range(n - 3, 0, -1): + c = b + 1 + for d in range(c + 1, n): + counter[nums[d] - nums[c]] += 1 + for a in range(b): + ans += counter[nums[a] + nums[b]] + return ans diff --git a/solution/2000-2099/2000.Reverse Prefix of Word/Solution.php b/solution/2000-2099/2000.Reverse Prefix of Word/Solution.php index 71069b4168ad5..38c92b0c566d0 100644 --- a/solution/2000-2099/2000.Reverse Prefix of Word/Solution.php +++ b/solution/2000-2099/2000.Reverse Prefix of Word/Solution.php @@ -20,4 +20,4 @@ function reversePrefix($word, $ch) { $rs = $rs . substr($word, strlen($rs)); return $rs; } -} \ No newline at end of file +} diff --git a/solution/2000-2099/2000.Reverse Prefix of Word/Solution2.java b/solution/2000-2099/2000.Reverse Prefix of Word/Solution2.java new file mode 100644 index 0000000000000..e476d26a7a3b1 --- /dev/null +++ b/solution/2000-2099/2000.Reverse Prefix of Word/Solution2.java @@ -0,0 +1,12 @@ +class Solution { + public String reversePrefix(String word, char ch) { + int j = word.indexOf(ch); + if (j == -1) { + return word; + } + return new StringBuilder(word.substring(0, j + 1)) + .reverse() + .append(word.substring(j + 1)) + .toString(); + } +} \ No newline at end of file diff --git a/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/Solution.cpp b/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/Solution.cpp index 1b537341d88b0..05a3404eb3be1 100644 --- a/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/Solution.cpp +++ b/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/Solution.cpp @@ -1,44 +1,44 @@ -class Solution { -public: - vector smallestMissingValueSubtree(vector& parents, vector& nums) { - int n = nums.size(); - vector g[n]; - bool vis[n]; - bool has[n + 2]; - memset(vis, false, sizeof(vis)); - memset(has, false, sizeof(has)); - int idx = -1; - for (int i = 0; i < n; ++i) { - if (i) { - g[parents[i]].push_back(i); - } - if (nums[i] == 1) { - idx = i; - } - } - vector ans(n, 1); - if (idx == -1) { - return ans; - } - function dfs = [&](int i) { - if (vis[i]) { - return; - } - vis[i] = true; - if (nums[i] < n + 2) { - has[nums[i]] = true; - } - for (int j : g[i]) { - dfs(j); - } - }; - for (int i = 2; ~idx; idx = parents[idx]) { - dfs(idx); - while (has[i]) { - ++i; - } - ans[idx] = i; - } - return ans; - } +class Solution { +public: + vector smallestMissingValueSubtree(vector& parents, vector& nums) { + int n = nums.size(); + vector g[n]; + bool vis[n]; + bool has[n + 2]; + memset(vis, false, sizeof(vis)); + memset(has, false, sizeof(has)); + int idx = -1; + for (int i = 0; i < n; ++i) { + if (i) { + g[parents[i]].push_back(i); + } + if (nums[i] == 1) { + idx = i; + } + } + vector ans(n, 1); + if (idx == -1) { + return ans; + } + function dfs = [&](int i) { + if (vis[i]) { + return; + } + vis[i] = true; + if (nums[i] < n + 2) { + has[nums[i]] = true; + } + for (int j : g[i]) { + dfs(j); + } + }; + for (int i = 2; ~idx; idx = parents[idx]) { + dfs(idx); + while (has[i]) { + ++i; + } + ans[idx] = i; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/Solution.java b/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/Solution.java index 147e270be32ef..556c1fc4399d6 100644 --- a/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/Solution.java +++ b/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/Solution.java @@ -1,50 +1,50 @@ -class Solution { - private List[] g; - private boolean[] vis; - private boolean[] has; - private int[] nums; - - public int[] smallestMissingValueSubtree(int[] parents, int[] nums) { - int n = nums.length; - this.nums = nums; - g = new List[n]; - vis = new boolean[n]; - has = new boolean[n + 2]; - Arrays.setAll(g, i -> new ArrayList<>()); - int idx = -1; - for (int i = 0; i < n; ++i) { - if (i > 0) { - g[parents[i]].add(i); - } - if (nums[i] == 1) { - idx = i; - } - } - int[] ans = new int[n]; - Arrays.fill(ans, 1); - if (idx == -1) { - return ans; - } - for (int i = 2; idx != -1; idx = parents[idx]) { - dfs(idx); - while (has[i]) { - ++i; - } - ans[idx] = i; - } - return ans; - } - - private void dfs(int i) { - if (vis[i]) { - return; - } - vis[i] = true; - if (nums[i] < has.length) { - has[nums[i]] = true; - } - for (int j : g[i]) { - dfs(j); - } - } +class Solution { + private List[] g; + private boolean[] vis; + private boolean[] has; + private int[] nums; + + public int[] smallestMissingValueSubtree(int[] parents, int[] nums) { + int n = nums.length; + this.nums = nums; + g = new List[n]; + vis = new boolean[n]; + has = new boolean[n + 2]; + Arrays.setAll(g, i -> new ArrayList<>()); + int idx = -1; + for (int i = 0; i < n; ++i) { + if (i > 0) { + g[parents[i]].add(i); + } + if (nums[i] == 1) { + idx = i; + } + } + int[] ans = new int[n]; + Arrays.fill(ans, 1); + if (idx == -1) { + return ans; + } + for (int i = 2; idx != -1; idx = parents[idx]) { + dfs(idx); + while (has[i]) { + ++i; + } + ans[idx] = i; + } + return ans; + } + + private void dfs(int i) { + if (vis[i]) { + return; + } + vis[i] = true; + if (nums[i] < has.length) { + has[nums[i]] = true; + } + for (int j : g[i]) { + dfs(j); + } + } } \ No newline at end of file diff --git a/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/Solution.py b/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/Solution.py index 2f3ffd9114ac3..e7187ed19e88f 100644 --- a/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/Solution.py +++ b/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/Solution.py @@ -1,34 +1,34 @@ -class Solution: - def smallestMissingValueSubtree( - self, parents: List[int], nums: List[int] - ) -> List[int]: - def dfs(i: int): - if vis[i]: - return - vis[i] = True - if nums[i] < len(has): - has[nums[i]] = True - for j in g[i]: - dfs(j) - - n = len(nums) - ans = [1] * n - g = [[] for _ in range(n)] - idx = -1 - for i, p in enumerate(parents): - if i: - g[p].append(i) - if nums[i] == 1: - idx = i - if idx == -1: - return ans - vis = [False] * n - has = [False] * (n + 2) - i = 2 - while idx != -1: - dfs(idx) - while has[i]: - i += 1 - ans[idx] = i - idx = parents[idx] - return ans +class Solution: + def smallestMissingValueSubtree( + self, parents: List[int], nums: List[int] + ) -> List[int]: + def dfs(i: int): + if vis[i]: + return + vis[i] = True + if nums[i] < len(has): + has[nums[i]] = True + for j in g[i]: + dfs(j) + + n = len(nums) + ans = [1] * n + g = [[] for _ in range(n)] + idx = -1 + for i, p in enumerate(parents): + if i: + g[p].append(i) + if nums[i] == 1: + idx = i + if idx == -1: + return ans + vis = [False] * n + has = [False] * (n + 2) + i = 2 + while idx != -1: + dfs(idx) + while has[i]: + i += 1 + ans[idx] = i + idx = parents[idx] + return ans diff --git a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.cpp b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.cpp index 96d4107c4dfe3..13e509d25aadb 100644 --- a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.cpp +++ b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.cpp @@ -1,16 +1,12 @@ class Solution { public: int countKDifference(vector& nums, int k) { + int n = nums.size(); int ans = 0; - int cnt[110]{}; - for (int num : nums) { - if (num >= k) { - ans += cnt[num - k]; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + ans += abs(nums[i] - nums[j]) == k; } - if (num + k <= 100) { - ans += cnt[num + k]; - } - ++cnt[num]; } return ans; } diff --git a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.go b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.go index b1430429b39b9..784bc9b522719 100644 --- a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.go +++ b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.go @@ -1,13 +1,19 @@ -func countKDifference(nums []int, k int) (ans int) { - cnt := [110]int{} - for _, num := range nums { - if num >= k { - ans += cnt[num-k] +func countKDifference(nums []int, k int) int { + n := len(nums) + ans := 0 + for i := 0; i < n; i++ { + for j := i + 1; j < n; j++ { + if abs(nums[i]-nums[j]) == k { + ans++ + } } - if num+k <= 100 { - ans += cnt[num+k] - } - cnt[num]++ } - return + return ans +} + +func abs(x int) int { + if x > 0 { + return x + } + return -x } \ No newline at end of file diff --git a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.java b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.java index 2cca9224382cd..dfcff3bafe5d8 100644 --- a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.java +++ b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.java @@ -1,15 +1,12 @@ class Solution { public int countKDifference(int[] nums, int k) { int ans = 0; - int[] cnt = new int[110]; - for (int num : nums) { - if (num >= k) { - ans += cnt[num - k]; + for (int i = 0, n = nums.length; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + if (Math.abs(nums[i] - nums[j]) == k) { + ++ans; + } } - if (num + k <= 100) { - ans += cnt[num + k]; - } - ++cnt[num]; } return ans; } diff --git a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.py b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.py index fc27cb88a4895..e39996f067b4a 100644 --- a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.py +++ b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.py @@ -1,8 +1,6 @@ class Solution: def countKDifference(self, nums: List[int], k: int) -> int: - ans = 0 - cnt = Counter() - for num in nums: - ans += cnt[num - k] + cnt[num + k] - cnt[num] += 1 - return ans + n = len(nums) + return sum( + abs(nums[i] - nums[j]) == k for i in range(n) for j in range(i + 1, n) + ) diff --git a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.rs b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.rs index 3bf3edbc1e5f1..5d852a5a57f30 100644 --- a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.rs +++ b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution.rs @@ -1,15 +1,13 @@ impl Solution { pub fn count_k_difference(nums: Vec, k: i32) -> i32 { - let mut arr = [0; 101]; let mut res = 0; - for num in nums { - if num - k >= 1 { - res += arr[(num - k) as usize]; + let n = nums.len(); + for i in 0..n - 1 { + for j in i..n { + if (nums[i] - nums[j]).abs() == k { + res += 1; + } } - if num + k <= 100 { - res += arr[(num + k) as usize]; - } - arr[num as usize] += 1; } res } diff --git a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution2.cpp b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution2.cpp new file mode 100644 index 0000000000000..96d4107c4dfe3 --- /dev/null +++ b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int countKDifference(vector& nums, int k) { + int ans = 0; + int cnt[110]{}; + for (int num : nums) { + if (num >= k) { + ans += cnt[num - k]; + } + if (num + k <= 100) { + ans += cnt[num + k]; + } + ++cnt[num]; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution2.go b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution2.go new file mode 100644 index 0000000000000..b1430429b39b9 --- /dev/null +++ b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution2.go @@ -0,0 +1,13 @@ +func countKDifference(nums []int, k int) (ans int) { + cnt := [110]int{} + for _, num := range nums { + if num >= k { + ans += cnt[num-k] + } + if num+k <= 100 { + ans += cnt[num+k] + } + cnt[num]++ + } + return +} \ No newline at end of file diff --git a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution2.java b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution2.java new file mode 100644 index 0000000000000..2cca9224382cd --- /dev/null +++ b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public int countKDifference(int[] nums, int k) { + int ans = 0; + int[] cnt = new int[110]; + for (int num : nums) { + if (num >= k) { + ans += cnt[num - k]; + } + if (num + k <= 100) { + ans += cnt[num + k]; + } + ++cnt[num]; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution2.py b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution2.py new file mode 100644 index 0000000000000..fc27cb88a4895 --- /dev/null +++ b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def countKDifference(self, nums: List[int], k: int) -> int: + ans = 0 + cnt = Counter() + for num in nums: + ans += cnt[num - k] + cnt[num + k] + cnt[num] += 1 + return ans diff --git a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution2.rs b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution2.rs new file mode 100644 index 0000000000000..3bf3edbc1e5f1 --- /dev/null +++ b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution2.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn count_k_difference(nums: Vec, k: i32) -> i32 { + let mut arr = [0; 101]; + let mut res = 0; + for num in nums { + if num - k >= 1 { + res += arr[(num - k) as usize]; + } + if num + k <= 100 { + res += arr[(num + k) as usize]; + } + arr[num as usize] += 1; + } + res + } +} diff --git a/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.cpp b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.cpp index f67003f8e1869..f38c485c55137 100644 --- a/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.cpp +++ b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.cpp @@ -1,16 +1,22 @@ -class Solution { -public: - long long maxTaxiEarnings(int n, vector>& rides) { - sort(rides.begin(), rides.end(), [](const vector& a, const vector& b) { return a[1] < b[1]; }); - int m = rides.size(); - vector f(m + 1); - for (int i = 1; i <= m; ++i) { - auto& r = rides[i - 1]; - int st = r[0], ed = r[1], tip = r[2]; - auto it = lower_bound(rides.begin(), rides.begin() + i, st + 1, [](auto& a, int val) { return a[1] < val; }); - int j = distance(rides.begin(), it); - f[i] = max(f[i - 1], f[j] + ed - st + tip); - } - return f.back(); - } +class Solution { +public: + long long maxTaxiEarnings(int n, vector>& rides) { + sort(rides.begin(), rides.end()); + int m = rides.size(); + long long f[m]; + memset(f, -1, sizeof(f)); + function dfs = [&](int i) -> long long { + if (i >= m) { + return 0; + } + if (f[i] != -1) { + return f[i]; + } + auto& r = rides[i]; + int st = r[0], ed = r[1], tip = r[2]; + int j = lower_bound(rides.begin() + i + 1, rides.end(), ed, [](auto& a, int val) { return a[0] < val; }) - rides.begin(); + return f[i] = max(dfs(i + 1), dfs(j) + ed - st + tip); + }; + return dfs(0); + } }; \ No newline at end of file diff --git a/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.go b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.go index bba18926713b4..349c9f8dd2e88 100644 --- a/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.go +++ b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.go @@ -1,12 +1,18 @@ func maxTaxiEarnings(n int, rides [][]int) int64 { - sort.Slice(rides, func(i, j int) bool { return rides[i][1] < rides[j][1] }) + sort.Slice(rides, func(i, j int) bool { return rides[i][0] < rides[j][0] }) m := len(rides) - f := make([]int64, m+1) - for i := 1; i <= m; i++ { - r := rides[i-1] - st, ed, tip := r[0], r[1], r[2] - j := sort.Search(m, func(j int) bool { return rides[j][1] >= st+1 }) - f[i] = max(f[i-1], f[j]+int64(ed-st+tip)) + f := make([]int64, m) + var dfs func(int) int64 + dfs = func(i int) int64 { + if i >= m { + return 0 + } + if f[i] == 0 { + st, ed, tip := rides[i][0], rides[i][1], rides[i][2] + j := sort.Search(m, func(j int) bool { return rides[j][0] >= ed }) + f[i] = max(dfs(i+1), int64(ed-st+tip)+dfs(j)) + } + return f[i] } - return f[m] + return dfs(0) } \ No newline at end of file diff --git a/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.java b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.java index d9f0eb55c3268..6f08a16f1cb60 100644 --- a/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.java +++ b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.java @@ -1,27 +1,39 @@ -class Solution { - public long maxTaxiEarnings(int n, int[][] rides) { - Arrays.sort(rides, (a, b) -> a[1] - b[1]); - int m = rides.length; - long[] f = new long[m + 1]; - for (int i = 1; i <= m; ++i) { - int[] r = rides[i - 1]; - int st = r[0], ed = r[1], tip = r[2]; - int j = search(rides, st + 1, i); - f[i] = Math.max(f[i - 1], f[j] + ed - st + tip); - } - return f[m]; - } - - private int search(int[][] nums, int x, int r) { - int l = 0; - while (l < r) { - int mid = (l + r) >> 1; - if (nums[mid][1] >= x) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } +class Solution { + private int m; + private int[][] rides; + private Long[] f; + + public long maxTaxiEarnings(int n, int[][] rides) { + Arrays.sort(rides, (a, b) -> a[0] - b[0]); + m = rides.length; + f = new Long[m]; + this.rides = rides; + return dfs(0); + } + + private long dfs(int i) { + if (i >= m) { + return 0; + } + if (f[i] != null) { + return f[i]; + } + int[] r = rides[i]; + int st = r[0], ed = r[1], tip = r[2]; + int j = search(ed, i + 1); + return f[i] = Math.max(dfs(i + 1), dfs(j) + ed - st + tip); + } + + private int search(int x, int l) { + int r = m; + while (l < r) { + int mid = (l + r) >> 1; + if (rides[mid][0] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } } \ No newline at end of file diff --git a/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.py b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.py index 8826e9a8b17be..b92ca27653501 100644 --- a/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.py +++ b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.py @@ -1,8 +1,12 @@ -class Solution: - def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: - rides.sort(key=lambda x: x[1]) - f = [0] * (len(rides) + 1) - for i, (st, ed, tip) in enumerate(rides, 1): - j = bisect_left(rides, st + 1, hi=i, key=lambda x: x[1]) - f[i] = max(f[i - 1], f[j] + ed - st + tip) - return f[-1] +class Solution: + def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: + @cache + def dfs(i: int) -> int: + if i >= len(rides): + return 0 + st, ed, tip = rides[i] + j = bisect_left(rides, ed, lo=i + 1, key=lambda x: x[0]) + return max(dfs(i + 1), dfs(j) + ed - st + tip) + + rides.sort() + return dfs(0) diff --git a/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.ts b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.ts index ae8373962a778..c23065e9200be 100644 --- a/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.ts +++ b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.ts @@ -1,12 +1,12 @@ function maxTaxiEarnings(n: number, rides: number[][]): number { - rides.sort((a, b) => a[1] - b[1]); + rides.sort((a, b) => a[0] - b[0]); const m = rides.length; - const f: number[] = Array(m + 1).fill(0); - const search = (x: number, r: number): number => { - let l = 0; + const f: number[] = Array(m).fill(-1); + const search = (x: number, l: number): number => { + let r = m; while (l < r) { const mid = (l + r) >> 1; - if (rides[mid][1] >= x) { + if (rides[mid][0] >= x) { r = mid; } else { l = mid + 1; @@ -14,10 +14,16 @@ function maxTaxiEarnings(n: number, rides: number[][]): number { } return l; }; - for (let i = 1; i <= m; ++i) { - const [st, ed, tip] = rides[i - 1]; - const j = search(st + 1, i); - f[i] = Math.max(f[i - 1], f[j] + ed - st + tip); - } - return f[m]; + const dfs = (i: number): number => { + if (i >= m) { + return 0; + } + if (f[i] === -1) { + const [st, ed, tip] = rides[i]; + const j = search(ed, i + 1); + f[i] = Math.max(dfs(i + 1), dfs(j) + ed - st + tip); + } + return f[i]; + }; + return dfs(0); } diff --git a/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution2.cpp b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution2.cpp new file mode 100644 index 0000000000000..4d4ea76ed6b42 --- /dev/null +++ b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + long long maxTaxiEarnings(int n, vector>& rides) { + sort(rides.begin(), rides.end(), [](const vector& a, const vector& b) { return a[1] < b[1]; }); + int m = rides.size(); + vector f(m + 1); + for (int i = 1; i <= m; ++i) { + auto& r = rides[i - 1]; + int st = r[0], ed = r[1], tip = r[2]; + auto it = lower_bound(rides.begin(), rides.begin() + i, st + 1, [](auto& a, int val) { return a[1] < val; }); + int j = distance(rides.begin(), it); + f[i] = max(f[i - 1], f[j] + ed - st + tip); + } + return f.back(); + } +}; \ No newline at end of file diff --git a/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution2.go b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution2.go new file mode 100644 index 0000000000000..bba18926713b4 --- /dev/null +++ b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution2.go @@ -0,0 +1,12 @@ +func maxTaxiEarnings(n int, rides [][]int) int64 { + sort.Slice(rides, func(i, j int) bool { return rides[i][1] < rides[j][1] }) + m := len(rides) + f := make([]int64, m+1) + for i := 1; i <= m; i++ { + r := rides[i-1] + st, ed, tip := r[0], r[1], r[2] + j := sort.Search(m, func(j int) bool { return rides[j][1] >= st+1 }) + f[i] = max(f[i-1], f[j]+int64(ed-st+tip)) + } + return f[m] +} \ No newline at end of file diff --git a/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution2.java b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution2.java new file mode 100644 index 0000000000000..7da05ff0dc4ad --- /dev/null +++ b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution2.java @@ -0,0 +1,27 @@ +class Solution { + public long maxTaxiEarnings(int n, int[][] rides) { + Arrays.sort(rides, (a, b) -> a[1] - b[1]); + int m = rides.length; + long[] f = new long[m + 1]; + for (int i = 1; i <= m; ++i) { + int[] r = rides[i - 1]; + int st = r[0], ed = r[1], tip = r[2]; + int j = search(rides, st + 1, i); + f[i] = Math.max(f[i - 1], f[j] + ed - st + tip); + } + return f[m]; + } + + private int search(int[][] nums, int x, int r) { + int l = 0; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid][1] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } +} \ No newline at end of file diff --git a/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution2.py b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution2.py new file mode 100644 index 0000000000000..168015131e1f2 --- /dev/null +++ b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: + rides.sort(key=lambda x: x[1]) + f = [0] * (len(rides) + 1) + for i, (st, ed, tip) in enumerate(rides, 1): + j = bisect_left(rides, st + 1, hi=i, key=lambda x: x[1]) + f[i] = max(f[i - 1], f[j] + ed - st + tip) + return f[-1] diff --git a/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution2.ts b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution2.ts new file mode 100644 index 0000000000000..ae8373962a778 --- /dev/null +++ b/solution/2000-2099/2008.Maximum Earnings From Taxi/Solution2.ts @@ -0,0 +1,23 @@ +function maxTaxiEarnings(n: number, rides: number[][]): number { + rides.sort((a, b) => a[1] - b[1]); + const m = rides.length; + const f: number[] = Array(m + 1).fill(0); + const search = (x: number, r: number): number => { + let l = 0; + while (l < r) { + const mid = (l + r) >> 1; + if (rides[mid][1] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + for (let i = 1; i <= m; ++i) { + const [st, ed, tip] = rides[i - 1]; + const j = search(st + 1, i); + f[i] = Math.max(f[i - 1], f[j] + ed - st + tip); + } + return f[m]; +} diff --git a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.cpp b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.cpp index 8ded724cd635e..a1000bdc0befd 100644 --- a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.cpp +++ b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.cpp @@ -5,10 +5,8 @@ class Solution { int m = unique(nums.begin(), nums.end()) - nums.begin(); int n = nums.size(); int ans = n; - for (int i = 0, j = 0; i < m; ++i) { - while (j < m && nums[j] - nums[i] <= n - 1) { - ++j; - } + for (int i = 0; i < m; ++i) { + int j = upper_bound(nums.begin() + i, nums.begin() + m, nums[i] + n - 1) - nums.begin(); ans = min(ans, n - (j - i)); } return ans; diff --git a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.go b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.go index 2b2c2625cf4fc..d280fefaff395 100644 --- a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.go +++ b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.go @@ -9,10 +9,8 @@ func minOperations(nums []int) int { } } ans := n - for i, j := 0, 0; i < m; i++ { - for j < m && nums[j]-nums[i] <= n-1 { - j++ - } + for i := 0; i < m; i++ { + j := sort.Search(m, func(k int) bool { return nums[k] > nums[i]+n-1 }) ans = min(ans, n-(j-i)) } return ans diff --git a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.java b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.java index 5f9a07bc5b1c6..33f39b82821a2 100644 --- a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.java +++ b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.java @@ -9,12 +9,22 @@ public int minOperations(int[] nums) { } } int ans = n; - for (int i = 0, j = 0; i < m; ++i) { - while (j < m && nums[j] - nums[i] <= n - 1) { - ++j; - } + for (int i = 0; i < m; ++i) { + int j = search(nums, nums[i] + n - 1, i, m); ans = Math.min(ans, n - (j - i)); } return ans; } + + private int search(int[] nums, int x, int left, int right) { + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] > x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } } \ No newline at end of file diff --git a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.py b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.py index ea11259e51c6d..7da329b18137d 100644 --- a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.py +++ b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.py @@ -1,10 +1,8 @@ class Solution: def minOperations(self, nums: List[int]) -> int: - n = len(nums) + ans = n = len(nums) nums = sorted(set(nums)) - ans, j = n, 0 for i, v in enumerate(nums): - while j < len(nums) and nums[j] - v <= n - 1: - j += 1 + j = bisect_right(nums, v + n - 1) ans = min(ans, n - (j - i)) return ans diff --git a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.cpp b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.cpp new file mode 100644 index 0000000000000..8ded724cd635e --- /dev/null +++ b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int minOperations(vector& nums) { + sort(nums.begin(), nums.end()); + int m = unique(nums.begin(), nums.end()) - nums.begin(); + int n = nums.size(); + int ans = n; + for (int i = 0, j = 0; i < m; ++i) { + while (j < m && nums[j] - nums[i] <= n - 1) { + ++j; + } + ans = min(ans, n - (j - i)); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.go b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.go new file mode 100644 index 0000000000000..2b2c2625cf4fc --- /dev/null +++ b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.go @@ -0,0 +1,19 @@ +func minOperations(nums []int) int { + sort.Ints(nums) + n := len(nums) + m := 1 + for i := 1; i < n; i++ { + if nums[i] != nums[i-1] { + nums[m] = nums[i] + m++ + } + } + ans := n + for i, j := 0, 0; i < m; i++ { + for j < m && nums[j]-nums[i] <= n-1 { + j++ + } + ans = min(ans, n-(j-i)) + } + return ans +} \ No newline at end of file diff --git a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.java b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.java new file mode 100644 index 0000000000000..5f9a07bc5b1c6 --- /dev/null +++ b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.java @@ -0,0 +1,20 @@ +class Solution { + public int minOperations(int[] nums) { + int n = nums.length; + Arrays.sort(nums); + int m = 1; + for (int i = 1; i < n; ++i) { + if (nums[i] != nums[i - 1]) { + nums[m++] = nums[i]; + } + } + int ans = n; + for (int i = 0, j = 0; i < m; ++i) { + while (j < m && nums[j] - nums[i] <= n - 1) { + ++j; + } + ans = Math.min(ans, n - (j - i)); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.py b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.py new file mode 100644 index 0000000000000..ea11259e51c6d --- /dev/null +++ b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def minOperations(self, nums: List[int]) -> int: + n = len(nums) + nums = sorted(set(nums)) + ans, j = n, 0 + for i, v in enumerate(nums): + while j < len(nums) and nums[j] - v <= n - 1: + j += 1 + ans = min(ans, n - (j - i)) + return ans diff --git a/solution/2000-2099/2011.Final Value of Variable After Performing Operations/Solution.c b/solution/2000-2099/2011.Final Value of Variable After Performing Operations/Solution.c index cac3031dcda94..656eb5e30eb45 100644 --- a/solution/2000-2099/2011.Final Value of Variable After Performing Operations/Solution.c +++ b/solution/2000-2099/2011.Final Value of Variable After Performing Operations/Solution.c @@ -4,4 +4,4 @@ int finalValueAfterOperations(char** operations, int operationsSize) { ans += operations[i][1] == '+' ? 1 : -1; } return ans; -} +} \ No newline at end of file diff --git a/solution/2000-2099/2011.Final Value of Variable After Performing Operations/Solution.ts b/solution/2000-2099/2011.Final Value of Variable After Performing Operations/Solution.ts index c5c55d14ccd3e..acc0823407810 100644 --- a/solution/2000-2099/2011.Final Value of Variable After Performing Operations/Solution.ts +++ b/solution/2000-2099/2011.Final Value of Variable After Performing Operations/Solution.ts @@ -1,3 +1,7 @@ function finalValueAfterOperations(operations: string[]): number { - return operations.reduce((r, v) => r + (v[1] === '+' ? 1 : -1), 0); + let ans = 0; + for (let operation of operations) { + ans += operation.includes('+') ? 1 : -1; + } + return ans; } diff --git a/solution/2000-2099/2011.Final Value of Variable After Performing Operations/Solution2.ts b/solution/2000-2099/2011.Final Value of Variable After Performing Operations/Solution2.ts new file mode 100644 index 0000000000000..c5c55d14ccd3e --- /dev/null +++ b/solution/2000-2099/2011.Final Value of Variable After Performing Operations/Solution2.ts @@ -0,0 +1,3 @@ +function finalValueAfterOperations(operations: string[]): number { + return operations.reduce((r, v) => r + (v[1] === '+' ? 1 : -1), 0); +} diff --git a/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.cpp b/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.cpp index 7089561bf76bb..456f657448808 100644 --- a/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.cpp +++ b/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - int sumOfBeauties(vector& nums) { - int n = nums.size(); - vector right(n, nums[n - 1]); - for (int i = n - 2; i; --i) { - right[i] = min(right[i + 1], nums[i]); - } - int ans = 0; - for (int i = 1, l = nums[0]; i < n - 1; ++i) { - int r = right[i + 1]; - if (l < nums[i] && nums[i] < r) { - ans += 2; - } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { - ans += 1; - } - l = max(l, nums[i]); - } - return ans; - } +class Solution { +public: + int sumOfBeauties(vector& nums) { + int n = nums.size(); + vector right(n, nums[n - 1]); + for (int i = n - 2; i; --i) { + right[i] = min(right[i + 1], nums[i]); + } + int ans = 0; + for (int i = 1, l = nums[0]; i < n - 1; ++i) { + int r = right[i + 1]; + if (l < nums[i] && nums[i] < r) { + ans += 2; + } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { + ans += 1; + } + l = max(l, nums[i]); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.java b/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.java index fec95d8691258..59ec24436f8f5 100644 --- a/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.java +++ b/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.java @@ -1,22 +1,22 @@ -class Solution { - public int sumOfBeauties(int[] nums) { - int n = nums.length; - int[] right = new int[n]; - right[n - 1] = nums[n - 1]; - for (int i = n - 2; i > 0; --i) { - right[i] = Math.min(right[i + 1], nums[i]); - } - int ans = 0; - int l = nums[0]; - for (int i = 1; i < n - 1; ++i) { - int r = right[i + 1]; - if (l < nums[i] && nums[i] < r) { - ans += 2; - } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { - ans += 1; - } - l = Math.max(l, nums[i]); - } - return ans; - } +class Solution { + public int sumOfBeauties(int[] nums) { + int n = nums.length; + int[] right = new int[n]; + right[n - 1] = nums[n - 1]; + for (int i = n - 2; i > 0; --i) { + right[i] = Math.min(right[i + 1], nums[i]); + } + int ans = 0; + int l = nums[0]; + for (int i = 1; i < n - 1; ++i) { + int r = right[i + 1]; + if (l < nums[i] && nums[i] < r) { + ans += 2; + } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { + ans += 1; + } + l = Math.max(l, nums[i]); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.py b/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.py index f462ac563ccca..2b3710ab5b6b5 100644 --- a/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.py +++ b/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.py @@ -1,16 +1,16 @@ -class Solution: - def sumOfBeauties(self, nums: List[int]) -> int: - n = len(nums) - right = [nums[-1]] * n - for i in range(n - 2, -1, -1): - right[i] = min(right[i + 1], nums[i]) - ans = 0 - l = nums[0] - for i in range(1, n - 1): - r = right[i + 1] - if l < nums[i] < r: - ans += 2 - elif nums[i - 1] < nums[i] < nums[i + 1]: - ans += 1 - l = max(l, nums[i]) - return ans +class Solution: + def sumOfBeauties(self, nums: List[int]) -> int: + n = len(nums) + right = [nums[-1]] * n + for i in range(n - 2, -1, -1): + right[i] = min(right[i + 1], nums[i]) + ans = 0 + l = nums[0] + for i in range(1, n - 1): + r = right[i + 1] + if l < nums[i] < r: + ans += 2 + elif nums[i - 1] < nums[i] < nums[i + 1]: + ans += 1 + l = max(l, nums[i]) + return ans diff --git a/solution/2000-2099/2019.The Score of Students Solving Math Expression/Solution.cpp b/solution/2000-2099/2019.The Score of Students Solving Math Expression/Solution.cpp index 6fa0f30a45df1..cd65586754ea5 100644 --- a/solution/2000-2099/2019.The Score of Students Solving Math Expression/Solution.cpp +++ b/solution/2000-2099/2019.The Score of Students Solving Math Expression/Solution.cpp @@ -1,55 +1,55 @@ -class Solution { -public: - int scoreOfStudents(string s, vector& answers) { - int n = s.size(); - int x = cal(s); - int m = (n + 1) >> 1; - unordered_set f[m][m]; - for (int i = 0; i < m; ++i) { - f[i][i] = {s[i * 2] - '0'}; - } - for (int i = m - 1; ~i; --i) { - for (int j = i; j < m; ++j) { - for (int k = i; k < j; ++k) { - for (int l : f[i][k]) { - for (int r : f[k + 1][j]) { - char op = s[k << 1 | 1]; - if (op == '+' && l + r <= 1000) { - f[i][j].insert(l + r); - } else if (op == '*' && l * r <= 1000) { - f[i][j].insert(l * r); - } - } - } - } - } - } - int cnt[1001]{}; - for (int t : answers) { - ++cnt[t]; - } - int ans = 5 * cnt[x]; - for (int i = 0; i <= 1000; ++i) { - if (i != x && f[0][m - 1].count(i)) { - ans += cnt[i] << 1; - } - } - return ans; - } - - int cal(string& s) { - int res = 0; - int pre = s[0] - '0'; - for (int i = 1; i < s.size(); i += 2) { - int cur = s[i + 1] - '0'; - if (s[i] == '*') { - pre *= cur; - } else { - res += pre; - pre = cur; - } - } - res += pre; - return res; - } +class Solution { +public: + int scoreOfStudents(string s, vector& answers) { + int n = s.size(); + int x = cal(s); + int m = (n + 1) >> 1; + unordered_set f[m][m]; + for (int i = 0; i < m; ++i) { + f[i][i] = {s[i * 2] - '0'}; + } + for (int i = m - 1; ~i; --i) { + for (int j = i; j < m; ++j) { + for (int k = i; k < j; ++k) { + for (int l : f[i][k]) { + for (int r : f[k + 1][j]) { + char op = s[k << 1 | 1]; + if (op == '+' && l + r <= 1000) { + f[i][j].insert(l + r); + } else if (op == '*' && l * r <= 1000) { + f[i][j].insert(l * r); + } + } + } + } + } + } + int cnt[1001]{}; + for (int t : answers) { + ++cnt[t]; + } + int ans = 5 * cnt[x]; + for (int i = 0; i <= 1000; ++i) { + if (i != x && f[0][m - 1].count(i)) { + ans += cnt[i] << 1; + } + } + return ans; + } + + int cal(string& s) { + int res = 0; + int pre = s[0] - '0'; + for (int i = 1; i < s.size(); i += 2) { + int cur = s[i + 1] - '0'; + if (s[i] == '*') { + pre *= cur; + } else { + res += pre; + pre = cur; + } + } + res += pre; + return res; + } }; \ No newline at end of file diff --git a/solution/2000-2099/2019.The Score of Students Solving Math Expression/Solution.java b/solution/2000-2099/2019.The Score of Students Solving Math Expression/Solution.java index 961803cb332a9..1168138ed23f2 100644 --- a/solution/2000-2099/2019.The Score of Students Solving Math Expression/Solution.java +++ b/solution/2000-2099/2019.The Score of Students Solving Math Expression/Solution.java @@ -1,57 +1,57 @@ -class Solution { - public int scoreOfStudents(String s, int[] answers) { - int n = s.length(); - int x = cal(s); - int m = (n + 1) >> 1; - Set[][] f = new Set[m][m]; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < m; ++j) { - f[i][j] = new HashSet<>(); - } - f[i][i].add(s.charAt(i << 1) - '0'); - } - for (int i = m - 1; i >= 0; --i) { - for (int j = i; j < m; ++j) { - for (int k = i; k < j; ++k) { - for (int l : f[i][k]) { - for (int r : f[k + 1][j]) { - char op = s.charAt(k << 1 | 1); - if (op == '+' && l + r <= 1000) { - f[i][j].add(l + r); - } else if (op == '*' && l * r <= 1000) { - f[i][j].add(l * r); - } - } - } - } - } - } - int[] cnt = new int[1001]; - for (int ans : answers) { - ++cnt[ans]; - } - int ans = 5 * cnt[x]; - for (int i = 0; i <= 1000; ++i) { - if (i != x && f[0][m - 1].contains(i)) { - ans += 2 * cnt[i]; - } - } - return ans; - } - - private int cal(String s) { - int res = 0, pre = s.charAt(0) - '0'; - for (int i = 1; i < s.length(); i += 2) { - char op = s.charAt(i); - int cur = s.charAt(i + 1) - '0'; - if (op == '*') { - pre *= cur; - } else { - res += pre; - pre = cur; - } - } - res += pre; - return res; - } +class Solution { + public int scoreOfStudents(String s, int[] answers) { + int n = s.length(); + int x = cal(s); + int m = (n + 1) >> 1; + Set[][] f = new Set[m][m]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < m; ++j) { + f[i][j] = new HashSet<>(); + } + f[i][i].add(s.charAt(i << 1) - '0'); + } + for (int i = m - 1; i >= 0; --i) { + for (int j = i; j < m; ++j) { + for (int k = i; k < j; ++k) { + for (int l : f[i][k]) { + for (int r : f[k + 1][j]) { + char op = s.charAt(k << 1 | 1); + if (op == '+' && l + r <= 1000) { + f[i][j].add(l + r); + } else if (op == '*' && l * r <= 1000) { + f[i][j].add(l * r); + } + } + } + } + } + } + int[] cnt = new int[1001]; + for (int ans : answers) { + ++cnt[ans]; + } + int ans = 5 * cnt[x]; + for (int i = 0; i <= 1000; ++i) { + if (i != x && f[0][m - 1].contains(i)) { + ans += 2 * cnt[i]; + } + } + return ans; + } + + private int cal(String s) { + int res = 0, pre = s.charAt(0) - '0'; + for (int i = 1; i < s.length(); i += 2) { + char op = s.charAt(i); + int cur = s.charAt(i + 1) - '0'; + if (op == '*') { + pre *= cur; + } else { + res += pre; + pre = cur; + } + } + res += pre; + return res; + } } \ No newline at end of file diff --git a/solution/2000-2099/2019.The Score of Students Solving Math Expression/Solution.py b/solution/2000-2099/2019.The Score of Students Solving Math Expression/Solution.py index ea768f1a62367..d56b220dc6eca 100644 --- a/solution/2000-2099/2019.The Score of Students Solving Math Expression/Solution.py +++ b/solution/2000-2099/2019.The Score of Students Solving Math Expression/Solution.py @@ -1,34 +1,34 @@ -class Solution: - def scoreOfStudents(self, s: str, answers: List[int]) -> int: - def cal(s: str) -> int: - res, pre = 0, int(s[0]) - for i in range(1, n, 2): - if s[i] == "*": - pre *= int(s[i + 1]) - else: - res += pre - pre = int(s[i + 1]) - res += pre - return res - - n = len(s) - x = cal(s) - m = (n + 1) >> 1 - f = [[set() for _ in range(m)] for _ in range(m)] - for i in range(m): - f[i][i] = {int(s[i << 1])} - for i in range(m - 1, -1, -1): - for j in range(i, m): - for k in range(i, j): - for l in f[i][k]: - for r in f[k + 1][j]: - if s[k << 1 | 1] == "+" and l + r <= 1000: - f[i][j].add(l + r) - elif s[k << 1 | 1] == "*" and l * r <= 1000: - f[i][j].add(l * r) - cnt = Counter(answers) - ans = cnt[x] * 5 - for k, v in cnt.items(): - if k != x and k in f[0][m - 1]: - ans += v << 1 - return ans +class Solution: + def scoreOfStudents(self, s: str, answers: List[int]) -> int: + def cal(s: str) -> int: + res, pre = 0, int(s[0]) + for i in range(1, n, 2): + if s[i] == "*": + pre *= int(s[i + 1]) + else: + res += pre + pre = int(s[i + 1]) + res += pre + return res + + n = len(s) + x = cal(s) + m = (n + 1) >> 1 + f = [[set() for _ in range(m)] for _ in range(m)] + for i in range(m): + f[i][i] = {int(s[i << 1])} + for i in range(m - 1, -1, -1): + for j in range(i, m): + for k in range(i, j): + for l in f[i][k]: + for r in f[k + 1][j]: + if s[k << 1 | 1] == "+" and l + r <= 1000: + f[i][j].add(l + r) + elif s[k << 1 | 1] == "*" and l * r <= 1000: + f[i][j].add(l * r) + cnt = Counter(answers) + ans = cnt[x] * 5 + for k, v in cnt.items(): + if k != x and k in f[0][m - 1]: + ans += v << 1 + return ans diff --git a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.cpp b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.cpp index c394d753250f6..1a36f0e37081e 100644 --- a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.cpp +++ b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.cpp @@ -1,17 +1,11 @@ class Solution { public: int numOfPairs(vector& nums, string target) { - unordered_map cnt; - for (auto& x : nums) ++cnt[x]; + int n = nums.size(); int ans = 0; - for (int i = 1; i < target.size(); ++i) { - string a = target.substr(0, i); - string b = target.substr(i); - int x = cnt[a], y = cnt[b]; - if (a != b) { - ans += x * y; - } else { - ans += x * (y - 1); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (i != j && nums[i] + nums[j] == target) ++ans; } } return ans; diff --git a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.go b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.go index c7cdf664679cc..6d1242fa928f6 100644 --- a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.go +++ b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.go @@ -1,15 +1,10 @@ func numOfPairs(nums []string, target string) (ans int) { - cnt := map[string]int{} - for _, x := range nums { - cnt[x]++ - } - for i := 1; i < len(target); i++ { - a, b := target[:i], target[i:] - if a != b { - ans += cnt[a] * cnt[b] - } else { - ans += cnt[a] * (cnt[a] - 1) + for i, a := range nums { + for j, b := range nums { + if i != j && a+b == target { + ans++ + } } } - return + return ans } \ No newline at end of file diff --git a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.java b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.java index 5852c65731c85..aad0be17abcec 100644 --- a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.java +++ b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.java @@ -1,21 +1,14 @@ -class Solution { - public int numOfPairs(String[] nums, String target) { - Map cnt = new HashMap<>(); - for (String x : nums) { - cnt.merge(x, 1, Integer::sum); - } - int ans = 0; - for (int i = 1; i < target.length(); ++i) { - String a = target.substring(0, i); - String b = target.substring(i); - int x = cnt.getOrDefault(a, 0); - int y = cnt.getOrDefault(b, 0); - if (!a.equals(b)) { - ans += x * y; - } else { - ans += x * (y - 1); - } - } - return ans; - } +class Solution { + public int numOfPairs(String[] nums, String target) { + int n = nums.length; + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (i != j && target.equals(nums[i] + nums[j])) { + ++ans; + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.py b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.py index 93d8542509a88..07e6abb3990c5 100644 --- a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.py +++ b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.py @@ -1,11 +1,6 @@ class Solution: def numOfPairs(self, nums: List[str], target: str) -> int: - cnt = Counter(nums) - ans = 0 - for i in range(1, len(target)): - a, b = target[:i], target[i:] - if a != b: - ans += cnt[a] * cnt[b] - else: - ans += cnt[a] * (cnt[a] - 1) - return ans + n = len(nums) + return sum( + i != j and nums[i] + nums[j] == target for i in range(n) for j in range(n) + ) diff --git a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution2.cpp b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution2.cpp new file mode 100644 index 0000000000000..c394d753250f6 --- /dev/null +++ b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int numOfPairs(vector& nums, string target) { + unordered_map cnt; + for (auto& x : nums) ++cnt[x]; + int ans = 0; + for (int i = 1; i < target.size(); ++i) { + string a = target.substr(0, i); + string b = target.substr(i); + int x = cnt[a], y = cnt[b]; + if (a != b) { + ans += x * y; + } else { + ans += x * (y - 1); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution2.go b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution2.go new file mode 100644 index 0000000000000..c7cdf664679cc --- /dev/null +++ b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution2.go @@ -0,0 +1,15 @@ +func numOfPairs(nums []string, target string) (ans int) { + cnt := map[string]int{} + for _, x := range nums { + cnt[x]++ + } + for i := 1; i < len(target); i++ { + a, b := target[:i], target[i:] + if a != b { + ans += cnt[a] * cnt[b] + } else { + ans += cnt[a] * (cnt[a] - 1) + } + } + return +} \ No newline at end of file diff --git a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution2.java b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution2.java new file mode 100644 index 0000000000000..a2f1e22162ccb --- /dev/null +++ b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution2.java @@ -0,0 +1,21 @@ +class Solution { + public int numOfPairs(String[] nums, String target) { + Map cnt = new HashMap<>(); + for (String x : nums) { + cnt.merge(x, 1, Integer::sum); + } + int ans = 0; + for (int i = 1; i < target.length(); ++i) { + String a = target.substring(0, i); + String b = target.substring(i); + int x = cnt.getOrDefault(a, 0); + int y = cnt.getOrDefault(b, 0); + if (!a.equals(b)) { + ans += x * y; + } else { + ans += x * (y - 1); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution2.py b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution2.py new file mode 100644 index 0000000000000..93d8542509a88 --- /dev/null +++ b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def numOfPairs(self, nums: List[str], target: str) -> int: + cnt = Counter(nums) + ans = 0 + for i in range(1, len(target)): + a, b = target[:i], target[i:] + if a != b: + ans += cnt[a] * cnt[b] + else: + ans += cnt[a] * (cnt[a] - 1) + return ans diff --git a/solution/2000-2099/2024.Maximize the Confusion of an Exam/Solution.cpp b/solution/2000-2099/2024.Maximize the Confusion of an Exam/Solution.cpp index 8658ef1a080d2..8b95cee63e360 100644 --- a/solution/2000-2099/2024.Maximize the Confusion of an Exam/Solution.cpp +++ b/solution/2000-2099/2024.Maximize the Confusion of an Exam/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - int maxConsecutiveAnswers(string answerKey, int k) { - return max(get('T', k, answerKey), get('F', k, answerKey)); - } - - int get(char c, int k, string& answerKey) { - int l = 0, r = 0; - while (r < answerKey.size()) { - if (answerKey[r++] == c) --k; - if (k < 0 && answerKey[l++] == c) ++k; - } - return r - l; - } +class Solution { +public: + int maxConsecutiveAnswers(string answerKey, int k) { + return max(get('T', k, answerKey), get('F', k, answerKey)); + } + + int get(char c, int k, string& answerKey) { + int l = 0, r = 0; + while (r < answerKey.size()) { + if (answerKey[r++] == c) --k; + if (k < 0 && answerKey[l++] == c) ++k; + } + return r - l; + } }; \ No newline at end of file diff --git a/solution/2000-2099/2027.Minimum Moves to Convert String/Solution.c b/solution/2000-2099/2027.Minimum Moves to Convert String/Solution.c index 7cace571cf4ea..bc75aaa31d5d9 100644 --- a/solution/2000-2099/2027.Minimum Moves to Convert String/Solution.c +++ b/solution/2000-2099/2027.Minimum Moves to Convert String/Solution.c @@ -11,4 +11,4 @@ int minimumMoves(char* s) { } } return ans; -} +} \ No newline at end of file diff --git a/solution/2000-2099/2028.Find Missing Observations/Solution.cpp b/solution/2000-2099/2028.Find Missing Observations/Solution.cpp index 98658ffe5fde7..8f54085bfbdbd 100644 --- a/solution/2000-2099/2028.Find Missing Observations/Solution.cpp +++ b/solution/2000-2099/2028.Find Missing Observations/Solution.cpp @@ -1,12 +1,12 @@ -class Solution { -public: - vector missingRolls(vector& rolls, int mean, int n) { - int m = rolls.size(); - int s = (n + m) * mean; - for (int& v : rolls) s -= v; - if (s > n * 6 || s < n) return {}; - vector ans(n, s / n); - for (int i = 0; i < s % n; ++i) ++ans[i]; - return ans; - } +class Solution { +public: + vector missingRolls(vector& rolls, int mean, int n) { + int m = rolls.size(); + int s = (n + m) * mean; + for (int& v : rolls) s -= v; + if (s > n * 6 || s < n) return {}; + vector ans(n, s / n); + for (int i = 0; i < s % n; ++i) ++ans[i]; + return ans; + } }; \ No newline at end of file diff --git a/solution/2000-2099/2028.Find Missing Observations/Solution.java b/solution/2000-2099/2028.Find Missing Observations/Solution.java index cac733fd51f93..c9bd269042374 100644 --- a/solution/2000-2099/2028.Find Missing Observations/Solution.java +++ b/solution/2000-2099/2028.Find Missing Observations/Solution.java @@ -1,18 +1,18 @@ -class Solution { - public int[] missingRolls(int[] rolls, int mean, int n) { - int m = rolls.length; - int s = (n + m) * mean; - for (int v : rolls) { - s -= v; - } - if (s > n * 6 || s < n) { - return new int[0]; - } - int[] ans = new int[n]; - Arrays.fill(ans, s / n); - for (int i = 0; i < s % n; ++i) { - ++ans[i]; - } - return ans; - } +class Solution { + public int[] missingRolls(int[] rolls, int mean, int n) { + int m = rolls.length; + int s = (n + m) * mean; + for (int v : rolls) { + s -= v; + } + if (s > n * 6 || s < n) { + return new int[0]; + } + int[] ans = new int[n]; + Arrays.fill(ans, s / n); + for (int i = 0; i < s % n; ++i) { + ++ans[i]; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2000-2099/2028.Find Missing Observations/Solution.py b/solution/2000-2099/2028.Find Missing Observations/Solution.py index de1ce41206bef..f69de736c0890 100644 --- a/solution/2000-2099/2028.Find Missing Observations/Solution.py +++ b/solution/2000-2099/2028.Find Missing Observations/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]: - m = len(rolls) - s = (n + m) * mean - sum(rolls) - if s > n * 6 or s < n: - return [] - ans = [s // n] * n - for i in range(s % n): - ans[i] += 1 - return ans +class Solution: + def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]: + m = len(rolls) + s = (n + m) * mean - sum(rolls) + if s > n * 6 or s < n: + return [] + ans = [s // n] * n + for i in range(s % n): + ans[i] += 1 + return ans diff --git a/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/Solution.cpp b/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/Solution.cpp index a9fe2dee03a78..38a4124172037 100644 --- a/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/Solution.cpp +++ b/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/Solution.cpp @@ -1,43 +1,43 @@ -class BinaryIndexedTree { -private: - int n; - vector c; - -public: - BinaryIndexedTree(int n) - : n(n) - , c(n + 1, 0) {} - - void update(int x, int v) { - for (; x <= n; x += x & -x) { - c[x] += v; - } - } - - int query(int x) { - int s = 0; - for (; x > 0; x -= x & -x) { - s += c[x]; - } - return s; - } -}; - -class Solution { -public: - int subarraysWithMoreZerosThanOnes(vector& nums) { - int n = nums.size(); - int base = n + 1; - BinaryIndexedTree tree(n + base); - tree.update(base, 1); - const int mod = 1e9 + 7; - int ans = 0, s = 0; - for (int x : nums) { - s += (x == 0) ? -1 : 1; - ans += tree.query(s - 1 + base); - ans %= mod; - tree.update(s + base, 1); - } - return ans; - } +class BinaryIndexedTree { +private: + int n; + vector c; + +public: + BinaryIndexedTree(int n) + : n(n) + , c(n + 1, 0) {} + + void update(int x, int v) { + for (; x <= n; x += x & -x) { + c[x] += v; + } + } + + int query(int x) { + int s = 0; + for (; x > 0; x -= x & -x) { + s += c[x]; + } + return s; + } +}; + +class Solution { +public: + int subarraysWithMoreZerosThanOnes(vector& nums) { + int n = nums.size(); + int base = n + 1; + BinaryIndexedTree tree(n + base); + tree.update(base, 1); + const int mod = 1e9 + 7; + int ans = 0, s = 0; + for (int x : nums) { + s += (x == 0) ? -1 : 1; + ans += tree.query(s - 1 + base); + ans %= mod; + tree.update(s + base, 1); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/Solution.java b/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/Solution.java index bcd4b546e12c7..0df35390f66b5 100644 --- a/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/Solution.java +++ b/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/Solution.java @@ -1,41 +1,41 @@ -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void update(int x, int v) { - for (; x <= n; x += x & -x) { - c[x] += v; - } - } - - public int query(int x) { - int s = 0; - for (; x > 0; x -= x & -x) { - s += c[x]; - } - return s; - } -} - -class Solution { - public int subarraysWithMoreZerosThanOnes(int[] nums) { - int n = nums.length; - int base = n + 1; - BinaryIndexedTree tree = new BinaryIndexedTree(n + base); - tree.update(base, 1); - final int mod = (int) 1e9 + 7; - int ans = 0, s = 0; - for (int x : nums) { - s += x == 0 ? -1 : 1; - ans += tree.query(s - 1 + base); - ans %= mod; - tree.update(s + base, 1); - } - return ans; - } +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int v) { + for (; x <= n; x += x & -x) { + c[x] += v; + } + } + + public int query(int x) { + int s = 0; + for (; x > 0; x -= x & -x) { + s += c[x]; + } + return s; + } +} + +class Solution { + public int subarraysWithMoreZerosThanOnes(int[] nums) { + int n = nums.length; + int base = n + 1; + BinaryIndexedTree tree = new BinaryIndexedTree(n + base); + tree.update(base, 1); + final int mod = (int) 1e9 + 7; + int ans = 0, s = 0; + for (int x : nums) { + s += x == 0 ? -1 : 1; + ans += tree.query(s - 1 + base); + ans %= mod; + tree.update(s + base, 1); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/Solution.py b/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/Solution.py index 1c25a0160d06a..e038bdb871c8a 100644 --- a/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/Solution.py +++ b/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/Solution.py @@ -1,34 +1,34 @@ -class BinaryIndexedTree: - __slots__ = ["n", "c"] - - def __init__(self, n: int): - self.n = n - self.c = [0] * (n + 1) - - def update(self, x: int, v: int): - while x <= self.n: - self.c[x] += v - x += x & -x - - def query(self, x: int) -> int: - s = 0 - while x: - s += self.c[x] - x -= x & -x - return s - - -class Solution: - def subarraysWithMoreZerosThanOnes(self, nums: List[int]) -> int: - n = len(nums) - base = n + 1 - tree = BinaryIndexedTree(n + base) - tree.update(base, 1) - mod = 10**9 + 7 - ans = s = 0 - for x in nums: - s += x or -1 - ans += tree.query(s - 1 + base) - ans %= mod - tree.update(s + base, 1) - return ans +class BinaryIndexedTree: + __slots__ = ["n", "c"] + + def __init__(self, n: int): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x: int, v: int): + while x <= self.n: + self.c[x] += v + x += x & -x + + def query(self, x: int) -> int: + s = 0 + while x: + s += self.c[x] + x -= x & -x + return s + + +class Solution: + def subarraysWithMoreZerosThanOnes(self, nums: List[int]) -> int: + n = len(nums) + base = n + 1 + tree = BinaryIndexedTree(n + base) + tree.update(base, 1) + mod = 10**9 + 7 + ans = s = 0 + for x in nums: + s += x or -1 + ans += tree.query(s - 1 + base) + ans %= mod + tree.update(s + base, 1) + return ans diff --git a/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/Solution2.py b/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/Solution2.py new file mode 100644 index 0000000000000..4d104814ad6eb --- /dev/null +++ b/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/Solution2.py @@ -0,0 +1,14 @@ +from sortedcontainers import SortedList + + +class Solution: + def subarraysWithMoreZerosThanOnes(self, nums: List[int]) -> int: + sl = SortedList([0]) + mod = 10**9 + 7 + ans = s = 0 + for x in nums: + s += x or -1 + ans += sl.bisect_left(s) + ans %= mod + sl.add(s) + return ans diff --git a/solution/2000-2099/2036.Maximum Alternating Subarray Sum/Solution.cpp b/solution/2000-2099/2036.Maximum Alternating Subarray Sum/Solution.cpp index 3a807d8890d34..4cdeb21d5469c 100644 --- a/solution/2000-2099/2036.Maximum Alternating Subarray Sum/Solution.cpp +++ b/solution/2000-2099/2036.Maximum Alternating Subarray Sum/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - long long maximumAlternatingSubarraySum(vector& nums) { - using ll = long long; - const ll inf = 1LL << 60; - ll ans = -inf, f = -inf, g = -inf; - for (int x : nums) { - ll ff = max(g, 0LL) + x; - g = f - x; - f = ff; - ans = max({ans, f, g}); - } - return ans; - } +class Solution { +public: + long long maximumAlternatingSubarraySum(vector& nums) { + using ll = long long; + const ll inf = 1LL << 60; + ll ans = -inf, f = -inf, g = -inf; + for (int x : nums) { + ll ff = max(g, 0LL) + x; + g = f - x; + f = ff; + ans = max({ans, f, g}); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2000-2099/2036.Maximum Alternating Subarray Sum/Solution.java b/solution/2000-2099/2036.Maximum Alternating Subarray Sum/Solution.java index 1f9cac5e9025d..8a96f7eb5392b 100644 --- a/solution/2000-2099/2036.Maximum Alternating Subarray Sum/Solution.java +++ b/solution/2000-2099/2036.Maximum Alternating Subarray Sum/Solution.java @@ -1,13 +1,13 @@ -class Solution { - public long maximumAlternatingSubarraySum(int[] nums) { - final long inf = 1L << 60; - long ans = -inf, f = -inf, g = -inf; - for (int x : nums) { - long ff = Math.max(g, 0) + x; - g = f - x; - f = ff; - ans = Math.max(ans, Math.max(f, g)); - } - return ans; - } +class Solution { + public long maximumAlternatingSubarraySum(int[] nums) { + final long inf = 1L << 60; + long ans = -inf, f = -inf, g = -inf; + for (int x : nums) { + long ff = Math.max(g, 0) + x; + g = f - x; + f = ff; + ans = Math.max(ans, Math.max(f, g)); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2000-2099/2036.Maximum Alternating Subarray Sum/Solution.py b/solution/2000-2099/2036.Maximum Alternating Subarray Sum/Solution.py index e9456817e9244..a4773a406fd7b 100644 --- a/solution/2000-2099/2036.Maximum Alternating Subarray Sum/Solution.py +++ b/solution/2000-2099/2036.Maximum Alternating Subarray Sum/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def maximumAlternatingSubarraySum(self, nums: List[int]) -> int: - ans = f = g = -inf - for x in nums: - f, g = max(g, 0) + x, f - x - ans = max(ans, f, g) - return ans +class Solution: + def maximumAlternatingSubarraySum(self, nums: List[int]) -> int: + ans = f = g = -inf + for x in nums: + f, g = max(g, 0) + x, f - x + ans = max(ans, f, g) + return ans diff --git a/solution/2000-2099/2037.Minimum Number of Moves to Seat Everyone/Solution.c b/solution/2000-2099/2037.Minimum Number of Moves to Seat Everyone/Solution.c index fe3ea0a0291e4..f0d28e69d1556 100644 --- a/solution/2000-2099/2037.Minimum Number of Moves to Seat Everyone/Solution.c +++ b/solution/2000-2099/2037.Minimum Number of Moves to Seat Everyone/Solution.c @@ -10,4 +10,4 @@ int minMovesToSeat(int* seats, int seatsSize, int* students, int studentsSize) { ans += abs(seats[i] - students[i]); } return ans; -} +} \ No newline at end of file diff --git a/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/Solution.cpp b/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/Solution.cpp index 390cda71e76c1..95a61a1c472f2 100644 --- a/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/Solution.cpp +++ b/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - bool winnerOfGame(string colors) { - int n = colors.size(); - int a = 0, b = 0; - for (int i = 0, j = 0; i < n; i = j) { - while (j < n && colors[j] == colors[i]) { - ++j; - } - int m = j - i - 2; - if (m > 0) { - if (colors[i] == 'A') { - a += m; - } else { - b += m; - } - } - } - return a > b; - } +class Solution { +public: + bool winnerOfGame(string colors) { + int n = colors.size(); + int a = 0, b = 0; + for (int i = 0, j = 0; i < n; i = j) { + while (j < n && colors[j] == colors[i]) { + ++j; + } + int m = j - i - 2; + if (m > 0) { + if (colors[i] == 'A') { + a += m; + } else { + b += m; + } + } + } + return a > b; + } }; \ No newline at end of file diff --git a/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/Solution.java b/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/Solution.java index 5c661deae1d71..290729b99241b 100644 --- a/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/Solution.java +++ b/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/Solution.java @@ -1,20 +1,20 @@ -class Solution { - public boolean winnerOfGame(String colors) { - int n = colors.length(); - int a = 0, b = 0; - for (int i = 0, j = 0; i < n; i = j) { - while (j < n && colors.charAt(j) == colors.charAt(i)) { - ++j; - } - int m = j - i - 2; - if (m > 0) { - if (colors.charAt(i) == 'A') { - a += m; - } else { - b += m; - } - } - } - return a > b; - } +class Solution { + public boolean winnerOfGame(String colors) { + int n = colors.length(); + int a = 0, b = 0; + for (int i = 0, j = 0; i < n; i = j) { + while (j < n && colors.charAt(j) == colors.charAt(i)) { + ++j; + } + int m = j - i - 2; + if (m > 0) { + if (colors.charAt(i) == 'A') { + a += m; + } else { + b += m; + } + } + } + return a > b; + } } \ No newline at end of file diff --git a/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/Solution.py b/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/Solution.py index 2c0c87e414600..b61fcf71200c8 100644 --- a/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/Solution.py +++ b/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def winnerOfGame(self, colors: str) -> bool: - a = b = 0 - for c, v in groupby(colors): - m = len(list(v)) - 2 - if m > 0 and c == 'A': - a += m - elif m > 0 and c == 'B': - b += m - return a > b +class Solution: + def winnerOfGame(self, colors: str) -> bool: + a = b = 0 + for c, v in groupby(colors): + m = len(list(v)) - 2 + if m > 0 and c == 'A': + a += m + elif m > 0 and c == 'B': + b += m + return a > b diff --git a/solution/2000-2099/2039.The Time When the Network Becomes Idle/Solution.cpp b/solution/2000-2099/2039.The Time When the Network Becomes Idle/Solution.cpp index 8e0f2a2407d1f..57352997376f5 100644 --- a/solution/2000-2099/2039.The Time When the Network Becomes Idle/Solution.cpp +++ b/solution/2000-2099/2039.The Time When the Network Becomes Idle/Solution.cpp @@ -1,33 +1,33 @@ -class Solution { -public: - int networkBecomesIdle(vector>& edges, vector& patience) { - int n = patience.size(); - vector g[n]; - for (auto& e : edges) { - int u = e[0], v = e[1]; - g[u].push_back(v); - g[v].push_back(u); - } - queue q{{0}}; - bool vis[n]; - memset(vis, false, sizeof(vis)); - vis[0] = true; - int ans = 0, d = 0; - while (!q.empty()) { - ++d; - int t = d * 2; - for (int i = q.size(); i; --i) { - int u = q.front(); - q.pop(); - for (int v : g[u]) { - if (!vis[v]) { - vis[v] = true; - q.push(v); - ans = max(ans, (t - 1) / patience[v] * patience[v] + t + 1); - } - } - } - } - return ans; - } +class Solution { +public: + int networkBecomesIdle(vector>& edges, vector& patience) { + int n = patience.size(); + vector g[n]; + for (auto& e : edges) { + int u = e[0], v = e[1]; + g[u].push_back(v); + g[v].push_back(u); + } + queue q{{0}}; + bool vis[n]; + memset(vis, false, sizeof(vis)); + vis[0] = true; + int ans = 0, d = 0; + while (!q.empty()) { + ++d; + int t = d * 2; + for (int i = q.size(); i; --i) { + int u = q.front(); + q.pop(); + for (int v : g[u]) { + if (!vis[v]) { + vis[v] = true; + q.push(v); + ans = max(ans, (t - 1) / patience[v] * patience[v] + t + 1); + } + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2000-2099/2039.The Time When the Network Becomes Idle/Solution.java b/solution/2000-2099/2039.The Time When the Network Becomes Idle/Solution.java index b259a633ab166..b9d4aef8f9094 100644 --- a/solution/2000-2099/2039.The Time When the Network Becomes Idle/Solution.java +++ b/solution/2000-2099/2039.The Time When the Network Becomes Idle/Solution.java @@ -1,32 +1,32 @@ -class Solution { - public int networkBecomesIdle(int[][] edges, int[] patience) { - int n = patience.length; - List[] g = new List[n]; - Arrays.setAll(g, k -> new ArrayList<>()); - for (int[] e : edges) { - int u = e[0], v = e[1]; - g[u].add(v); - g[v].add(u); - } - Deque q = new ArrayDeque<>(); - q.offer(0); - boolean[] vis = new boolean[n]; - vis[0] = true; - int ans = 0, d = 0; - while (!q.isEmpty()) { - ++d; - int t = d * 2; - for (int i = q.size(); i > 0; --i) { - int u = q.poll(); - for (int v : g[u]) { - if (!vis[v]) { - vis[v] = true; - q.offer(v); - ans = Math.max(ans, (t - 1) / patience[v] * patience[v] + t + 1); - } - } - } - } - return ans; - } +class Solution { + public int networkBecomesIdle(int[][] edges, int[] patience) { + int n = patience.length; + List[] g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (int[] e : edges) { + int u = e[0], v = e[1]; + g[u].add(v); + g[v].add(u); + } + Deque q = new ArrayDeque<>(); + q.offer(0); + boolean[] vis = new boolean[n]; + vis[0] = true; + int ans = 0, d = 0; + while (!q.isEmpty()) { + ++d; + int t = d * 2; + for (int i = q.size(); i > 0; --i) { + int u = q.poll(); + for (int v : g[u]) { + if (!vis[v]) { + vis[v] = true; + q.offer(v); + ans = Math.max(ans, (t - 1) / patience[v] * patience[v] + t + 1); + } + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2000-2099/2039.The Time When the Network Becomes Idle/Solution.py b/solution/2000-2099/2039.The Time When the Network Becomes Idle/Solution.py index 51a365cb69498..1f26e18d5aab1 100644 --- a/solution/2000-2099/2039.The Time When the Network Becomes Idle/Solution.py +++ b/solution/2000-2099/2039.The Time When the Network Becomes Idle/Solution.py @@ -1,20 +1,20 @@ -class Solution: - def networkBecomesIdle(self, edges: List[List[int]], patience: List[int]) -> int: - g = defaultdict(list) - for u, v in edges: - g[u].append(v) - g[v].append(u) - q = deque([0]) - vis = {0} - ans = d = 0 - while q: - d += 1 - t = d * 2 - for _ in range(len(q)): - u = q.popleft() - for v in g[u]: - if v not in vis: - vis.add(v) - q.append(v) - ans = max(ans, (t - 1) // patience[v] * patience[v] + t + 1) - return ans +class Solution: + def networkBecomesIdle(self, edges: List[List[int]], patience: List[int]) -> int: + g = defaultdict(list) + for u, v in edges: + g[u].append(v) + g[v].append(u) + q = deque([0]) + vis = {0} + ans = d = 0 + while q: + d += 1 + t = d * 2 + for _ in range(len(q)): + u = q.popleft() + for v in g[u]: + if v not in vis: + vis.add(v) + q.append(v) + ans = max(ans, (t - 1) // patience[v] * patience[v] + t + 1) + return ans diff --git a/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/Solution.c b/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/Solution.c index 9ffc8c7014bbc..e7121a30666ce 100644 --- a/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/Solution.c +++ b/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/Solution.c @@ -18,4 +18,4 @@ bool areNumbersAscending(char* s) { return 0; } return 1; -} +} \ No newline at end of file diff --git a/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/Solution2.py b/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/Solution2.py new file mode 100644 index 0000000000000..69c4f2825e29e --- /dev/null +++ b/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/Solution2.py @@ -0,0 +1,16 @@ +class Solution: + def areNumbersAscending(self, s: str) -> bool: + pre = i = 0 + n = len(s) + while i < n: + if s[i].isdigit(): + cur = 0 + while i < n and s[i].isdigit(): + cur = cur * 10 + int(s[i]) + i += 1 + if pre >= cur: + return False + pre = cur + else: + i += 1 + return True diff --git a/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution2.cpp b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution2.cpp new file mode 100644 index 0000000000000..c8e8122f8587b --- /dev/null +++ b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution2.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int mx; + int ans; + + int countMaxOrSubsets(vector& nums) { + dfs(0, 0, nums); + return ans; + } + + void dfs(int u, int t, vector& nums) { + if (u == nums.size()) { + if (t > mx) { + mx = t; + ans = 1; + } else if (t == mx) + ++ans; + return; + } + dfs(u + 1, t, nums); + dfs(u + 1, t | nums[u], nums); + } +}; \ No newline at end of file diff --git a/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution2.go b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution2.go new file mode 100644 index 0000000000000..d017ea1ba963b --- /dev/null +++ b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution2.go @@ -0,0 +1,20 @@ +func countMaxOrSubsets(nums []int) int { + n := len(nums) + ans := 0 + mx := 0 + for mask := 1; mask < 1<> i) & 1) == 1 { + t |= v + } + } + if mx < t { + mx = t + ans = 1 + } else if mx == t { + ans++ + } + } + return ans +} \ No newline at end of file diff --git a/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution2.java b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution2.java new file mode 100644 index 0000000000000..75143a8b30763 --- /dev/null +++ b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution2.java @@ -0,0 +1,25 @@ +class Solution { + private int mx; + private int ans; + private int[] nums; + + public int countMaxOrSubsets(int[] nums) { + this.nums = nums; + dfs(0, 0); + return ans; + } + + private void dfs(int u, int t) { + if (u == nums.length) { + if (t > mx) { + mx = t; + ans = 1; + } else if (t == mx) { + ++ans; + } + return; + } + dfs(u + 1, t); + dfs(u + 1, t | nums[u]); + } +} \ No newline at end of file diff --git a/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution2.py b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution2.py new file mode 100644 index 0000000000000..c7fb372d8f204 --- /dev/null +++ b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution2.py @@ -0,0 +1,16 @@ +class Solution: + def countMaxOrSubsets(self, nums: List[int]) -> int: + def dfs(u, t): + nonlocal ans, mx + if u == len(nums): + if t > mx: + mx, ans = t, 1 + elif t == mx: + ans += 1 + return + dfs(u + 1, t | nums[u]) + dfs(u + 1, t) + + ans = mx = 0 + dfs(0, 0) + return ans diff --git a/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution2.ts b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution2.ts new file mode 100644 index 0000000000000..e3c35b2161906 --- /dev/null +++ b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution2.ts @@ -0,0 +1,21 @@ +function countMaxOrSubsets(nums: number[]): number { + const n = nums.length; + let res = 0; + let max = -Infinity; + const dfs = (i: number, sum: number) => { + for (let j = i; j < n; j++) { + const num = sum | nums[j]; + if (num >= max) { + if (num > max) { + max = num; + res = 0; + } + res++; + } + dfs(j + 1, num); + } + }; + dfs(0, 0); + + return res; +} diff --git a/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution3.cpp b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution3.cpp new file mode 100644 index 0000000000000..aebbbcaebe217 --- /dev/null +++ b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution3.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int countMaxOrSubsets(vector& nums) { + int n = nums.size(); + int ans = 0; + int mx = 0; + for (int mask = 1; mask < 1 << n; ++mask) { + int t = 0; + for (int i = 0; i < n; ++i) { + if ((mask >> i) & 1) { + t |= nums[i]; + } + } + if (mx < t) { + mx = t; + ans = 1; + } else if (mx == t) + ++ans; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution3.go b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution3.go new file mode 100644 index 0000000000000..0047a1dbf7d07 --- /dev/null +++ b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution3.go @@ -0,0 +1,18 @@ +func countMaxOrSubsets(nums []int) int { + mx, ans := 0, 0 + var dfs func(u, t int) + dfs = func(u, t int) { + if u == len(nums) { + if t > mx { + mx, ans = t, 1 + } else if t == mx { + ans++ + } + return + } + dfs(u+1, t) + dfs(u+1, t|nums[u]) + } + dfs(0, 0) + return ans +} \ No newline at end of file diff --git a/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution3.java b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution3.java new file mode 100644 index 0000000000000..401802a01543c --- /dev/null +++ b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution3.java @@ -0,0 +1,22 @@ +class Solution { + public int countMaxOrSubsets(int[] nums) { + int n = nums.length; + int ans = 0; + int mx = 0; + for (int mask = 1; mask < 1 << n; ++mask) { + int t = 0; + for (int i = 0; i < n; ++i) { + if (((mask >> i) & 1) == 1) { + t |= nums[i]; + } + } + if (mx < t) { + mx = t; + ans = 1; + } else if (mx == t) { + ++ans; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution3.py b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution3.py new file mode 100644 index 0000000000000..7f6b040cf392b --- /dev/null +++ b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution3.py @@ -0,0 +1,16 @@ +class Solution: + def countMaxOrSubsets(self, nums: List[int]) -> int: + n = len(nums) + ans = 0 + mx = 0 + for mask in range(1 << n): + t = 0 + for i, v in enumerate(nums): + if (mask >> i) & 1: + t |= v + if mx < t: + mx = t + ans = 1 + elif mx == t: + ans += 1 + return ans diff --git a/solution/2000-2099/2048.Next Greater Numerically Balanced Number/Solution.cpp b/solution/2000-2099/2048.Next Greater Numerically Balanced Number/Solution.cpp index de89a0cbea319..e2321a285c2da 100644 --- a/solution/2000-2099/2048.Next Greater Numerically Balanced Number/Solution.cpp +++ b/solution/2000-2099/2048.Next Greater Numerically Balanced Number/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - int nextBeautifulNumber(int n) { - for (int x = n + 1;; ++x) { - int cnt[10]{}; - for (int y = x; y > 0; y /= 10) { - ++cnt[y % 10]; - } - bool ok = true; - for (int y = x; y > 0; y /= 10) { - if (y % 10 != cnt[y % 10]) { - ok = false; - break; - } - } - if (ok) { - return x; - } - } - } +class Solution { +public: + int nextBeautifulNumber(int n) { + for (int x = n + 1;; ++x) { + int cnt[10]{}; + for (int y = x; y > 0; y /= 10) { + ++cnt[y % 10]; + } + bool ok = true; + for (int y = x; y > 0; y /= 10) { + if (y % 10 != cnt[y % 10]) { + ok = false; + break; + } + } + if (ok) { + return x; + } + } + } }; \ No newline at end of file diff --git a/solution/2000-2099/2048.Next Greater Numerically Balanced Number/Solution.java b/solution/2000-2099/2048.Next Greater Numerically Balanced Number/Solution.java index c9d5176a54146..da3752f4d0828 100644 --- a/solution/2000-2099/2048.Next Greater Numerically Balanced Number/Solution.java +++ b/solution/2000-2099/2048.Next Greater Numerically Balanced Number/Solution.java @@ -1,20 +1,20 @@ -class Solution { - public int nextBeautifulNumber(int n) { - for (int x = n + 1;; ++x) { - int[] cnt = new int[10]; - for (int y = x; y > 0; y /= 10) { - ++cnt[y % 10]; - } - boolean ok = true; - for (int y = x; y > 0; y /= 10) { - if (y % 10 != cnt[y % 10]) { - ok = false; - break; - } - } - if (ok) { - return x; - } - } - } +class Solution { + public int nextBeautifulNumber(int n) { + for (int x = n + 1;; ++x) { + int[] cnt = new int[10]; + for (int y = x; y > 0; y /= 10) { + ++cnt[y % 10]; + } + boolean ok = true; + for (int y = x; y > 0; y /= 10) { + if (y % 10 != cnt[y % 10]) { + ok = false; + break; + } + } + if (ok) { + return x; + } + } + } } \ No newline at end of file diff --git a/solution/2000-2099/2048.Next Greater Numerically Balanced Number/Solution.py b/solution/2000-2099/2048.Next Greater Numerically Balanced Number/Solution.py index 6d57e8ba368de..15aaea7d063e9 100644 --- a/solution/2000-2099/2048.Next Greater Numerically Balanced Number/Solution.py +++ b/solution/2000-2099/2048.Next Greater Numerically Balanced Number/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def nextBeautifulNumber(self, n: int) -> int: - for x in count(n + 1): - y = x - cnt = [0] * 10 - while y: - y, v = divmod(y, 10) - cnt[v] += 1 - if all(v == 0 or i == v for i, v in enumerate(cnt)): - return x +class Solution: + def nextBeautifulNumber(self, n: int) -> int: + for x in count(n + 1): + y = x + cnt = [0] * 10 + while y: + y, v = divmod(y, 10) + cnt[v] += 1 + if all(v == 0 or i == v for i, v in enumerate(cnt)): + return x diff --git a/solution/2000-2099/2049.Count Nodes With the Highest Score/Solution.cpp b/solution/2000-2099/2049.Count Nodes With the Highest Score/Solution.cpp index 5ff09c5828cb1..94fdcd4f17e58 100644 --- a/solution/2000-2099/2049.Count Nodes With the Highest Score/Solution.cpp +++ b/solution/2000-2099/2049.Count Nodes With the Highest Score/Solution.cpp @@ -1,35 +1,35 @@ -class Solution { -public: - int countHighestScoreNodes(vector& parents) { - int n = parents.size(); - vector g[n]; - for (int i = 1; i < n; ++i) { - g[parents[i]].push_back(i); - } - int ans = 0; - long long mx = 0; - function dfs = [&](int i, int fa) { - long long score = 1; - int cnt = 1; - for (int j : g[i]) { - if (j != fa) { - int t = dfs(j, i); - cnt += t; - score *= t; - } - } - if (n - cnt) { - score *= n - cnt; - } - if (mx < score) { - mx = score; - ans = 1; - } else if (mx == score) { - ++ans; - } - return cnt; - }; - dfs(0, -1); - return ans; - } +class Solution { +public: + int countHighestScoreNodes(vector& parents) { + int n = parents.size(); + vector g[n]; + for (int i = 1; i < n; ++i) { + g[parents[i]].push_back(i); + } + int ans = 0; + long long mx = 0; + function dfs = [&](int i, int fa) { + long long score = 1; + int cnt = 1; + for (int j : g[i]) { + if (j != fa) { + int t = dfs(j, i); + cnt += t; + score *= t; + } + } + if (n - cnt) { + score *= n - cnt; + } + if (mx < score) { + mx = score; + ans = 1; + } else if (mx == score) { + ++ans; + } + return cnt; + }; + dfs(0, -1); + return ans; + } }; \ No newline at end of file diff --git a/solution/2000-2099/2049.Count Nodes With the Highest Score/Solution.cs b/solution/2000-2099/2049.Count Nodes With the Highest Score/Solution.cs index 6e8df1379e693..4c3cc9b149c5f 100644 --- a/solution/2000-2099/2049.Count Nodes With the Highest Score/Solution.cs +++ b/solution/2000-2099/2049.Count Nodes With the Highest Score/Solution.cs @@ -1,46 +1,46 @@ -public class Solution { - private List[] g; - private int ans; - private long mx; - private int n; - - public int CountHighestScoreNodes(int[] parents) { - n = parents.Length; - g = new List[n]; - for (int i = 0; i < n; ++i) { - g[i] = new List(); - } - for (int i = 1; i < n; ++i) { - g[parents[i]].Add(i); - } - - Dfs(0, -1); - return ans; - } - - private int Dfs(int i, int fa) { - int cnt = 1; - long score = 1; - - foreach (int j in g[i]) { - if (j != fa) { - int t = Dfs(j, i); - cnt += t; - score *= t; - } - } - - if (n - cnt > 0) { - score *= n - cnt; - } - - if (mx < score) { - mx = score; - ans = 1; - } else if (mx == score) { - ++ans; - } - - return cnt; - } -} \ No newline at end of file +public class Solution { + private List[] g; + private int ans; + private long mx; + private int n; + + public int CountHighestScoreNodes(int[] parents) { + n = parents.Length; + g = new List[n]; + for (int i = 0; i < n; ++i) { + g[i] = new List(); + } + for (int i = 1; i < n; ++i) { + g[parents[i]].Add(i); + } + + Dfs(0, -1); + return ans; + } + + private int Dfs(int i, int fa) { + int cnt = 1; + long score = 1; + + foreach (int j in g[i]) { + if (j != fa) { + int t = Dfs(j, i); + cnt += t; + score *= t; + } + } + + if (n - cnt > 0) { + score *= n - cnt; + } + + if (mx < score) { + mx = score; + ans = 1; + } else if (mx == score) { + ++ans; + } + + return cnt; + } +} diff --git a/solution/2000-2099/2049.Count Nodes With the Highest Score/Solution.java b/solution/2000-2099/2049.Count Nodes With the Highest Score/Solution.java index 2b0036f6860e5..e639b57259af5 100644 --- a/solution/2000-2099/2049.Count Nodes With the Highest Score/Solution.java +++ b/solution/2000-2099/2049.Count Nodes With the Highest Score/Solution.java @@ -1,39 +1,39 @@ -class Solution { - private List[] g; - private int ans; - private long mx; - private int n; - - public int countHighestScoreNodes(int[] parents) { - n = parents.length; - g = new List[n]; - Arrays.setAll(g, i -> new ArrayList<>()); - for (int i = 1; i < n; ++i) { - g[parents[i]].add(i); - } - dfs(0, -1); - return ans; - } - - private int dfs(int i, int fa) { - int cnt = 1; - long score = 1; - for (int j : g[i]) { - if (j != fa) { - int t = dfs(j, i); - cnt += t; - score *= t; - } - } - if (n - cnt > 0) { - score *= n - cnt; - } - if (mx < score) { - mx = score; - ans = 1; - } else if (mx == score) { - ++ans; - } - return cnt; - } +class Solution { + private List[] g; + private int ans; + private long mx; + private int n; + + public int countHighestScoreNodes(int[] parents) { + n = parents.length; + g = new List[n]; + Arrays.setAll(g, i -> new ArrayList<>()); + for (int i = 1; i < n; ++i) { + g[parents[i]].add(i); + } + dfs(0, -1); + return ans; + } + + private int dfs(int i, int fa) { + int cnt = 1; + long score = 1; + for (int j : g[i]) { + if (j != fa) { + int t = dfs(j, i); + cnt += t; + score *= t; + } + } + if (n - cnt > 0) { + score *= n - cnt; + } + if (mx < score) { + mx = score; + ans = 1; + } else if (mx == score) { + ++ans; + } + return cnt; + } } \ No newline at end of file diff --git a/solution/2000-2099/2049.Count Nodes With the Highest Score/Solution.py b/solution/2000-2099/2049.Count Nodes With the Highest Score/Solution.py index 98c76cea5b05d..b3f2991e6096a 100644 --- a/solution/2000-2099/2049.Count Nodes With the Highest Score/Solution.py +++ b/solution/2000-2099/2049.Count Nodes With the Highest Score/Solution.py @@ -1,26 +1,26 @@ -class Solution: - def countHighestScoreNodes(self, parents: List[int]) -> int: - def dfs(i: int, fa: int): - cnt = score = 1 - for j in g[i]: - if j != fa: - t = dfs(j, i) - score *= t - cnt += t - if n - cnt: - score *= n - cnt - nonlocal ans, mx - if mx < score: - mx = score - ans = 1 - elif mx == score: - ans += 1 - return cnt - - n = len(parents) - g = [[] for _ in range(n)] - for i in range(1, n): - g[parents[i]].append(i) - ans = mx = 0 - dfs(0, -1) - return ans +class Solution: + def countHighestScoreNodes(self, parents: List[int]) -> int: + def dfs(i: int, fa: int): + cnt = score = 1 + for j in g[i]: + if j != fa: + t = dfs(j, i) + score *= t + cnt += t + if n - cnt: + score *= n - cnt + nonlocal ans, mx + if mx < score: + mx = score + ans = 1 + elif mx == score: + ans += 1 + return cnt + + n = len(parents) + g = [[] for _ in range(n)] + for i in range(1, n): + g[parents[i]].append(i) + ans = mx = 0 + dfs(0, -1) + return ans diff --git a/solution/2000-2099/2057.Smallest Index With Equal Value/Solution.cpp b/solution/2000-2099/2057.Smallest Index With Equal Value/Solution.cpp new file mode 100644 index 0000000000000..beb1a32a49953 --- /dev/null +++ b/solution/2000-2099/2057.Smallest Index With Equal Value/Solution.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + int smallestEqual(vector& nums) { + for (int i = 0; i < nums.size(); ++i) + if (i % 10 == nums[i]) + return i; + return -1; + } +}; \ No newline at end of file diff --git a/solution/2000-2099/2058.Find the Minimum and Maximum Number of Nodes Between Critical Points/Solution.java b/solution/2000-2099/2058.Find the Minimum and Maximum Number of Nodes Between Critical Points/Solution.java index 40cf7f1fd3d8f..35561da25d1f7 100644 --- a/solution/2000-2099/2058.Find the Minimum and Maximum Number of Nodes Between Critical Points/Solution.java +++ b/solution/2000-2099/2058.Find the Minimum and Maximum Number of Nodes Between Critical Points/Solution.java @@ -9,6 +9,7 @@ * } */ class Solution { + public int[] nodesBetweenCriticalPoints(ListNode head) { ListNode prev = head; ListNode curr = head.next; diff --git a/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution.cpp b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution.cpp index 21c9d09ea2595..a5a8dce39e47a 100644 --- a/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution.cpp +++ b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution.cpp @@ -28,4 +28,4 @@ class Solution { } return -1; } -}; +}; \ No newline at end of file diff --git a/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution.java b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution.java index 99f47f80e8537..dc02dfddfd0ac 100644 --- a/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution.java +++ b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution.java @@ -25,4 +25,4 @@ public int minimumOperations(int[] nums, int start, int goal) { } return -1; } -} +} \ No newline at end of file diff --git a/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution2.cpp b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution2.cpp new file mode 100644 index 0000000000000..b01855ac4f291 --- /dev/null +++ b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution2.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int minimumOperations(vector& nums, int start, int goal) { + queue q{{start}}; + vector vis(1001); + int ans = 0; + while (!q.empty()) { + ++ans; + for (int n = q.size(); n > 0; --n) { + int x = q.front(); + q.pop(); + for (int y : next(nums, x)) { + if (y == goal) return ans; + if (y >= 0 && y <= 1000 && !vis[y]) { + vis[y] = true; + q.push(y); + } + } + } + } + return -1; + } + + vector next(vector& nums, int x) { + vector res; + for (int num : nums) { + res.push_back(x + num); + res.push_back(x - num); + res.push_back(x ^ num); + } + return res; + } +}; \ No newline at end of file diff --git a/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution2.go b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution2.go new file mode 100644 index 0000000000000..9c31ed337f294 --- /dev/null +++ b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution2.go @@ -0,0 +1,29 @@ +func minimumOperations(nums []int, start int, goal int) int { + next := func(x int) []int { + var res []int + for _, num := range nums { + res = append(res, []int{x + num, x - num, x ^ num}...) + } + return res + } + q := []int{start} + vis := make([]bool, 1001) + ans := 0 + for len(q) > 0 { + ans++ + for n := len(q); n > 0; n-- { + x := q[0] + q = q[1:] + for _, y := range next(x) { + if y == goal { + return ans + } + if y >= 0 && y <= 1000 && !vis[y] { + vis[y] = true + q = append(q, y) + } + } + } + } + return -1 +} \ No newline at end of file diff --git a/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution2.java b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution2.java new file mode 100644 index 0000000000000..502d9265041f9 --- /dev/null +++ b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution2.java @@ -0,0 +1,34 @@ +class Solution { + public int minimumOperations(int[] nums, int start, int goal) { + Deque q = new ArrayDeque<>(); + q.offer(start); + boolean[] vis = new boolean[1001]; + int ans = 0; + while (!q.isEmpty()) { + ++ans; + for (int n = q.size(); n > 0; --n) { + int x = q.poll(); + for (int y : next(nums, x)) { + if (y == goal) { + return ans; + } + if (y >= 0 && y <= 1000 && !vis[y]) { + vis[y] = true; + q.offer(y); + } + } + } + } + return -1; + } + + private List next(int[] nums, int x) { + List res = new ArrayList<>(); + for (int num : nums) { + res.add(x + num); + res.add(x - num); + res.add(x ^ num); + } + return res; + } +} \ No newline at end of file diff --git a/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution2.py b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution2.py new file mode 100644 index 0000000000000..7c7f43fec0d2b --- /dev/null +++ b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution2.py @@ -0,0 +1,24 @@ +class Solution: + def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: + def next(x): + res = [] + for num in nums: + res.append(x + num) + res.append(x - num) + res.append(x ^ num) + return res + + q = deque([start]) + vis = {start} + ans = 0 + while q: + ans += 1 + for _ in range(len(q)): + x = q.popleft() + for y in next(x): + if y == goal: + return ans + if 0 <= y <= 1000 and y not in vis: + vis.add(y) + q.append(y) + return -1 diff --git a/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution3.cpp b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution3.cpp new file mode 100644 index 0000000000000..c9baf652aa45b --- /dev/null +++ b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution3.cpp @@ -0,0 +1,43 @@ +class Solution { +public: + int minimumOperations(vector& nums, int start, int goal) { + unordered_map m1; + unordered_map m2; + m1[start] = 0; + m2[goal] = 0; + queue q1{{start}}; + queue q2{{goal}}; + while (!q1.empty() && !q2.empty()) { + int t = q1.size() <= q2.size() ? extend(m1, m2, q1, nums) : extend(m2, m1, q2, nums); + if (t != -1) return t; + } + return -1; + } + + int extend(unordered_map& m1, unordered_map& m2, queue& q, vector& nums) { + for (int i = q.size(); i > 0; --i) { + int x = q.front(); + int step = m1[x]; + q.pop(); + for (int y : next(nums, x)) { + if (m1.count(y)) continue; + if (m2.count(y)) return step + 1 + m2[y]; + if (y >= 0 && y <= 1000) { + m1[y] = step + 1; + q.push(y); + } + } + } + return -1; + } + + vector next(vector& nums, int x) { + vector res; + for (int num : nums) { + res.push_back(x + num); + res.push_back(x - num); + res.push_back(x ^ num); + } + return res; + } +}; \ No newline at end of file diff --git a/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution3.go b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution3.go new file mode 100644 index 0000000000000..8434172cbff65 --- /dev/null +++ b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution3.go @@ -0,0 +1,42 @@ +func minimumOperations(nums []int, start int, goal int) int { + next := func(x int) []int { + var res []int + for _, num := range nums { + res = append(res, []int{x + num, x - num, x ^ num}...) + } + return res + } + m1, m2 := map[int]int{start: 0}, map[int]int{goal: 0} + q1, q2 := []int{start}, []int{goal} + extend := func() int { + for i := len(q1); i > 0; i-- { + x := q1[0] + q1 = q1[1:] + step, _ := m1[x] + for _, y := range next(x) { + if _, ok := m1[y]; ok { + continue + } + if v, ok := m2[y]; ok { + return step + 1 + v + } + if y >= 0 && y <= 1000 { + m1[y] = step + 1 + q1 = append(q1, y) + } + } + } + return -1 + } + for len(q1) > 0 && len(q2) > 0 { + if len(q1) > len(q2) { + m1, m2 = m2, m1 + q1, q2 = q2, q1 + } + t := extend() + if t != -1 { + return t + } + } + return -1 +} \ No newline at end of file diff --git a/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution3.java b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution3.java new file mode 100644 index 0000000000000..a7912fd89cbe7 --- /dev/null +++ b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution3.java @@ -0,0 +1,52 @@ +class Solution { + private int[] nums; + + public int minimumOperations(int[] nums, int start, int goal) { + this.nums = nums; + Map m1 = new HashMap<>(); + Map m2 = new HashMap<>(); + Deque q1 = new ArrayDeque<>(); + Deque q2 = new ArrayDeque<>(); + m1.put(start, 0); + m2.put(goal, 0); + q1.offer(start); + q2.offer(goal); + while (!q1.isEmpty() && !q2.isEmpty()) { + int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); + if (t != -1) { + return t; + } + } + return -1; + } + + private int extend(Map m1, Map m2, Deque q) { + for (int i = q.size(); i > 0; --i) { + int x = q.poll(); + int step = m1.get(x); + for (int y : next(x)) { + if (m1.containsKey(y)) { + continue; + } + if (m2.containsKey(y)) { + return step + 1 + m2.get(y); + } + if (y >= 0 && y <= 1000) { + m1.put(y, step + 1); + q.offer(y); + } + } + } + return -1; + } + + private List next(int x) { + List res = new ArrayList<>(); + for (int num : nums) { + res.add(x + num); + res.add(x - num); + res.add(x ^ num); + } + return res; + } +} \ No newline at end of file diff --git a/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution3.py b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution3.py new file mode 100644 index 0000000000000..f69de2447bb95 --- /dev/null +++ b/solution/2000-2099/2059.Minimum Operations to Convert Number/Solution3.py @@ -0,0 +1,31 @@ +class Solution: + def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: + def next(x): + res = [] + for num in nums: + res.append(x + num) + res.append(x - num) + res.append(x ^ num) + return res + + def extend(m1, m2, q): + for _ in range(len(q)): + x = q.popleft() + step = m1[x] + for y in next(x): + if y in m1: + continue + if y in m2: + return step + 1 + m2[y] + if 0 <= y <= 1000: + m1[y] = step + 1 + q.append(y) + return -1 + + m1, m2 = {start: 0}, {goal: 0} + q1, q2 = deque([start]), deque([goal]) + while q1 and q2: + t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) + if t != -1: + return t + return -1 diff --git a/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/Solution2.cpp b/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/Solution2.cpp new file mode 100644 index 0000000000000..9674c1fa4abdd --- /dev/null +++ b/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/Solution2.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int numberOfCleanRooms(vector>& room) { + int dirs[5] = {0, 1, 0, -1, 0}; + int i = 0, j = 0, k = 0; + int m = room.size(), n = room[0].size(); + bool vis[m][n][4]; + memset(vis, false, sizeof(vis)); + int ans = 0; + while (!vis[i][j][k]) { + vis[i][j][k] = true; + ans += room[i][j] == 0 ? 1 : 0; + room[i][j] = -1; + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && room[x][y] != 1) { + i = x; + j = y; + } else { + k = (k + 1) % 4; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/Solution2.go b/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/Solution2.go new file mode 100644 index 0000000000000..59727af7ad588 --- /dev/null +++ b/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/Solution2.go @@ -0,0 +1,23 @@ +func numberOfCleanRooms(room [][]int) (ans int) { + m, n := len(room), len(room[0]) + vis := make([][][4]bool, m) + for i := range vis { + vis[i] = make([][4]bool, n) + } + dirs := [5]int{0, 1, 0, -1, 0} + var i, j, k int + for !vis[i][j][k] { + vis[i][j][k] = true + if room[i][j] == 0 { + ans++ + room[i][j] = -1 + } + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n && room[x][y] != 1 { + i, j = x, y + } else { + k = (k + 1) % 4 + } + } + return +} \ No newline at end of file diff --git a/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/Solution2.java b/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/Solution2.java new file mode 100644 index 0000000000000..8091d4ebf230b --- /dev/null +++ b/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/Solution2.java @@ -0,0 +1,22 @@ +class Solution { + public int numberOfCleanRooms(int[][] room) { + int[] dirs = {0, 1, 0, -1, 0}; + int i = 0, j = 0, k = 0; + int m = room.length, n = room[0].length; + boolean[][][] vis = new boolean[m][n][4]; + int ans = 0; + while (!vis[i][j][k]) { + vis[i][j][k] = true; + ans += room[i][j] == 0 ? 1 : 0; + room[i][j] = -1; + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && room[x][y] != 1) { + i = x; + j = y; + } else { + k = (k + 1) % 4; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/Solution2.py b/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/Solution2.py new file mode 100644 index 0000000000000..455cb1e6b0f60 --- /dev/null +++ b/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/Solution2.py @@ -0,0 +1,16 @@ +class Solution: + def numberOfCleanRooms(self, room: List[List[int]]) -> int: + dirs = (0, 1, 0, -1, 0) + i = j = k = 0 + ans = 0 + vis = set() + while (i, j, k) not in vis: + vis.add((i, j, k)) + ans += room[i][j] == 0 + room[i][j] = -1 + x, y = i + dirs[k], j + dirs[k + 1] + if 0 <= x < len(room) and 0 <= y < len(room[0]) and room[x][y] != 1: + i, j = x, y + else: + k = (k + 1) % 4 + return ans diff --git a/solution/2000-2099/2062.Count Vowel Substrings of a String/Solution2.py b/solution/2000-2099/2062.Count Vowel Substrings of a String/Solution2.py new file mode 100644 index 0000000000000..1716ea8343c95 --- /dev/null +++ b/solution/2000-2099/2062.Count Vowel Substrings of a String/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def countVowelSubstrings(self, word: str) -> int: + s = set('aeiou') + ans, n = 0, len(word) + for i in range(n): + t = set() + for c in word[i:]: + if c not in s: + break + t.add(c) + ans += len(t) == 5 + return ans diff --git a/solution/2000-2099/2068.Check Whether Two Strings are Almost Equivalent/Solution.cs b/solution/2000-2099/2068.Check Whether Two Strings are Almost Equivalent/Solution.cs index 65415ab448f78..61814f357fc08 100644 --- a/solution/2000-2099/2068.Check Whether Two Strings are Almost Equivalent/Solution.cs +++ b/solution/2000-2099/2068.Check Whether Two Strings are Almost Equivalent/Solution.cs @@ -9,4 +9,4 @@ public bool CheckAlmostEquivalent(string word1, string word2) { } return cnt.All(x => Math.Abs(x) <= 3); } -} \ No newline at end of file +} diff --git a/solution/2000-2099/2068.Check Whether Two Strings are Almost Equivalent/Solution.php b/solution/2000-2099/2068.Check Whether Two Strings are Almost Equivalent/Solution.php index 8fac2775f77cc..d86785082bed3 100644 --- a/solution/2000-2099/2068.Check Whether Two Strings are Almost Equivalent/Solution.php +++ b/solution/2000-2099/2068.Check Whether Two Strings are Almost Equivalent/Solution.php @@ -17,4 +17,4 @@ function checkAlmostEquivalent($word1, $word2) { } return true; } -} \ No newline at end of file +} diff --git a/solution/2000-2099/2073.Time Needed to Buy Tickets/Solution.cpp b/solution/2000-2099/2073.Time Needed to Buy Tickets/Solution.cpp index 47b871b6be7fd..03b07970f1918 100644 --- a/solution/2000-2099/2073.Time Needed to Buy Tickets/Solution.cpp +++ b/solution/2000-2099/2073.Time Needed to Buy Tickets/Solution.cpp @@ -11,4 +11,4 @@ class Solution { } return ans; } -}; +}; \ No newline at end of file diff --git a/solution/2000-2099/2073.Time Needed to Buy Tickets/Solution.java b/solution/2000-2099/2073.Time Needed to Buy Tickets/Solution.java index 1e881783fee1b..f9c6f7d7394c1 100644 --- a/solution/2000-2099/2073.Time Needed to Buy Tickets/Solution.java +++ b/solution/2000-2099/2073.Time Needed to Buy Tickets/Solution.java @@ -10,4 +10,4 @@ public int timeRequiredToBuy(int[] tickets, int k) { } return ans; } -} +} \ No newline at end of file diff --git a/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution.cpp b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution.cpp index ea7332169f602..d79f26f9059fa 100644 --- a/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution.cpp +++ b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution.cpp @@ -1,13 +1,11 @@ class Solution { public: int maxDistance(vector& colors) { - int n = colors.size(); - if (colors[0] != colors[n - 1]) return n - 1; - int i = 0, j = n; - while (colors[++i] == colors[0]) - ; - while (colors[--j] == colors[0]) - ; - return max(n - i - 1, j); + int ans = 0, n = colors.size(); + for (int i = 0; i < n; ++i) + for (int j = i + 1; j < n; ++j) + if (colors[i] != colors[j]) + ans = max(ans, abs(i - j)); + return ans; } }; \ No newline at end of file diff --git a/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution.go b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution.go index ec306e8075cf5..1745d3c861d40 100644 --- a/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution.go +++ b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution.go @@ -1,14 +1,18 @@ func maxDistance(colors []int) int { - n := len(colors) - if colors[0] != colors[n-1] { - return n - 1 + ans, n := 0, len(colors) + for i := 0; i < n; i++ { + for j := i + 1; j < n; j++ { + if colors[i] != colors[j] { + ans = max(ans, abs(i-j)) + } + } } - i, j := 1, n-2 - for colors[i] == colors[0] { - i++ + return ans +} + +func abs(x int) int { + if x >= 0 { + return x } - for colors[j] == colors[0] { - j-- - } - return max(n-i-1, j) + return -x } \ No newline at end of file diff --git a/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution.java b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution.java index 04e7a41d6334e..759bd7931160f 100644 --- a/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution.java +++ b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution.java @@ -1,14 +1,13 @@ class Solution { public int maxDistance(int[] colors) { - int n = colors.length; - if (colors[0] != colors[n - 1]) { - return n - 1; + int ans = 0, n = colors.length; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + if (colors[i] != colors[j]) { + ans = Math.max(ans, Math.abs(i - j)); + } + } } - int i = 0, j = n - 1; - while (colors[++i] == colors[0]) - ; - while (colors[--j] == colors[0]) - ; - return Math.max(n - i - 1, j); + return ans; } } \ No newline at end of file diff --git a/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution.py b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution.py index 50cf4d1eee602..ed4b530ddce7e 100644 --- a/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution.py +++ b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution.py @@ -1,11 +1,8 @@ class Solution: def maxDistance(self, colors: List[int]) -> int: - n = len(colors) - if colors[0] != colors[-1]: - return n - 1 - i, j = 1, n - 2 - while colors[i] == colors[0]: - i += 1 - while colors[j] == colors[0]: - j -= 1 - return max(n - i - 1, j) + ans, n = 0, len(colors) + for i in range(n): + for j in range(i + 1, n): + if colors[i] != colors[j]: + ans = max(ans, abs(i - j)) + return ans diff --git a/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution2.cpp b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution2.cpp new file mode 100644 index 0000000000000..ea7332169f602 --- /dev/null +++ b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution2.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int maxDistance(vector& colors) { + int n = colors.size(); + if (colors[0] != colors[n - 1]) return n - 1; + int i = 0, j = n; + while (colors[++i] == colors[0]) + ; + while (colors[--j] == colors[0]) + ; + return max(n - i - 1, j); + } +}; \ No newline at end of file diff --git a/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution2.go b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution2.go new file mode 100644 index 0000000000000..ec306e8075cf5 --- /dev/null +++ b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution2.go @@ -0,0 +1,14 @@ +func maxDistance(colors []int) int { + n := len(colors) + if colors[0] != colors[n-1] { + return n - 1 + } + i, j := 1, n-2 + for colors[i] == colors[0] { + i++ + } + for colors[j] == colors[0] { + j-- + } + return max(n-i-1, j) +} \ No newline at end of file diff --git a/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution2.java b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution2.java new file mode 100644 index 0000000000000..04e7a41d6334e --- /dev/null +++ b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public int maxDistance(int[] colors) { + int n = colors.length; + if (colors[0] != colors[n - 1]) { + return n - 1; + } + int i = 0, j = n - 1; + while (colors[++i] == colors[0]) + ; + while (colors[--j] == colors[0]) + ; + return Math.max(n - i - 1, j); + } +} \ No newline at end of file diff --git a/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution2.py b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution2.py new file mode 100644 index 0000000000000..50cf4d1eee602 --- /dev/null +++ b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def maxDistance(self, colors: List[int]) -> int: + n = len(colors) + if colors[0] != colors[-1]: + return n - 1 + i, j = 1, n - 2 + while colors[i] == colors[0]: + i += 1 + while colors[j] == colors[0]: + j -= 1 + return max(n - i - 1, j) diff --git a/solution/2000-2099/2079.Watering Plants/Solution.c b/solution/2000-2099/2079.Watering Plants/Solution.c index b971f832b08cf..389eab88e5cd5 100644 --- a/solution/2000-2099/2079.Watering Plants/Solution.c +++ b/solution/2000-2099/2079.Watering Plants/Solution.c @@ -11,4 +11,4 @@ int wateringPlants(int* plants, int plantsSize, int capacity) { } } return ans; -} +} \ No newline at end of file diff --git a/solution/2000-2099/2080.Range Frequency Queries/Solution.py b/solution/2000-2099/2080.Range Frequency Queries/Solution.py index 5d95b7b06bb3c..14e2f13e90b02 100644 --- a/solution/2000-2099/2080.Range Frequency Queries/Solution.py +++ b/solution/2000-2099/2080.Range Frequency Queries/Solution.py @@ -1,17 +1,17 @@ -class RangeFreqQuery: - def __init__(self, arr: List[int]): - self.mp = defaultdict(list) - for i, x in enumerate(arr): - self.mp[x].append(i) - - def query(self, left: int, right: int, value: int) -> int: - if value not in self.mp: - return 0 - arr = self.mp[value] - l, r = bisect_right(arr, left - 1), bisect_right(arr, right) - return r - l - - -# Your RangeFreqQuery object will be instantiated and called as such: -# obj = RangeFreqQuery(arr) -# param_1 = obj.query(left,right,value) +class RangeFreqQuery: + def __init__(self, arr: List[int]): + self.mp = defaultdict(list) + for i, x in enumerate(arr): + self.mp[x].append(i) + + def query(self, left: int, right: int, value: int) -> int: + if value not in self.mp: + return 0 + arr = self.mp[value] + l, r = bisect_right(arr, left - 1), bisect_right(arr, right) + return r - l + + +# Your RangeFreqQuery object will be instantiated and called as such: +# obj = RangeFreqQuery(arr) +# param_1 = obj.query(left,right,value) diff --git a/solution/2000-2099/2084.Drop Type 1 Orders for Customers With Type 0 Orders/Solution2.sql b/solution/2000-2099/2084.Drop Type 1 Orders for Customers With Type 0 Orders/Solution2.sql new file mode 100644 index 0000000000000..34bc67a7d647a --- /dev/null +++ b/solution/2000-2099/2084.Drop Type 1 Orders for Customers With Type 0 Orders/Solution2.sql @@ -0,0 +1,8 @@ +SELECT DISTINCT + a.order_id, + a.customer_id, + a.order_type +FROM + Orders AS a + LEFT JOIN Orders AS b ON a.customer_id = b.customer_id AND a.order_type != b.order_type +WHERE b.order_type IS NULL OR b.order_type = 1; diff --git a/solution/2000-2099/2090.K Radius Subarray Averages/Solution.cpp b/solution/2000-2099/2090.K Radius Subarray Averages/Solution.cpp index f5a1b6e64079e..f0682fae3c557 100644 --- a/solution/2000-2099/2090.K Radius Subarray Averages/Solution.cpp +++ b/solution/2000-2099/2090.K Radius Subarray Averages/Solution.cpp @@ -2,13 +2,15 @@ class Solution { public: vector getAverages(vector& nums, int k) { int n = nums.size(); + long s[n + 1]; + s[0] = 0; + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } vector ans(n, -1); - long s = 0; for (int i = 0; i < n; ++i) { - s += nums[i]; - if (i >= k * 2) { - ans[i - k] = s / (k * 2 + 1); - s -= nums[i - k * 2]; + if (i - k >= 0 && i + k < n) { + ans[i] = (s[i + k + 1] - s[i - k]) / (k << 1 | 1); } } return ans; diff --git a/solution/2000-2099/2090.K Radius Subarray Averages/Solution.go b/solution/2000-2099/2090.K Radius Subarray Averages/Solution.go index 2a261c950e403..672a6b277c552 100644 --- a/solution/2000-2099/2090.K Radius Subarray Averages/Solution.go +++ b/solution/2000-2099/2090.K Radius Subarray Averages/Solution.go @@ -1,12 +1,14 @@ func getAverages(nums []int, k int) []int { - ans := make([]int, len(nums)) - s := 0 + n := len(nums) + s := make([]int, n+1) for i, v := range nums { + s[i+1] = s[i] + v + } + ans := make([]int, n) + for i := 0; i < n; i++ { ans[i] = -1 - s += v - if i >= k*2 { - ans[i-k] = s / (k*2 + 1) - s -= nums[i-k*2] + if i-k >= 0 && i+k < n { + ans[i] = (s[i+k+1] - s[i-k]) / (k<<1 | 1) } } return ans diff --git a/solution/2000-2099/2090.K Radius Subarray Averages/Solution.py b/solution/2000-2099/2090.K Radius Subarray Averages/Solution.py index 74e99367c92b2..d40cb12522961 100644 --- a/solution/2000-2099/2090.K Radius Subarray Averages/Solution.py +++ b/solution/2000-2099/2090.K Radius Subarray Averages/Solution.py @@ -1,10 +1,9 @@ class Solution: def getAverages(self, nums: List[int], k: int) -> List[int]: - s = 0 - ans = [-1] * len(nums) - for i, v in enumerate(nums): - s += v - if i >= k * 2: - ans[i - k] = s // (k * 2 + 1) - s -= nums[i - k * 2] + n = len(nums) + ans = [-1] * n + s = list(accumulate(nums, initial=0)) + for i in range(n): + if i - k >= 0 and i + k < n: + ans[i] = (s[i + k + 1] - s[i - k]) // (k << 1 | 1) return ans diff --git a/solution/2000-2099/2090.K Radius Subarray Averages/Solution.ts b/solution/2000-2099/2090.K Radius Subarray Averages/Solution.ts index 95708268e942c..51073963e6038 100644 --- a/solution/2000-2099/2090.K Radius Subarray Averages/Solution.ts +++ b/solution/2000-2099/2090.K Radius Subarray Averages/Solution.ts @@ -1,12 +1,13 @@ function getAverages(nums: number[], k: number): number[] { const n = nums.length; + const s = new Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } const ans: number[] = new Array(n).fill(-1); - let s = 0; for (let i = 0; i < n; ++i) { - s += nums[i]; - if (i >= k * 2) { - ans[i - k] = Math.floor(s / (k * 2 + 1)); - s -= nums[i - k * 2]; + if (i - k >= 0 && i + k < n) { + ans[i] = Math.floor((s[i + k + 1] - s[i - k]) / ((k << 1) | 1)); } } return ans; diff --git a/solution/2000-2099/2090.K Radius Subarray Averages/Solution2.cpp b/solution/2000-2099/2090.K Radius Subarray Averages/Solution2.cpp new file mode 100644 index 0000000000000..f5a1b6e64079e --- /dev/null +++ b/solution/2000-2099/2090.K Radius Subarray Averages/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector getAverages(vector& nums, int k) { + int n = nums.size(); + vector ans(n, -1); + long s = 0; + for (int i = 0; i < n; ++i) { + s += nums[i]; + if (i >= k * 2) { + ans[i - k] = s / (k * 2 + 1); + s -= nums[i - k * 2]; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2000-2099/2090.K Radius Subarray Averages/Solution2.go b/solution/2000-2099/2090.K Radius Subarray Averages/Solution2.go new file mode 100644 index 0000000000000..2a261c950e403 --- /dev/null +++ b/solution/2000-2099/2090.K Radius Subarray Averages/Solution2.go @@ -0,0 +1,13 @@ +func getAverages(nums []int, k int) []int { + ans := make([]int, len(nums)) + s := 0 + for i, v := range nums { + ans[i] = -1 + s += v + if i >= k*2 { + ans[i-k] = s / (k*2 + 1) + s -= nums[i-k*2] + } + } + return ans +} \ No newline at end of file diff --git a/solution/2000-2099/2090.K Radius Subarray Averages/Solution2.java b/solution/2000-2099/2090.K Radius Subarray Averages/Solution2.java new file mode 100644 index 0000000000000..a4111a38ce296 --- /dev/null +++ b/solution/2000-2099/2090.K Radius Subarray Averages/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public int[] getAverages(int[] nums, int k) { + int n = nums.length; + int[] ans = new int[n]; + Arrays.fill(ans, -1); + long s = 0; + for (int i = 0; i < n; ++i) { + s += nums[i]; + if (i >= k * 2) { + ans[i - k] = (int) (s / (k * 2 + 1)); + s -= nums[i - k * 2]; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2000-2099/2090.K Radius Subarray Averages/Solution2.py b/solution/2000-2099/2090.K Radius Subarray Averages/Solution2.py new file mode 100644 index 0000000000000..74e99367c92b2 --- /dev/null +++ b/solution/2000-2099/2090.K Radius Subarray Averages/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def getAverages(self, nums: List[int], k: int) -> List[int]: + s = 0 + ans = [-1] * len(nums) + for i, v in enumerate(nums): + s += v + if i >= k * 2: + ans[i - k] = s // (k * 2 + 1) + s -= nums[i - k * 2] + return ans diff --git a/solution/2000-2099/2090.K Radius Subarray Averages/Solution2.ts b/solution/2000-2099/2090.K Radius Subarray Averages/Solution2.ts new file mode 100644 index 0000000000000..95708268e942c --- /dev/null +++ b/solution/2000-2099/2090.K Radius Subarray Averages/Solution2.ts @@ -0,0 +1,13 @@ +function getAverages(nums: number[], k: number): number[] { + const n = nums.length; + const ans: number[] = new Array(n).fill(-1); + let s = 0; + for (let i = 0; i < n; ++i) { + s += nums[i]; + if (i >= k * 2) { + ans[i - k] = Math.floor(s / (k * 2 + 1)); + s -= nums[i - k * 2]; + } + } + return ans; +} diff --git a/solution/2100-2199/2100.Find Good Days to Rob the Bank/Solution.cpp b/solution/2100-2199/2100.Find Good Days to Rob the Bank/Solution.cpp index 931cda976ed09..8948561741f00 100644 --- a/solution/2100-2199/2100.Find Good Days to Rob the Bank/Solution.cpp +++ b/solution/2100-2199/2100.Find Good Days to Rob the Bank/Solution.cpp @@ -12,7 +12,7 @@ class Solution { if (security[i] <= security[i + 1]) right[i] = right[i + 1] + 1; vector ans; - for (int i = tiem; i < n - time; ++i) + for (int i = time; i < n - time; ++i) if (time <= min(left[i], right[i])) ans.push_back(i); return ans; diff --git a/solution/2100-2199/2101.Detonate the Maximum Bombs/Solution.cpp b/solution/2100-2199/2101.Detonate the Maximum Bombs/Solution.cpp index b523c70986c8e..2d7322f3aba77 100644 --- a/solution/2100-2199/2101.Detonate the Maximum Bombs/Solution.cpp +++ b/solution/2100-2199/2101.Detonate the Maximum Bombs/Solution.cpp @@ -1,38 +1,38 @@ -class Solution { -public: - int maximumDetonation(vector>& bombs) { - int n = bombs.size(); - vector> g(n, vector(n)); - for (int i = 0; i < n; ++i) - for (int j = 0; j < n; ++j) - g[i][j] = check(i, j, bombs); - int ans = 0; - for (int k = 0; k < n; ++k) { - queue q{{k}}; - vector vis(n); - vis[k] = true; - int cnt = 0; - while (!q.empty()) { - int i = q.front(); - q.pop(); - ++cnt; - for (int j = 0; j < n; ++j) { - if (g[i][j] && !vis[j]) { - vis[j] = true; - q.push(j); - } - } - } - ans = max(ans, cnt); - } - return ans; - } - - bool check(int i, int j, vector>& bombs) { - if (i == j) return false; - long long x = bombs[i][0] - bombs[j][0]; - long long y = bombs[i][1] - bombs[j][1]; - long long r = bombs[i][2]; - return r * r >= x * x + y * y; - } +class Solution { +public: + int maximumDetonation(vector>& bombs) { + int n = bombs.size(); + vector> g(n, vector(n)); + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + g[i][j] = check(i, j, bombs); + int ans = 0; + for (int k = 0; k < n; ++k) { + queue q{{k}}; + vector vis(n); + vis[k] = true; + int cnt = 0; + while (!q.empty()) { + int i = q.front(); + q.pop(); + ++cnt; + for (int j = 0; j < n; ++j) { + if (g[i][j] && !vis[j]) { + vis[j] = true; + q.push(j); + } + } + } + ans = max(ans, cnt); + } + return ans; + } + + bool check(int i, int j, vector>& bombs) { + if (i == j) return false; + long long x = bombs[i][0] - bombs[j][0]; + long long y = bombs[i][1] - bombs[j][1]; + long long r = bombs[i][2]; + return r * r >= x * x + y * y; + } }; \ No newline at end of file diff --git a/solution/2100-2199/2101.Detonate the Maximum Bombs/Solution.java b/solution/2100-2199/2101.Detonate the Maximum Bombs/Solution.java index 21676fd55876f..161b71f10a0c9 100644 --- a/solution/2100-2199/2101.Detonate the Maximum Bombs/Solution.java +++ b/solution/2100-2199/2101.Detonate the Maximum Bombs/Solution.java @@ -1,44 +1,44 @@ -class Solution { - private int[][] bombs; - - public int maximumDetonation(int[][] bombs) { - this.bombs = bombs; - int n = bombs.length; - boolean[][] g = new boolean[n][n]; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - g[i][j] = check(i, j); - } - } - int ans = 0; - for (int k = 0; k < n; ++k) { - Deque q = new ArrayDeque<>(); - q.offer(k); - boolean[] vis = new boolean[n]; - vis[k] = true; - int cnt = 0; - while (!q.isEmpty()) { - int i = q.poll(); - ++cnt; - for (int j = 0; j < n; ++j) { - if (g[i][j] && !vis[j]) { - vis[j] = true; - q.offer(j); - } - } - } - ans = Math.max(ans, cnt); - } - return ans; - } - - private boolean check(int i, int j) { - if (i == j) { - return false; - } - long x = bombs[i][0] - bombs[j][0]; - long y = bombs[i][1] - bombs[j][1]; - long r = bombs[i][2]; - return r * r >= x * x + y * y; - } +class Solution { + private int[][] bombs; + + public int maximumDetonation(int[][] bombs) { + this.bombs = bombs; + int n = bombs.length; + boolean[][] g = new boolean[n][n]; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + g[i][j] = check(i, j); + } + } + int ans = 0; + for (int k = 0; k < n; ++k) { + Deque q = new ArrayDeque<>(); + q.offer(k); + boolean[] vis = new boolean[n]; + vis[k] = true; + int cnt = 0; + while (!q.isEmpty()) { + int i = q.poll(); + ++cnt; + for (int j = 0; j < n; ++j) { + if (g[i][j] && !vis[j]) { + vis[j] = true; + q.offer(j); + } + } + } + ans = Math.max(ans, cnt); + } + return ans; + } + + private boolean check(int i, int j) { + if (i == j) { + return false; + } + long x = bombs[i][0] - bombs[j][0]; + long y = bombs[i][1] - bombs[j][1]; + long r = bombs[i][2]; + return r * r >= x * x + y * y; + } } \ No newline at end of file diff --git a/solution/2100-2199/2101.Detonate the Maximum Bombs/Solution.py b/solution/2100-2199/2101.Detonate the Maximum Bombs/Solution.py index 8cc6c1d05faeb..bd4d3a01a3acd 100644 --- a/solution/2100-2199/2101.Detonate the Maximum Bombs/Solution.py +++ b/solution/2100-2199/2101.Detonate the Maximum Bombs/Solution.py @@ -1,30 +1,30 @@ -class Solution: - def maximumDetonation(self, bombs: List[List[int]]) -> int: - def check(i, j): - if i == j: - return False - x, y = bombs[i][0] - bombs[j][0], bombs[i][1] - bombs[j][1] - r = bombs[i][2] - return r * r >= x * x + y * y - - g = defaultdict(list) - n = len(bombs) - for i in range(n): - for j in range(n): - if check(i, j): - g[i].append(j) - ans = 0 - for k in range(n): - q = deque([k]) - vis = [False] * n - vis[k] = True - cnt = 0 - while q: - i = q.popleft() - cnt += 1 - for j in g[i]: - if not vis[j]: - vis[j] = True - q.append(j) - ans = max(ans, cnt) - return ans +class Solution: + def maximumDetonation(self, bombs: List[List[int]]) -> int: + def check(i, j): + if i == j: + return False + x, y = bombs[i][0] - bombs[j][0], bombs[i][1] - bombs[j][1] + r = bombs[i][2] + return r * r >= x * x + y * y + + g = defaultdict(list) + n = len(bombs) + for i in range(n): + for j in range(n): + if check(i, j): + g[i].append(j) + ans = 0 + for k in range(n): + q = deque([k]) + vis = [False] * n + vis[k] = True + cnt = 0 + while q: + i = q.popleft() + cnt += 1 + for j in g[i]: + if not vis[j]: + vis[j] = True + q.append(j) + ans = max(ans, cnt) + return ans diff --git a/solution/2100-2199/2103.Rings and Rods/Solution.c b/solution/2100-2199/2103.Rings and Rods/Solution.c index 47cfaa9e5e772..768cffd0cb8a8 100644 --- a/solution/2100-2199/2103.Rings and Rods/Solution.c +++ b/solution/2100-2199/2103.Rings and Rods/Solution.c @@ -1,25 +1,25 @@ -int countPoints(char* rings) { - int d['Z']; - memset(d, 0, sizeof(d)); - d['R'] = 1; - d['G'] = 2; - d['B'] = 4; - - int mask[10]; - memset(mask, 0, sizeof(mask)); - - for (int i = 0, n = strlen(rings); i < n; i += 2) { - int c = rings[i]; - int j = rings[i + 1] - '0'; - mask[j] |= d[c]; - } - - int ans = 0; - for (int i = 0; i < 10; i++) { - if (mask[i] == 7) { - ans++; - } - } - - return ans; -} +int countPoints(char* rings) { + int d['Z']; + memset(d, 0, sizeof(d)); + d['R'] = 1; + d['G'] = 2; + d['B'] = 4; + + int mask[10]; + memset(mask, 0, sizeof(mask)); + + for (int i = 0, n = strlen(rings); i < n; i += 2) { + int c = rings[i]; + int j = rings[i + 1] - '0'; + mask[j] |= d[c]; + } + + int ans = 0; + for (int i = 0; i < 10; i++) { + if (mask[i] == 7) { + ans++; + } + } + + return ans; +} \ No newline at end of file diff --git a/solution/2100-2199/2103.Rings and Rods/Solution.cpp b/solution/2100-2199/2103.Rings and Rods/Solution.cpp index d561b7ae3108d..a47522e28e055 100644 --- a/solution/2100-2199/2103.Rings and Rods/Solution.cpp +++ b/solution/2100-2199/2103.Rings and Rods/Solution.cpp @@ -1,13 +1,13 @@ -class Solution { -public: - int countPoints(string rings) { - int d['Z']{['R'] = 1, ['G'] = 2, ['B'] = 4}; - int mask[10]{}; - for (int i = 0, n = rings.size(); i < n; i += 2) { - int c = rings[i]; - int j = rings[i + 1] - '0'; - mask[j] |= d[c]; - } - return count(mask, mask + 10, 7); - } +class Solution { +public: + int countPoints(string rings) { + int d['Z']{['R'] = 1, ['G'] = 2, ['B'] = 4}; + int mask[10]{}; + for (int i = 0, n = rings.size(); i < n; i += 2) { + int c = rings[i]; + int j = rings[i + 1] - '0'; + mask[j] |= d[c]; + } + return count(mask, mask + 10, 7); + } }; \ No newline at end of file diff --git a/solution/2100-2199/2103.Rings and Rods/Solution.java b/solution/2100-2199/2103.Rings and Rods/Solution.java index f1c2d529c9dda..c53fbee3cc08a 100644 --- a/solution/2100-2199/2103.Rings and Rods/Solution.java +++ b/solution/2100-2199/2103.Rings and Rods/Solution.java @@ -1,21 +1,21 @@ -class Solution { - public int countPoints(String rings) { - int[] d = new int['Z']; - d['R'] = 1; - d['G'] = 2; - d['B'] = 4; - int[] mask = new int[10]; - for (int i = 0, n = rings.length(); i < n; i += 2) { - int c = rings.charAt(i); - int j = rings.charAt(i + 1) - '0'; - mask[j] |= d[c]; - } - int ans = 0; - for (int x : mask) { - if (x == 7) { - ++ans; - } - } - return ans; - } +class Solution { + public int countPoints(String rings) { + int[] d = new int['Z']; + d['R'] = 1; + d['G'] = 2; + d['B'] = 4; + int[] mask = new int[10]; + for (int i = 0, n = rings.length(); i < n; i += 2) { + int c = rings.charAt(i); + int j = rings.charAt(i + 1) - '0'; + mask[j] |= d[c]; + } + int ans = 0; + for (int x : mask) { + if (x == 7) { + ++ans; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2100-2199/2103.Rings and Rods/Solution.py b/solution/2100-2199/2103.Rings and Rods/Solution.py index 3acf68f2620b4..b4759a7e4bbe4 100644 --- a/solution/2100-2199/2103.Rings and Rods/Solution.py +++ b/solution/2100-2199/2103.Rings and Rods/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def countPoints(self, rings: str) -> int: - mask = [0] * 10 - d = {"R": 1, "G": 2, "B": 4} - for i in range(0, len(rings), 2): - c = rings[i] - j = int(rings[i + 1]) - mask[j] |= d[c] - return mask.count(7) +class Solution: + def countPoints(self, rings: str) -> int: + mask = [0] * 10 + d = {"R": 1, "G": 2, "B": 4} + for i in range(0, len(rings), 2): + c = rings[i] + j = int(rings[i + 1]) + mask[j] |= d[c] + return mask.count(7) diff --git a/solution/2100-2199/2103.Rings and Rods/Solution2.ts b/solution/2100-2199/2103.Rings and Rods/Solution2.ts new file mode 100644 index 0000000000000..15c96aec2ed52 --- /dev/null +++ b/solution/2100-2199/2103.Rings and Rods/Solution2.ts @@ -0,0 +1,7 @@ +function countPoints(rings: string): number { + let c = 0; + for (let i = 0; i <= 9; i++) { + if (rings.includes('B' + i) && rings.includes('R' + i) && rings.includes('G' + i)) c++; + } + return c; +} diff --git a/solution/2100-2199/2104.Sum of Subarray Ranges/Solution.cpp b/solution/2100-2199/2104.Sum of Subarray Ranges/Solution.cpp index b7f772d0292df..fd72d13903409 100644 --- a/solution/2100-2199/2104.Sum of Subarray Ranges/Solution.cpp +++ b/solution/2100-2199/2104.Sum of Subarray Ranges/Solution.cpp @@ -1,31 +1,15 @@ class Solution { public: long long subArrayRanges(vector& nums) { - long long mx = f(nums); - for (int i = 0; i < nums.size(); ++i) nums[i] *= -1; - long long mi = f(nums); - return mx + mi; - } - - long long f(vector& nums) { - stack stk; - int n = nums.size(); - vector left(n, -1); - vector right(n, n); - for (int i = 0; i < n; ++i) { - while (!stk.empty() && nums[stk.top()] <= nums[i]) stk.pop(); - if (!stk.empty()) left[i] = stk.top(); - stk.push(i); - } - stk = stack(); - for (int i = n - 1; i >= 0; --i) { - while (!stk.empty() && nums[stk.top()] < nums[i]) stk.pop(); - if (!stk.empty()) right[i] = stk.top(); - stk.push(i); - } long long ans = 0; - for (int i = 0; i < n; ++i) { - ans += (long long) (i - left[i]) * (right[i] - i) * nums[i]; + int n = nums.size(); + for (int i = 0; i < n - 1; ++i) { + int mi = nums[i], mx = nums[i]; + for (int j = i + 1; j < n; ++j) { + mi = min(mi, nums[j]); + mx = max(mx, nums[j]); + ans += (mx - mi); + } } return ans; } diff --git a/solution/2100-2199/2104.Sum of Subarray Ranges/Solution.go b/solution/2100-2199/2104.Sum of Subarray Ranges/Solution.go index b7ed482c6b03d..02aaadae16a3d 100644 --- a/solution/2100-2199/2104.Sum of Subarray Ranges/Solution.go +++ b/solution/2100-2199/2104.Sum of Subarray Ranges/Solution.go @@ -1,42 +1,13 @@ func subArrayRanges(nums []int) int64 { - f := func(nums []int) int64 { - stk := []int{} - n := len(nums) - left := make([]int, n) - right := make([]int, n) - for i := range left { - left[i] = -1 - right[i] = n + var ans int64 + n := len(nums) + for i := 0; i < n-1; i++ { + mi, mx := nums[i], nums[i] + for j := i + 1; j < n; j++ { + mi = min(mi, nums[j]) + mx = max(mx, nums[j]) + ans += (int64)(mx - mi) } - for i, v := range nums { - for len(stk) > 0 && nums[stk[len(stk)-1]] <= v { - stk = stk[:len(stk)-1] - } - if len(stk) > 0 { - left[i] = stk[len(stk)-1] - } - stk = append(stk, i) - } - stk = []int{} - for i := n - 1; i >= 0; i-- { - for len(stk) > 0 && nums[stk[len(stk)-1]] < nums[i] { - stk = stk[:len(stk)-1] - } - if len(stk) > 0 { - right[i] = stk[len(stk)-1] - } - stk = append(stk, i) - } - ans := 0 - for i, v := range nums { - ans += (i - left[i]) * (right[i] - i) * v - } - return int64(ans) - } - mx := f(nums) - for i := range nums { - nums[i] *= -1 } - mi := f(nums) - return mx + mi + return ans } \ No newline at end of file diff --git a/solution/2100-2199/2104.Sum of Subarray Ranges/Solution.java b/solution/2100-2199/2104.Sum of Subarray Ranges/Solution.java index c60f52b082754..268914dfdc70b 100644 --- a/solution/2100-2199/2104.Sum of Subarray Ranges/Solution.java +++ b/solution/2100-2199/2104.Sum of Subarray Ranges/Solution.java @@ -1,44 +1,15 @@ -```java class Solution { +class Solution { public long subArrayRanges(int[] nums) { - long mx = f(nums); - for (int i = 0; i < nums.length; ++i) { - nums[i] *= -1; - } - long mi = f(nums); - return mx + mi; - } - - private long f(int[] nums) { - Deque stk = new ArrayDeque<>(); + long ans = 0; int n = nums.length; - int[] left = new int[n]; - int[] right = new int[n]; - Arrays.fill(left, -1); - Arrays.fill(right, n); - for (int i = 0; i < n; ++i) { - while (!stk.isEmpty() && nums[stk.peek()] <= nums[i]) { - stk.pop(); + for (int i = 0; i < n - 1; ++i) { + int mi = nums[i], mx = nums[i]; + for (int j = i + 1; j < n; ++j) { + mi = Math.min(mi, nums[j]); + mx = Math.max(mx, nums[j]); + ans += (mx - mi); } - if (!stk.isEmpty()) { - left[i] = stk.peek(); - } - stk.push(i); - } - stk.clear(); - for (int i = n - 1; i >= 0; --i) { - while (!stk.isEmpty() && nums[stk.peek()] < nums[i]) { - stk.pop(); - } - if (!stk.isEmpty()) { - right[i] = stk.peek(); - } - stk.push(i); - } - long s = 0; - for (int i = 0; i < n; ++i) { - s += (long) (i - left[i]) * (right[i] - i) * nums[i]; } - return s; + return ans; } -} -``` \ No newline at end of file +} \ No newline at end of file diff --git a/solution/2100-2199/2104.Sum of Subarray Ranges/Solution.py b/solution/2100-2199/2104.Sum of Subarray Ranges/Solution.py index dda7cf1d7ff5b..1fd1f9b25c496 100644 --- a/solution/2100-2199/2104.Sum of Subarray Ranges/Solution.py +++ b/solution/2100-2199/2104.Sum of Subarray Ranges/Solution.py @@ -1,25 +1,10 @@ class Solution: def subArrayRanges(self, nums: List[int]) -> int: - def f(nums): - stk = [] - n = len(nums) - left = [-1] * n - right = [n] * n - for i, v in enumerate(nums): - while stk and nums[stk[-1]] <= v: - stk.pop() - if stk: - left[i] = stk[-1] - stk.append(i) - stk = [] - for i in range(n - 1, -1, -1): - while stk and nums[stk[-1]] < nums[i]: - stk.pop() - if stk: - right[i] = stk[-1] - stk.append(i) - return sum((i - left[i]) * (right[i] - i) * v for i, v in enumerate(nums)) - - mx = f(nums) - mi = f([-v for v in nums]) - return mx + mi + ans, n = 0, len(nums) + for i in range(n - 1): + mi = mx = nums[i] + for j in range(i + 1, n): + mi = min(mi, nums[j]) + mx = max(mx, nums[j]) + ans += mx - mi + return ans diff --git a/solution/2100-2199/2104.Sum of Subarray Ranges/Solution2.cpp b/solution/2100-2199/2104.Sum of Subarray Ranges/Solution2.cpp new file mode 100644 index 0000000000000..b7f772d0292df --- /dev/null +++ b/solution/2100-2199/2104.Sum of Subarray Ranges/Solution2.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + long long subArrayRanges(vector& nums) { + long long mx = f(nums); + for (int i = 0; i < nums.size(); ++i) nums[i] *= -1; + long long mi = f(nums); + return mx + mi; + } + + long long f(vector& nums) { + stack stk; + int n = nums.size(); + vector left(n, -1); + vector right(n, n); + for (int i = 0; i < n; ++i) { + while (!stk.empty() && nums[stk.top()] <= nums[i]) stk.pop(); + if (!stk.empty()) left[i] = stk.top(); + stk.push(i); + } + stk = stack(); + for (int i = n - 1; i >= 0; --i) { + while (!stk.empty() && nums[stk.top()] < nums[i]) stk.pop(); + if (!stk.empty()) right[i] = stk.top(); + stk.push(i); + } + long long ans = 0; + for (int i = 0; i < n; ++i) { + ans += (long long) (i - left[i]) * (right[i] - i) * nums[i]; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2100-2199/2104.Sum of Subarray Ranges/Solution2.go b/solution/2100-2199/2104.Sum of Subarray Ranges/Solution2.go new file mode 100644 index 0000000000000..b7ed482c6b03d --- /dev/null +++ b/solution/2100-2199/2104.Sum of Subarray Ranges/Solution2.go @@ -0,0 +1,42 @@ +func subArrayRanges(nums []int) int64 { + f := func(nums []int) int64 { + stk := []int{} + n := len(nums) + left := make([]int, n) + right := make([]int, n) + for i := range left { + left[i] = -1 + right[i] = n + } + for i, v := range nums { + for len(stk) > 0 && nums[stk[len(stk)-1]] <= v { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + left[i] = stk[len(stk)-1] + } + stk = append(stk, i) + } + stk = []int{} + for i := n - 1; i >= 0; i-- { + for len(stk) > 0 && nums[stk[len(stk)-1]] < nums[i] { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + right[i] = stk[len(stk)-1] + } + stk = append(stk, i) + } + ans := 0 + for i, v := range nums { + ans += (i - left[i]) * (right[i] - i) * v + } + return int64(ans) + } + mx := f(nums) + for i := range nums { + nums[i] *= -1 + } + mi := f(nums) + return mx + mi +} \ No newline at end of file diff --git a/solution/2100-2199/2104.Sum of Subarray Ranges/Solution2.java b/solution/2100-2199/2104.Sum of Subarray Ranges/Solution2.java new file mode 100644 index 0000000000000..3b064aabd16ef --- /dev/null +++ b/solution/2100-2199/2104.Sum of Subarray Ranges/Solution2.java @@ -0,0 +1,43 @@ +class Solution { + public long subArrayRanges(int[] nums) { + long mx = f(nums); + for (int i = 0; i < nums.length; ++i) { + nums[i] *= -1; + } + long mi = f(nums); + return mx + mi; + } + + private long f(int[] nums) { + Deque stk = new ArrayDeque<>(); + int n = nums.length; + int[] left = new int[n]; + int[] right = new int[n]; + Arrays.fill(left, -1); + Arrays.fill(right, n); + for (int i = 0; i < n; ++i) { + while (!stk.isEmpty() && nums[stk.peek()] <= nums[i]) { + stk.pop(); + } + if (!stk.isEmpty()) { + left[i] = stk.peek(); + } + stk.push(i); + } + stk.clear(); + for (int i = n - 1; i >= 0; --i) { + while (!stk.isEmpty() && nums[stk.peek()] < nums[i]) { + stk.pop(); + } + if (!stk.isEmpty()) { + right[i] = stk.peek(); + } + stk.push(i); + } + long s = 0; + for (int i = 0; i < n; ++i) { + s += (long) (i - left[i]) * (right[i] - i) * nums[i]; + } + return s; + } +} \ No newline at end of file diff --git a/solution/2100-2199/2104.Sum of Subarray Ranges/Solution2.py b/solution/2100-2199/2104.Sum of Subarray Ranges/Solution2.py new file mode 100644 index 0000000000000..dda7cf1d7ff5b --- /dev/null +++ b/solution/2100-2199/2104.Sum of Subarray Ranges/Solution2.py @@ -0,0 +1,25 @@ +class Solution: + def subArrayRanges(self, nums: List[int]) -> int: + def f(nums): + stk = [] + n = len(nums) + left = [-1] * n + right = [n] * n + for i, v in enumerate(nums): + while stk and nums[stk[-1]] <= v: + stk.pop() + if stk: + left[i] = stk[-1] + stk.append(i) + stk = [] + for i in range(n - 1, -1, -1): + while stk and nums[stk[-1]] < nums[i]: + stk.pop() + if stk: + right[i] = stk[-1] + stk.append(i) + return sum((i - left[i]) * (right[i] - i) * v for i, v in enumerate(nums)) + + mx = f(nums) + mi = f([-v for v in nums]) + return mx + mi diff --git a/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/Solution.cpp b/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/Solution.cpp index e1a1d1540752e..829b20adc2bad 100644 --- a/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/Solution.cpp +++ b/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/Solution.cpp @@ -1,19 +1,19 @@ -class Solution { -public: - int shareCandies(vector& candies, int k) { - unordered_map cnt; - int n = candies.size(); - for (int i = k; i < n; ++i) { - ++cnt[candies[i]]; - } - int ans = cnt.size(); - for (int i = k; i < n; ++i) { - ++cnt[candies[i - k]]; - if (--cnt[candies[i]] == 0) { - cnt.erase(candies[i]); - } - ans = max(ans, (int) cnt.size()); - } - return ans; - } +class Solution { +public: + int shareCandies(vector& candies, int k) { + unordered_map cnt; + int n = candies.size(); + for (int i = k; i < n; ++i) { + ++cnt[candies[i]]; + } + int ans = cnt.size(); + for (int i = k; i < n; ++i) { + ++cnt[candies[i - k]]; + if (--cnt[candies[i]] == 0) { + cnt.erase(candies[i]); + } + ans = max(ans, (int) cnt.size()); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/Solution.java b/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/Solution.java index 6bdb8089df6a2..7130159a096f9 100644 --- a/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/Solution.java +++ b/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/Solution.java @@ -1,18 +1,18 @@ -class Solution { - public int shareCandies(int[] candies, int k) { - Map cnt = new HashMap<>(); - int n = candies.length; - for (int i = k; i < n; ++i) { - cnt.merge(candies[i], 1, Integer::sum); - } - int ans = cnt.size(); - for (int i = k; i < n; ++i) { - cnt.merge(candies[i - k], 1, Integer::sum); - if (cnt.merge(candies[i], -1, Integer::sum) == 0) { - cnt.remove(candies[i]); - } - ans = Math.max(ans, cnt.size()); - } - return ans; - } +class Solution { + public int shareCandies(int[] candies, int k) { + Map cnt = new HashMap<>(); + int n = candies.length; + for (int i = k; i < n; ++i) { + cnt.merge(candies[i], 1, Integer::sum); + } + int ans = cnt.size(); + for (int i = k; i < n; ++i) { + cnt.merge(candies[i - k], 1, Integer::sum); + if (cnt.merge(candies[i], -1, Integer::sum) == 0) { + cnt.remove(candies[i]); + } + ans = Math.max(ans, cnt.size()); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/Solution.py b/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/Solution.py index b7a262f81700e..9dccd0dfba93d 100644 --- a/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/Solution.py +++ b/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def shareCandies(self, candies: List[int], k: int) -> int: - cnt = Counter(candies[k:]) - ans = len(cnt) - for i in range(k, len(candies)): - cnt[candies[i - k]] += 1 - cnt[candies[i]] -= 1 - if cnt[candies[i]] == 0: - cnt.pop(candies[i]) - ans = max(ans, len(cnt)) - return ans +class Solution: + def shareCandies(self, candies: List[int], k: int) -> int: + cnt = Counter(candies[k:]) + ans = len(cnt) + for i in range(k, len(candies)): + cnt[candies[i - k]] += 1 + cnt[candies[i]] -= 1 + if cnt[candies[i]] == 0: + cnt.pop(candies[i]) + ans = max(ans, len(cnt)) + return ans diff --git a/solution/2100-2199/2108.Find First Palindromic String in the Array/Solution.c b/solution/2100-2199/2108.Find First Palindromic String in the Array/Solution.c index 790444b170665..4ad8efd0fd41a 100644 --- a/solution/2100-2199/2108.Find First Palindromic String in the Array/Solution.c +++ b/solution/2100-2199/2108.Find First Palindromic String in the Array/Solution.c @@ -14,4 +14,4 @@ char* firstPalindrome(char** words, int wordsSize) { } } return ""; -} +} \ No newline at end of file diff --git a/solution/2100-2199/2109.Adding Spaces to a String/Solution2.py b/solution/2100-2199/2109.Adding Spaces to a String/Solution2.py new file mode 100644 index 0000000000000..053ad13ac924f --- /dev/null +++ b/solution/2100-2199/2109.Adding Spaces to a String/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def addSpaces(self, s: str, spaces: List[int]) -> str: + ans = [] + i, j = len(s) - 1, len(spaces) - 1 + while i >= 0: + ans.append(s[i]) + if j >= 0 and i == spaces[j]: + ans.append(' ') + j -= 1 + i -= 1 + return ''.join(ans[::-1]) diff --git a/solution/2100-2199/2111.Minimum Operations to Make the Array K-Increasing/Solution.py b/solution/2100-2199/2111.Minimum Operations to Make the Array K-Increasing/Solution.py index 1baa6e604ec1a..cd2dbf118d184 100644 --- a/solution/2100-2199/2111.Minimum Operations to Make the Array K-Increasing/Solution.py +++ b/solution/2100-2199/2111.Minimum Operations to Make the Array K-Increasing/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def kIncreasing(self, arr: List[int], k: int) -> int: - def lis(arr): - t = [] - for x in arr: - idx = bisect_right(t, x) - if idx == len(t): - t.append(x) - else: - t[idx] = x - return len(arr) - len(t) - - return sum(lis(arr[i::k]) for i in range(k)) +class Solution: + def kIncreasing(self, arr: List[int], k: int) -> int: + def lis(arr): + t = [] + for x in arr: + idx = bisect_right(t, x) + if idx == len(t): + t.append(x) + else: + t[idx] = x + return len(arr) - len(t) + + return sum(lis(arr[i::k]) for i in range(k)) diff --git a/solution/2100-2199/2114.Maximum Number of Words Found in Sentences/Solution.c b/solution/2100-2199/2114.Maximum Number of Words Found in Sentences/Solution.c index de8e459432617..64341dca91c28 100644 --- a/solution/2100-2199/2114.Maximum Number of Words Found in Sentences/Solution.c +++ b/solution/2100-2199/2114.Maximum Number of Words Found in Sentences/Solution.c @@ -13,4 +13,4 @@ int mostWordsFound(char** sentences, int sentencesSize) { ans = max(ans, count); } return ans; -} +} \ No newline at end of file diff --git a/solution/2100-2199/2117.Abbreviating the Product of a Range/Solution.java b/solution/2100-2199/2117.Abbreviating the Product of a Range/Solution.java index 82745fb60a9bb..83714b60bbd9d 100644 --- a/solution/2100-2199/2117.Abbreviating the Product of a Range/Solution.java +++ b/solution/2100-2199/2117.Abbreviating the Product of a Range/Solution.java @@ -1,38 +1,38 @@ -class Solution { - - public String abbreviateProduct(int left, int right) { - int cnt2 = 0, cnt5 = 0; - for (int i = left; i <= right; ++i) { - int x = i; - for (; x % 2 == 0; x /= 2) { - ++cnt2; - } - for (; x % 5 == 0; x /= 5) { - ++cnt5; - } - } - int c = Math.min(cnt2, cnt5); - cnt2 = cnt5 = c; - long suf = 1; - double pre = 1; - boolean gt = false; - for (int i = left; i <= right; ++i) { - for (suf *= i; cnt2 > 0 && suf % 2 == 0; suf /= 2) { - --cnt2; - } - for (; cnt5 > 0 && suf % 5 == 0; suf /= 5) { - --cnt5; - } - if (suf >= (long) 1e10) { - gt = true; - suf %= (long) 1e10; - } - for (pre *= i; pre > 1e5; pre /= 10) { - } - } - if (gt) { - return (int) pre + "..." + String.format("%05d", suf % (int) 1e5) + "e" + c; - } - return suf + "e" + c; - } +class Solution { + + public String abbreviateProduct(int left, int right) { + int cnt2 = 0, cnt5 = 0; + for (int i = left; i <= right; ++i) { + int x = i; + for (; x % 2 == 0; x /= 2) { + ++cnt2; + } + for (; x % 5 == 0; x /= 5) { + ++cnt5; + } + } + int c = Math.min(cnt2, cnt5); + cnt2 = cnt5 = c; + long suf = 1; + double pre = 1; + boolean gt = false; + for (int i = left; i <= right; ++i) { + for (suf *= i; cnt2 > 0 && suf % 2 == 0; suf /= 2) { + --cnt2; + } + for (; cnt5 > 0 && suf % 5 == 0; suf /= 5) { + --cnt5; + } + if (suf >= (long) 1e10) { + gt = true; + suf %= (long) 1e10; + } + for (pre *= i; pre > 1e5; pre /= 10) { + } + } + if (gt) { + return (int) pre + "..." + String.format("%05d", suf % (int) 1e5) + "e" + c; + } + return suf + "e" + c; + } } \ No newline at end of file diff --git a/solution/2100-2199/2117.Abbreviating the Product of a Range/Solution.py b/solution/2100-2199/2117.Abbreviating the Product of a Range/Solution.py index d5737a6158fe0..1473b889d3756 100644 --- a/solution/2100-2199/2117.Abbreviating the Product of a Range/Solution.py +++ b/solution/2100-2199/2117.Abbreviating the Product of a Range/Solution.py @@ -1,30 +1,33 @@ -class Solution: - def abbreviateProduct(self, left: int, right: int) -> str: - cnt2 = cnt5 = 0 - for x in range(left, right + 1): - while x % 2 == 0: - cnt2 += 1 - x //= 2 - while x % 5 == 0: - cnt5 += 1 - x //= 5 - c = cnt2 = cnt5 = min(cnt2, cnt5) - pre = suf = 1 - gt = False - for x in range(left, right + 1): - suf *= x - while cnt2 and suf % 2 == 0: - suf //= 2 - cnt2 -= 1 - while cnt5 and suf % 5 == 0: - suf //= 5 - cnt5 -= 1 - if suf >= 1e10: - gt = True - suf %= int(1e10) - pre *= x - while pre > 1e5: - pre /= 10 - if gt: - return str(int(pre)) + "..." + str(suf % int(1e5)).zfill(5) + 'e' + str(c) - return str(suf) + "e" + str(c) +import numpy + + +class Solution: + def abbreviateProduct(self, left: int, right: int) -> str: + cnt2 = cnt5 = 0 + z = numpy.float128(0) + for x in range(left, right + 1): + z += numpy.log10(x) + while x % 2 == 0: + x //= 2 + cnt2 += 1 + while x % 5 == 0: + x //= 5 + cnt5 += 1 + c = cnt2 = cnt5 = min(cnt2, cnt5) + suf = y = 1 + gt = False + for x in range(left, right + 1): + while cnt2 and x % 2 == 0: + x //= 2 + cnt2 -= 1 + while cnt5 and x % 5 == 0: + x //= 5 + cnt5 -= 1 + suf = suf * x % 100000 + if not gt: + y *= x + gt = y >= 1e10 + if not gt: + return str(y) + "e" + str(c) + pre = int(pow(10, z - int(z) + 4)) + return str(pre) + "..." + str(suf).zfill(5) + "e" + str(c) diff --git a/solution/2100-2199/2117.Abbreviating the Product of a Range/Solution2.py b/solution/2100-2199/2117.Abbreviating the Product of a Range/Solution2.py new file mode 100644 index 0000000000000..22b78d5705115 --- /dev/null +++ b/solution/2100-2199/2117.Abbreviating the Product of a Range/Solution2.py @@ -0,0 +1,30 @@ +class Solution: + def abbreviateProduct(self, left: int, right: int) -> str: + cnt2 = cnt5 = 0 + for x in range(left, right + 1): + while x % 2 == 0: + cnt2 += 1 + x //= 2 + while x % 5 == 0: + cnt5 += 1 + x //= 5 + c = cnt2 = cnt5 = min(cnt2, cnt5) + pre = suf = 1 + gt = False + for x in range(left, right + 1): + suf *= x + while cnt2 and suf % 2 == 0: + suf //= 2 + cnt2 -= 1 + while cnt5 and suf % 5 == 0: + suf //= 5 + cnt5 -= 1 + if suf >= 1e10: + gt = True + suf %= int(1e10) + pre *= x + while pre > 1e5: + pre /= 10 + if gt: + return str(int(pre)) + "..." + str(suf % int(1e5)).zfill(5) + 'e' + str(c) + return str(suf) + "e" + str(c) diff --git a/solution/2100-2199/2118.Build the Equation/Solution.sql b/solution/2100-2199/2118.Build the Equation/Solution.sql index 5b8f07424ece8..8eb9f8bcda7ee 100644 --- a/solution/2100-2199/2118.Build the Equation/Solution.sql +++ b/solution/2100-2199/2118.Build the Equation/Solution.sql @@ -19,4 +19,4 @@ WITH ) SELECT CONCAT(GROUP_CONCAT(it ORDER BY power DESC SEPARATOR ""), '=0') AS equation -FROM T; \ No newline at end of file +FROM T; diff --git a/solution/2100-2199/2120.Execution of All Suffix Instructions Staying in a Grid/Solution.c b/solution/2100-2199/2120.Execution of All Suffix Instructions Staying in a Grid/Solution.c index 4d507cc8da11c..5a524a254a5e2 100644 --- a/solution/2100-2199/2120.Execution of All Suffix Instructions Staying in a Grid/Solution.c +++ b/solution/2100-2199/2120.Execution of All Suffix Instructions Staying in a Grid/Solution.c @@ -26,4 +26,4 @@ int* executeInstructions(int n, int* startPos, int startPosSize, char* s, int* r } *returnSize = m; return ans; -} +} \ No newline at end of file diff --git a/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/Solution.cpp b/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/Solution.cpp index b265a65dca559..64f6ef2b389bc 100644 --- a/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/Solution.cpp +++ b/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/Solution.cpp @@ -1,46 +1,46 @@ -class Solution { -public: - int minimumOperations(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - vector match(m * n, -1); - unordered_set vis; - unordered_map> g; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if ((i + j) % 2 && grid[i][j]) { - int x = i * n + j; - if (i < m - 1 && grid[i + 1][j]) { - g[x].push_back(x + n); - } - if (i && grid[i - 1][j]) { - g[x].push_back(x - n); - } - if (j < n - 1 && grid[i][j + 1]) { - g[x].push_back(x + 1); - } - if (j && grid[i][j - 1]) { - g[x].push_back(x - 1); - } - } - } - } - int ans = 0; - function find = [&](int i) -> int { - for (int& j : g[i]) { - if (!vis.count(j)) { - vis.insert(j); - if (match[j] == -1 || find(match[j])) { - match[j] = i; - return 1; - } - } - } - return 0; - }; - for (auto& [i, _] : g) { - ans += find(i); - vis.clear(); - } - return ans; - } +class Solution { +public: + int minimumOperations(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + vector match(m * n, -1); + unordered_set vis; + unordered_map> g; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if ((i + j) % 2 && grid[i][j]) { + int x = i * n + j; + if (i < m - 1 && grid[i + 1][j]) { + g[x].push_back(x + n); + } + if (i && grid[i - 1][j]) { + g[x].push_back(x - n); + } + if (j < n - 1 && grid[i][j + 1]) { + g[x].push_back(x + 1); + } + if (j && grid[i][j - 1]) { + g[x].push_back(x - 1); + } + } + } + } + int ans = 0; + function find = [&](int i) -> int { + for (int& j : g[i]) { + if (!vis.count(j)) { + vis.insert(j); + if (match[j] == -1 || find(match[j])) { + match[j] = i; + return 1; + } + } + } + return 0; + }; + for (auto& [i, _] : g) { + ans += find(i); + vis.clear(); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/Solution.java b/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/Solution.java index b5f4a4b56f91a..76849a765af7c 100644 --- a/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/Solution.java +++ b/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/Solution.java @@ -1,48 +1,48 @@ -class Solution { - private Map> g = new HashMap<>(); - private Set vis = new HashSet<>(); - private int[] match; - - public int minimumOperations(int[][] grid) { - int m = grid.length, n = grid[0].length; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if ((i + j) % 2 == 1 && grid[i][j] == 1) { - int x = i * n + j; - if (i < m - 1 && grid[i + 1][j] == 1) { - g.computeIfAbsent(x, z -> new ArrayList<>()).add(x + n); - } - if (i > 0 && grid[i - 1][j] == 1) { - g.computeIfAbsent(x, z -> new ArrayList<>()).add(x - n); - } - if (j < n - 1 && grid[i][j + 1] == 1) { - g.computeIfAbsent(x, z -> new ArrayList<>()).add(x + 1); - } - if (j > 0 && grid[i][j - 1] == 1) { - g.computeIfAbsent(x, z -> new ArrayList<>()).add(x - 1); - } - } - } - } - match = new int[m * n]; - Arrays.fill(match, -1); - int ans = 0; - for (int i : g.keySet()) { - ans += find(i); - vis.clear(); - } - return ans; - } - - private int find(int i) { - for (int j : g.get(i)) { - if (vis.add(j)) { - if (match[j] == -1 || find(match[j]) == 1) { - match[j] = i; - return 1; - } - } - } - return 0; - } +class Solution { + private Map> g = new HashMap<>(); + private Set vis = new HashSet<>(); + private int[] match; + + public int minimumOperations(int[][] grid) { + int m = grid.length, n = grid[0].length; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if ((i + j) % 2 == 1 && grid[i][j] == 1) { + int x = i * n + j; + if (i < m - 1 && grid[i + 1][j] == 1) { + g.computeIfAbsent(x, z -> new ArrayList<>()).add(x + n); + } + if (i > 0 && grid[i - 1][j] == 1) { + g.computeIfAbsent(x, z -> new ArrayList<>()).add(x - n); + } + if (j < n - 1 && grid[i][j + 1] == 1) { + g.computeIfAbsent(x, z -> new ArrayList<>()).add(x + 1); + } + if (j > 0 && grid[i][j - 1] == 1) { + g.computeIfAbsent(x, z -> new ArrayList<>()).add(x - 1); + } + } + } + } + match = new int[m * n]; + Arrays.fill(match, -1); + int ans = 0; + for (int i : g.keySet()) { + ans += find(i); + vis.clear(); + } + return ans; + } + + private int find(int i) { + for (int j : g.get(i)) { + if (vis.add(j)) { + if (match[j] == -1 || find(match[j]) == 1) { + match[j] = i; + return 1; + } + } + } + return 0; + } } \ No newline at end of file diff --git a/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/Solution.py b/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/Solution.py index 00cb6b66ac777..8388aee9c6f2d 100644 --- a/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/Solution.py +++ b/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/Solution.py @@ -1,32 +1,32 @@ -class Solution: - def minimumOperations(self, grid: List[List[int]]) -> int: - def find(i: int) -> int: - for j in g[i]: - if j not in vis: - vis.add(j) - if match[j] == -1 or find(match[j]): - match[j] = i - return 1 - return 0 - - g = defaultdict(list) - m, n = len(grid), len(grid[0]) - for i, row in enumerate(grid): - for j, v in enumerate(row): - if (i + j) % 2 and v: - x = i * n + j - if i < m - 1 and grid[i + 1][j]: - g[x].append(x + n) - if i and grid[i - 1][j]: - g[x].append(x - n) - if j < n - 1 and grid[i][j + 1]: - g[x].append(x + 1) - if j and grid[i][j - 1]: - g[x].append(x - 1) - - match = [-1] * (m * n) - ans = 0 - for i in g.keys(): - vis = set() - ans += find(i) - return ans +class Solution: + def minimumOperations(self, grid: List[List[int]]) -> int: + def find(i: int) -> int: + for j in g[i]: + if j not in vis: + vis.add(j) + if match[j] == -1 or find(match[j]): + match[j] = i + return 1 + return 0 + + g = defaultdict(list) + m, n = len(grid), len(grid[0]) + for i, row in enumerate(grid): + for j, v in enumerate(row): + if (i + j) % 2 and v: + x = i * n + j + if i < m - 1 and grid[i + 1][j]: + g[x].append(x + n) + if i and grid[i - 1][j]: + g[x].append(x - n) + if j < n - 1 and grid[i][j + 1]: + g[x].append(x + 1) + if j and grid[i][j - 1]: + g[x].append(x - 1) + + match = [-1] * (m * n) + ans = 0 + for i in g.keys(): + vis = set() + ans += find(i) + return ans diff --git a/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.c b/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.c index 7a8045e67388c..43f6fa52c7b65 100644 --- a/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.c +++ b/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.c @@ -14,4 +14,4 @@ int numberOfBeams(char** bank, int bankSize) { } } return ans; -} +} \ No newline at end of file diff --git a/solution/2100-2199/2127.Maximum Employees to Be Invited to a Meeting/Solution.py b/solution/2100-2199/2127.Maximum Employees to Be Invited to a Meeting/Solution.py index 10190f53cdd37..747e6f279804d 100644 --- a/solution/2100-2199/2127.Maximum Employees to Be Invited to a Meeting/Solution.py +++ b/solution/2100-2199/2127.Maximum Employees to Be Invited to a Meeting/Solution.py @@ -1,37 +1,37 @@ -class Solution: - def maximumInvitations(self, favorite: List[int]) -> int: - def max_cycle(fa: List[int]) -> int: - n = len(fa) - vis = [False] * n - ans = 0 - for i in range(n): - if vis[i]: - continue - cycle = [] - j = i - while not vis[j]: - cycle.append(j) - vis[j] = True - j = fa[j] - for k, v in enumerate(cycle): - if v == j: - ans = max(ans, len(cycle) - k) - break - return ans - - def topological_sort(fa: List[int]) -> int: - n = len(fa) - indeg = [0] * n - dist = [1] * n - for v in fa: - indeg[v] += 1 - q = deque(i for i, v in enumerate(indeg) if v == 0) - while q: - i = q.popleft() - dist[fa[i]] = max(dist[fa[i]], dist[i] + 1) - indeg[fa[i]] -= 1 - if indeg[fa[i]] == 0: - q.append(fa[i]) - return sum(dist[i] for i, v in enumerate(fa) if i == fa[fa[i]]) - - return max(max_cycle(favorite), topological_sort(favorite)) +class Solution: + def maximumInvitations(self, favorite: List[int]) -> int: + def max_cycle(fa: List[int]) -> int: + n = len(fa) + vis = [False] * n + ans = 0 + for i in range(n): + if vis[i]: + continue + cycle = [] + j = i + while not vis[j]: + cycle.append(j) + vis[j] = True + j = fa[j] + for k, v in enumerate(cycle): + if v == j: + ans = max(ans, len(cycle) - k) + break + return ans + + def topological_sort(fa: List[int]) -> int: + n = len(fa) + indeg = [0] * n + dist = [1] * n + for v in fa: + indeg[v] += 1 + q = deque(i for i, v in enumerate(indeg) if v == 0) + while q: + i = q.popleft() + dist[fa[i]] = max(dist[fa[i]], dist[i] + 1) + indeg[fa[i]] -= 1 + if indeg[fa[i]] == 0: + q.append(fa[i]) + return sum(dist[i] for i, v in enumerate(fa) if i == fa[fa[i]]) + + return max(max_cycle(favorite), topological_sort(favorite)) diff --git a/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/Solution.cpp b/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/Solution.cpp index 33c5450970191..940c4ccd8b093 100644 --- a/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/Solution.cpp +++ b/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/Solution.cpp @@ -1,14 +1,14 @@ -class Solution { -public: - bool removeOnes(vector>& grid) { - unordered_set s; - for (auto& row : grid) { - string t; - for (int x : row) { - t.push_back('0' + (row[0] == 0 ? x : x ^ 1)); - } - s.insert(t); - } - return s.size() == 1; - } +class Solution { +public: + bool removeOnes(vector>& grid) { + unordered_set s; + for (auto& row : grid) { + string t; + for (int x : row) { + t.push_back('0' + (row[0] == 0 ? x : x ^ 1)); + } + s.insert(t); + } + return s.size() == 1; + } }; \ No newline at end of file diff --git a/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/Solution.java b/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/Solution.java index 59d81a3895c30..ea9522b9d2dcd 100644 --- a/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/Solution.java +++ b/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/Solution.java @@ -1,14 +1,14 @@ -class Solution { - public boolean removeOnes(int[][] grid) { - Set s = new HashSet<>(); - int n = grid[0].length; - for (var row : grid) { - var cs = new char[n]; - for (int i = 0; i < n; ++i) { - cs[i] = (char) (row[0] ^ row[i]); - } - s.add(String.valueOf(cs)); - } - return s.size() == 1; - } +class Solution { + public boolean removeOnes(int[][] grid) { + Set s = new HashSet<>(); + int n = grid[0].length; + for (var row : grid) { + var cs = new char[n]; + for (int i = 0; i < n; ++i) { + cs[i] = (char) (row[0] ^ row[i]); + } + s.add(String.valueOf(cs)); + } + return s.size() == 1; + } } \ No newline at end of file diff --git a/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/Solution.py b/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/Solution.py index c5328231f0a70..4cce4dc6fdd3d 100644 --- a/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/Solution.py +++ b/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def removeOnes(self, grid: List[List[int]]) -> bool: - s = set() - for row in grid: - t = tuple(row) if row[0] == grid[0][0] else tuple(x ^ 1 for x in row) - s.add(t) - return len(s) == 1 +class Solution: + def removeOnes(self, grid: List[List[int]]) -> bool: + s = set() + for row in grid: + t = tuple(row) if row[0] == grid[0][0] else tuple(x ^ 1 for x in row) + s.add(t) + return len(s) == 1 diff --git a/solution/2100-2199/2129.Capitalize the Title/Solution2.ts b/solution/2100-2199/2129.Capitalize the Title/Solution2.ts new file mode 100644 index 0000000000000..a094c14d20ba0 --- /dev/null +++ b/solution/2100-2199/2129.Capitalize the Title/Solution2.ts @@ -0,0 +1,10 @@ +function capitalizeTitle(title: string): string { + return title + .split(' ') + .map(s => + s.length < 3 + ? s.toLowerCase() + : s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase(), + ) + .join(' '); +} diff --git a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.cpp b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.cpp index 080a2d3cb5cd4..0f5dbcc3d15ba 100644 --- a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.cpp +++ b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.cpp @@ -11,34 +11,10 @@ class Solution { public: int pairSum(ListNode* head) { - ListNode* slow = head; - ListNode* fast = head->next; - while (fast && fast->next) { - slow = slow->next; - fast = fast->next->next; - } - ListNode* pa = head; - ListNode* q = slow->next; - slow->next = nullptr; - ListNode* pb = reverse(q); - int ans = 0; - while (pa) { - ans = max(ans, pa->val + pb->val); - pa = pa->next; - pb = pb->next; - } + vector s; + for (; head != nullptr; head = head->next) s.push_back(head->val); + int ans = 0, n = s.size(); + for (int i = 0; i < (n >> 1); ++i) ans = max(ans, s[i] + s[n - i - 1]); return ans; } - - ListNode* reverse(ListNode* head) { - ListNode* dummy = new ListNode(); - ListNode* curr = head; - while (curr) { - ListNode* next = curr->next; - curr->next = dummy->next; - dummy->next = curr; - curr = next; - } - return dummy->next; - } }; \ No newline at end of file diff --git a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.go b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.go index a70bead7cf46a..b9c0bfae06e04 100644 --- a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.go +++ b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.go @@ -6,30 +6,15 @@ * } */ func pairSum(head *ListNode) int { - reverse := func(head *ListNode) *ListNode { - dummy := &ListNode{} - curr := head - for curr != nil { - next := curr.Next - curr.Next = dummy.Next - dummy.Next = curr - curr = next - } - return dummy.Next - } - slow, fast := head, head.Next - for fast != nil && fast.Next != nil { - slow, fast = slow.Next, fast.Next.Next + var s []int + for ; head != nil; head = head.Next { + s = append(s, head.Val) } - pa := head - q := slow.Next - slow.Next = nil - pb := reverse(q) - ans := 0 - for pa != nil { - ans = max(ans, pa.Val+pb.Val) - pa = pa.Next - pb = pb.Next + ans, n := 0, len(s) + for i := 0; i < (n >> 1); i++ { + if ans < s[i]+s[n-i-1] { + ans = s[i] + s[n-i-1] + } } return ans } \ No newline at end of file diff --git a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.java b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.java index 51cb89e9d982d..a871ce1a668b0 100644 --- a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.java +++ b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.java @@ -10,34 +10,14 @@ */ class Solution { public int pairSum(ListNode head) { - ListNode slow = head; - ListNode fast = head.next; - while (fast != null && fast.next != null) { - slow = slow.next; - fast = fast.next.next; + List s = new ArrayList<>(); + for (; head != null; head = head.next) { + s.add(head.val); } - ListNode pa = head; - ListNode q = slow.next; - slow.next = null; - ListNode pb = reverse(q); - int ans = 0; - while (pa != null) { - ans = Math.max(ans, pa.val + pb.val); - pa = pa.next; - pb = pb.next; + int ans = 0, n = s.size(); + for (int i = 0; i < (n >> 1); ++i) { + ans = Math.max(ans, s.get(i) + s.get(n - 1 - i)); } return ans; } - - private ListNode reverse(ListNode head) { - ListNode dummy = new ListNode(); - ListNode curr = head; - while (curr != null) { - ListNode next = curr.next; - curr.next = dummy.next; - dummy.next = curr; - curr = next; - } - return dummy.next; - } } \ No newline at end of file diff --git a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.py b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.py index 4d795e010959d..24b6b699ea802 100644 --- a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.py +++ b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.py @@ -5,26 +5,9 @@ # self.next = next class Solution: def pairSum(self, head: Optional[ListNode]) -> int: - def reverse(head): - dummy = ListNode() - curr = head - while curr: - next = curr.next - curr.next = dummy.next - dummy.next = curr - curr = next - return dummy.next - - slow, fast = head, head.next - while fast and fast.next: - slow, fast = slow.next, fast.next.next - pa = head - q = slow.next - slow.next = None - pb = reverse(q) - ans = 0 - while pa and pb: - ans = max(ans, pa.val + pb.val) - pa = pa.next - pb = pb.next - return ans + s = [] + while head: + s.append(head.val) + head = head.next + n = len(s) + return max(s[i] + s[-(i + 1)] for i in range(n >> 1)) diff --git a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.ts b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.ts index 36833224893de..988544973133d 100644 --- a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.ts +++ b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution.ts @@ -11,26 +11,16 @@ */ function pairSum(head: ListNode | null): number { - let fast = head; - let slow = head; - while (fast) { - fast = fast.next.next; - slow = slow.next; + const arr = []; + let node = head; + while (node) { + arr.push(node.val); + node = node.next; } - let prev = null; - while (slow) { - const next = slow.next; - slow.next = prev; - prev = slow; - slow = next; - } - let left = head; - let right = prev; + const n = arr.length; let ans = 0; - while (left && right) { - ans = Math.max(ans, left.val + right.val); - left = left.next; - right = right.next; + for (let i = 0; i < n >> 1; i++) { + ans = Math.max(ans, arr[i] + arr[n - 1 - i]); } return ans; } diff --git a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution2.cpp b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution2.cpp new file mode 100644 index 0000000000000..080a2d3cb5cd4 --- /dev/null +++ b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution2.cpp @@ -0,0 +1,44 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + int pairSum(ListNode* head) { + ListNode* slow = head; + ListNode* fast = head->next; + while (fast && fast->next) { + slow = slow->next; + fast = fast->next->next; + } + ListNode* pa = head; + ListNode* q = slow->next; + slow->next = nullptr; + ListNode* pb = reverse(q); + int ans = 0; + while (pa) { + ans = max(ans, pa->val + pb->val); + pa = pa->next; + pb = pb->next; + } + return ans; + } + + ListNode* reverse(ListNode* head) { + ListNode* dummy = new ListNode(); + ListNode* curr = head; + while (curr) { + ListNode* next = curr->next; + curr->next = dummy->next; + dummy->next = curr; + curr = next; + } + return dummy->next; + } +}; \ No newline at end of file diff --git a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution2.go b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution2.go new file mode 100644 index 0000000000000..a70bead7cf46a --- /dev/null +++ b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution2.go @@ -0,0 +1,35 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func pairSum(head *ListNode) int { + reverse := func(head *ListNode) *ListNode { + dummy := &ListNode{} + curr := head + for curr != nil { + next := curr.Next + curr.Next = dummy.Next + dummy.Next = curr + curr = next + } + return dummy.Next + } + slow, fast := head, head.Next + for fast != nil && fast.Next != nil { + slow, fast = slow.Next, fast.Next.Next + } + pa := head + q := slow.Next + slow.Next = nil + pb := reverse(q) + ans := 0 + for pa != nil { + ans = max(ans, pa.Val+pb.Val) + pa = pa.Next + pb = pb.Next + } + return ans +} \ No newline at end of file diff --git a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution2.java b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution2.java new file mode 100644 index 0000000000000..51cb89e9d982d --- /dev/null +++ b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution2.java @@ -0,0 +1,43 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public int pairSum(ListNode head) { + ListNode slow = head; + ListNode fast = head.next; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + ListNode pa = head; + ListNode q = slow.next; + slow.next = null; + ListNode pb = reverse(q); + int ans = 0; + while (pa != null) { + ans = Math.max(ans, pa.val + pb.val); + pa = pa.next; + pb = pb.next; + } + return ans; + } + + private ListNode reverse(ListNode head) { + ListNode dummy = new ListNode(); + ListNode curr = head; + while (curr != null) { + ListNode next = curr.next; + curr.next = dummy.next; + dummy.next = curr; + curr = next; + } + return dummy.next; + } +} \ No newline at end of file diff --git a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution2.py b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution2.py new file mode 100644 index 0000000000000..4d795e010959d --- /dev/null +++ b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution2.py @@ -0,0 +1,30 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def pairSum(self, head: Optional[ListNode]) -> int: + def reverse(head): + dummy = ListNode() + curr = head + while curr: + next = curr.next + curr.next = dummy.next + dummy.next = curr + curr = next + return dummy.next + + slow, fast = head, head.next + while fast and fast.next: + slow, fast = slow.next, fast.next.next + pa = head + q = slow.next + slow.next = None + pb = reverse(q) + ans = 0 + while pa and pb: + ans = max(ans, pa.val + pb.val) + pa = pa.next + pb = pb.next + return ans diff --git a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution2.ts b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution2.ts new file mode 100644 index 0000000000000..36833224893de --- /dev/null +++ b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/Solution2.ts @@ -0,0 +1,36 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function pairSum(head: ListNode | null): number { + let fast = head; + let slow = head; + while (fast) { + fast = fast.next.next; + slow = slow.next; + } + let prev = null; + while (slow) { + const next = slow.next; + slow.next = prev; + prev = slow; + slow = next; + } + let left = head; + let right = prev; + let ans = 0; + while (left && right) { + ans = Math.max(ans, left.val + right.val); + left = left.next; + right = right.next; + } + return ans; +} diff --git a/solution/2100-2199/2132.Stamping the Grid/Solution.cpp b/solution/2100-2199/2132.Stamping the Grid/Solution.cpp index 5fe5172a0871e..d13ffd94e72b4 100644 --- a/solution/2100-2199/2132.Stamping the Grid/Solution.cpp +++ b/solution/2100-2199/2132.Stamping the Grid/Solution.cpp @@ -1,35 +1,35 @@ -class Solution { -public: - bool possibleToStamp(vector>& grid, int stampHeight, int stampWidth) { - int m = grid.size(), n = grid[0].size(); - vector> s(m + 1, vector(n + 1)); - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + grid[i - 1][j - 1]; - } - } - - vector> d(m + 2, vector(n + 2)); - for (int i = 1; i + stampHeight - 1 <= m; ++i) { - for (int j = 1; j + stampWidth - 1 <= n; ++j) { - int x = i + stampHeight - 1, y = j + stampWidth - 1; - if (s[x][y] - s[x][j - 1] - s[i - 1][y] + s[i - 1][j - 1] == 0) { - d[i][j]++; - d[i][y + 1]--; - d[x + 1][j]--; - d[x + 1][y + 1]++; - } - } - } - - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - d[i][j] += d[i - 1][j] + d[i][j - 1] - d[i - 1][j - 1]; - if (grid[i - 1][j - 1] == 0 && d[i][j] == 0) { - return false; - } - } - } - return true; - } +class Solution { +public: + bool possibleToStamp(vector>& grid, int stampHeight, int stampWidth) { + int m = grid.size(), n = grid[0].size(); + vector> s(m + 1, vector(n + 1)); + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + grid[i - 1][j - 1]; + } + } + + vector> d(m + 2, vector(n + 2)); + for (int i = 1; i + stampHeight - 1 <= m; ++i) { + for (int j = 1; j + stampWidth - 1 <= n; ++j) { + int x = i + stampHeight - 1, y = j + stampWidth - 1; + if (s[x][y] - s[x][j - 1] - s[i - 1][y] + s[i - 1][j - 1] == 0) { + d[i][j]++; + d[i][y + 1]--; + d[x + 1][j]--; + d[x + 1][y + 1]++; + } + } + } + + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + d[i][j] += d[i - 1][j] + d[i][j - 1] - d[i - 1][j - 1]; + if (grid[i - 1][j - 1] == 0 && d[i][j] == 0) { + return false; + } + } + } + return true; + } }; \ No newline at end of file diff --git a/solution/2100-2199/2132.Stamping the Grid/Solution.java b/solution/2100-2199/2132.Stamping the Grid/Solution.java index de13971a61a91..295ae2fe261a1 100644 --- a/solution/2100-2199/2132.Stamping the Grid/Solution.java +++ b/solution/2100-2199/2132.Stamping the Grid/Solution.java @@ -1,32 +1,32 @@ -class Solution { - public boolean possibleToStamp(int[][] grid, int stampHeight, int stampWidth) { - int m = grid.length, n = grid[0].length; - int[][] s = new int[m + 1][n + 1]; - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + grid[i - 1][j - 1]; - } - } - int[][] d = new int[m + 2][n + 2]; - for (int i = 1; i + stampHeight - 1 <= m; ++i) { - for (int j = 1; j + stampWidth - 1 <= n; ++j) { - int x = i + stampHeight - 1, y = j + stampWidth - 1; - if (s[x][y] - s[x][j - 1] - s[i - 1][y] + s[i - 1][j - 1] == 0) { - d[i][j]++; - d[i][y + 1]--; - d[x + 1][j]--; - d[x + 1][y + 1]++; - } - } - } - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - d[i][j] += d[i - 1][j] + d[i][j - 1] - d[i - 1][j - 1]; - if (grid[i - 1][j - 1] == 0 && d[i][j] == 0) { - return false; - } - } - } - return true; - } +class Solution { + public boolean possibleToStamp(int[][] grid, int stampHeight, int stampWidth) { + int m = grid.length, n = grid[0].length; + int[][] s = new int[m + 1][n + 1]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + grid[i - 1][j - 1]; + } + } + int[][] d = new int[m + 2][n + 2]; + for (int i = 1; i + stampHeight - 1 <= m; ++i) { + for (int j = 1; j + stampWidth - 1 <= n; ++j) { + int x = i + stampHeight - 1, y = j + stampWidth - 1; + if (s[x][y] - s[x][j - 1] - s[i - 1][y] + s[i - 1][j - 1] == 0) { + d[i][j]++; + d[i][y + 1]--; + d[x + 1][j]--; + d[x + 1][y + 1]++; + } + } + } + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + d[i][j] += d[i - 1][j] + d[i][j - 1] - d[i - 1][j - 1]; + if (grid[i - 1][j - 1] == 0 && d[i][j] == 0) { + return false; + } + } + } + return true; + } } \ No newline at end of file diff --git a/solution/2100-2199/2132.Stamping the Grid/Solution.py b/solution/2100-2199/2132.Stamping the Grid/Solution.py index 01410b59c171f..64905d59c15fa 100644 --- a/solution/2100-2199/2132.Stamping the Grid/Solution.py +++ b/solution/2100-2199/2132.Stamping the Grid/Solution.py @@ -1,24 +1,24 @@ -class Solution: - def possibleToStamp( - self, grid: List[List[int]], stampHeight: int, stampWidth: int - ) -> bool: - m, n = len(grid), len(grid[0]) - s = [[0] * (n + 1) for _ in range(m + 1)] - for i, row in enumerate(grid, 1): - for j, v in enumerate(row, 1): - s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + v - d = [[0] * (n + 2) for _ in range(m + 2)] - for i in range(1, m - stampHeight + 2): - for j in range(1, n - stampWidth + 2): - x, y = i + stampHeight - 1, j + stampWidth - 1 - if s[x][y] - s[x][j - 1] - s[i - 1][y] + s[i - 1][j - 1] == 0: - d[i][j] += 1 - d[i][y + 1] -= 1 - d[x + 1][j] -= 1 - d[x + 1][y + 1] += 1 - for i, row in enumerate(grid, 1): - for j, v in enumerate(row, 1): - d[i][j] += d[i - 1][j] + d[i][j - 1] - d[i - 1][j - 1] - if v == 0 and d[i][j] == 0: - return False - return True +class Solution: + def possibleToStamp( + self, grid: List[List[int]], stampHeight: int, stampWidth: int + ) -> bool: + m, n = len(grid), len(grid[0]) + s = [[0] * (n + 1) for _ in range(m + 1)] + for i, row in enumerate(grid, 1): + for j, v in enumerate(row, 1): + s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + v + d = [[0] * (n + 2) for _ in range(m + 2)] + for i in range(1, m - stampHeight + 2): + for j in range(1, n - stampWidth + 2): + x, y = i + stampHeight - 1, j + stampWidth - 1 + if s[x][y] - s[x][j - 1] - s[i - 1][y] + s[i - 1][j - 1] == 0: + d[i][j] += 1 + d[i][y + 1] -= 1 + d[x + 1][j] -= 1 + d[x + 1][y + 1] += 1 + for i, row in enumerate(grid, 1): + for j, v in enumerate(row, 1): + d[i][j] += d[i - 1][j] + d[i][j - 1] - d[i - 1][j - 1] + if v == 0 and d[i][j] == 0: + return False + return True diff --git a/solution/2100-2199/2135.Count Words Obtained After Adding a Letter/Solution.java b/solution/2100-2199/2135.Count Words Obtained After Adding a Letter/Solution.java index a66ec67c54fda..3936e4274895c 100644 --- a/solution/2100-2199/2135.Count Words Obtained After Adding a Letter/Solution.java +++ b/solution/2100-2199/2135.Count Words Obtained After Adding a Letter/Solution.java @@ -1,4 +1,5 @@ class Solution { + public int wordCount(String[] startWords, String[] targetWords) { Set s = new HashSet<>(); for (String word : startWords) { diff --git a/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/Solution.cpp b/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/Solution.cpp index c7c9ea1de6861..18af2a96feab0 100644 --- a/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/Solution.cpp +++ b/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - int earliestFullBloom(vector& plantTime, vector& growTime) { - int n = plantTime.size(); - vector idx(n); - iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) { return growTime[j] < growTime[i]; }); - int ans = 0, t = 0; - for (int i : idx) { - t += plantTime[i]; - ans = max(ans, t + growTime[i]); - } - return ans; - } +class Solution { +public: + int earliestFullBloom(vector& plantTime, vector& growTime) { + int n = plantTime.size(); + vector idx(n); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { return growTime[j] < growTime[i]; }); + int ans = 0, t = 0; + for (int i : idx) { + t += plantTime[i]; + ans = max(ans, t + growTime[i]); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/Solution.java b/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/Solution.java index da7cba16a5f1f..7fe75ce8c772a 100644 --- a/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/Solution.java +++ b/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/Solution.java @@ -1,16 +1,16 @@ -class Solution { - public int earliestFullBloom(int[] plantTime, int[] growTime) { - int n = plantTime.length; - Integer[] idx = new Integer[n]; - for (int i = 0; i < n; i++) { - idx[i] = i; - } - Arrays.sort(idx, (i, j) -> growTime[j] - growTime[i]); - int ans = 0, t = 0; - for (int i : idx) { - t += plantTime[i]; - ans = Math.max(ans, t + growTime[i]); - } - return ans; - } +class Solution { + public int earliestFullBloom(int[] plantTime, int[] growTime) { + int n = plantTime.length; + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; i++) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> growTime[j] - growTime[i]); + int ans = 0, t = 0; + for (int i : idx) { + t += plantTime[i]; + ans = Math.max(ans, t + growTime[i]); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/Solution.py b/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/Solution.py index 96e825f307eca..5287902da0719 100644 --- a/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/Solution.py +++ b/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int: - ans = t = 0 - for pt, gt in sorted(zip(plantTime, growTime), key=lambda x: -x[1]): - t += pt - ans = max(ans, t + gt) - return ans +class Solution: + def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int: + ans = t = 0 + for pt, gt in sorted(zip(plantTime, growTime), key=lambda x: -x[1]): + t += pt + ans = max(ans, t + gt) + return ans diff --git a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.cpp b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.cpp index 6ecfd244689cf..0ff5cf7075c15 100644 --- a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.cpp +++ b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.cpp @@ -1,17 +1,15 @@ class Solution { public: int minMoves(int target, int maxDoubles) { - int ans = 0; - while (maxDoubles > 0 && target > 1) { - ++ans; - if (target % 2 == 1) { - --target; - } else { - --maxDoubles; - target >>= 1; - } + if (target == 1) { + return 0; } - ans += target - 1; - return ans; + if (maxDoubles == 0) { + return target - 1; + } + if (target % 2 == 0 && maxDoubles > 0) { + return 1 + minMoves(target >> 1, maxDoubles - 1); + } + return 1 + minMoves(target - 1, maxDoubles); } }; \ No newline at end of file diff --git a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.go b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.go index 0a7b08de6a694..200d0ee48b026 100644 --- a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.go +++ b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.go @@ -1,13 +1,12 @@ -func minMoves(target int, maxDoubles int) (ans int) { - for maxDoubles > 0 && target > 1 { - ans++ - if target&1 == 1 { - target-- - } else { - maxDoubles-- - target >>= 1 - } +func minMoves(target int, maxDoubles int) int { + if target == 1 { + return 0 } - ans += target - 1 - return + if maxDoubles == 0 { + return target - 1 + } + if target%2 == 0 && maxDoubles > 0 { + return 1 + minMoves(target>>1, maxDoubles-1) + } + return 1 + minMoves(target-1, maxDoubles) } \ No newline at end of file diff --git a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.java b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.java index 0d40a3e55eda5..8764ce3688d3f 100644 --- a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.java +++ b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.java @@ -1,16 +1,14 @@ class Solution { public int minMoves(int target, int maxDoubles) { - int ans = 0; - while (maxDoubles > 0 && target > 1) { - ++ans; - if (target % 2 == 1) { - --target; - } else { - --maxDoubles; - target >>= 1; - } + if (target == 1) { + return 0; } - ans += target - 1; - return ans; + if (maxDoubles == 0) { + return target - 1; + } + if (target % 2 == 0 && maxDoubles > 0) { + return 1 + minMoves(target >> 1, maxDoubles - 1); + } + return 1 + minMoves(target - 1, maxDoubles); } } \ No newline at end of file diff --git a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.py b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.py index 92c04a2b7973a..2e76193c48c9a 100644 --- a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.py +++ b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.py @@ -1,12 +1,9 @@ class Solution: def minMoves(self, target: int, maxDoubles: int) -> int: - ans = 0 - while maxDoubles and target > 1: - ans += 1 - if target % 2 == 1: - target -= 1 - else: - maxDoubles -= 1 - target >>= 1 - ans += target - 1 - return ans + if target == 1: + return 0 + if maxDoubles == 0: + return target - 1 + if target % 2 == 0 and maxDoubles: + return 1 + self.minMoves(target >> 1, maxDoubles - 1) + return 1 + self.minMoves(target - 1, maxDoubles) diff --git a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.ts b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.ts index 9d5022b8d2063..7c9bf9fddee21 100644 --- a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.ts +++ b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution.ts @@ -1,14 +1,12 @@ function minMoves(target: number, maxDoubles: number): number { - let ans = 0; - while (maxDoubles && target > 1) { - ++ans; - if (target & 1) { - --target; - } else { - --maxDoubles; - target >>= 1; - } + if (target === 1) { + return 0; } - ans += target - 1; - return ans; + if (maxDoubles === 0) { + return target - 1; + } + if (target % 2 === 0 && maxDoubles) { + return 1 + minMoves(target >> 1, maxDoubles - 1); + } + return 1 + minMoves(target - 1, maxDoubles); } diff --git a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution2.cpp b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution2.cpp new file mode 100644 index 0000000000000..6ecfd244689cf --- /dev/null +++ b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int minMoves(int target, int maxDoubles) { + int ans = 0; + while (maxDoubles > 0 && target > 1) { + ++ans; + if (target % 2 == 1) { + --target; + } else { + --maxDoubles; + target >>= 1; + } + } + ans += target - 1; + return ans; + } +}; \ No newline at end of file diff --git a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution2.go b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution2.go new file mode 100644 index 0000000000000..0a7b08de6a694 --- /dev/null +++ b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution2.go @@ -0,0 +1,13 @@ +func minMoves(target int, maxDoubles int) (ans int) { + for maxDoubles > 0 && target > 1 { + ans++ + if target&1 == 1 { + target-- + } else { + maxDoubles-- + target >>= 1 + } + } + ans += target - 1 + return +} \ No newline at end of file diff --git a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution2.java b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution2.java new file mode 100644 index 0000000000000..0d40a3e55eda5 --- /dev/null +++ b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public int minMoves(int target, int maxDoubles) { + int ans = 0; + while (maxDoubles > 0 && target > 1) { + ++ans; + if (target % 2 == 1) { + --target; + } else { + --maxDoubles; + target >>= 1; + } + } + ans += target - 1; + return ans; + } +} \ No newline at end of file diff --git a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution2.py b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution2.py new file mode 100644 index 0000000000000..92c04a2b7973a --- /dev/null +++ b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def minMoves(self, target: int, maxDoubles: int) -> int: + ans = 0 + while maxDoubles and target > 1: + ans += 1 + if target % 2 == 1: + target -= 1 + else: + maxDoubles -= 1 + target >>= 1 + ans += target - 1 + return ans diff --git a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution2.ts b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution2.ts new file mode 100644 index 0000000000000..9d5022b8d2063 --- /dev/null +++ b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution2.ts @@ -0,0 +1,14 @@ +function minMoves(target: number, maxDoubles: number): number { + let ans = 0; + while (maxDoubles && target > 1) { + ++ans; + if (target & 1) { + --target; + } else { + --maxDoubles; + target >>= 1; + } + } + ans += target - 1; + return ans; +} diff --git a/solution/2100-2199/2140.Solving Questions With Brainpower/Solution2.cpp b/solution/2100-2199/2140.Solving Questions With Brainpower/Solution2.cpp new file mode 100644 index 0000000000000..1a1a37bcbb0ee --- /dev/null +++ b/solution/2100-2199/2140.Solving Questions With Brainpower/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + long long mostPoints(vector>& questions) { + int n = questions.size(); + long long f[n + 1]; + memset(f, 0, sizeof(f)); + for (int i = n - 1; ~i; --i) { + int p = questions[i][0], b = questions[i][1]; + int j = i + b + 1; + f[i] = max(f[i + 1], p + (j > n ? 0 : f[j])); + } + return f[0]; + } +}; \ No newline at end of file diff --git a/solution/2100-2199/2140.Solving Questions With Brainpower/Solution2.go b/solution/2100-2199/2140.Solving Questions With Brainpower/Solution2.go new file mode 100644 index 0000000000000..46dec02edf99d --- /dev/null +++ b/solution/2100-2199/2140.Solving Questions With Brainpower/Solution2.go @@ -0,0 +1,12 @@ +func mostPoints(questions [][]int) int64 { + n := len(questions) + f := make([]int64, n+1) + for i := n - 1; i >= 0; i-- { + p := int64(questions[i][0]) + if j := i + questions[i][1] + 1; j <= n { + p += f[j] + } + f[i] = max(f[i+1], p) + } + return f[0] +} \ No newline at end of file diff --git a/solution/2100-2199/2140.Solving Questions With Brainpower/Solution2.java b/solution/2100-2199/2140.Solving Questions With Brainpower/Solution2.java new file mode 100644 index 0000000000000..23fb1c7f110e3 --- /dev/null +++ b/solution/2100-2199/2140.Solving Questions With Brainpower/Solution2.java @@ -0,0 +1,12 @@ +class Solution { + public long mostPoints(int[][] questions) { + int n = questions.length; + long[] f = new long[n + 1]; + for (int i = n - 1; i >= 0; --i) { + int p = questions[i][0], b = questions[i][1]; + int j = i + b + 1; + f[i] = Math.max(f[i + 1], p + (j > n ? 0 : f[j])); + } + return f[0]; + } +} \ No newline at end of file diff --git a/solution/2100-2199/2140.Solving Questions With Brainpower/Solution2.py b/solution/2100-2199/2140.Solving Questions With Brainpower/Solution2.py new file mode 100644 index 0000000000000..fe7f3b9c3131b --- /dev/null +++ b/solution/2100-2199/2140.Solving Questions With Brainpower/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def mostPoints(self, questions: List[List[int]]) -> int: + n = len(questions) + f = [0] * (n + 1) + for i in range(n - 1, -1, -1): + p, b = questions[i] + j = i + b + 1 + f[i] = max(f[i + 1], p + (0 if j > n else f[j])) + return f[0] diff --git a/solution/2100-2199/2140.Solving Questions With Brainpower/Solution2.ts b/solution/2100-2199/2140.Solving Questions With Brainpower/Solution2.ts new file mode 100644 index 0000000000000..9d7d52b008f4d --- /dev/null +++ b/solution/2100-2199/2140.Solving Questions With Brainpower/Solution2.ts @@ -0,0 +1,10 @@ +function mostPoints(questions: number[][]): number { + const n = questions.length; + const f = Array(n + 1).fill(0); + for (let i = n - 1; i >= 0; --i) { + const [p, b] = questions[i]; + const j = i + b + 1; + f[i] = Math.max(f[i + 1], p + (j > n ? 0 : f[j])); + } + return f[0]; +} diff --git a/solution/2100-2199/2141.Maximum Running Time of N Computers/Solution.cpp b/solution/2100-2199/2141.Maximum Running Time of N Computers/Solution.cpp index d3427984e6afb..d1af25c99d754 100644 --- a/solution/2100-2199/2141.Maximum Running Time of N Computers/Solution.cpp +++ b/solution/2100-2199/2141.Maximum Running Time of N Computers/Solution.cpp @@ -1,22 +1,22 @@ -class Solution { -public: - long long maxRunTime(int n, vector& batteries) { - long long l = 0, r = 0; - for (int x : batteries) { - r += x; - } - while (l < r) { - long long mid = (l + r + 1) >> 1; - long long s = 0; - for (int x : batteries) { - s += min(1LL * x, mid); - } - if (s >= n * mid) { - l = mid; - } else { - r = mid - 1; - } - } - return l; - } +class Solution { +public: + long long maxRunTime(int n, vector& batteries) { + long long l = 0, r = 0; + for (int x : batteries) { + r += x; + } + while (l < r) { + long long mid = (l + r + 1) >> 1; + long long s = 0; + for (int x : batteries) { + s += min(1LL * x, mid); + } + if (s >= n * mid) { + l = mid; + } else { + r = mid - 1; + } + } + return l; + } }; \ No newline at end of file diff --git a/solution/2100-2199/2141.Maximum Running Time of N Computers/Solution.java b/solution/2100-2199/2141.Maximum Running Time of N Computers/Solution.java index a7f97be0f5a61..c8b4b1aaa1220 100644 --- a/solution/2100-2199/2141.Maximum Running Time of N Computers/Solution.java +++ b/solution/2100-2199/2141.Maximum Running Time of N Computers/Solution.java @@ -1,21 +1,21 @@ -class Solution { - public long maxRunTime(int n, int[] batteries) { - long l = 0, r = 0; - for (int x : batteries) { - r += x; - } - while (l < r) { - long mid = (l + r + 1) >> 1; - long s = 0; - for (int x : batteries) { - s += Math.min(mid, x); - } - if (s >= n * mid) { - l = mid; - } else { - r = mid - 1; - } - } - return l; - } +class Solution { + public long maxRunTime(int n, int[] batteries) { + long l = 0, r = 0; + for (int x : batteries) { + r += x; + } + while (l < r) { + long mid = (l + r + 1) >> 1; + long s = 0; + for (int x : batteries) { + s += Math.min(mid, x); + } + if (s >= n * mid) { + l = mid; + } else { + r = mid - 1; + } + } + return l; + } } \ No newline at end of file diff --git a/solution/2100-2199/2141.Maximum Running Time of N Computers/Solution.py b/solution/2100-2199/2141.Maximum Running Time of N Computers/Solution.py index 252bfb5cff3f9..8c66a4c32bf2a 100644 --- a/solution/2100-2199/2141.Maximum Running Time of N Computers/Solution.py +++ b/solution/2100-2199/2141.Maximum Running Time of N Computers/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def maxRunTime(self, n: int, batteries: List[int]) -> int: - l, r = 0, sum(batteries) - while l < r: - mid = (l + r + 1) >> 1 - if sum(min(x, mid) for x in batteries) >= n * mid: - l = mid - else: - r = mid - 1 - return l +class Solution: + def maxRunTime(self, n: int, batteries: List[int]) -> int: + l, r = 0, sum(batteries) + while l < r: + mid = (l + r + 1) >> 1 + if sum(min(x, mid) for x in batteries) >= n * mid: + l = mid + else: + r = mid - 1 + return l diff --git a/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/Solution.cpp b/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/Solution.cpp index 2da3e66dfa06e..62347c2b60f57 100644 --- a/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/Solution.cpp +++ b/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/Solution.cpp @@ -1,29 +1,29 @@ -class Solution { -public: - int countSubranges(vector& nums1, vector& nums2) { - int n = nums1.size(); - int s1 = accumulate(nums1.begin(), nums1.end(), 0); - int s2 = accumulate(nums2.begin(), nums2.end(), 0); - int f[n][s1 + s2 + 1]; - memset(f, 0, sizeof(f)); - int ans = 0; - const int mod = 1e9 + 7; - for (int i = 0; i < n; ++i) { - int a = nums1[i], b = nums2[i]; - f[i][a + s2]++; - f[i][-b + s2]++; - if (i) { - for (int j = 0; j <= s1 + s2; ++j) { - if (j >= a) { - f[i][j] = (f[i][j] + f[i - 1][j - a]) % mod; - } - if (j + b <= s1 + s2) { - f[i][j] = (f[i][j] + f[i - 1][j + b]) % mod; - } - } - } - ans = (ans + f[i][s2]) % mod; - } - return ans; - } +class Solution { +public: + int countSubranges(vector& nums1, vector& nums2) { + int n = nums1.size(); + int s1 = accumulate(nums1.begin(), nums1.end(), 0); + int s2 = accumulate(nums2.begin(), nums2.end(), 0); + int f[n][s1 + s2 + 1]; + memset(f, 0, sizeof(f)); + int ans = 0; + const int mod = 1e9 + 7; + for (int i = 0; i < n; ++i) { + int a = nums1[i], b = nums2[i]; + f[i][a + s2]++; + f[i][-b + s2]++; + if (i) { + for (int j = 0; j <= s1 + s2; ++j) { + if (j >= a) { + f[i][j] = (f[i][j] + f[i - 1][j - a]) % mod; + } + if (j + b <= s1 + s2) { + f[i][j] = (f[i][j] + f[i - 1][j + b]) % mod; + } + } + } + ans = (ans + f[i][s2]) % mod; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/Solution.java b/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/Solution.java index 6f049243a4b1c..50f652baf19a8 100644 --- a/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/Solution.java +++ b/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/Solution.java @@ -1,27 +1,27 @@ -class Solution { - public int countSubranges(int[] nums1, int[] nums2) { - int n = nums1.length; - int s1 = Arrays.stream(nums1).sum(); - int s2 = Arrays.stream(nums2).sum(); - int[][] f = new int[n][s1 + s2 + 1]; - int ans = 0; - final int mod = (int) 1e9 + 7; - for (int i = 0; i < n; ++i) { - int a = nums1[i], b = nums2[i]; - f[i][a + s2]++; - f[i][-b + s2]++; - if (i > 0) { - for (int j = 0; j <= s1 + s2; ++j) { - if (j >= a) { - f[i][j] = (f[i][j] + f[i - 1][j - a]) % mod; - } - if (j + b <= s1 + s2) { - f[i][j] = (f[i][j] + f[i - 1][j + b]) % mod; - } - } - } - ans = (ans + f[i][s2]) % mod; - } - return ans; - } +class Solution { + public int countSubranges(int[] nums1, int[] nums2) { + int n = nums1.length; + int s1 = Arrays.stream(nums1).sum(); + int s2 = Arrays.stream(nums2).sum(); + int[][] f = new int[n][s1 + s2 + 1]; + int ans = 0; + final int mod = (int) 1e9 + 7; + for (int i = 0; i < n; ++i) { + int a = nums1[i], b = nums2[i]; + f[i][a + s2]++; + f[i][-b + s2]++; + if (i > 0) { + for (int j = 0; j <= s1 + s2; ++j) { + if (j >= a) { + f[i][j] = (f[i][j] + f[i - 1][j - a]) % mod; + } + if (j + b <= s1 + s2) { + f[i][j] = (f[i][j] + f[i - 1][j + b]) % mod; + } + } + } + ans = (ans + f[i][s2]) % mod; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/Solution.py b/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/Solution.py index a8868cdb34b67..4bec9dc2107a5 100644 --- a/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/Solution.py +++ b/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/Solution.py @@ -1,18 +1,18 @@ -class Solution: - def countSubranges(self, nums1: List[int], nums2: List[int]) -> int: - n = len(nums1) - s1, s2 = sum(nums1), sum(nums2) - f = [[0] * (s1 + s2 + 1) for _ in range(n)] - ans = 0 - mod = 10**9 + 7 - for i, (a, b) in enumerate(zip(nums1, nums2)): - f[i][a + s2] += 1 - f[i][-b + s2] += 1 - if i: - for j in range(s1 + s2 + 1): - if j >= a: - f[i][j] = (f[i][j] + f[i - 1][j - a]) % mod - if j + b < s1 + s2 + 1: - f[i][j] = (f[i][j] + f[i - 1][j + b]) % mod - ans = (ans + f[i][s2]) % mod - return ans +class Solution: + def countSubranges(self, nums1: List[int], nums2: List[int]) -> int: + n = len(nums1) + s1, s2 = sum(nums1), sum(nums2) + f = [[0] * (s1 + s2 + 1) for _ in range(n)] + ans = 0 + mod = 10**9 + 7 + for i, (a, b) in enumerate(zip(nums1, nums2)): + f[i][a + s2] += 1 + f[i][-b + s2] += 1 + if i: + for j in range(s1 + s2 + 1): + if j >= a: + f[i][j] = (f[i][j] + f[i - 1][j - a]) % mod + if j + b < s1 + s2 + 1: + f[i][j] = (f[i][j] + f[i - 1][j + b]) % mod + ans = (ans + f[i][s2]) % mod + return ans diff --git a/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/Solution.cpp b/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/Solution.cpp index 18b54a1545e0c..35eb0127fbd36 100644 --- a/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/Solution.cpp +++ b/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/Solution.cpp @@ -1,14 +1,14 @@ -class Solution { -public: - int minimumCost(vector& cost) { - sort(cost.rbegin(), cost.rend()); - int ans = 0; - for (int i = 0; i < cost.size(); i += 3) { - ans += cost[i]; - if (i < cost.size() - 1) { - ans += cost[i + 1]; - } - } - return ans; - } +class Solution { +public: + int minimumCost(vector& cost) { + sort(cost.rbegin(), cost.rend()); + int ans = 0; + for (int i = 0; i < cost.size(); i += 3) { + ans += cost[i]; + if (i < cost.size() - 1) { + ans += cost[i + 1]; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/Solution.java b/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/Solution.java index a3bac850cafde..889547886a3d0 100644 --- a/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/Solution.java +++ b/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/Solution.java @@ -1,13 +1,13 @@ -class Solution { - public int minimumCost(int[] cost) { - Arrays.sort(cost); - int ans = 0; - for (int i = cost.length - 1; i >= 0; i -= 3) { - ans += cost[i]; - if (i > 0) { - ans += cost[i - 1]; - } - } - return ans; - } +class Solution { + public int minimumCost(int[] cost) { + Arrays.sort(cost); + int ans = 0; + for (int i = cost.length - 1; i >= 0; i -= 3) { + ans += cost[i]; + if (i > 0) { + ans += cost[i - 1]; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/Solution.py b/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/Solution.py index 609c9e8c49eeb..66b001f75e1a8 100644 --- a/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/Solution.py +++ b/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/Solution.py @@ -1,4 +1,4 @@ -class Solution: - def minimumCost(self, cost: List[int]) -> int: - cost.sort(reverse=True) - return sum(cost) - sum(cost[2::3]) +class Solution: + def minimumCost(self, cost: List[int]) -> int: + cost.sort(reverse=True) + return sum(cost) - sum(cost[2::3]) diff --git a/solution/2100-2199/2147.Number of Ways to Divide a Long Corridor/Solution.ts b/solution/2100-2199/2147.Number of Ways to Divide a Long Corridor/Solution.ts new file mode 100644 index 0000000000000..09b01d9a27d29 --- /dev/null +++ b/solution/2100-2199/2147.Number of Ways to Divide a Long Corridor/Solution.ts @@ -0,0 +1,22 @@ +function numberOfWays(corridor: string): number { + const M: number = 1e9 + 7; + const seatNumbers: number[] = []; + + for (let i = 0; i < corridor.length; i++) { + if (corridor.charAt(i) === 'S') { + seatNumbers.push(i); + } + } + + if (seatNumbers.length % 2 !== 0 || seatNumbers.length === 0) { + return 0; + } + + let result: number = 1; + + for (let i = 2; i < seatNumbers.length; i += 2) { + result = (result * (seatNumbers[i] - seatNumbers[i - 1])) % M; + } + + return result; +} diff --git a/solution/2100-2199/2148.Count Elements With Strictly Smaller and Greater Elements/Solution.java b/solution/2100-2199/2148.Count Elements With Strictly Smaller and Greater Elements/Solution.java index d6eeffb45affc..1077ac80373d0 100644 --- a/solution/2100-2199/2148.Count Elements With Strictly Smaller and Greater Elements/Solution.java +++ b/solution/2100-2199/2148.Count Elements With Strictly Smaller and Greater Elements/Solution.java @@ -1,4 +1,5 @@ class Solution { + public int countElements(int[] nums) { int mi = 1000000, mx = -1000000; for (int num : nums) { diff --git a/solution/2100-2199/2149.Rearrange Array Elements by Sign/Solution.java b/solution/2100-2199/2149.Rearrange Array Elements by Sign/Solution.java index 5c6a42260c364..e933560968777 100644 --- a/solution/2100-2199/2149.Rearrange Array Elements by Sign/Solution.java +++ b/solution/2100-2199/2149.Rearrange Array Elements by Sign/Solution.java @@ -1,4 +1,5 @@ class Solution { + public int[] rearrangeArray(int[] nums) { int[] ans = new int[nums.length]; int i = 0, j = 1; diff --git a/solution/2100-2199/2150.Find All Lonely Numbers in the Array/Solution.java b/solution/2100-2199/2150.Find All Lonely Numbers in the Array/Solution.java index 0d1b9e492a607..6ac1cd88650ce 100644 --- a/solution/2100-2199/2150.Find All Lonely Numbers in the Array/Solution.java +++ b/solution/2100-2199/2150.Find All Lonely Numbers in the Array/Solution.java @@ -1,4 +1,5 @@ class Solution { + public List findLonely(int[] nums) { Map counter = new HashMap<>(); for (int num : nums) { diff --git a/solution/2100-2199/2154.Keep Multiplying Found Values by Two/Solution.java b/solution/2100-2199/2154.Keep Multiplying Found Values by Two/Solution.java index 13752ba1f6dbc..9ba887fdd175a 100644 --- a/solution/2100-2199/2154.Keep Multiplying Found Values by Two/Solution.java +++ b/solution/2100-2199/2154.Keep Multiplying Found Values by Two/Solution.java @@ -1,4 +1,5 @@ class Solution { + public int findFinalValue(int[] nums, int original) { Set s = new HashSet<>(); for (int num : nums) { diff --git a/solution/2100-2199/2155.All Divisions With the Highest Score of a Binary Array/Solution.java b/solution/2100-2199/2155.All Divisions With the Highest Score of a Binary Array/Solution.java index b40fc961bb947..abb45aa11d3ae 100644 --- a/solution/2100-2199/2155.All Divisions With the Highest Score of a Binary Array/Solution.java +++ b/solution/2100-2199/2155.All Divisions With the Highest Score of a Binary Array/Solution.java @@ -1,4 +1,5 @@ class Solution { + public List maxScoreIndices(int[] nums) { int left = 0, right = sum(nums); int mx = right; diff --git a/solution/2100-2199/2158.Amount of New Area Painted Each Day/Solution.cpp b/solution/2100-2199/2158.Amount of New Area Painted Each Day/Solution.cpp index b6a4c44c3c744..5b360bd36efbd 100644 --- a/solution/2100-2199/2158.Amount of New Area Painted Each Day/Solution.cpp +++ b/solution/2100-2199/2158.Amount of New Area Painted Each Day/Solution.cpp @@ -1,94 +1,94 @@ -class Node { -public: - Node* left; - Node* right; - int l; - int r; - int mid; - int v; - int add; - - Node(int l, int r) { - this->l = l; - this->r = r; - this->mid = (l + r) >> 1; - this->left = this->right = nullptr; - v = add = 0; - } -}; - -class SegmentTree { -private: - Node* root; - -public: - SegmentTree() { - root = new Node(1, 100010); - } - - void modify(int l, int r, int v) { - modify(l, r, v, root); - } - - void modify(int l, int r, int v, Node* node) { - if (l > r) return; - if (node->l >= l && node->r <= r) { - node->v = node->r - node->l + 1; - node->add = v; - return; - } - pushdown(node); - if (l <= node->mid) modify(l, r, v, node->left); - if (r > node->mid) modify(l, r, v, node->right); - pushup(node); - } - - int query(int l, int r) { - return query(l, r, root); - } - - int query(int l, int r, Node* node) { - if (l > r) return 0; - if (node->l >= l && node->r <= r) return node->v; - pushdown(node); - int v = 0; - if (l <= node->mid) v += query(l, r, node->left); - if (r > node->mid) v += query(l, r, node->right); - return v; - } - - void pushup(Node* node) { - node->v = node->left->v + node->right->v; - } - - void pushdown(Node* node) { - if (!node->left) node->left = new Node(node->l, node->mid); - if (!node->right) node->right = new Node(node->mid + 1, node->r); - if (node->add) { - Node* left = node->left; - Node* right = node->right; - left->v = left->r - left->l + 1; - right->v = right->r - right->l + 1; - left->add = node->add; - right->add = node->add; - node->add = 0; - } - } -}; - -class Solution { -public: - vector amountPainted(vector>& paint) { - int n = paint.size(); - vector ans(n); - SegmentTree* tree = new SegmentTree(); - for (int i = 0; i < n; ++i) { - int l = paint[i][0] + 1; - int r = paint[i][1]; - int v = tree->query(l, r); - ans[i] = r - l + 1 - v; - tree->modify(l, r, 1); - } - return ans; - } +class Node { +public: + Node* left; + Node* right; + int l; + int r; + int mid; + int v; + int add; + + Node(int l, int r) { + this->l = l; + this->r = r; + this->mid = (l + r) >> 1; + this->left = this->right = nullptr; + v = add = 0; + } +}; + +class SegmentTree { +private: + Node* root; + +public: + SegmentTree() { + root = new Node(1, 100010); + } + + void modify(int l, int r, int v) { + modify(l, r, v, root); + } + + void modify(int l, int r, int v, Node* node) { + if (l > r) return; + if (node->l >= l && node->r <= r) { + node->v = node->r - node->l + 1; + node->add = v; + return; + } + pushdown(node); + if (l <= node->mid) modify(l, r, v, node->left); + if (r > node->mid) modify(l, r, v, node->right); + pushup(node); + } + + int query(int l, int r) { + return query(l, r, root); + } + + int query(int l, int r, Node* node) { + if (l > r) return 0; + if (node->l >= l && node->r <= r) return node->v; + pushdown(node); + int v = 0; + if (l <= node->mid) v += query(l, r, node->left); + if (r > node->mid) v += query(l, r, node->right); + return v; + } + + void pushup(Node* node) { + node->v = node->left->v + node->right->v; + } + + void pushdown(Node* node) { + if (!node->left) node->left = new Node(node->l, node->mid); + if (!node->right) node->right = new Node(node->mid + 1, node->r); + if (node->add) { + Node* left = node->left; + Node* right = node->right; + left->v = left->r - left->l + 1; + right->v = right->r - right->l + 1; + left->add = node->add; + right->add = node->add; + node->add = 0; + } + } +}; + +class Solution { +public: + vector amountPainted(vector>& paint) { + int n = paint.size(); + vector ans(n); + SegmentTree* tree = new SegmentTree(); + for (int i = 0; i < n; ++i) { + int l = paint[i][0] + 1; + int r = paint[i][1]; + int v = tree->query(l, r); + ans[i] = r - l + 1 - v; + tree->modify(l, r, 1); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2100-2199/2158.Amount of New Area Painted Each Day/Solution.java b/solution/2100-2199/2158.Amount of New Area Painted Each Day/Solution.java index e6e46340823cd..5e8c11bc58e6f 100644 --- a/solution/2100-2199/2158.Amount of New Area Painted Each Day/Solution.java +++ b/solution/2100-2199/2158.Amount of New Area Painted Each Day/Solution.java @@ -1,104 +1,104 @@ -class Node { - Node left; - Node right; - int l; - int r; - int mid; - int v; - int add; - - public Node(int l, int r) { - this.l = l; - this.r = r; - this.mid = (l + r) >> 1; - } -} - -class SegmentTree { - private Node root = new Node(1, 100010); - - public SegmentTree() { - } - - public void modify(int l, int r, int v) { - modify(l, r, v, root); - } - - public void modify(int l, int r, int v, Node node) { - if (l > r) { - return; - } - if (node.l >= l && node.r <= r) { - node.v = node.r - node.l + 1; - node.add = v; - return; - } - pushdown(node); - if (l <= node.mid) { - modify(l, r, v, node.left); - } - if (r > node.mid) { - modify(l, r, v, node.right); - } - pushup(node); - } - - public int query(int l, int r) { - return query(l, r, root); - } - - public int query(int l, int r, Node node) { - if (l > r) { - return 0; - } - if (node.l >= l && node.r <= r) { - return node.v; - } - pushdown(node); - int v = 0; - if (l <= node.mid) { - v += query(l, r, node.left); - } - if (r > node.mid) { - v += query(l, r, node.right); - } - return v; - } - - public void pushup(Node node) { - node.v = node.left.v + node.right.v; - } - - public void pushdown(Node node) { - if (node.left == null) { - node.left = new Node(node.l, node.mid); - } - if (node.right == null) { - node.right = new Node(node.mid + 1, node.r); - } - if (node.add != 0) { - Node left = node.left, right = node.right; - left.add = node.add; - right.add = node.add; - left.v = left.r - left.l + 1; - right.v = right.r - right.l + 1; - node.add = 0; - } - } -} - -class Solution { - public int[] amountPainted(int[][] paint) { - SegmentTree tree = new SegmentTree(); - int n = paint.length; - int[] ans = new int[n]; - for (int i = 0; i < n; ++i) { - int l = paint[i][0] + 1; - int r = paint[i][1]; - int v = tree.query(l, r); - ans[i] = r - l + 1 - v; - tree.modify(l, r, 1); - } - return ans; - } +class Node { + Node left; + Node right; + int l; + int r; + int mid; + int v; + int add; + + public Node(int l, int r) { + this.l = l; + this.r = r; + this.mid = (l + r) >> 1; + } +} + +class SegmentTree { + private Node root = new Node(1, 100010); + + public SegmentTree() { + } + + public void modify(int l, int r, int v) { + modify(l, r, v, root); + } + + public void modify(int l, int r, int v, Node node) { + if (l > r) { + return; + } + if (node.l >= l && node.r <= r) { + node.v = node.r - node.l + 1; + node.add = v; + return; + } + pushdown(node); + if (l <= node.mid) { + modify(l, r, v, node.left); + } + if (r > node.mid) { + modify(l, r, v, node.right); + } + pushup(node); + } + + public int query(int l, int r) { + return query(l, r, root); + } + + public int query(int l, int r, Node node) { + if (l > r) { + return 0; + } + if (node.l >= l && node.r <= r) { + return node.v; + } + pushdown(node); + int v = 0; + if (l <= node.mid) { + v += query(l, r, node.left); + } + if (r > node.mid) { + v += query(l, r, node.right); + } + return v; + } + + public void pushup(Node node) { + node.v = node.left.v + node.right.v; + } + + public void pushdown(Node node) { + if (node.left == null) { + node.left = new Node(node.l, node.mid); + } + if (node.right == null) { + node.right = new Node(node.mid + 1, node.r); + } + if (node.add != 0) { + Node left = node.left, right = node.right; + left.add = node.add; + right.add = node.add; + left.v = left.r - left.l + 1; + right.v = right.r - right.l + 1; + node.add = 0; + } + } +} + +class Solution { + public int[] amountPainted(int[][] paint) { + SegmentTree tree = new SegmentTree(); + int n = paint.length; + int[] ans = new int[n]; + for (int i = 0; i < n; ++i) { + int l = paint[i][0] + 1; + int r = paint[i][1]; + int v = tree.query(l, r); + ans[i] = r - l + 1 - v; + tree.modify(l, r, 1); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2100-2199/2158.Amount of New Area Painted Each Day/Solution.py b/solution/2100-2199/2158.Amount of New Area Painted Each Day/Solution.py index 1c605780d2a4a..255b16d512a9b 100644 --- a/solution/2100-2199/2158.Amount of New Area Painted Each Day/Solution.py +++ b/solution/2100-2199/2158.Amount of New Area Painted Each Day/Solution.py @@ -1,73 +1,73 @@ -class Node: - def __init__(self, l, r): - self.left = None - self.right = None - self.l = l - self.r = r - self.mid = (l + r) >> 1 - self.v = 0 - self.add = 0 - - -class SegmentTree: - def __init__(self): - self.root = Node(1, 10**5 + 10) - - def modify(self, l, r, v, node=None): - if l > r: - return - if node is None: - node = self.root - if node.l >= l and node.r <= r: - node.v = node.r - node.l + 1 - node.add = v - return - self.pushdown(node) - if l <= node.mid: - self.modify(l, r, v, node.left) - if r > node.mid: - self.modify(l, r, v, node.right) - self.pushup(node) - - def query(self, l, r, node=None): - if l > r: - return 0 - if node is None: - node = self.root - if node.l >= l and node.r <= r: - return node.v - self.pushdown(node) - v = 0 - if l <= node.mid: - v += self.query(l, r, node.left) - if r > node.mid: - v += self.query(l, r, node.right) - return v - - def pushup(self, node): - node.v = node.left.v + node.right.v - - def pushdown(self, node): - if node.left is None: - node.left = Node(node.l, node.mid) - if node.right is None: - node.right = Node(node.mid + 1, node.r) - if node.add: - left, right = node.left, node.right - left.v = left.r - left.l + 1 - right.v = right.r - right.l + 1 - left.add = node.add - right.add = node.add - node.add = 0 - - -class Solution: - def amountPainted(self, paint: List[List[int]]) -> List[int]: - tree = SegmentTree() - ans = [] - for i, (start, end) in enumerate(paint): - l, r = start + 1, end - v = tree.query(l, r) - ans.append(r - l + 1 - v) - tree.modify(l, r, 1) - return ans +class Node: + def __init__(self, l, r): + self.left = None + self.right = None + self.l = l + self.r = r + self.mid = (l + r) >> 1 + self.v = 0 + self.add = 0 + + +class SegmentTree: + def __init__(self): + self.root = Node(1, 10**5 + 10) + + def modify(self, l, r, v, node=None): + if l > r: + return + if node is None: + node = self.root + if node.l >= l and node.r <= r: + node.v = node.r - node.l + 1 + node.add = v + return + self.pushdown(node) + if l <= node.mid: + self.modify(l, r, v, node.left) + if r > node.mid: + self.modify(l, r, v, node.right) + self.pushup(node) + + def query(self, l, r, node=None): + if l > r: + return 0 + if node is None: + node = self.root + if node.l >= l and node.r <= r: + return node.v + self.pushdown(node) + v = 0 + if l <= node.mid: + v += self.query(l, r, node.left) + if r > node.mid: + v += self.query(l, r, node.right) + return v + + def pushup(self, node): + node.v = node.left.v + node.right.v + + def pushdown(self, node): + if node.left is None: + node.left = Node(node.l, node.mid) + if node.right is None: + node.right = Node(node.mid + 1, node.r) + if node.add: + left, right = node.left, node.right + left.v = left.r - left.l + 1 + right.v = right.r - right.l + 1 + left.add = node.add + right.add = node.add + node.add = 0 + + +class Solution: + def amountPainted(self, paint: List[List[int]]) -> List[int]: + tree = SegmentTree() + ans = [] + for i, (start, end) in enumerate(paint): + l, r = start + 1, end + v = tree.query(l, r) + ans.append(r - l + 1 - v) + tree.modify(l, r, 1) + return ans diff --git a/solution/2100-2199/2160.Minimum Sum of Four Digit Number After Splitting Digits/Solution.c b/solution/2100-2199/2160.Minimum Sum of Four Digit Number After Splitting Digits/Solution.c index 9c4179b97fc5c..f7b0e8ed05d5c 100644 --- a/solution/2100-2199/2160.Minimum Sum of Four Digit Number After Splitting Digits/Solution.c +++ b/solution/2100-2199/2160.Minimum Sum of Four Digit Number After Splitting Digits/Solution.c @@ -10,4 +10,4 @@ int minimumSum(int num) { } qsort(nums, 4, sizeof(int), cmp); return 10 * (nums[0] + nums[1]) + nums[2] + nums[3]; -} +} \ No newline at end of file diff --git a/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/Solution.cpp b/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/Solution.cpp index 03453b1c1dbdd..dc333db84ba5f 100644 --- a/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/Solution.cpp +++ b/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/Solution.cpp @@ -1,40 +1,40 @@ -class Solution { -public: - long long minimumDifference(vector& nums) { - int m = nums.size(); - int n = m / 3; - - using ll = long long; - ll s = 0; - ll pre[m + 1]; - priority_queue q1; - for (int i = 1; i <= n * 2; ++i) { - int x = nums[i - 1]; - s += x; - q1.push(x); - if (q1.size() > n) { - s -= q1.top(); - q1.pop(); - } - pre[i] = s; - } - s = 0; - ll suf[m + 1]; - priority_queue, greater> q2; - for (int i = m; i > n; --i) { - int x = nums[i - 1]; - s += x; - q2.push(x); - if (q2.size() > n) { - s -= q2.top(); - q2.pop(); - } - suf[i] = s; - } - ll ans = 1e18; - for (int i = n; i <= n * 2; ++i) { - ans = min(ans, pre[i] - suf[i + 1]); - } - return ans; - } +class Solution { +public: + long long minimumDifference(vector& nums) { + int m = nums.size(); + int n = m / 3; + + using ll = long long; + ll s = 0; + ll pre[m + 1]; + priority_queue q1; + for (int i = 1; i <= n * 2; ++i) { + int x = nums[i - 1]; + s += x; + q1.push(x); + if (q1.size() > n) { + s -= q1.top(); + q1.pop(); + } + pre[i] = s; + } + s = 0; + ll suf[m + 1]; + priority_queue, greater> q2; + for (int i = m; i > n; --i) { + int x = nums[i - 1]; + s += x; + q2.push(x); + if (q2.size() > n) { + s -= q2.top(); + q2.pop(); + } + suf[i] = s; + } + ll ans = 1e18; + for (int i = n; i <= n * 2; ++i) { + ans = min(ans, pre[i] - suf[i + 1]); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/Solution.java b/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/Solution.java index 5cb1e539c72b6..2d9f0bb9b3f48 100644 --- a/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/Solution.java +++ b/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/Solution.java @@ -1,35 +1,35 @@ -class Solution { - public long minimumDifference(int[] nums) { - int m = nums.length; - int n = m / 3; - long s = 0; - long[] pre = new long[m + 1]; - PriorityQueue pq = new PriorityQueue<>((a, b) -> b - a); - for (int i = 1; i <= n * 2; ++i) { - int x = nums[i - 1]; - s += x; - pq.offer(x); - if (pq.size() > n) { - s -= pq.poll(); - } - pre[i] = s; - } - s = 0; - long[] suf = new long[m + 1]; - pq = new PriorityQueue<>(); - for (int i = m; i > n; --i) { - int x = nums[i - 1]; - s += x; - pq.offer(x); - if (pq.size() > n) { - s -= pq.poll(); - } - suf[i] = s; - } - long ans = 1L << 60; - for (int i = n; i <= n * 2; ++i) { - ans = Math.min(ans, pre[i] - suf[i + 1]); - } - return ans; - } +class Solution { + public long minimumDifference(int[] nums) { + int m = nums.length; + int n = m / 3; + long s = 0; + long[] pre = new long[m + 1]; + PriorityQueue pq = new PriorityQueue<>((a, b) -> b - a); + for (int i = 1; i <= n * 2; ++i) { + int x = nums[i - 1]; + s += x; + pq.offer(x); + if (pq.size() > n) { + s -= pq.poll(); + } + pre[i] = s; + } + s = 0; + long[] suf = new long[m + 1]; + pq = new PriorityQueue<>(); + for (int i = m; i > n; --i) { + int x = nums[i - 1]; + s += x; + pq.offer(x); + if (pq.size() > n) { + s -= pq.poll(); + } + suf[i] = s; + } + long ans = 1L << 60; + for (int i = n; i <= n * 2; ++i) { + ans = Math.min(ans, pre[i] - suf[i + 1]); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/Solution.py b/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/Solution.py index b4721ac331fbd..127fc49f2dd06 100644 --- a/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/Solution.py +++ b/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/Solution.py @@ -1,27 +1,27 @@ -class Solution: - def minimumDifference(self, nums: List[int]) -> int: - m = len(nums) - n = m // 3 - - s = 0 - pre = [0] * (m + 1) - q1 = [] - for i, x in enumerate(nums[: n * 2], 1): - s += x - heappush(q1, -x) - if len(q1) > n: - s -= -heappop(q1) - pre[i] = s - - s = 0 - suf = [0] * (m + 1) - q2 = [] - for i in range(m, n, -1): - x = nums[i - 1] - s += x - heappush(q2, x) - if len(q2) > n: - s -= heappop(q2) - suf[i] = s - - return min(pre[i] - suf[i + 1] for i in range(n, n * 2 + 1)) +class Solution: + def minimumDifference(self, nums: List[int]) -> int: + m = len(nums) + n = m // 3 + + s = 0 + pre = [0] * (m + 1) + q1 = [] + for i, x in enumerate(nums[: n * 2], 1): + s += x + heappush(q1, -x) + if len(q1) > n: + s -= -heappop(q1) + pre[i] = s + + s = 0 + suf = [0] * (m + 1) + q2 = [] + for i in range(m, n, -1): + x = nums[i - 1] + s += x + heappush(q2, x) + if len(q2) > n: + s -= heappop(q2) + suf[i] = s + + return min(pre[i] - suf[i + 1] for i in range(n, n * 2 + 1)) diff --git a/solution/2100-2199/2172.Maximum AND Sum of Array/Solution.cpp b/solution/2100-2199/2172.Maximum AND Sum of Array/Solution.cpp index 248b690fbcd42..fbaf2aada9784 100644 --- a/solution/2100-2199/2172.Maximum AND Sum of Array/Solution.cpp +++ b/solution/2100-2199/2172.Maximum AND Sum of Array/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - int maximumANDSum(vector& nums, int numSlots) { - int n = nums.size(); - int m = numSlots << 1; - int f[1 << m]; - memset(f, 0, sizeof(f)); - for (int i = 0; i < 1 << m; ++i) { - int cnt = __builtin_popcount(i); - if (cnt > n) { - continue; - } - for (int j = 0; j < m; ++j) { - if (i >> j & 1) { - f[i] = max(f[i], f[i ^ (1 << j)] + (nums[cnt - 1] & (j / 2 + 1))); - } - } - } - return *max_element(f, f + (1 << m)); - } +class Solution { +public: + int maximumANDSum(vector& nums, int numSlots) { + int n = nums.size(); + int m = numSlots << 1; + int f[1 << m]; + memset(f, 0, sizeof(f)); + for (int i = 0; i < 1 << m; ++i) { + int cnt = __builtin_popcount(i); + if (cnt > n) { + continue; + } + for (int j = 0; j < m; ++j) { + if (i >> j & 1) { + f[i] = max(f[i], f[i ^ (1 << j)] + (nums[cnt - 1] & (j / 2 + 1))); + } + } + } + return *max_element(f, f + (1 << m)); + } }; \ No newline at end of file diff --git a/solution/2100-2199/2172.Maximum AND Sum of Array/Solution.java b/solution/2100-2199/2172.Maximum AND Sum of Array/Solution.java index 3d0d3653e5cbf..6c7ea8b59b6ed 100644 --- a/solution/2100-2199/2172.Maximum AND Sum of Array/Solution.java +++ b/solution/2100-2199/2172.Maximum AND Sum of Array/Solution.java @@ -1,21 +1,21 @@ -class Solution { - public int maximumANDSum(int[] nums, int numSlots) { - int n = nums.length; - int m = numSlots << 1; - int[] f = new int[1 << m]; - int ans = 0; - for (int i = 0; i < 1 << m; ++i) { - int cnt = Integer.bitCount(i); - if (cnt > n) { - continue; - } - for (int j = 0; j < m; ++j) { - if ((i >> j & 1) == 1) { - f[i] = Math.max(f[i], f[i ^ (1 << j)] + (nums[cnt - 1] & (j / 2 + 1))); - } - } - ans = Math.max(ans, f[i]); - } - return ans; - } +class Solution { + public int maximumANDSum(int[] nums, int numSlots) { + int n = nums.length; + int m = numSlots << 1; + int[] f = new int[1 << m]; + int ans = 0; + for (int i = 0; i < 1 << m; ++i) { + int cnt = Integer.bitCount(i); + if (cnt > n) { + continue; + } + for (int j = 0; j < m; ++j) { + if ((i >> j & 1) == 1) { + f[i] = Math.max(f[i], f[i ^ (1 << j)] + (nums[cnt - 1] & (j / 2 + 1))); + } + } + ans = Math.max(ans, f[i]); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2100-2199/2172.Maximum AND Sum of Array/Solution.py b/solution/2100-2199/2172.Maximum AND Sum of Array/Solution.py index 0a0dd54256c80..2317ee29c69f4 100644 --- a/solution/2100-2199/2172.Maximum AND Sum of Array/Solution.py +++ b/solution/2100-2199/2172.Maximum AND Sum of Array/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def maximumANDSum(self, nums: List[int], numSlots: int) -> int: - n = len(nums) - m = numSlots << 1 - f = [0] * (1 << m) - for i in range(1 << m): - cnt = i.bit_count() - if cnt > n: - continue - for j in range(m): - if i >> j & 1: - f[i] = max(f[i], f[i ^ (1 << j)] + (nums[cnt - 1] & (j // 2 + 1))) - return max(f) +class Solution: + def maximumANDSum(self, nums: List[int], numSlots: int) -> int: + n = len(nums) + m = numSlots << 1 + f = [0] * (1 << m) + for i in range(1 << m): + cnt = i.bit_count() + if cnt > n: + continue + for j in range(m): + if i >> j & 1: + f[i] = max(f[i], f[i ^ (1 << j)] + (nums[cnt - 1] & (j // 2 + 1))) + return max(f) diff --git a/solution/2100-2199/2176.Count Equal and Divisible Pairs in an Array/Solution.c b/solution/2100-2199/2176.Count Equal and Divisible Pairs in an Array/Solution.c index 0f6cc120f0304..abc891707a297 100644 --- a/solution/2100-2199/2176.Count Equal and Divisible Pairs in an Array/Solution.c +++ b/solution/2100-2199/2176.Count Equal and Divisible Pairs in an Array/Solution.c @@ -8,4 +8,4 @@ int countPairs(int* nums, int numsSize, int k) { } } return ans; -} +} \ No newline at end of file diff --git a/solution/2100-2199/2177.Find Three Consecutive Integers That Sum to a Given Number/Solution.cpp b/solution/2100-2199/2177.Find Three Consecutive Integers That Sum to a Given Number/Solution.cpp index 9bb61fded789c..29b751649da51 100644 --- a/solution/2100-2199/2177.Find Three Consecutive Integers That Sum to a Given Number/Solution.cpp +++ b/solution/2100-2199/2177.Find Three Consecutive Integers That Sum to a Given Number/Solution.cpp @@ -1,10 +1,10 @@ -class Solution { -public: - vector sumOfThree(long long num) { - if (num % 3) { - return {}; - } - long long x = num / 3; - return {x - 1, x, x + 1}; - } +class Solution { +public: + vector sumOfThree(long long num) { + if (num % 3) { + return {}; + } + long long x = num / 3; + return {x - 1, x, x + 1}; + } }; \ No newline at end of file diff --git a/solution/2100-2199/2177.Find Three Consecutive Integers That Sum to a Given Number/Solution.py b/solution/2100-2199/2177.Find Three Consecutive Integers That Sum to a Given Number/Solution.py index f42098519a852..d37f1de97c10e 100644 --- a/solution/2100-2199/2177.Find Three Consecutive Integers That Sum to a Given Number/Solution.py +++ b/solution/2100-2199/2177.Find Three Consecutive Integers That Sum to a Given Number/Solution.py @@ -1,4 +1,4 @@ -class Solution: - def sumOfThree(self, num: int) -> List[int]: - x, mod = divmod(num, 3) - return [] if mod else [x - 1, x, x + 1] +class Solution: + def sumOfThree(self, num: int) -> List[int]: + x, mod = divmod(num, 3) + return [] if mod else [x - 1, x, x + 1] diff --git a/solution/2100-2199/2178.Maximum Split of Positive Even Integers/Solution.cs b/solution/2100-2199/2178.Maximum Split of Positive Even Integers/Solution.cs index c0f4b6ea18a1a..7738442ea7f0c 100644 --- a/solution/2100-2199/2178.Maximum Split of Positive Even Integers/Solution.cs +++ b/solution/2100-2199/2178.Maximum Split of Positive Even Integers/Solution.cs @@ -1,14 +1,14 @@ -public class Solution { - public IList MaximumEvenSplit(long finalSum) { - IList ans = new List(); - if (finalSum % 2 == 1) { - return ans; - } - for (long i = 2; i <= finalSum; i += 2) { - ans.Add(i); - finalSum -= i; - } - ans[ans.Count - 1] += finalSum; - return ans; - } -} \ No newline at end of file +public class Solution { + public IList MaximumEvenSplit(long finalSum) { + IList ans = new List(); + if (finalSum % 2 == 1) { + return ans; + } + for (long i = 2; i <= finalSum; i += 2) { + ans.Add(i); + finalSum -= i; + } + ans[ans.Count - 1] += finalSum; + return ans; + } +} diff --git a/solution/2100-2199/2179.Count Good Triplets in an Array/Solution2.cpp b/solution/2100-2199/2179.Count Good Triplets in an Array/Solution2.cpp new file mode 100644 index 0000000000000..f79e91090c769 --- /dev/null +++ b/solution/2100-2199/2179.Count Good Triplets in an Array/Solution2.cpp @@ -0,0 +1,71 @@ +class Node { +public: + int l; + int r; + int v; +}; + +class SegmentTree { +public: + vector tr; + + SegmentTree(int n) { + tr.resize(4 * n); + for (int i = 0; i < tr.size(); ++i) tr[i] = new Node(); + build(1, 1, n); + } + + void build(int u, int l, int r) { + tr[u]->l = l; + tr[u]->r = r; + if (l == r) return; + int mid = (l + r) >> 1; + build(u << 1, l, mid); + build(u << 1 | 1, mid + 1, r); + } + + void modify(int u, int x, int v) { + if (tr[u]->l == x && tr[u]->r == x) { + tr[u]->v += v; + return; + } + int mid = (tr[u]->l + tr[u]->r) >> 1; + if (x <= mid) + modify(u << 1, x, v); + else + modify(u << 1 | 1, x, v); + pushup(u); + } + + void pushup(int u) { + tr[u]->v = tr[u << 1]->v + tr[u << 1 | 1]->v; + } + + int query(int u, int l, int r) { + if (tr[u]->l >= l && tr[u]->r <= r) return tr[u]->v; + int mid = (tr[u]->l + tr[u]->r) >> 1; + int v = 0; + if (l <= mid) v += query(u << 1, l, r); + if (r > mid) v += query(u << 1 | 1, l, r); + return v; + } +}; + +class Solution { +public: + long long goodTriplets(vector& nums1, vector& nums2) { + int n = nums1.size(); + vector pos(n); + for (int i = 0; i < n; ++i) pos[nums2[i]] = i + 1; + SegmentTree* tree = new SegmentTree(n); + long long ans = 0; + for (int& num : nums1) { + int p = pos[num]; + int left = tree->query(1, 1, p); + int right = n - p - (tree->query(1, 1, n) - tree->query(1, 1, p)); + ans += 1ll * left * right; + tree->modify(1, p, 1); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2100-2199/2179.Count Good Triplets in an Array/Solution2.java b/solution/2100-2199/2179.Count Good Triplets in an Array/Solution2.java new file mode 100644 index 0000000000000..13aee4a049a7e --- /dev/null +++ b/solution/2100-2199/2179.Count Good Triplets in an Array/Solution2.java @@ -0,0 +1,81 @@ +class Solution { + public long goodTriplets(int[] nums1, int[] nums2) { + int n = nums1.length; + int[] pos = new int[n]; + SegmentTree tree = new SegmentTree(n); + for (int i = 0; i < n; ++i) { + pos[nums2[i]] = i + 1; + } + long ans = 0; + for (int num : nums1) { + int p = pos[num]; + long left = tree.query(1, 1, p); + long right = n - p - (tree.query(1, 1, n) - tree.query(1, 1, p)); + ans += left * right; + tree.modify(1, p, 1); + } + return ans; + } +} + +class Node { + int l; + int r; + int v; +} + +class SegmentTree { + private Node[] tr; + + public SegmentTree(int n) { + tr = new Node[4 * n]; + for (int i = 0; i < tr.length; ++i) { + tr[i] = new Node(); + } + build(1, 1, n); + } + + public void build(int u, int l, int r) { + tr[u].l = l; + tr[u].r = r; + if (l == r) { + return; + } + int mid = (l + r) >> 1; + build(u << 1, l, mid); + build(u << 1 | 1, mid + 1, r); + } + + public void modify(int u, int x, int v) { + if (tr[u].l == x && tr[u].r == x) { + tr[u].v += v; + return; + } + int mid = (tr[u].l + tr[u].r) >> 1; + if (x <= mid) { + modify(u << 1, x, v); + } else { + modify(u << 1 | 1, x, v); + } + pushup(u); + } + + public void pushup(int u) { + tr[u].v = tr[u << 1].v + tr[u << 1 | 1].v; + } + + public int query(int u, int l, int r) { + if (tr[u].l >= l && tr[u].r <= r) { + return tr[u].v; + } + int mid = (tr[u].l + tr[u].r) >> 1; + int v = 0; + if (l <= mid) { + v += query(u << 1, l, r); + } + if (r > mid) { + v += query(u << 1 | 1, l, r); + } + return v; + } +} \ No newline at end of file diff --git a/solution/2100-2199/2179.Count Good Triplets in an Array/Solution2.py b/solution/2100-2199/2179.Count Good Triplets in an Array/Solution2.py new file mode 100644 index 0000000000000..016a6d8afaaa2 --- /dev/null +++ b/solution/2100-2199/2179.Count Good Triplets in an Array/Solution2.py @@ -0,0 +1,60 @@ +class Node: + def __init__(self): + self.l = 0 + self.r = 0 + self.v = 0 + + +class SegmentTree: + def __init__(self, n): + self.tr = [Node() for _ in range(4 * n)] + self.build(1, 1, n) + + def build(self, u, l, r): + self.tr[u].l = l + self.tr[u].r = r + if l == r: + return + mid = (l + r) >> 1 + self.build(u << 1, l, mid) + self.build(u << 1 | 1, mid + 1, r) + + def modify(self, u, x, v): + if self.tr[u].l == x and self.tr[u].r == x: + self.tr[u].v += v + return + mid = (self.tr[u].l + self.tr[u].r) >> 1 + if x <= mid: + self.modify(u << 1, x, v) + else: + self.modify(u << 1 | 1, x, v) + self.pushup(u) + + def pushup(self, u): + self.tr[u].v = self.tr[u << 1].v + self.tr[u << 1 | 1].v + + def query(self, u, l, r): + if self.tr[u].l >= l and self.tr[u].r <= r: + return self.tr[u].v + mid = (self.tr[u].l + self.tr[u].r) >> 1 + v = 0 + if l <= mid: + v += self.query(u << 1, l, r) + if r > mid: + v += self.query(u << 1 | 1, l, r) + return v + + +class Solution: + def goodTriplets(self, nums1: List[int], nums2: List[int]) -> int: + pos = {v: i for i, v in enumerate(nums2, 1)} + ans = 0 + n = len(nums1) + tree = SegmentTree(n) + for num in nums1: + p = pos[num] + left = tree.query(1, 1, p) + right = n - p - (tree.query(1, 1, n) - tree.query(1, 1, p)) + ans += left * right + tree.modify(1, p, 1) + return ans diff --git a/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution.cpp b/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution.cpp index 11d900c5123c8..7df0588b37075 100644 --- a/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution.cpp +++ b/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution.cpp @@ -1,12 +1,14 @@ class Solution { public: int countEven(int num) { - int ans = num / 10 * 5 - 1; - int s = 0; - for (int x = num / 10; x > 0; x /= 10) { - s += x % 10; + int ans = 0; + for (int i = 1; i <= num; ++i) { + int s = 0; + for (int x = i; x; x /= 10) { + s += x % 10; + } + ans += s % 2 == 0; } - ans += (num % 10 + 2 - (s & 1)) >> 1; return ans; } }; \ No newline at end of file diff --git a/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution.go b/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution.go index 8bdb0bf218ca8..08fa483f04972 100644 --- a/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution.go +++ b/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution.go @@ -1,9 +1,12 @@ func countEven(num int) (ans int) { - ans = num/10*5 - 1 - s := 0 - for x := num / 10; x > 0; x /= 10 { - s += x % 10 + for i := 1; i <= num; i++ { + s := 0 + for x := i; x > 0; x /= 10 { + s += x % 10 + } + if s%2 == 0 { + ans++ + } } - ans += (num%10 + 2 - (s & 1)) >> 1 return } \ No newline at end of file diff --git a/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution.py b/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution.py index 4c8315d045da6..90777e6a149de 100644 --- a/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution.py +++ b/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution.py @@ -1,9 +1,10 @@ class Solution: def countEven(self, num: int) -> int: - ans = num // 10 * 5 - 1 - x, s = num // 10, 0 - while x: - s += x % 10 - x //= 10 - ans += (num % 10 + 2 - (s & 1)) >> 1 + ans = 0 + for x in range(1, num + 1): + s = 0 + while x: + s += x % 10 + x //= 10 + ans += s % 2 == 0 return ans diff --git a/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution.ts b/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution.ts index ffd79e561ac28..2246dad660d81 100644 --- a/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution.ts +++ b/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution.ts @@ -1,9 +1,13 @@ function countEven(num: number): number { - let ans = Math.floor(num / 10) * 5 - 1; - let s = 0; - for (let x = Math.floor(num / 10); x; x = Math.floor(x / 10)) { - s += x % 10; + let ans = 0; + for (let i = 1; i <= num; ++i) { + let s = 0; + for (let x = i; x; x = Math.floor(x / 10)) { + s += x % 10; + } + if (s % 2 == 0) { + ++ans; + } } - ans += ((num % 10) + 2 - (s & 1)) >> 1; return ans; } diff --git a/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution2.cpp b/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution2.cpp new file mode 100644 index 0000000000000..11d900c5123c8 --- /dev/null +++ b/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution2.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int countEven(int num) { + int ans = num / 10 * 5 - 1; + int s = 0; + for (int x = num / 10; x > 0; x /= 10) { + s += x % 10; + } + ans += (num % 10 + 2 - (s & 1)) >> 1; + return ans; + } +}; \ No newline at end of file diff --git a/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution2.go b/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution2.go new file mode 100644 index 0000000000000..8bdb0bf218ca8 --- /dev/null +++ b/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution2.go @@ -0,0 +1,9 @@ +func countEven(num int) (ans int) { + ans = num/10*5 - 1 + s := 0 + for x := num / 10; x > 0; x /= 10 { + s += x % 10 + } + ans += (num%10 + 2 - (s & 1)) >> 1 + return +} \ No newline at end of file diff --git a/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution2.java b/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution2.java new file mode 100644 index 0000000000000..497d329ead489 --- /dev/null +++ b/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution2.java @@ -0,0 +1,11 @@ +class Solution { + public int countEven(int num) { + int ans = num / 10 * 5 - 1; + int s = 0; + for (int x = num / 10; x > 0; x /= 10) { + s += x % 10; + } + ans += (num % 10 + 2 - (s & 1)) >> 1; + return ans; + } +} \ No newline at end of file diff --git a/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution2.py b/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution2.py new file mode 100644 index 0000000000000..4c8315d045da6 --- /dev/null +++ b/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def countEven(self, num: int) -> int: + ans = num // 10 * 5 - 1 + x, s = num // 10, 0 + while x: + s += x % 10 + x //= 10 + ans += (num % 10 + 2 - (s & 1)) >> 1 + return ans diff --git a/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution2.ts b/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution2.ts new file mode 100644 index 0000000000000..ffd79e561ac28 --- /dev/null +++ b/solution/2100-2199/2180.Count Integers With Even Digit Sum/Solution2.ts @@ -0,0 +1,9 @@ +function countEven(num: number): number { + let ans = Math.floor(num / 10) * 5 - 1; + let s = 0; + for (let x = Math.floor(num / 10); x; x = Math.floor(x / 10)) { + s += x % 10; + } + ans += ((num % 10) + 2 - (s & 1)) >> 1; + return ans; +} diff --git a/solution/2100-2199/2181.Merge Nodes in Between Zeros/Solution.c b/solution/2100-2199/2181.Merge Nodes in Between Zeros/Solution.c index abb11d7b716a5..4a9888c3abd70 100644 --- a/solution/2100-2199/2181.Merge Nodes in Between Zeros/Solution.c +++ b/solution/2100-2199/2181.Merge Nodes in Between Zeros/Solution.c @@ -22,4 +22,4 @@ struct ListNode* mergeNodes(struct ListNode* head) { head = head->next; } return dummy.next; -} +} \ No newline at end of file diff --git a/solution/2100-2199/2182.Construct String With Repeat Limit/Solution.cpp b/solution/2100-2199/2182.Construct String With Repeat Limit/Solution.cpp index 302fa9d22a6dd..50bdda45ccc91 100644 --- a/solution/2100-2199/2182.Construct String With Repeat Limit/Solution.cpp +++ b/solution/2100-2199/2182.Construct String With Repeat Limit/Solution.cpp @@ -1,31 +1,31 @@ -class Solution { -public: - string repeatLimitedString(string s, int repeatLimit) { - int cnt[26]{}; - for (char& c : s) { - ++cnt[c - 'a']; - } - string ans; - for (int i = 25, j = 24; ~i; --i) { - j = min(j, i - 1); - while (1) { - for (int k = min(cnt[i], repeatLimit); k; --k) { - ans += 'a' + i; - --cnt[i]; - } - if (cnt[i] == 0) { - break; - } - while (j >= 0 && cnt[j] == 0) { - --j; - } - if (j < 0) { - break; - } - ans += 'a' + j; - --cnt[j]; - } - } - return ans; - } +class Solution { +public: + string repeatLimitedString(string s, int repeatLimit) { + int cnt[26]{}; + for (char& c : s) { + ++cnt[c - 'a']; + } + string ans; + for (int i = 25, j = 24; ~i; --i) { + j = min(j, i - 1); + while (1) { + for (int k = min(cnt[i], repeatLimit); k; --k) { + ans += 'a' + i; + --cnt[i]; + } + if (cnt[i] == 0) { + break; + } + while (j >= 0 && cnt[j] == 0) { + --j; + } + if (j < 0) { + break; + } + ans += 'a' + j; + --cnt[j]; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2100-2199/2182.Construct String With Repeat Limit/Solution.java b/solution/2100-2199/2182.Construct String With Repeat Limit/Solution.java index cfeb5d51f7afd..b38fe4ae78db2 100644 --- a/solution/2100-2199/2182.Construct String With Repeat Limit/Solution.java +++ b/solution/2100-2199/2182.Construct String With Repeat Limit/Solution.java @@ -1,30 +1,30 @@ -class Solution { - public String repeatLimitedString(String s, int repeatLimit) { - int[] cnt = new int[26]; - for (int i = 0; i < s.length(); ++i) { - ++cnt[s.charAt(i) - 'a']; - } - StringBuilder ans = new StringBuilder(); - for (int i = 25, j = 24; i >= 0; --i) { - j = Math.min(j, i - 1); - while (true) { - for (int k = Math.min(cnt[i], repeatLimit); k > 0; --k) { - ans.append((char) ('a' + i)); - --cnt[i]; - } - if (cnt[i] == 0) { - break; - } - while (j >= 0 && cnt[j] == 0) { - --j; - } - if (j < 0) { - break; - } - ans.append((char) ('a' + j)); - --cnt[j]; - } - } - return ans.toString(); - } +class Solution { + public String repeatLimitedString(String s, int repeatLimit) { + int[] cnt = new int[26]; + for (int i = 0; i < s.length(); ++i) { + ++cnt[s.charAt(i) - 'a']; + } + StringBuilder ans = new StringBuilder(); + for (int i = 25, j = 24; i >= 0; --i) { + j = Math.min(j, i - 1); + while (true) { + for (int k = Math.min(cnt[i], repeatLimit); k > 0; --k) { + ans.append((char) ('a' + i)); + --cnt[i]; + } + if (cnt[i] == 0) { + break; + } + while (j >= 0 && cnt[j] == 0) { + --j; + } + if (j < 0) { + break; + } + ans.append((char) ('a' + j)); + --cnt[j]; + } + } + return ans.toString(); + } } \ No newline at end of file diff --git a/solution/2100-2199/2182.Construct String With Repeat Limit/Solution.py b/solution/2100-2199/2182.Construct String With Repeat Limit/Solution.py index d95c866de91f2..949861d912859 100644 --- a/solution/2100-2199/2182.Construct String With Repeat Limit/Solution.py +++ b/solution/2100-2199/2182.Construct String With Repeat Limit/Solution.py @@ -1,22 +1,22 @@ -class Solution: - def repeatLimitedString(self, s: str, repeatLimit: int) -> str: - cnt = [0] * 26 - for c in s: - cnt[ord(c) - ord("a")] += 1 - ans = [] - j = 24 - for i in range(25, -1, -1): - j = min(i - 1, j) - while 1: - x = min(repeatLimit, cnt[i]) - cnt[i] -= x - ans.append(ascii_lowercase[i] * x) - if cnt[i] == 0: - break - while j >= 0 and cnt[j] == 0: - j -= 1 - if j < 0: - break - cnt[j] -= 1 - ans.append(ascii_lowercase[j]) - return "".join(ans) +class Solution: + def repeatLimitedString(self, s: str, repeatLimit: int) -> str: + cnt = [0] * 26 + for c in s: + cnt[ord(c) - ord("a")] += 1 + ans = [] + j = 24 + for i in range(25, -1, -1): + j = min(i - 1, j) + while 1: + x = min(repeatLimit, cnt[i]) + cnt[i] -= x + ans.append(ascii_lowercase[i] * x) + if cnt[i] == 0: + break + while j >= 0 and cnt[j] == 0: + j -= 1 + if j < 0: + break + cnt[j] -= 1 + ans.append(ascii_lowercase[j]) + return "".join(ans) diff --git a/solution/2100-2199/2185.Counting Words With a Given Prefix/Solution.c b/solution/2100-2199/2185.Counting Words With a Given Prefix/Solution.c index c2c06caa73f65..14e639ff5af00 100644 --- a/solution/2100-2199/2185.Counting Words With a Given Prefix/Solution.c +++ b/solution/2100-2199/2185.Counting Words With a Given Prefix/Solution.c @@ -7,4 +7,4 @@ int prefixCount(char** words, int wordsSize, char* pref) { } } return ans; -} +} \ No newline at end of file diff --git a/solution/2100-2199/2185.Counting Words With a Given Prefix/Solution2.cpp b/solution/2100-2199/2185.Counting Words With a Given Prefix/Solution2.cpp new file mode 100644 index 0000000000000..e4c188fa2498f --- /dev/null +++ b/solution/2100-2199/2185.Counting Words With a Given Prefix/Solution2.cpp @@ -0,0 +1,45 @@ +class Trie { +public: + Trie() + : children(26) + , cnt(0) {} + + void insert(string w) { + Trie* node = this; + for (auto& c : w) { + int i = c - 'a'; + if (!node->children[i]) { + node->children[i] = new Trie(); + } + node = node->children[i]; + ++node->cnt; + } + } + + int search(string pref) { + Trie* node = this; + for (auto& c : pref) { + int i = c - 'a'; + if (!node->children[i]) { + return 0; + } + node = node->children[i]; + } + return node->cnt; + } + +private: + vector children; + int cnt; +}; + +class Solution { +public: + int prefixCount(vector& words, string pref) { + Trie* tree = new Trie(); + for (auto& w : words) { + tree->insert(w); + } + return tree->search(pref); + } +}; \ No newline at end of file diff --git a/solution/2100-2199/2185.Counting Words With a Given Prefix/Solution2.go b/solution/2100-2199/2185.Counting Words With a Given Prefix/Solution2.go new file mode 100644 index 0000000000000..07bff5bb97232 --- /dev/null +++ b/solution/2100-2199/2185.Counting Words With a Given Prefix/Solution2.go @@ -0,0 +1,40 @@ +type Trie struct { + children [26]*Trie + cnt int +} + +func newTrie() *Trie { + return &Trie{} +} + +func (this *Trie) insert(w string) { + node := this + for _, c := range w { + c -= 'a' + if node.children[c] == nil { + node.children[c] = newTrie() + } + node = node.children[c] + node.cnt++ + } +} + +func (this *Trie) search(pref string) int { + node := this + for _, c := range pref { + c -= 'a' + if node.children[c] == nil { + return 0 + } + node = node.children[c] + } + return node.cnt +} + +func prefixCount(words []string, pref string) int { + tree := newTrie() + for _, w := range words { + tree.insert(w) + } + return tree.search(pref) +} \ No newline at end of file diff --git a/solution/2100-2199/2185.Counting Words With a Given Prefix/Solution2.java b/solution/2100-2199/2185.Counting Words With a Given Prefix/Solution2.java new file mode 100644 index 0000000000000..a31199ba0cada --- /dev/null +++ b/solution/2100-2199/2185.Counting Words With a Given Prefix/Solution2.java @@ -0,0 +1,38 @@ +class Trie { + private Trie[] children = new Trie[26]; + private int cnt; + + public void insert(String w) { + Trie node = this; + for (int i = 0; i < w.length(); ++i) { + int j = w.charAt(i) - 'a'; + if (node.children[j] == null) { + node.children[j] = new Trie(); + } + node = node.children[j]; + ++node.cnt; + } + } + + public int search(String pref) { + Trie node = this; + for (int i = 0; i < pref.length(); ++i) { + int j = pref.charAt(i) - 'a'; + if (node.children[j] == null) { + return 0; + } + node = node.children[j]; + } + return node.cnt; + } +} + +class Solution { + public int prefixCount(String[] words, String pref) { + Trie tree = new Trie(); + for (String w : words) { + tree.insert(w); + } + return tree.search(pref); + } +} \ No newline at end of file diff --git a/solution/2100-2199/2185.Counting Words With a Given Prefix/Solution2.py b/solution/2100-2199/2185.Counting Words With a Given Prefix/Solution2.py new file mode 100644 index 0000000000000..e3d3c211b6bbc --- /dev/null +++ b/solution/2100-2199/2185.Counting Words With a Given Prefix/Solution2.py @@ -0,0 +1,30 @@ +class Trie: + def __init__(self): + self.children = [None] * 26 + self.cnt = 0 + + def insert(self, w): + node = self + for c in w: + i = ord(c) - ord('a') + if node.children[i] is None: + node.children[i] = Trie() + node = node.children[i] + node.cnt += 1 + + def search(self, pref): + node = self + for c in pref: + i = ord(c) - ord('a') + if node.children[i] is None: + return 0 + node = node.children[i] + return node.cnt + + +class Solution: + def prefixCount(self, words: List[str], pref: str) -> int: + tree = Trie() + for w in words: + tree.insert(w) + return tree.search(pref) diff --git a/solution/2100-2199/2188.Minimum Time to Finish the Race/Solution.cpp b/solution/2100-2199/2188.Minimum Time to Finish the Race/Solution.cpp index d801f5d8431b9..2235c694d994a 100644 --- a/solution/2100-2199/2188.Minimum Time to Finish the Race/Solution.cpp +++ b/solution/2100-2199/2188.Minimum Time to Finish the Race/Solution.cpp @@ -1,27 +1,27 @@ -class Solution { -public: - int minimumFinishTime(vector>& tires, int changeTime, int numLaps) { - int cost[18]; - memset(cost, 0x3f, sizeof(cost)); - for (auto& e : tires) { - int f = e[0], r = e[1]; - int s = 0; - long long t = f; - for (int i = 1; t <= changeTime + f; ++i) { - s += t; - cost[i] = min(cost[i], s); - t *= r; - } - } - int f[numLaps + 1]; - memset(f, 0x3f, sizeof(f)); - f[0] = -changeTime; - for (int i = 1; i <= numLaps; ++i) { - for (int j = 1; j < min(18, i + 1); ++j) { - f[i] = min(f[i], f[i - j] + cost[j]); - } - f[i] += changeTime; - } - return f[numLaps]; - } +class Solution { +public: + int minimumFinishTime(vector>& tires, int changeTime, int numLaps) { + int cost[18]; + memset(cost, 0x3f, sizeof(cost)); + for (auto& e : tires) { + int f = e[0], r = e[1]; + int s = 0; + long long t = f; + for (int i = 1; t <= changeTime + f; ++i) { + s += t; + cost[i] = min(cost[i], s); + t *= r; + } + } + int f[numLaps + 1]; + memset(f, 0x3f, sizeof(f)); + f[0] = -changeTime; + for (int i = 1; i <= numLaps; ++i) { + for (int j = 1; j < min(18, i + 1); ++j) { + f[i] = min(f[i], f[i - j] + cost[j]); + } + f[i] += changeTime; + } + return f[numLaps]; + } }; \ No newline at end of file diff --git a/solution/2100-2199/2188.Minimum Time to Finish the Race/Solution.java b/solution/2100-2199/2188.Minimum Time to Finish the Race/Solution.java index 7be109be6b4e3..f12d4341e62db 100644 --- a/solution/2100-2199/2188.Minimum Time to Finish the Race/Solution.java +++ b/solution/2100-2199/2188.Minimum Time to Finish the Race/Solution.java @@ -1,26 +1,26 @@ -class Solution { - public int minimumFinishTime(int[][] tires, int changeTime, int numLaps) { - final int inf = 1 << 30; - int[] cost = new int[18]; - Arrays.fill(cost, inf); - for (int[] e : tires) { - int f = e[0], r = e[1]; - int s = 0, t = f; - for (int i = 1; t <= changeTime + f; ++i) { - s += t; - cost[i] = Math.min(cost[i], s); - t *= r; - } - } - int[] f = new int[numLaps + 1]; - Arrays.fill(f, inf); - f[0] = -changeTime; - for (int i = 1; i <= numLaps; ++i) { - for (int j = 1; j < Math.min(18, i + 1); ++j) { - f[i] = Math.min(f[i], f[i - j] + cost[j]); - } - f[i] += changeTime; - } - return f[numLaps]; - } +class Solution { + public int minimumFinishTime(int[][] tires, int changeTime, int numLaps) { + final int inf = 1 << 30; + int[] cost = new int[18]; + Arrays.fill(cost, inf); + for (int[] e : tires) { + int f = e[0], r = e[1]; + int s = 0, t = f; + for (int i = 1; t <= changeTime + f; ++i) { + s += t; + cost[i] = Math.min(cost[i], s); + t *= r; + } + } + int[] f = new int[numLaps + 1]; + Arrays.fill(f, inf); + f[0] = -changeTime; + for (int i = 1; i <= numLaps; ++i) { + for (int j = 1; j < Math.min(18, i + 1); ++j) { + f[i] = Math.min(f[i], f[i - j] + cost[j]); + } + f[i] += changeTime; + } + return f[numLaps]; + } } \ No newline at end of file diff --git a/solution/2100-2199/2188.Minimum Time to Finish the Race/Solution.py b/solution/2100-2199/2188.Minimum Time to Finish the Race/Solution.py index b76a70150ea4b..495f8524165da 100644 --- a/solution/2100-2199/2188.Minimum Time to Finish the Race/Solution.py +++ b/solution/2100-2199/2188.Minimum Time to Finish the Race/Solution.py @@ -1,19 +1,19 @@ -class Solution: - def minimumFinishTime( - self, tires: List[List[int]], changeTime: int, numLaps: int - ) -> int: - cost = [inf] * 18 - for f, r in tires: - i, s, t = 1, 0, f - while t <= changeTime + f: - s += t - cost[i] = min(cost[i], s) - t *= r - i += 1 - f = [inf] * (numLaps + 1) - f[0] = -changeTime - for i in range(1, numLaps + 1): - for j in range(1, min(18, i + 1)): - f[i] = min(f[i], f[i - j] + cost[j]) - f[i] += changeTime - return f[numLaps] +class Solution: + def minimumFinishTime( + self, tires: List[List[int]], changeTime: int, numLaps: int + ) -> int: + cost = [inf] * 18 + for f, r in tires: + i, s, t = 1, 0, f + while t <= changeTime + f: + s += t + cost[i] = min(cost[i], s) + t *= r + i += 1 + f = [inf] * (numLaps + 1) + f[0] = -changeTime + for i in range(1, numLaps + 1): + for j in range(1, min(18, i + 1)): + f[i] = min(f[i], f[i - j] + cost[j]) + f[i] += changeTime + return f[numLaps] diff --git a/solution/2100-2199/2190.Most Frequent Number Following Key In an Array/Solution.php b/solution/2100-2199/2190.Most Frequent Number Following Key In an Array/Solution.php index 6b3ebfe858ffb..7cf8538ad0d3d 100644 --- a/solution/2100-2199/2190.Most Frequent Number Following Key In an Array/Solution.php +++ b/solution/2100-2199/2190.Most Frequent Number Following Key In an Array/Solution.php @@ -18,4 +18,4 @@ function mostFrequent($nums, $key) { } return $maxNum; } -} \ No newline at end of file +} diff --git a/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/Solution.cpp b/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/Solution.cpp index 1b6e4faae9d17..8f65cb1fa19cb 100644 --- a/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/Solution.cpp +++ b/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/Solution.cpp @@ -1,32 +1,32 @@ -class Solution { -public: - vector> getAncestors(int n, vector>& edges) { - vector g[n]; - for (auto& e : edges) { - g[e[0]].push_back(e[1]); - } - vector> ans(n); - auto bfs = [&](int s) { - queue q; - q.push(s); - bool vis[n]; - memset(vis, 0, sizeof(vis)); - vis[s] = true; - while (q.size()) { - int i = q.front(); - q.pop(); - for (int j : g[i]) { - if (!vis[j]) { - vis[j] = true; - ans[j].push_back(s); - q.push(j); - } - } - } - }; - for (int i = 0; i < n; ++i) { - bfs(i); - } - return ans; - } +class Solution { +public: + vector> getAncestors(int n, vector>& edges) { + vector g[n]; + for (auto& e : edges) { + g[e[0]].push_back(e[1]); + } + vector> ans(n); + auto bfs = [&](int s) { + queue q; + q.push(s); + bool vis[n]; + memset(vis, 0, sizeof(vis)); + vis[s] = true; + while (q.size()) { + int i = q.front(); + q.pop(); + for (int j : g[i]) { + if (!vis[j]) { + vis[j] = true; + ans[j].push_back(s); + q.push(j); + } + } + } + }; + for (int i = 0; i < n; ++i) { + bfs(i); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/Solution.java b/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/Solution.java index c380d79d2d2a2..67057e9c76d05 100644 --- a/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/Solution.java +++ b/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/Solution.java @@ -1,39 +1,39 @@ -class Solution { - private int n; - private List[] g; - private List> ans; - - public List> getAncestors(int n, int[][] edges) { - g = new List[n]; - this.n = n; - Arrays.setAll(g, i -> new ArrayList<>()); - for (var e : edges) { - g[e[0]].add(e[1]); - } - ans = new ArrayList<>(); - for (int i = 0; i < n; ++i) { - ans.add(new ArrayList<>()); - } - for (int i = 0; i < n; ++i) { - bfs(i); - } - return ans; - } - - private void bfs(int s) { - Deque q = new ArrayDeque<>(); - q.offer(s); - boolean[] vis = new boolean[n]; - vis[s] = true; - while (!q.isEmpty()) { - int i = q.poll(); - for (int j : g[i]) { - if (!vis[j]) { - vis[j] = true; - q.offer(j); - ans.get(j).add(s); - } - } - } - } +class Solution { + private int n; + private List[] g; + private List> ans; + + public List> getAncestors(int n, int[][] edges) { + g = new List[n]; + this.n = n; + Arrays.setAll(g, i -> new ArrayList<>()); + for (var e : edges) { + g[e[0]].add(e[1]); + } + ans = new ArrayList<>(); + for (int i = 0; i < n; ++i) { + ans.add(new ArrayList<>()); + } + for (int i = 0; i < n; ++i) { + bfs(i); + } + return ans; + } + + private void bfs(int s) { + Deque q = new ArrayDeque<>(); + q.offer(s); + boolean[] vis = new boolean[n]; + vis[s] = true; + while (!q.isEmpty()) { + int i = q.poll(); + for (int j : g[i]) { + if (!vis[j]) { + vis[j] = true; + q.offer(j); + ans.get(j).add(s); + } + } + } + } } \ No newline at end of file diff --git a/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/Solution.py b/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/Solution.py index f1f156f7468df..0b4064d1de58a 100644 --- a/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/Solution.py +++ b/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/Solution.py @@ -1,20 +1,20 @@ -class Solution: - def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: - def bfs(s: int): - q = deque([s]) - vis = {s} - while q: - i = q.popleft() - for j in g[i]: - if j not in vis: - vis.add(j) - q.append(j) - ans[j].append(s) - - g = defaultdict(list) - for u, v in edges: - g[u].append(v) - ans = [[] for _ in range(n)] - for i in range(n): - bfs(i) - return ans +class Solution: + def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: + def bfs(s: int): + q = deque([s]) + vis = {s} + while q: + i = q.popleft() + for j in g[i]: + if j not in vis: + vis.add(j) + q.append(j) + ans[j].append(s) + + g = defaultdict(list) + for u, v in edges: + g[u].append(v) + ans = [[] for _ in range(n)] + for i in range(n): + bfs(i) + return ans diff --git a/solution/2100-2199/2194.Cells in a Range on an Excel Sheet/Solution.py b/solution/2100-2199/2194.Cells in a Range on an Excel Sheet/Solution.py index 8fabcebd33657..85a3bbbdb63f2 100644 --- a/solution/2100-2199/2194.Cells in a Range on an Excel Sheet/Solution.py +++ b/solution/2100-2199/2194.Cells in a Range on an Excel Sheet/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def cellsInRange(self, s: str) -> List[str]: - return [ - chr(i) + str(j) - for i in range(ord(s[0]), ord(s[-2]) + 1) - for j in range(int(s[1]), int(s[-1]) + 1) - ] +class Solution: + def cellsInRange(self, s: str) -> List[str]: + return [ + chr(i) + str(j) + for i in range(ord(s[0]), ord(s[-2]) + 1) + for j in range(int(s[1]), int(s[-1]) + 1) + ] diff --git a/solution/2100-2199/2198.Number of Single Divisor Triplets/Solution.cpp b/solution/2100-2199/2198.Number of Single Divisor Triplets/Solution.cpp index e444bc0f65b20..c152e424a6f69 100644 --- a/solution/2100-2199/2198.Number of Single Divisor Triplets/Solution.cpp +++ b/solution/2100-2199/2198.Number of Single Divisor Triplets/Solution.cpp @@ -1,27 +1,27 @@ -class Solution { -public: - long long singleDivisorTriplet(vector& nums) { - vector counter(101); - for (int& x : nums) ++counter[x]; - long long ans = 0; - for (int i = 1; i <= 100; ++i) { - for (int j = 1; j <= 100; ++j) { - for (int k = 1; k <= 100; ++k) { - int cnt1 = counter[i], cnt2 = counter[j], cnt3 = counter[k]; - int s = i + j + k; - int cnt = (s % i == 0) + (s % j == 0) + (s % k == 0); - if (cnt != 1) continue; - if (i == j) - ans += 1ll * cnt1 * (cnt1 - 1) * cnt3; - else if (i == k) - ans += 1ll * cnt1 * (cnt1 - 1) * cnt2; - else if (j == k) - ans += 1ll * cnt1 * cnt2 * (cnt2 - 1); - else - ans += 1ll * cnt1 * cnt2 * cnt3; - } - } - } - return ans; - } +class Solution { +public: + long long singleDivisorTriplet(vector& nums) { + vector counter(101); + for (int& x : nums) ++counter[x]; + long long ans = 0; + for (int i = 1; i <= 100; ++i) { + for (int j = 1; j <= 100; ++j) { + for (int k = 1; k <= 100; ++k) { + int cnt1 = counter[i], cnt2 = counter[j], cnt3 = counter[k]; + int s = i + j + k; + int cnt = (s % i == 0) + (s % j == 0) + (s % k == 0); + if (cnt != 1) continue; + if (i == j) + ans += 1ll * cnt1 * (cnt1 - 1) * cnt3; + else if (i == k) + ans += 1ll * cnt1 * (cnt1 - 1) * cnt2; + else if (j == k) + ans += 1ll * cnt1 * cnt2 * (cnt2 - 1); + else + ans += 1ll * cnt1 * cnt2 * cnt3; + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2100-2199/2198.Number of Single Divisor Triplets/Solution.java b/solution/2100-2199/2198.Number of Single Divisor Triplets/Solution.java index 04862f406614e..64a8c74add157 100644 --- a/solution/2100-2199/2198.Number of Single Divisor Triplets/Solution.java +++ b/solution/2100-2199/2198.Number of Single Divisor Triplets/Solution.java @@ -1,40 +1,40 @@ -class Solution { - public long singleDivisorTriplet(int[] nums) { - int[] counter = new int[101]; - for (int x : nums) { - ++counter[x]; - } - long ans = 0; - for (int i = 1; i <= 100; ++i) { - for (int j = 1; j <= 100; ++j) { - for (int k = 1; k <= 100; ++k) { - int cnt1 = counter[i], cnt2 = counter[j], cnt3 = counter[k]; - int s = i + j + k; - int cnt = 0; - if (s % i == 0) { - ++cnt; - } - if (s % j == 0) { - ++cnt; - } - if (s % k == 0) { - ++cnt; - } - if (cnt != 1) { - continue; - } - if (i == j) { - ans += (long) cnt1 * (cnt1 - 1) * cnt3; - } else if (i == k) { - ans += (long) cnt1 * (cnt1 - 1) * cnt2; - } else if (j == k) { - ans += (long) cnt1 * cnt2 * (cnt2 - 1); - } else { - ans += (long) cnt1 * cnt2 * cnt3; - } - } - } - } - return ans; - } +class Solution { + public long singleDivisorTriplet(int[] nums) { + int[] counter = new int[101]; + for (int x : nums) { + ++counter[x]; + } + long ans = 0; + for (int i = 1; i <= 100; ++i) { + for (int j = 1; j <= 100; ++j) { + for (int k = 1; k <= 100; ++k) { + int cnt1 = counter[i], cnt2 = counter[j], cnt3 = counter[k]; + int s = i + j + k; + int cnt = 0; + if (s % i == 0) { + ++cnt; + } + if (s % j == 0) { + ++cnt; + } + if (s % k == 0) { + ++cnt; + } + if (cnt != 1) { + continue; + } + if (i == j) { + ans += (long) cnt1 * (cnt1 - 1) * cnt3; + } else if (i == k) { + ans += (long) cnt1 * (cnt1 - 1) * cnt2; + } else if (j == k) { + ans += (long) cnt1 * cnt2 * (cnt2 - 1); + } else { + ans += (long) cnt1 * cnt2 * cnt3; + } + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2100-2199/2198.Number of Single Divisor Triplets/Solution.py b/solution/2100-2199/2198.Number of Single Divisor Triplets/Solution.py index 0cbee86cb0b12..508cfccaac862 100644 --- a/solution/2100-2199/2198.Number of Single Divisor Triplets/Solution.py +++ b/solution/2100-2199/2198.Number of Single Divisor Triplets/Solution.py @@ -1,21 +1,21 @@ -class Solution: - def singleDivisorTriplet(self, nums: List[int]) -> int: - def check(a, b, c): - s = a + b + c - return sum(s % x == 0 for x in [a, b, c]) == 1 - - counter = Counter(nums) - ans = 0 - for a, cnt1 in counter.items(): - for b, cnt2 in counter.items(): - for c, cnt3 in counter.items(): - if check(a, b, c): - if a == b: - ans += cnt1 * (cnt1 - 1) * cnt3 - elif a == c: - ans += cnt1 * (cnt1 - 1) * cnt2 - elif b == c: - ans += cnt1 * cnt2 * (cnt2 - 1) - else: - ans += cnt1 * cnt2 * cnt3 - return ans +class Solution: + def singleDivisorTriplet(self, nums: List[int]) -> int: + def check(a, b, c): + s = a + b + c + return sum(s % x == 0 for x in [a, b, c]) == 1 + + counter = Counter(nums) + ans = 0 + for a, cnt1 in counter.items(): + for b, cnt2 in counter.items(): + for c, cnt3 in counter.items(): + if check(a, b, c): + if a == b: + ans += cnt1 * (cnt1 - 1) * cnt3 + elif a == c: + ans += cnt1 * (cnt1 - 1) * cnt2 + elif b == c: + ans += cnt1 * cnt2 * (cnt2 - 1) + else: + ans += cnt1 * cnt2 * cnt3 + return ans diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.cpp b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.cpp index 58c3adb6840c8..d5fa87ca2d76a 100644 --- a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.cpp +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - vector findKDistantIndices(vector& nums, int key, int k) { - int n = nums.size(); - vector ans; - for (int i = 0, j = 0; i < n; ++i) { - while (j < i - k || (j < n && nums[j] != key)) { - ++j; - } - if (j < n && j <= i + k) { - ans.push_back(i); - } - } - return ans; - } +class Solution { +public: + vector findKDistantIndices(vector& nums, int key, int k) { + int n = nums.size(); + vector ans; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (abs(i - j) <= k && nums[j] == key) { + ans.push_back(i); + break; + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.go b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.go index 9f87a7fe27a93..8e5d3a68c9bc6 100644 --- a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.go +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.go @@ -1,12 +1,18 @@ func findKDistantIndices(nums []int, key int, k int) (ans []int) { - n := len(nums) - for i, j := 0, 0; i < n; i++ { - for j < i-k || (j < n && nums[j] != key) { - j++ - } - if j < n && j <= i+k { - ans = append(ans, i) + for i := range nums { + for j, x := range nums { + if abs(i-j) <= k && x == key { + ans = append(ans, i) + break + } } } - return + return ans +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x } \ No newline at end of file diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.java b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.java index 9dddaba757419..4e3632276d4c5 100644 --- a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.java +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public List findKDistantIndices(int[] nums, int key, int k) { - int n = nums.length; - List ans = new ArrayList<>(); - for (int i = 0, j = 0; i < n; ++i) { - while (j < i - k || (j < n && nums[j] != key)) { - ++j; - } - if (j < n && j <= i + k) { - ans.add(i); - } - } - return ans; - } +class Solution { + public List findKDistantIndices(int[] nums, int key, int k) { + int n = nums.length; + List ans = new ArrayList<>(); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (Math.abs(i - j) <= k && nums[j] == key) { + ans.add(i); + break; + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.py b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.py index b552876bbed4e..6baa7c41b883b 100644 --- a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.py +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.py @@ -1,10 +1,8 @@ -class Solution: - def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: - ans = [] - j, n = 0, len(nums) - for i in range(n): - while j < i - k or (j < n and nums[j] != key): - j += 1 - if j < n and j <= (i + k): - ans.append(i) - return ans +class Solution: + def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: + ans = [] + n = len(nums) + for i in range(n): + if any(abs(i - j) <= k and nums[j] == key for j in range(n)): + ans.append(i) + return ans diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.ts b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.ts index 85fd8fe4a5796..af9c507dc539e 100644 --- a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.ts +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.ts @@ -1,12 +1,12 @@ function findKDistantIndices(nums: number[], key: number, k: number): number[] { const n = nums.length; const ans: number[] = []; - for (let i = 0, j = 0; i < n; ++i) { - while (j < i - k || (j < n && nums[j] !== key)) { - ++j; - } - if (j < n && j <= i + k) { - ans.push(i); + for (let i = 0; i < n; ++i) { + for (let j = 0; j < n; ++j) { + if (Math.abs(i - j) <= k && nums[j] === key) { + ans.push(i); + break; + } } } return ans; diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution2.cpp b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution2.cpp new file mode 100644 index 0000000000000..930f640bf4937 --- /dev/null +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution2.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + vector findKDistantIndices(vector& nums, int key, int k) { + vector idx; + int n = nums.size(); + for (int i = 0; i < n; ++i) { + if (nums[i] == key) { + idx.push_back(i); + } + } + vector ans; + for (int i = 0; i < n; ++i) { + auto it1 = lower_bound(idx.begin(), idx.end(), i - k); + auto it2 = upper_bound(idx.begin(), idx.end(), i + k) - 1; + if (it1 <= it2) { + ans.push_back(i); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution2.go b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution2.go new file mode 100644 index 0000000000000..1d70dc5f50f5f --- /dev/null +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution2.go @@ -0,0 +1,16 @@ +func findKDistantIndices(nums []int, key int, k int) (ans []int) { + idx := []int{} + for i, x := range nums { + if x == key { + idx = append(idx, i) + } + } + for i := range nums { + l := sort.SearchInts(idx, i-k) + r := sort.SearchInts(idx, i+k+1) - 1 + if l <= r { + ans = append(ans, i) + } + } + return +} \ No newline at end of file diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution2.java b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution2.java new file mode 100644 index 0000000000000..ac88a707397b2 --- /dev/null +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution2.java @@ -0,0 +1,21 @@ +class Solution { + public List findKDistantIndices(int[] nums, int key, int k) { + List idx = new ArrayList<>(); + for (int i = 0; i < nums.length; i++) { + if (nums[i] == key) { + idx.add(i); + } + } + List ans = new ArrayList<>(); + for (int i = 0; i < nums.length; ++i) { + int l = Collections.binarySearch(idx, i - k); + int r = Collections.binarySearch(idx, i + k + 1); + l = l < 0 ? -l - 1 : l; + r = r < 0 ? -r - 2 : r - 1; + if (l <= r) { + ans.add(i); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution2.py b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution2.py new file mode 100644 index 0000000000000..4541301a3387f --- /dev/null +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: + idx = [i for i, x in enumerate(nums) if x == key] + ans = [] + for i in range(len(nums)): + l = bisect_left(idx, i - k) + r = bisect_right(idx, i + k) - 1 + if l <= r: + ans.append(i) + return ans diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution2.ts b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution2.ts new file mode 100644 index 0000000000000..d54d092f88c17 --- /dev/null +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution2.ts @@ -0,0 +1,30 @@ +function findKDistantIndices(nums: number[], key: number, k: number): number[] { + const n = nums.length; + const idx: number[] = []; + for (let i = 0; i < n; i++) { + if (nums[i] === key) { + idx.push(i); + } + } + const search = (x: number): number => { + let [l, r] = [0, idx.length]; + while (l < r) { + const mid = (l + r) >> 1; + if (idx[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + const ans: number[] = []; + for (let i = 0; i < n; ++i) { + const l = search(i - k); + const r = search(i + k + 1) - 1; + if (l <= r) { + ans.push(i); + } + } + return ans; +} diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution3.cpp b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution3.cpp new file mode 100644 index 0000000000000..a070120abae30 --- /dev/null +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution3.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector findKDistantIndices(vector& nums, int key, int k) { + int n = nums.size(); + vector ans; + for (int i = 0, j = 0; i < n; ++i) { + while (j < i - k || (j < n && nums[j] != key)) { + ++j; + } + if (j < n && j <= i + k) { + ans.push_back(i); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution3.go b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution3.go new file mode 100644 index 0000000000000..9f87a7fe27a93 --- /dev/null +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution3.go @@ -0,0 +1,12 @@ +func findKDistantIndices(nums []int, key int, k int) (ans []int) { + n := len(nums) + for i, j := 0, 0; i < n; i++ { + for j < i-k || (j < n && nums[j] != key) { + j++ + } + if j < n && j <= i+k { + ans = append(ans, i) + } + } + return +} \ No newline at end of file diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution3.java b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution3.java new file mode 100644 index 0000000000000..6349412359553 --- /dev/null +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution3.java @@ -0,0 +1,15 @@ +class Solution { + public List findKDistantIndices(int[] nums, int key, int k) { + int n = nums.length; + List ans = new ArrayList<>(); + for (int i = 0, j = 0; i < n; ++i) { + while (j < i - k || (j < n && nums[j] != key)) { + ++j; + } + if (j < n && j <= i + k) { + ans.add(i); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution3.py b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution3.py new file mode 100644 index 0000000000000..88b4ccd69d986 --- /dev/null +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution3.py @@ -0,0 +1,10 @@ +class Solution: + def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: + ans = [] + j, n = 0, len(nums) + for i in range(n): + while j < i - k or (j < n and nums[j] != key): + j += 1 + if j < n and j <= (i + k): + ans.append(i) + return ans diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution3.ts b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution3.ts new file mode 100644 index 0000000000000..85fd8fe4a5796 --- /dev/null +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution3.ts @@ -0,0 +1,13 @@ +function findKDistantIndices(nums: number[], key: number, k: number): number[] { + const n = nums.length; + const ans: number[] = []; + for (let i = 0, j = 0; i < n; ++i) { + while (j < i - k || (j < n && nums[j] !== key)) { + ++j; + } + if (j < n && j <= i + k) { + ans.push(i); + } + } + return ans; +} diff --git a/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/Solution.cpp b/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/Solution.cpp index f3898893ed415..d0ad85aadee18 100644 --- a/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/Solution.cpp +++ b/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/Solution.cpp @@ -1,25 +1,25 @@ -class Solution { -public: - int digArtifacts(int n, vector>& artifacts, vector>& dig) { - unordered_set s; - for (auto& p : dig) { - s.insert(p[0] * n + p[1]); - } - auto check = [&](vector& a) { - int x1 = a[0], y1 = a[1], x2 = a[2], y2 = a[3]; - for (int x = x1; x <= x2; ++x) { - for (int y = y1; y <= y2; ++y) { - if (!s.count(x * n + y)) { - return 0; - } - } - } - return 1; - }; - int ans = 0; - for (auto& a : artifacts) { - ans += check(a); - } - return ans; - } +class Solution { +public: + int digArtifacts(int n, vector>& artifacts, vector>& dig) { + unordered_set s; + for (auto& p : dig) { + s.insert(p[0] * n + p[1]); + } + auto check = [&](vector& a) { + int x1 = a[0], y1 = a[1], x2 = a[2], y2 = a[3]; + for (int x = x1; x <= x2; ++x) { + for (int y = y1; y <= y2; ++y) { + if (!s.count(x * n + y)) { + return 0; + } + } + } + return 1; + }; + int ans = 0; + for (auto& a : artifacts) { + ans += check(a); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/Solution.java b/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/Solution.java index e6374a6fc62d8..1865cd7c29dc5 100644 --- a/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/Solution.java +++ b/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/Solution.java @@ -1,28 +1,28 @@ -class Solution { - private Set s = new HashSet<>(); - private int n; - - public int digArtifacts(int n, int[][] artifacts, int[][] dig) { - this.n = n; - for (var p : dig) { - s.add(p[0] * n + p[1]); - } - int ans = 0; - for (var a : artifacts) { - ans += check(a); - } - return ans; - } - - private int check(int[] a) { - int x1 = a[0], y1 = a[1], x2 = a[2], y2 = a[3]; - for (int x = x1; x <= x2; ++x) { - for (int y = y1; y <= y2; ++y) { - if (!s.contains(x * n + y)) { - return 0; - } - } - } - return 1; - } +class Solution { + private Set s = new HashSet<>(); + private int n; + + public int digArtifacts(int n, int[][] artifacts, int[][] dig) { + this.n = n; + for (var p : dig) { + s.add(p[0] * n + p[1]); + } + int ans = 0; + for (var a : artifacts) { + ans += check(a); + } + return ans; + } + + private int check(int[] a) { + int x1 = a[0], y1 = a[1], x2 = a[2], y2 = a[3]; + for (int x = x1; x <= x2; ++x) { + for (int y = y1; y <= y2; ++y) { + if (!s.contains(x * n + y)) { + return 0; + } + } + } + return 1; + } } \ No newline at end of file diff --git a/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/Solution.py b/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/Solution.py index 66e068e36e4a5..a9d974af728ba 100644 --- a/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/Solution.py +++ b/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def digArtifacts( - self, n: int, artifacts: List[List[int]], dig: List[List[int]] - ) -> int: - def check(a: List[int]) -> bool: - x1, y1, x2, y2 = a - return all( - (x, y) in s for x in range(x1, x2 + 1) for y in range(y1, y2 + 1) - ) - - s = {(i, j) for i, j in dig} - return sum(check(a) for a in artifacts) +class Solution: + def digArtifacts( + self, n: int, artifacts: List[List[int]], dig: List[List[int]] + ) -> int: + def check(a: List[int]) -> bool: + x1, y1, x2, y2 = a + return all( + (x, y) in s for x in range(x1, x2 + 1) for y in range(y1, y2 + 1) + ) + + s = {(i, j) for i, j in dig} + return sum(check(a) for a in artifacts) diff --git a/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/Solution.cpp b/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/Solution.cpp index 839bb94b7ddc8..89bceac73d28c 100644 --- a/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/Solution.cpp +++ b/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/Solution.cpp @@ -1,39 +1,39 @@ -class Solution { -public: - vector distanceToCycle(int n, vector>& edges) { - unordered_set g[n]; - for (auto& e : edges) { - int a = e[0], b = e[1]; - g[a].insert(b); - g[b].insert(a); - } - queue q; - for (int i = 0; i < n; ++i) { - if (g[i].size() == 1) { - q.push(i); - } - } - int f[n]; - int seq[n]; - int k = 0; - while (!q.empty()) { - int i = q.front(); - q.pop(); - seq[k++] = i; - for (int j : g[i]) { - g[j].erase(i); - f[i] = j; - if (g[j].size() == 1) { - q.push(j); - } - } - g[i].clear(); - } - vector ans(n); - for (; k; --k) { - int i = seq[k - 1]; - ans[i] = ans[f[i]] + 1; - } - return ans; - } +class Solution { +public: + vector distanceToCycle(int n, vector>& edges) { + unordered_set g[n]; + for (auto& e : edges) { + int a = e[0], b = e[1]; + g[a].insert(b); + g[b].insert(a); + } + queue q; + for (int i = 0; i < n; ++i) { + if (g[i].size() == 1) { + q.push(i); + } + } + int f[n]; + int seq[n]; + int k = 0; + while (!q.empty()) { + int i = q.front(); + q.pop(); + seq[k++] = i; + for (int j : g[i]) { + g[j].erase(i); + f[i] = j; + if (g[j].size() == 1) { + q.push(j); + } + } + g[i].clear(); + } + vector ans(n); + for (; k; --k) { + int i = seq[k - 1]; + ans[i] = ans[f[i]] + 1; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/Solution.java b/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/Solution.java index 72b963fb175ba..61bdbe64a7aac 100644 --- a/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/Solution.java +++ b/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/Solution.java @@ -1,36 +1,36 @@ -class Solution { - public int[] distanceToCycle(int n, int[][] edges) { - Set[] g = new Set[n]; - Arrays.setAll(g, k -> new HashSet<>()); - for (var e : edges) { - int a = e[0], b = e[1]; - g[a].add(b); - g[b].add(a); - } - Deque q = new ArrayDeque<>(); - for (int i = 0; i < n; ++i) { - if (g[i].size() == 1) { - q.offer(i); - } - } - int[] f = new int[n]; - Deque seq = new ArrayDeque<>(); - while (!q.isEmpty()) { - int i = q.poll(); - seq.push(i); - for (int j : g[i]) { - g[j].remove(i); - f[i] = j; - if (g[j].size() == 1) { - q.offer(j); - } - } - } - int[] ans = new int[n]; - while (!seq.isEmpty()) { - int i = seq.pop(); - ans[i] = ans[f[i]] + 1; - } - return ans; - } +class Solution { + public int[] distanceToCycle(int n, int[][] edges) { + Set[] g = new Set[n]; + Arrays.setAll(g, k -> new HashSet<>()); + for (var e : edges) { + int a = e[0], b = e[1]; + g[a].add(b); + g[b].add(a); + } + Deque q = new ArrayDeque<>(); + for (int i = 0; i < n; ++i) { + if (g[i].size() == 1) { + q.offer(i); + } + } + int[] f = new int[n]; + Deque seq = new ArrayDeque<>(); + while (!q.isEmpty()) { + int i = q.poll(); + seq.push(i); + for (int j : g[i]) { + g[j].remove(i); + f[i] = j; + if (g[j].size() == 1) { + q.offer(j); + } + } + } + int[] ans = new int[n]; + while (!seq.isEmpty()) { + int i = seq.pop(); + ans[i] = ans[f[i]] + 1; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/Solution.py b/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/Solution.py index 55596d07f9d45..36bf287a9e2a2 100644 --- a/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/Solution.py +++ b/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/Solution.py @@ -1,22 +1,22 @@ -class Solution: - def distanceToCycle(self, n: int, edges: List[List[int]]) -> List[int]: - g = defaultdict(set) - for a, b in edges: - g[a].add(b) - g[b].add(a) - q = deque(i for i in range(n) if len(g[i]) == 1) - f = [0] * n - seq = [] - while q: - i = q.popleft() - seq.append(i) - for j in g[i]: - g[j].remove(i) - f[i] = j - if len(g[j]) == 1: - q.append(j) - g[i].clear() - ans = [0] * n - for i in seq[::-1]: - ans[i] = ans[f[i]] + 1 - return ans +class Solution: + def distanceToCycle(self, n: int, edges: List[List[int]]) -> List[int]: + g = defaultdict(set) + for a, b in edges: + g[a].add(b) + g[b].add(a) + q = deque(i for i in range(n) if len(g[i]) == 1) + f = [0] * n + seq = [] + while q: + i = q.popleft() + seq.append(i) + for j in g[i]: + g[j].remove(i) + f[i] = j + if len(g[j]) == 1: + q.append(j) + g[i].clear() + ans = [0] * n + for i in seq[::-1]: + ans[i] = ans[f[i]] + 1 + return ans diff --git a/solution/2200-2299/2206.Divide Array Into Equal Pairs/Solution.cpp b/solution/2200-2299/2206.Divide Array Into Equal Pairs/Solution.cpp index 6888aa74d560d..cfd673b74c6b5 100644 --- a/solution/2200-2299/2206.Divide Array Into Equal Pairs/Solution.cpp +++ b/solution/2200-2299/2206.Divide Array Into Equal Pairs/Solution.cpp @@ -1,11 +1,11 @@ -class Solution { -public: - bool divideArray(vector& nums) { - vector cnt(510); - for (int& v : nums) ++cnt[v]; - for (int& v : cnt) - if (v % 2) - return false; - return true; - } +class Solution { +public: + bool divideArray(vector& nums) { + vector cnt(510); + for (int& v : nums) ++cnt[v]; + for (int& v : cnt) + if (v % 2) + return false; + return true; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2206.Divide Array Into Equal Pairs/Solution.java b/solution/2200-2299/2206.Divide Array Into Equal Pairs/Solution.java index 4d8c8e3b7c0af..d21aca353d33a 100644 --- a/solution/2200-2299/2206.Divide Array Into Equal Pairs/Solution.java +++ b/solution/2200-2299/2206.Divide Array Into Equal Pairs/Solution.java @@ -1,14 +1,14 @@ -class Solution { - public boolean divideArray(int[] nums) { - int[] cnt = new int[510]; - for (int v : nums) { - ++cnt[v]; - } - for (int v : cnt) { - if (v % 2 != 0) { - return false; - } - } - return true; - } +class Solution { + public boolean divideArray(int[] nums) { + int[] cnt = new int[510]; + for (int v : nums) { + ++cnt[v]; + } + for (int v : cnt) { + if (v % 2 != 0) { + return false; + } + } + return true; + } } \ No newline at end of file diff --git a/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/Solution.cpp b/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/Solution.cpp index f385ff5be5a6b..ba5eefd57b0a9 100644 --- a/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/Solution.cpp +++ b/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - int halveArray(vector& nums) { - priority_queue q; - double s = 0; - for (int& v : nums) { - s += v; - q.push(v); - } - s /= 2.0; - int ans = 0; - while (s > 0) { - double t = q.top() / 2; - q.pop(); - s -= t; - q.push(t); - ++ans; - } - return ans; - } +class Solution { +public: + int halveArray(vector& nums) { + priority_queue q; + double s = 0; + for (int& v : nums) { + s += v; + q.push(v); + } + s /= 2.0; + int ans = 0; + while (s > 0) { + double t = q.top() / 2; + q.pop(); + s -= t; + q.push(t); + ++ans; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/Solution.java b/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/Solution.java index 07ef802ff10c5..8a12cf6776e6e 100644 --- a/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/Solution.java +++ b/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/Solution.java @@ -1,19 +1,19 @@ -class Solution { - public int halveArray(int[] nums) { - double s = 0; - PriorityQueue q = new PriorityQueue<>(Collections.reverseOrder()); - for (int v : nums) { - q.offer(v * 1.0); - s += v; - } - s /= 2.0; - int ans = 0; - while (s > 0) { - double t = q.poll(); - s -= t / 2.0; - q.offer(t / 2.0); - ++ans; - } - return ans; - } +class Solution { + public int halveArray(int[] nums) { + double s = 0; + PriorityQueue q = new PriorityQueue<>(Collections.reverseOrder()); + for (int v : nums) { + q.offer(v * 1.0); + s += v; + } + s /= 2.0; + int ans = 0; + while (s > 0) { + double t = q.poll(); + s -= t / 2.0; + q.offer(t / 2.0); + ++ans; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/Solution2.go b/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/Solution2.go new file mode 100644 index 0000000000000..3e2cd88d34bfd --- /dev/null +++ b/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/Solution2.go @@ -0,0 +1,21 @@ +func halveArray(nums []int) (ans int) { + half := 0 + for i := range nums { + nums[i] <<= 20 + half += nums[i] + } + h := hp{nums} + heap.Init(&h) + for half >>= 1; half > 0; ans++ { + half -= h.IntSlice[0] >> 1 + h.IntSlice[0] >>= 1 + heap.Fix(&h, 0) + } + return +} + +type hp struct{ sort.IntSlice } + +func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } +func (hp) Push(any) {} +func (hp) Pop() (_ any) { return } \ No newline at end of file diff --git a/solution/2200-2299/2210.Count Hills and Valleys in an Array/Solution.cpp b/solution/2200-2299/2210.Count Hills and Valleys in an Array/Solution.cpp index 68da0329f353a..a07c361d22a11 100644 --- a/solution/2200-2299/2210.Count Hills and Valleys in an Array/Solution.cpp +++ b/solution/2200-2299/2210.Count Hills and Valleys in an Array/Solution.cpp @@ -1,13 +1,13 @@ -class Solution { -public: - int countHillValley(vector& nums) { - int ans = 0; - for (int i = 1, j = 0; i < nums.size() - 1; ++i) { - if (nums[i] == nums[i + 1]) continue; - if (nums[i] > nums[j] && nums[i] > nums[i + 1]) ++ans; - if (nums[i] < nums[j] && nums[i] < nums[i + 1]) ++ans; - j = i; - } - return ans; - } +class Solution { +public: + int countHillValley(vector& nums) { + int ans = 0; + for (int i = 1, j = 0; i < nums.size() - 1; ++i) { + if (nums[i] == nums[i + 1]) continue; + if (nums[i] > nums[j] && nums[i] > nums[i + 1]) ++ans; + if (nums[i] < nums[j] && nums[i] < nums[i + 1]) ++ans; + j = i; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2210.Count Hills and Valleys in an Array/Solution.py b/solution/2200-2299/2210.Count Hills and Valleys in an Array/Solution.py index 041f6f096ad04..e97d65eed71de 100644 --- a/solution/2200-2299/2210.Count Hills and Valleys in an Array/Solution.py +++ b/solution/2200-2299/2210.Count Hills and Valleys in an Array/Solution.py @@ -1,12 +1,10 @@ class Solution: def countHillValley(self, nums: List[int]) -> int: - ans = j = 0 - for i in range(1, len(nums) - 1): - if nums[i] == nums[i + 1]: - continue - if nums[i] > nums[j] and nums[i] > nums[i + 1]: - ans += 1 - if nums[i] < nums[j] and nums[i] < nums[i + 1]: - ans += 1 - j = i - return ans + arr = [nums[0]] + for v in nums[1:]: + if v != arr[-1]: + arr.append(v) + return sum( + (arr[i] < arr[i - 1]) == (arr[i] < arr[i + 1]) + for i in range(1, len(arr) - 1) + ) diff --git a/solution/2200-2299/2210.Count Hills and Valleys in an Array/Solution2.py b/solution/2200-2299/2210.Count Hills and Valleys in an Array/Solution2.py new file mode 100644 index 0000000000000..041f6f096ad04 --- /dev/null +++ b/solution/2200-2299/2210.Count Hills and Valleys in an Array/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def countHillValley(self, nums: List[int]) -> int: + ans = j = 0 + for i in range(1, len(nums) - 1): + if nums[i] == nums[i + 1]: + continue + if nums[i] > nums[j] and nums[i] > nums[i + 1]: + ans += 1 + if nums[i] < nums[j] and nums[i] < nums[i + 1]: + ans += 1 + j = i + return ans diff --git a/solution/2200-2299/2213.Longest Substring of One Repeating Character/Solution.cpp b/solution/2200-2299/2213.Longest Substring of One Repeating Character/Solution.cpp index 84f3c737a2513..105f052de94c4 100644 --- a/solution/2200-2299/2213.Longest Substring of One Repeating Character/Solution.cpp +++ b/solution/2200-2299/2213.Longest Substring of One Repeating Character/Solution.cpp @@ -1,94 +1,94 @@ -class Node { -public: - int l, r, size, lmx, rmx, mx; - char lc, rc; -}; - -class SegmentTree { -private: - string s; - vector tr; - -public: - SegmentTree(string& s) { - this->s = s; - int n = s.size(); - tr.resize(n << 2); - for (int i = 0; i < tr.size(); ++i) tr[i] = new Node(); - build(1, 1, n); - } - - void build(int u, int l, int r) { - tr[u]->l = l; - tr[u]->r = r; - if (l == r) { - tr[u]->lmx = tr[u]->rmx = tr[u]->mx = tr[u]->size = 1; - tr[u]->lc = tr[u]->rc = s[l - 1]; - return; - } - int mid = (l + r) >> 1; - build(u << 1, l, mid); - build(u << 1 | 1, mid + 1, r); - pushup(u); - } - - void modify(int u, int x, char v) { - if (tr[u]->l == x && tr[u]->r == x) { - tr[u]->lc = tr[u]->rc = v; - return; - } - int mid = (tr[u]->l + tr[u]->r) >> 1; - if (x <= mid) - modify(u << 1, x, v); - else - modify(u << 1 | 1, x, v); - pushup(u); - } - - Node* query(int u, int l, int r) { - if (tr[u]->l >= l && tr[u]->r <= r) return tr[u]; - int mid = (tr[u]->l + tr[u]->r) >> 1; - if (r <= mid) return query(u << 1, l, r); - if (l > mid) query(u << 1 | 1, l, r); - Node* ans = new Node(); - Node* left = query(u << 1, l, r); - Node* right = query(u << 1 | 1, l, r); - pushup(ans, left, right); - return ans; - } - - void pushup(Node* root, Node* left, Node* right) { - root->lc = left->lc; - root->rc = right->rc; - root->size = left->size + right->size; - - root->mx = max(left->mx, right->mx); - root->lmx = left->lmx; - root->rmx = right->rmx; - - if (left->rc == right->lc) { - if (left->lmx == left->size) root->lmx += right->lmx; - if (right->rmx == right->size) root->rmx += left->rmx; - root->mx = max(root->mx, left->rmx + right->lmx); - } - } - - void pushup(int u) { - pushup(tr[u], tr[u << 1], tr[u << 1 | 1]); - } -}; - -class Solution { -public: - vector longestRepeating(string s, string queryCharacters, vector& queryIndices) { - SegmentTree* tree = new SegmentTree(s); - int k = queryCharacters.size(); - vector ans(k); - for (int i = 0; i < k; ++i) { - int x = queryIndices[i] + 1; - tree->modify(1, x, queryCharacters[i]); - ans[i] = tree->query(1, 1, s.size())->mx; - } - return ans; - } +class Node { +public: + int l, r, size, lmx, rmx, mx; + char lc, rc; +}; + +class SegmentTree { +private: + string s; + vector tr; + +public: + SegmentTree(string& s) { + this->s = s; + int n = s.size(); + tr.resize(n << 2); + for (int i = 0; i < tr.size(); ++i) tr[i] = new Node(); + build(1, 1, n); + } + + void build(int u, int l, int r) { + tr[u]->l = l; + tr[u]->r = r; + if (l == r) { + tr[u]->lmx = tr[u]->rmx = tr[u]->mx = tr[u]->size = 1; + tr[u]->lc = tr[u]->rc = s[l - 1]; + return; + } + int mid = (l + r) >> 1; + build(u << 1, l, mid); + build(u << 1 | 1, mid + 1, r); + pushup(u); + } + + void modify(int u, int x, char v) { + if (tr[u]->l == x && tr[u]->r == x) { + tr[u]->lc = tr[u]->rc = v; + return; + } + int mid = (tr[u]->l + tr[u]->r) >> 1; + if (x <= mid) + modify(u << 1, x, v); + else + modify(u << 1 | 1, x, v); + pushup(u); + } + + Node* query(int u, int l, int r) { + if (tr[u]->l >= l && tr[u]->r <= r) return tr[u]; + int mid = (tr[u]->l + tr[u]->r) >> 1; + if (r <= mid) return query(u << 1, l, r); + if (l > mid) query(u << 1 | 1, l, r); + Node* ans = new Node(); + Node* left = query(u << 1, l, r); + Node* right = query(u << 1 | 1, l, r); + pushup(ans, left, right); + return ans; + } + + void pushup(Node* root, Node* left, Node* right) { + root->lc = left->lc; + root->rc = right->rc; + root->size = left->size + right->size; + + root->mx = max(left->mx, right->mx); + root->lmx = left->lmx; + root->rmx = right->rmx; + + if (left->rc == right->lc) { + if (left->lmx == left->size) root->lmx += right->lmx; + if (right->rmx == right->size) root->rmx += left->rmx; + root->mx = max(root->mx, left->rmx + right->lmx); + } + } + + void pushup(int u) { + pushup(tr[u], tr[u << 1], tr[u << 1 | 1]); + } +}; + +class Solution { +public: + vector longestRepeating(string s, string queryCharacters, vector& queryIndices) { + SegmentTree* tree = new SegmentTree(s); + int k = queryCharacters.size(); + vector ans(k); + for (int i = 0; i < k; ++i) { + int x = queryIndices[i] + 1; + tree->modify(1, x, queryCharacters[i]); + ans[i] = tree->query(1, 1, s.size())->mx; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2213.Longest Substring of One Repeating Character/Solution.java b/solution/2200-2299/2213.Longest Substring of One Repeating Character/Solution.java index fa78fc4cd9ba5..98c0760d6021a 100644 --- a/solution/2200-2299/2213.Longest Substring of One Repeating Character/Solution.java +++ b/solution/2200-2299/2213.Longest Substring of One Repeating Character/Solution.java @@ -1,115 +1,115 @@ -class Node { - int l; - int r; - int size; - int lmx; - int rmx; - int mx; - char lc; - char rc; -} - -class SegmentTree { - private String s; - private Node[] tr; - - public SegmentTree(String s) { - int n = s.length(); - this.s = s; - tr = new Node[n << 2]; - for (int i = 0; i < tr.length; ++i) { - tr[i] = new Node(); - } - build(1, 1, n); - } - - public void build(int u, int l, int r) { - tr[u].l = l; - tr[u].r = r; - if (l == r) { - tr[u].lmx = 1; - tr[u].rmx = 1; - tr[u].mx = 1; - tr[u].size = 1; - tr[u].lc = s.charAt(l - 1); - tr[u].rc = s.charAt(l - 1); - return; - } - int mid = (l + r) >> 1; - build(u << 1, l, mid); - build(u << 1 | 1, mid + 1, r); - pushup(u); - } - - void modify(int u, int x, char v) { - if (tr[u].l == x && tr[u].r == x) { - tr[u].lc = v; - tr[u].rc = v; - return; - } - int mid = (tr[u].l + tr[u].r) >> 1; - if (x <= mid) { - modify(u << 1, x, v); - } else { - modify(u << 1 | 1, x, v); - } - pushup(u); - } - - Node query(int u, int l, int r) { - if (tr[u].l >= l && tr[u].r <= r) { - return tr[u]; - } - int mid = (tr[u].l + tr[u].r) >> 1; - if (r <= mid) { - return query(u << 1, l, r); - } - if (l > mid) { - return query(u << 1 | 1, l, r); - } - Node ans = new Node(); - Node left = query(u << 1, l, r); - Node right = query(u << 1 | 1, l, r); - pushup(ans, left, right); - return ans; - } - - void pushup(Node root, Node left, Node right) { - root.lc = left.lc; - root.rc = right.rc; - root.size = left.size + right.size; - - root.mx = Math.max(left.mx, right.mx); - root.lmx = left.lmx; - root.rmx = right.rmx; - - if (left.rc == right.lc) { - if (left.lmx == left.size) { - root.lmx += right.lmx; - } - if (right.rmx == right.size) { - root.rmx += left.rmx; - } - root.mx = Math.max(root.mx, left.rmx + right.lmx); - } - } - - void pushup(int u) { - pushup(tr[u], tr[u << 1], tr[u << 1 | 1]); - } -} - -class Solution { - public int[] longestRepeating(String s, String queryCharacters, int[] queryIndices) { - SegmentTree tree = new SegmentTree(s); - int k = queryCharacters.length(); - int[] ans = new int[k]; - for (int i = 0; i < k; ++i) { - int x = queryIndices[i] + 1; - char c = queryCharacters.charAt(i); - tree.modify(1, x, c); - ans[i] = tree.query(1, 1, s.length()).mx; - } - return ans; - } +class Node { + int l; + int r; + int size; + int lmx; + int rmx; + int mx; + char lc; + char rc; +} + +class SegmentTree { + private String s; + private Node[] tr; + + public SegmentTree(String s) { + int n = s.length(); + this.s = s; + tr = new Node[n << 2]; + for (int i = 0; i < tr.length; ++i) { + tr[i] = new Node(); + } + build(1, 1, n); + } + + public void build(int u, int l, int r) { + tr[u].l = l; + tr[u].r = r; + if (l == r) { + tr[u].lmx = 1; + tr[u].rmx = 1; + tr[u].mx = 1; + tr[u].size = 1; + tr[u].lc = s.charAt(l - 1); + tr[u].rc = s.charAt(l - 1); + return; + } + int mid = (l + r) >> 1; + build(u << 1, l, mid); + build(u << 1 | 1, mid + 1, r); + pushup(u); + } + + void modify(int u, int x, char v) { + if (tr[u].l == x && tr[u].r == x) { + tr[u].lc = v; + tr[u].rc = v; + return; + } + int mid = (tr[u].l + tr[u].r) >> 1; + if (x <= mid) { + modify(u << 1, x, v); + } else { + modify(u << 1 | 1, x, v); + } + pushup(u); + } + + Node query(int u, int l, int r) { + if (tr[u].l >= l && tr[u].r <= r) { + return tr[u]; + } + int mid = (tr[u].l + tr[u].r) >> 1; + if (r <= mid) { + return query(u << 1, l, r); + } + if (l > mid) { + return query(u << 1 | 1, l, r); + } + Node ans = new Node(); + Node left = query(u << 1, l, r); + Node right = query(u << 1 | 1, l, r); + pushup(ans, left, right); + return ans; + } + + void pushup(Node root, Node left, Node right) { + root.lc = left.lc; + root.rc = right.rc; + root.size = left.size + right.size; + + root.mx = Math.max(left.mx, right.mx); + root.lmx = left.lmx; + root.rmx = right.rmx; + + if (left.rc == right.lc) { + if (left.lmx == left.size) { + root.lmx += right.lmx; + } + if (right.rmx == right.size) { + root.rmx += left.rmx; + } + root.mx = Math.max(root.mx, left.rmx + right.lmx); + } + } + + void pushup(int u) { + pushup(tr[u], tr[u << 1], tr[u << 1 | 1]); + } +} + +class Solution { + public int[] longestRepeating(String s, String queryCharacters, int[] queryIndices) { + SegmentTree tree = new SegmentTree(s); + int k = queryCharacters.length(); + int[] ans = new int[k]; + for (int i = 0; i < k; ++i) { + int x = queryIndices[i] + 1; + char c = queryCharacters.charAt(i); + tree.modify(1, x, c); + ans[i] = tree.query(1, 1, s.length()).mx; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2200-2299/2213.Longest Substring of One Repeating Character/Solution.py b/solution/2200-2299/2213.Longest Substring of One Repeating Character/Solution.py index 81a273ee2c0f8..2aae88b6b0715 100644 --- a/solution/2200-2299/2213.Longest Substring of One Repeating Character/Solution.py +++ b/solution/2200-2299/2213.Longest Substring of One Repeating Character/Solution.py @@ -1,88 +1,88 @@ -class Node: - def __init__(self): - self.l = 0 - self.r = 0 - self.lmx = 0 - self.rmx = 0 - self.mx = 0 - self.size = 0 - self.lc = None - self.rc = None - - -N = 100010 -tr = [Node() for _ in range(N << 2)] - - -class SegmentTree: - def __init__(self, s): - n = len(s) - self.s = s - self.build(1, 1, n) - - def build(self, u, l, r): - tr[u].l = l - tr[u].r = r - if l == r: - tr[u].lmx = tr[u].rmx = tr[u].mx = tr[u].size = 1 - tr[u].lc = tr[u].rc = self.s[l - 1] - return - mid = (l + r) >> 1 - self.build(u << 1, l, mid) - self.build(u << 1 | 1, mid + 1, r) - self.pushup(u) - - def modify(self, u, x, v): - if tr[u].l == x and tr[u].r == x: - tr[u].lc = tr[u].rc = v - return - mid = (tr[u].l + tr[u].r) >> 1 - if x <= mid: - self.modify(u << 1, x, v) - else: - self.modify(u << 1 | 1, x, v) - self.pushup(u) - - def query(self, u, l, r): - if tr[u].l >= l and tr[u].r <= r: - return tr[u] - mid = (tr[u].l + tr[u].r) >> 1 - if r <= mid: - return self.query(u << 1, l, r) - if l > mid: - return self.query(u << 1 | 1, l, r) - left, right = self.query(u << 1, l, r), self.query(u << 1 | 1, l, r) - ans = Node() - self._pushup(ans, left, right) - return ans - - def _pushup(self, root, left, right): - root.lc, root.rc = left.lc, right.rc - root.size = left.size + right.size - - root.mx = max(left.mx, right.mx) - root.lmx, root.rmx = left.lmx, right.rmx - - if left.rc == right.lc: - if left.lmx == left.size: - root.lmx += right.lmx - if right.rmx == right.size: - root.rmx += left.rmx - root.mx = max(root.mx, left.rmx + right.lmx) - - def pushup(self, u): - self._pushup(tr[u], tr[u << 1], tr[u << 1 | 1]) - - -class Solution: - def longestRepeating( - self, s: str, queryCharacters: str, queryIndices: List[int] - ) -> List[int]: - tree = SegmentTree(s) - k = len(queryIndices) - ans = [] - for i, c in enumerate(queryCharacters): - x = queryIndices[i] + 1 - tree.modify(1, x, c) - ans.append(tree.query(1, 1, len(s)).mx) - return ans +class Node: + def __init__(self): + self.l = 0 + self.r = 0 + self.lmx = 0 + self.rmx = 0 + self.mx = 0 + self.size = 0 + self.lc = None + self.rc = None + + +N = 100010 +tr = [Node() for _ in range(N << 2)] + + +class SegmentTree: + def __init__(self, s): + n = len(s) + self.s = s + self.build(1, 1, n) + + def build(self, u, l, r): + tr[u].l = l + tr[u].r = r + if l == r: + tr[u].lmx = tr[u].rmx = tr[u].mx = tr[u].size = 1 + tr[u].lc = tr[u].rc = self.s[l - 1] + return + mid = (l + r) >> 1 + self.build(u << 1, l, mid) + self.build(u << 1 | 1, mid + 1, r) + self.pushup(u) + + def modify(self, u, x, v): + if tr[u].l == x and tr[u].r == x: + tr[u].lc = tr[u].rc = v + return + mid = (tr[u].l + tr[u].r) >> 1 + if x <= mid: + self.modify(u << 1, x, v) + else: + self.modify(u << 1 | 1, x, v) + self.pushup(u) + + def query(self, u, l, r): + if tr[u].l >= l and tr[u].r <= r: + return tr[u] + mid = (tr[u].l + tr[u].r) >> 1 + if r <= mid: + return self.query(u << 1, l, r) + if l > mid: + return self.query(u << 1 | 1, l, r) + left, right = self.query(u << 1, l, r), self.query(u << 1 | 1, l, r) + ans = Node() + self._pushup(ans, left, right) + return ans + + def _pushup(self, root, left, right): + root.lc, root.rc = left.lc, right.rc + root.size = left.size + right.size + + root.mx = max(left.mx, right.mx) + root.lmx, root.rmx = left.lmx, right.rmx + + if left.rc == right.lc: + if left.lmx == left.size: + root.lmx += right.lmx + if right.rmx == right.size: + root.rmx += left.rmx + root.mx = max(root.mx, left.rmx + right.lmx) + + def pushup(self, u): + self._pushup(tr[u], tr[u << 1], tr[u << 1 | 1]) + + +class Solution: + def longestRepeating( + self, s: str, queryCharacters: str, queryIndices: List[int] + ) -> List[int]: + tree = SegmentTree(s) + k = len(queryIndices) + ans = [] + for i, c in enumerate(queryCharacters): + x = queryIndices[i] + 1 + tree.modify(1, x, c) + ans.append(tree.query(1, 1, len(s)).mx) + return ans diff --git a/solution/2200-2299/2214.Minimum Health to Beat Game/Solution.cpp b/solution/2200-2299/2214.Minimum Health to Beat Game/Solution.cpp index 3765dee021f78..79376f3a69e8c 100644 --- a/solution/2200-2299/2214.Minimum Health to Beat Game/Solution.cpp +++ b/solution/2200-2299/2214.Minimum Health to Beat Game/Solution.cpp @@ -1,12 +1,12 @@ -class Solution { -public: - long long minimumHealth(vector& damage, int armor) { - long long s = 0; - int mx = damage[0]; - for (int& v : damage) { - s += v; - mx = max(mx, v); - } - return s - min(mx, armor) + 1; - } +class Solution { +public: + long long minimumHealth(vector& damage, int armor) { + long long s = 0; + int mx = damage[0]; + for (int& v : damage) { + s += v; + mx = max(mx, v); + } + return s - min(mx, armor) + 1; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2214.Minimum Health to Beat Game/Solution.java b/solution/2200-2299/2214.Minimum Health to Beat Game/Solution.java index 0ae90c736a765..1f199622477a3 100644 --- a/solution/2200-2299/2214.Minimum Health to Beat Game/Solution.java +++ b/solution/2200-2299/2214.Minimum Health to Beat Game/Solution.java @@ -1,11 +1,11 @@ -class Solution { - public long minimumHealth(int[] damage, int armor) { - long s = 0; - int mx = damage[0]; - for (int v : damage) { - s += v; - mx = Math.max(mx, v); - } - return s - Math.min(mx, armor) + 1; - } +class Solution { + public long minimumHealth(int[] damage, int armor) { + long s = 0; + int mx = damage[0]; + for (int v : damage) { + s += v; + mx = Math.max(mx, v); + } + return s - Math.min(mx, armor) + 1; + } } \ No newline at end of file diff --git a/solution/2200-2299/2214.Minimum Health to Beat Game/Solution.py b/solution/2200-2299/2214.Minimum Health to Beat Game/Solution.py index d79804b6076da..ff266baf2a989 100644 --- a/solution/2200-2299/2214.Minimum Health to Beat Game/Solution.py +++ b/solution/2200-2299/2214.Minimum Health to Beat Game/Solution.py @@ -1,3 +1,3 @@ -class Solution: - def minimumHealth(self, damage: List[int], armor: int) -> int: - return sum(damage) - min(max(damage), armor) + 1 +class Solution: + def minimumHealth(self, damage: List[int], armor: int) -> int: + return sum(damage) - min(max(damage), armor) + 1 diff --git a/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution.cpp b/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution.cpp index b88db1db12833..8879637fea128 100644 --- a/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution.cpp +++ b/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - vector> findDifference(vector& nums1, vector& nums2) { - unordered_set s1(nums1.begin(), nums1.end()); - unordered_set s2(nums2.begin(), nums2.end()); - vector> ans(2); - for (int v : s1) - if (!s2.count(v)) - ans[0].push_back(v); - for (int v : s2) - if (!s1.count(v)) - ans[1].push_back(v); - return ans; - } +class Solution { +public: + vector> findDifference(vector& nums1, vector& nums2) { + unordered_set s1(nums1.begin(), nums1.end()); + unordered_set s2(nums2.begin(), nums2.end()); + vector> ans(2); + for (int v : s1) + if (!s2.count(v)) + ans[0].push_back(v); + for (int v : s2) + if (!s1.count(v)) + ans[1].push_back(v); + return ans; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution.java b/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution.java index c058589122df5..6ff2a2fcf3985 100644 --- a/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution.java +++ b/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution.java @@ -1,31 +1,31 @@ -class Solution { - public List> findDifference(int[] nums1, int[] nums2) { - Set s1 = convert(nums1); - Set s2 = convert(nums2); - - List> ans = new ArrayList<>(); - List l1 = new ArrayList<>(); - List l2 = new ArrayList<>(); - for (int v : s1) { - if (!s2.contains(v)) { - l1.add(v); - } - } - for (int v : s2) { - if (!s1.contains(v)) { - l2.add(v); - } - } - ans.add(l1); - ans.add(l2); - return ans; - } - - private Set convert(int[] nums) { - Set s = new HashSet<>(); - for (int v : nums) { - s.add(v); - } - return s; - } +class Solution { + public List> findDifference(int[] nums1, int[] nums2) { + Set s1 = convert(nums1); + Set s2 = convert(nums2); + + List> ans = new ArrayList<>(); + List l1 = new ArrayList<>(); + List l2 = new ArrayList<>(); + for (int v : s1) { + if (!s2.contains(v)) { + l1.add(v); + } + } + for (int v : s2) { + if (!s1.contains(v)) { + l2.add(v); + } + } + ans.add(l1); + ans.add(l2); + return ans; + } + + private Set convert(int[] nums) { + Set s = new HashSet<>(); + for (int v : nums) { + s.add(v); + } + return s; + } } \ No newline at end of file diff --git a/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution.php b/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution.php index 68633a8d7fd8e..cbb366a94e7c5 100644 --- a/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution.php +++ b/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution.php @@ -22,4 +22,4 @@ function findDifference($nums1, $nums2) { } return $rs; } -} \ No newline at end of file +} diff --git a/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution.py b/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution.py index b6310c3fd1672..0a352801222e8 100644 --- a/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution.py +++ b/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution.py @@ -1,4 +1,4 @@ -class Solution: - def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: - s1, s2 = set(nums1), set(nums2) - return [list(s1 - s2), list(s2 - s1)] +class Solution: + def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: + s1, s2 = set(nums1), set(nums2) + return [list(s1 - s2), list(s2 - s1)] diff --git a/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution2.rs b/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution2.rs new file mode 100644 index 0000000000000..82c42f64d617c --- /dev/null +++ b/solution/2200-2299/2215.Find the Difference of Two Arrays/Solution2.rs @@ -0,0 +1,28 @@ +impl Solution { + pub fn find_difference(nums1: Vec, nums2: Vec) -> Vec> { + const N: usize = 2001; + let to_index = |i| (i as usize) + 1000; + + let mut is_in_nums1 = [false; N]; + let mut is_in_nums2 = [false; N]; + let mut res1 = vec![]; + let mut res2 = vec![]; + for &num in nums1.iter() { + is_in_nums1[to_index(num)] = true; + } + for &num in nums2.iter() { + is_in_nums2[to_index(num)] = true; + if !is_in_nums1[to_index(num)] { + res2.push(num); + is_in_nums1[to_index(num)] = true; + } + } + for &num in nums1.iter() { + if !is_in_nums2[to_index(num)] { + res1.push(num); + is_in_nums2[to_index(num)] = true; + } + } + vec![res1, res2] + } +} diff --git a/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution.cpp b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution.cpp index 764e5c5339136..5ba13dd0d8318 100644 --- a/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution.cpp +++ b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - int minDeletion(vector& nums) { - int n = nums.size(); - int ans = 0; - for (int i = 0; i < n - 1; ++i) { - if (nums[i] == nums[i + 1]) { - ++ans; - } else { - ++i; - } - } - ans += (n - ans) % 2; - return ans; - } +class Solution { +public: + int minDeletion(vector& nums) { + int n = nums.size(); + int ans = 0; + for (int i = 0; i < n - 1; ++i) { + if (nums[i] == nums[i + 1]) { + ++ans; + } else { + ++i; + } + } + ans += (n - ans) % 2; + return ans; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution.java b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution.java index b9ed2507f8fb8..72513c7c2d602 100644 --- a/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution.java +++ b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public int minDeletion(int[] nums) { - int n = nums.length; - int ans = 0; - for (int i = 0; i < n - 1; ++i) { - if (nums[i] == nums[i + 1]) { - ++ans; - } else { - ++i; - } - } - ans += (n - ans) % 2; - return ans; - } +class Solution { + public int minDeletion(int[] nums) { + int n = nums.length; + int ans = 0; + for (int i = 0; i < n - 1; ++i) { + if (nums[i] == nums[i + 1]) { + ++ans; + } else { + ++i; + } + } + ans += (n - ans) % 2; + return ans; + } } \ No newline at end of file diff --git a/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution.py b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution.py index 084aaf015c4b1..943b1234836e6 100644 --- a/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution.py +++ b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def minDeletion(self, nums: List[int]) -> int: - n = len(nums) - i = ans = 0 - while i < n - 1: - if nums[i] == nums[i + 1]: - ans += 1 - i += 1 - else: - i += 2 - ans += (n - ans) % 2 - return ans +class Solution: + def minDeletion(self, nums: List[int]) -> int: + n = len(nums) + i = ans = 0 + while i < n - 1: + if nums[i] == nums[i + 1]: + ans += 1 + i += 1 + else: + i += 2 + ans += (n - ans) % 2 + return ans diff --git a/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution2.cpp b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution2.cpp new file mode 100644 index 0000000000000..d05365fe16bc3 --- /dev/null +++ b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int minDeletion(vector& nums) { + int n = nums.size(); + int ans = 0; + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && nums[j] == nums[i]) { + ++j; + ++ans; + } + i = j + 1; + } + ans += (n - ans) % 2; + return ans; + } +}; \ No newline at end of file diff --git a/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution2.go b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution2.go new file mode 100644 index 0000000000000..5889556ae255d --- /dev/null +++ b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution2.go @@ -0,0 +1,12 @@ +func minDeletion(nums []int) (ans int) { + n := len(nums) + for i := 0; i < n; { + j := i + 1 + for ; j < n && nums[j] == nums[i]; j++ { + ans++ + } + i = j + 1 + } + ans += (n - ans) % 2 + return +} \ No newline at end of file diff --git a/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution2.java b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution2.java new file mode 100644 index 0000000000000..3192da152420c --- /dev/null +++ b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public int minDeletion(int[] nums) { + int n = nums.length; + int ans = 0; + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && nums[j] == nums[i]) { + ++j; + ++ans; + } + i = j + 1; + } + ans += (n - ans) % 2; + return ans; + } +} \ No newline at end of file diff --git a/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution2.py b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution2.py new file mode 100644 index 0000000000000..30f85119e19af --- /dev/null +++ b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def minDeletion(self, nums: List[int]) -> int: + n = len(nums) + ans = i = 0 + while i < n: + j = i + 1 + while j < n and nums[j] == nums[i]: + j += 1 + ans += 1 + i = j + 1 + ans += (n - ans) % 2 + return ans diff --git a/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution2.rs b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution2.rs new file mode 100644 index 0000000000000..3e015db62aeda --- /dev/null +++ b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution2.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn min_deletion(nums: Vec) -> i32 { + let n = nums.len(); + let mut ans = 0; + let mut i = 0; + while i < n { + let mut j = i + 1; + while j < n && nums[j] == nums[i] { + ans += 1; + j += 1; + } + i = j + 1; + } + ans += (n - ans) % 2; + ans as i32 + } +} diff --git a/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution2.ts b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution2.ts new file mode 100644 index 0000000000000..e4ea192606592 --- /dev/null +++ b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution2.ts @@ -0,0 +1,13 @@ +function minDeletion(nums: number[]): number { + const n = nums.length; + let ans = 0; + for (let i = 0; i < n; ) { + let j = i + 1; + for (; j < n && nums[j] === nums[i]; ++j) { + ++ans; + } + i = j + 1; + } + ans += (n - ans) % 2; + return ans; +} diff --git a/solution/2200-2299/2218.Maximum Value of K Coins From Piles/Solution.py b/solution/2200-2299/2218.Maximum Value of K Coins From Piles/Solution.py index cbf2272622475..7f5d6a9004b4f 100644 --- a/solution/2200-2299/2218.Maximum Value of K Coins From Piles/Solution.py +++ b/solution/2200-2299/2218.Maximum Value of K Coins From Piles/Solution.py @@ -1,10 +1,11 @@ class Solution: def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int: presum = [list(accumulate(p, initial=0)) for p in piles] - dp = [0] * (k + 1) - for s in presum: - for j in range(k, -1, -1): + n = len(piles) + dp = [[0] * (k + 1) for _ in range(n + 1)] + for i, s in enumerate(presum, 1): + for j in range(k + 1): for idx, v in enumerate(s): if j >= idx: - dp[j] = max(dp[j], dp[j - idx] + v) - return dp[-1] + dp[i][j] = max(dp[i][j], dp[i - 1][j - idx] + v) + return dp[-1][-1] diff --git a/solution/2200-2299/2218.Maximum Value of K Coins From Piles/Solution2.py b/solution/2200-2299/2218.Maximum Value of K Coins From Piles/Solution2.py new file mode 100644 index 0000000000000..cbf2272622475 --- /dev/null +++ b/solution/2200-2299/2218.Maximum Value of K Coins From Piles/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int: + presum = [list(accumulate(p, initial=0)) for p in piles] + dp = [0] * (k + 1) + for s in presum: + for j in range(k, -1, -1): + for idx, v in enumerate(s): + if j >= idx: + dp[j] = max(dp[j], dp[j - idx] + v) + return dp[-1] diff --git a/solution/2200-2299/2219.Maximum Sum Score of Array/Solution.cpp b/solution/2200-2299/2219.Maximum Sum Score of Array/Solution.cpp index 0d1e6762e5c15..916abcc987fd8 100644 --- a/solution/2200-2299/2219.Maximum Sum Score of Array/Solution.cpp +++ b/solution/2200-2299/2219.Maximum Sum Score of Array/Solution.cpp @@ -1,11 +1,11 @@ -class Solution { -public: - long long maximumSumScore(vector& nums) { - int n = nums.size(); - vector s(n + 1); - for (int i = 0; i < n; ++i) s[i + 1] = s[i] + nums[i]; - long long ans = INT_MIN; - for (int i = 0; i < n; ++i) ans = max(ans, max(s[i + 1], s[n] - s[i])); - return ans; - } +class Solution { +public: + long long maximumSumScore(vector& nums) { + int n = nums.size(); + vector s(n + 1); + for (int i = 0; i < n; ++i) s[i + 1] = s[i] + nums[i]; + long long ans = INT_MIN; + for (int i = 0; i < n; ++i) ans = max(ans, max(s[i + 1], s[n] - s[i])); + return ans; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2219.Maximum Sum Score of Array/Solution.java b/solution/2200-2299/2219.Maximum Sum Score of Array/Solution.java index 5aefff66ad047..d754fa4eb72c6 100644 --- a/solution/2200-2299/2219.Maximum Sum Score of Array/Solution.java +++ b/solution/2200-2299/2219.Maximum Sum Score of Array/Solution.java @@ -1,14 +1,14 @@ -class Solution { - public long maximumSumScore(int[] nums) { - int n = nums.length; - long[] s = new long[n + 1]; - for (int i = 0; i < n; ++i) { - s[i + 1] = s[i] + nums[i]; - } - long ans = Long.MIN_VALUE; - for (int i = 0; i < n; ++i) { - ans = Math.max(ans, Math.max(s[i + 1], s[n] - s[i])); - } - return ans; - } +class Solution { + public long maximumSumScore(int[] nums) { + int n = nums.length; + long[] s = new long[n + 1]; + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + long ans = Long.MIN_VALUE; + for (int i = 0; i < n; ++i) { + ans = Math.max(ans, Math.max(s[i + 1], s[n] - s[i])); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2200-2299/2219.Maximum Sum Score of Array/Solution.py b/solution/2200-2299/2219.Maximum Sum Score of Array/Solution.py index 35ff939c4b4a7..6b8795fe3ebc2 100644 --- a/solution/2200-2299/2219.Maximum Sum Score of Array/Solution.py +++ b/solution/2200-2299/2219.Maximum Sum Score of Array/Solution.py @@ -1,4 +1,4 @@ -class Solution: - def maximumSumScore(self, nums: List[int]) -> int: - s = [0] + list(accumulate(nums)) - return max(max(s[i + 1], s[-1] - s[i]) for i in range(len(nums))) +class Solution: + def maximumSumScore(self, nums: List[int]) -> int: + s = [0] + list(accumulate(nums)) + return max(max(s[i + 1], s[-1] - s[i]) for i in range(len(nums))) diff --git a/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/Solution.c b/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/Solution.c index 32efd6b123a29..00ab3a363bb2f 100644 --- a/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/Solution.c +++ b/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/Solution.c @@ -6,4 +6,4 @@ int minBitFlips(int start, int goal) { tmp >>= 1; } return ans; -} +} \ No newline at end of file diff --git a/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/Solution.cpp b/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/Solution.cpp index 06604f2c98b3d..92e676e7dbb69 100644 --- a/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/Solution.cpp +++ b/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/Solution.cpp @@ -1,12 +1,12 @@ -class Solution { -public: - int minBitFlips(int start, int goal) { - int t = start ^ goal; - int ans = 0; - while (t) { - ans += t & 1; - t >>= 1; - } - return ans; - } +class Solution { +public: + int minBitFlips(int start, int goal) { + int t = start ^ goal; + int ans = 0; + while (t) { + ans += t & 1; + t >>= 1; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/Solution.java b/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/Solution.java index 20a94d9e371b7..5b202baf2104c 100644 --- a/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/Solution.java +++ b/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/Solution.java @@ -1,11 +1,11 @@ -class Solution { - public int minBitFlips(int start, int goal) { - int t = start ^ goal; - int ans = 0; - while (t != 0) { - ans += t & 1; - t >>= 1; - } - return ans; - } +class Solution { + public int minBitFlips(int start, int goal) { + int t = start ^ goal; + int ans = 0; + while (t != 0) { + ans += t & 1; + t >>= 1; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/Solution.py b/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/Solution.py index ef32c0dd63cb1..5eb42286a6695 100644 --- a/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/Solution.py +++ b/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/Solution.py @@ -1,8 +1,8 @@ -class Solution: - def minBitFlips(self, start: int, goal: int) -> int: - t = start ^ goal - ans = 0 - while t: - ans += t & 1 - t >>= 1 - return ans +class Solution: + def minBitFlips(self, start: int, goal: int) -> int: + t = start ^ goal + ans = 0 + while t: + ans += t & 1 + t >>= 1 + return ans diff --git a/solution/2200-2299/2221.Find Triangular Sum of an Array/Solution.cpp b/solution/2200-2299/2221.Find Triangular Sum of an Array/Solution.cpp index d62aace77f57d..44ac097bb2420 100644 --- a/solution/2200-2299/2221.Find Triangular Sum of an Array/Solution.cpp +++ b/solution/2200-2299/2221.Find Triangular Sum of an Array/Solution.cpp @@ -1,10 +1,10 @@ -class Solution { -public: - int triangularSum(vector& nums) { - int n = nums.size(); - for (int i = n; i >= 0; --i) - for (int j = 0; j < i - 1; ++j) - nums[j] = (nums[j] + nums[j + 1]) % 10; - return nums[0]; - } +class Solution { +public: + int triangularSum(vector& nums) { + int n = nums.size(); + for (int i = n; i >= 0; --i) + for (int j = 0; j < i - 1; ++j) + nums[j] = (nums[j] + nums[j + 1]) % 10; + return nums[0]; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2221.Find Triangular Sum of an Array/Solution.java b/solution/2200-2299/2221.Find Triangular Sum of an Array/Solution.java index 4da5c2931ab16..aaf52d63cecc7 100644 --- a/solution/2200-2299/2221.Find Triangular Sum of an Array/Solution.java +++ b/solution/2200-2299/2221.Find Triangular Sum of an Array/Solution.java @@ -1,11 +1,11 @@ -class Solution { - public int triangularSum(int[] nums) { - int n = nums.length; - for (int i = n; i >= 0; --i) { - for (int j = 0; j < i - 1; ++j) { - nums[j] = (nums[j] + nums[j + 1]) % 10; - } - } - return nums[0]; - } +class Solution { + public int triangularSum(int[] nums) { + int n = nums.length; + for (int i = n; i >= 0; --i) { + for (int j = 0; j < i - 1; ++j) { + nums[j] = (nums[j] + nums[j + 1]) % 10; + } + } + return nums[0]; + } } \ No newline at end of file diff --git a/solution/2200-2299/2221.Find Triangular Sum of an Array/Solution.py b/solution/2200-2299/2221.Find Triangular Sum of an Array/Solution.py index 1844d2c190c8a..ed6981b63e65e 100644 --- a/solution/2200-2299/2221.Find Triangular Sum of an Array/Solution.py +++ b/solution/2200-2299/2221.Find Triangular Sum of an Array/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def triangularSum(self, nums: List[int]) -> int: - n = len(nums) - for i in range(n, 0, -1): - for j in range(i - 1): - nums[j] = (nums[j] + nums[j + 1]) % 10 - return nums[0] +class Solution: + def triangularSum(self, nums: List[int]) -> int: + n = len(nums) + for i in range(n, 0, -1): + for j in range(i - 1): + nums[j] = (nums[j] + nums[j + 1]) % 10 + return nums[0] diff --git a/solution/2200-2299/2229.Check if an Array Is Consecutive/Solution.cpp b/solution/2200-2299/2229.Check if an Array Is Consecutive/Solution.cpp index 4f00ec9952088..d464e98b7172b 100644 --- a/solution/2200-2299/2229.Check if an Array Is Consecutive/Solution.cpp +++ b/solution/2200-2299/2229.Check if an Array Is Consecutive/Solution.cpp @@ -1,10 +1,10 @@ -class Solution { -public: - bool isConsecutive(vector& nums) { - unordered_set s(nums.begin(), nums.end()); - int mi = *min_element(nums.begin(), nums.end()); - int mx = *max_element(nums.begin(), nums.end()); - int n = nums.size(); - return s.size() == n && mx == mi + n - 1; - } +class Solution { +public: + bool isConsecutive(vector& nums) { + unordered_set s(nums.begin(), nums.end()); + int mi = *min_element(nums.begin(), nums.end()); + int mx = *max_element(nums.begin(), nums.end()); + int n = nums.size(); + return s.size() == n && mx == mi + n - 1; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2229.Check if an Array Is Consecutive/Solution.java b/solution/2200-2299/2229.Check if an Array Is Consecutive/Solution.java index 65b0fdcbafd4a..e58dbdaa3d138 100644 --- a/solution/2200-2299/2229.Check if an Array Is Consecutive/Solution.java +++ b/solution/2200-2299/2229.Check if an Array Is Consecutive/Solution.java @@ -1,14 +1,14 @@ -class Solution { - public boolean isConsecutive(int[] nums) { - int mi = nums[0]; - int mx = nums[0]; - Set s = new HashSet<>(); - for (int v : nums) { - mi = Math.min(mi, v); - mx = Math.max(mx, v); - s.add(v); - } - int n = nums.length; - return s.size() == n && mx == mi + n - 1; - } +class Solution { + public boolean isConsecutive(int[] nums) { + int mi = nums[0]; + int mx = nums[0]; + Set s = new HashSet<>(); + for (int v : nums) { + mi = Math.min(mi, v); + mx = Math.max(mx, v); + s.add(v); + } + int n = nums.length; + return s.size() == n && mx == mi + n - 1; + } } \ No newline at end of file diff --git a/solution/2200-2299/2229.Check if an Array Is Consecutive/Solution.py b/solution/2200-2299/2229.Check if an Array Is Consecutive/Solution.py index a1f64a6e2dbe4..f44b88be569a9 100644 --- a/solution/2200-2299/2229.Check if an Array Is Consecutive/Solution.py +++ b/solution/2200-2299/2229.Check if an Array Is Consecutive/Solution.py @@ -1,5 +1,5 @@ -class Solution: - def isConsecutive(self, nums: List[int]) -> bool: - mi, mx = min(nums), max(nums) - n = len(nums) - return len(set(nums)) == n and mx == mi + n - 1 +class Solution: + def isConsecutive(self, nums: List[int]) -> bool: + mi, mx = min(nums), max(nums) + n = len(nums) + return len(set(nums)) == n and mx == mi + n - 1 diff --git a/solution/2200-2299/2235.Add Two Integers/Solution.c b/solution/2200-2299/2235.Add Two Integers/Solution.c index 1910b3e30f8ea..808a0f24fb347 100644 --- a/solution/2200-2299/2235.Add Two Integers/Solution.c +++ b/solution/2200-2299/2235.Add Two Integers/Solution.c @@ -1,3 +1,3 @@ int sum(int num1, int num2) { return num1 + num2; -} +} \ No newline at end of file diff --git a/solution/2200-2299/2235.Add Two Integers/Solution.cpp b/solution/2200-2299/2235.Add Two Integers/Solution.cpp index db1939d9a2798..cda7e7603edf6 100644 --- a/solution/2200-2299/2235.Add Two Integers/Solution.cpp +++ b/solution/2200-2299/2235.Add Two Integers/Solution.cpp @@ -1,6 +1,6 @@ -class Solution { -public: - int sum(int num1, int num2) { - return num1 + num2; - } +class Solution { +public: + int sum(int num1, int num2) { + return num1 + num2; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2235.Add Two Integers/Solution.java b/solution/2200-2299/2235.Add Two Integers/Solution.java index a7dbb7174c738..21b3f0bbeaa51 100644 --- a/solution/2200-2299/2235.Add Two Integers/Solution.java +++ b/solution/2200-2299/2235.Add Two Integers/Solution.java @@ -1,5 +1,5 @@ -class Solution { - public int sum(int num1, int num2) { - return num1 + num2; - } +class Solution { + public int sum(int num1, int num2) { + return num1 + num2; + } } \ No newline at end of file diff --git a/solution/2200-2299/2235.Add Two Integers/Solution.py b/solution/2200-2299/2235.Add Two Integers/Solution.py index 67e6af8b24e1c..29d001ddbddd3 100644 --- a/solution/2200-2299/2235.Add Two Integers/Solution.py +++ b/solution/2200-2299/2235.Add Two Integers/Solution.py @@ -1,3 +1,3 @@ -class Solution: - def sum(self, num1: int, num2: int) -> int: - return num1 + num2 +class Solution: + def sum(self, num1: int, num2: int) -> int: + return num1 + num2 diff --git a/solution/2200-2299/2235.Add Two Integers/Solution2.cpp b/solution/2200-2299/2235.Add Two Integers/Solution2.cpp new file mode 100644 index 0000000000000..4403a46884097 --- /dev/null +++ b/solution/2200-2299/2235.Add Two Integers/Solution2.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int sum(int num1, int num2) { + while (num2) { + unsigned int carry = (unsigned int) (num1 & num2) << 1; + num1 ^= num2; + num2 = carry; + } + return num1; + } +}; \ No newline at end of file diff --git a/solution/2200-2299/2235.Add Two Integers/Solution2.go b/solution/2200-2299/2235.Add Two Integers/Solution2.go new file mode 100644 index 0000000000000..845661f864740 --- /dev/null +++ b/solution/2200-2299/2235.Add Two Integers/Solution2.go @@ -0,0 +1,8 @@ +func sum(num1 int, num2 int) int { + for num2 != 0 { + carry := (num1 & num2) << 1 + num1 ^= num2 + num2 = carry + } + return num1 +} \ No newline at end of file diff --git a/solution/2200-2299/2235.Add Two Integers/Solution2.java b/solution/2200-2299/2235.Add Two Integers/Solution2.java new file mode 100644 index 0000000000000..eca6e23bf1f66 --- /dev/null +++ b/solution/2200-2299/2235.Add Two Integers/Solution2.java @@ -0,0 +1,10 @@ +class Solution { + public int sum(int num1, int num2) { + while (num2 != 0) { + int carry = (num1 & num2) << 1; + num1 ^= num2; + num2 = carry; + } + return num1; + } +} \ No newline at end of file diff --git a/solution/2200-2299/2235.Add Two Integers/Solution2.py b/solution/2200-2299/2235.Add Two Integers/Solution2.py new file mode 100644 index 0000000000000..c47ec0d455a54 --- /dev/null +++ b/solution/2200-2299/2235.Add Two Integers/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def sum(self, num1: int, num2: int) -> int: + num1, num2 = num1 & 0xFFFFFFFF, num2 & 0xFFFFFFFF + while num2: + carry = ((num1 & num2) << 1) & 0xFFFFFFFF + num1, num2 = num1 ^ num2, carry + return num1 if num1 < 0x80000000 else ~(num1 ^ 0xFFFFFFFF) diff --git a/solution/2200-2299/2235.Add Two Integers/Solution2.rs b/solution/2200-2299/2235.Add Two Integers/Solution2.rs new file mode 100644 index 0000000000000..94a64a4d84665 --- /dev/null +++ b/solution/2200-2299/2235.Add Two Integers/Solution2.rs @@ -0,0 +1,12 @@ +impl Solution { + pub fn sum(num1: i32, num2: i32) -> i32 { + let mut num1 = num1; + let mut num2 = num2; + while num2 != 0 { + let carry = (num1 & num2) << 1; + num1 ^= num2; + num2 = carry; + } + num1 + } +} diff --git a/solution/2200-2299/2235.Add Two Integers/Solution2.ts b/solution/2200-2299/2235.Add Two Integers/Solution2.ts new file mode 100644 index 0000000000000..d3d11a049905e --- /dev/null +++ b/solution/2200-2299/2235.Add Two Integers/Solution2.ts @@ -0,0 +1,8 @@ +function sum(num1: number, num2: number): number { + while (num2) { + const carry = (num1 & num2) << 1; + num1 ^= num2; + num2 = carry; + } + return num1; +} diff --git a/solution/2200-2299/2236.Root Equals Sum of Children/Solution.c b/solution/2200-2299/2236.Root Equals Sum of Children/Solution.c index abd63ccabec75..031ef50b5ccc4 100644 --- a/solution/2200-2299/2236.Root Equals Sum of Children/Solution.c +++ b/solution/2200-2299/2236.Root Equals Sum of Children/Solution.c @@ -9,4 +9,4 @@ bool checkTree(struct TreeNode* root) { return root->val == root->left->val + root->right->val; -} +} \ No newline at end of file diff --git a/solution/2200-2299/2236.Root Equals Sum of Children/Solution.cpp b/solution/2200-2299/2236.Root Equals Sum of Children/Solution.cpp index ef399a064a741..f9928150f7bda 100644 --- a/solution/2200-2299/2236.Root Equals Sum of Children/Solution.cpp +++ b/solution/2200-2299/2236.Root Equals Sum of Children/Solution.cpp @@ -1,17 +1,17 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - bool checkTree(TreeNode* root) { - return root->val == root->left->val + root->right->val; - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool checkTree(TreeNode* root) { + return root->val == root->left->val + root->right->val; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2236.Root Equals Sum of Children/Solution.java b/solution/2200-2299/2236.Root Equals Sum of Children/Solution.java index 5843f312af9aa..1db47f909844d 100644 --- a/solution/2200-2299/2236.Root Equals Sum of Children/Solution.java +++ b/solution/2200-2299/2236.Root Equals Sum of Children/Solution.java @@ -1,20 +1,20 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public boolean checkTree(TreeNode root) { - return root.val == root.left.val + root.right.val; - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean checkTree(TreeNode root) { + return root.val == root.left.val + root.right.val; + } } \ No newline at end of file diff --git a/solution/2200-2299/2236.Root Equals Sum of Children/Solution.py b/solution/2200-2299/2236.Root Equals Sum of Children/Solution.py index 7d07bbd46148d..d6b5398df608d 100644 --- a/solution/2200-2299/2236.Root Equals Sum of Children/Solution.py +++ b/solution/2200-2299/2236.Root Equals Sum of Children/Solution.py @@ -1,9 +1,9 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def checkTree(self, root: Optional[TreeNode]) -> bool: - return root.val == root.left.val + root.right.val +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def checkTree(self, root: Optional[TreeNode]) -> bool: + return root.val == root.left.val + root.right.val diff --git a/solution/2200-2299/2237.Count Positions on Street With Required Brightness/Solution.cpp b/solution/2200-2299/2237.Count Positions on Street With Required Brightness/Solution.cpp index 86d9c812c8ee9..c65992f931c1d 100644 --- a/solution/2200-2299/2237.Count Positions on Street With Required Brightness/Solution.cpp +++ b/solution/2200-2299/2237.Count Positions on Street With Required Brightness/Solution.cpp @@ -1,17 +1,17 @@ -class Solution { -public: - int meetRequirement(int n, vector>& lights, vector& requirement) { - vector d(100010); - for (auto& e : lights) { - int i = max(0, e[0] - e[1]), j = min(n - 1, e[0] + e[1]); - ++d[i]; - --d[j + 1]; - } - int s = 0, ans = 0; - for (int i = 0; i < n; ++i) { - s += d[i]; - if (s >= requirement[i]) ++ans; - } - return ans; - } +class Solution { +public: + int meetRequirement(int n, vector>& lights, vector& requirement) { + vector d(100010); + for (auto& e : lights) { + int i = max(0, e[0] - e[1]), j = min(n - 1, e[0] + e[1]); + ++d[i]; + --d[j + 1]; + } + int s = 0, ans = 0; + for (int i = 0; i < n; ++i) { + s += d[i]; + if (s >= requirement[i]) ++ans; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2237.Count Positions on Street With Required Brightness/Solution.java b/solution/2200-2299/2237.Count Positions on Street With Required Brightness/Solution.java index 8ed1a7ab7db76..400223cb61b3b 100644 --- a/solution/2200-2299/2237.Count Positions on Street With Required Brightness/Solution.java +++ b/solution/2200-2299/2237.Count Positions on Street With Required Brightness/Solution.java @@ -1,20 +1,20 @@ -class Solution { - public int meetRequirement(int n, int[][] lights, int[] requirement) { - int[] d = new int[100010]; - for (int[] e : lights) { - int i = Math.max(0, e[0] - e[1]); - int j = Math.min(n - 1, e[0] + e[1]); - ++d[i]; - --d[j + 1]; - } - int s = 0; - int ans = 0; - for (int i = 0; i < n; ++i) { - s += d[i]; - if (s >= requirement[i]) { - ++ans; - } - } - return ans; - } +class Solution { + public int meetRequirement(int n, int[][] lights, int[] requirement) { + int[] d = new int[100010]; + for (int[] e : lights) { + int i = Math.max(0, e[0] - e[1]); + int j = Math.min(n - 1, e[0] + e[1]); + ++d[i]; + --d[j + 1]; + } + int s = 0; + int ans = 0; + for (int i = 0; i < n; ++i) { + s += d[i]; + if (s >= requirement[i]) { + ++ans; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2200-2299/2237.Count Positions on Street With Required Brightness/Solution.py b/solution/2200-2299/2237.Count Positions on Street With Required Brightness/Solution.py index 623d8e83420f4..2f321f5440db9 100644 --- a/solution/2200-2299/2237.Count Positions on Street With Required Brightness/Solution.py +++ b/solution/2200-2299/2237.Count Positions on Street With Required Brightness/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def meetRequirement( - self, n: int, lights: List[List[int]], requirement: List[int] - ) -> int: - d = [0] * 100010 - for p, r in lights: - i, j = max(0, p - r), min(n - 1, p + r) - d[i] += 1 - d[j + 1] -= 1 - return sum(s >= r for s, r in zip(accumulate(d), requirement)) +class Solution: + def meetRequirement( + self, n: int, lights: List[List[int]], requirement: List[int] + ) -> int: + d = [0] * 100010 + for p, r in lights: + i, j = max(0, p - r), min(n - 1, p + r) + d[i] += 1 + d[j + 1] -= 1 + return sum(s >= r for s, r in zip(accumulate(d), requirement)) diff --git a/solution/2200-2299/2243.Calculate Digit Sum of a String/Solution2.py b/solution/2200-2299/2243.Calculate Digit Sum of a String/Solution2.py new file mode 100644 index 0000000000000..99b32441c75b8 --- /dev/null +++ b/solution/2200-2299/2243.Calculate Digit Sum of a String/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def digitSum(self, s: str, k: int) -> str: + if len(s) <= k: + return s + t = [] + while s: + t.append(str(sum(int(v) for v in s[:k]))) + s = s[k:] + return self.digitSum(''.join(t), k) diff --git a/solution/2200-2299/2244.Minimum Rounds to Complete All Tasks/Solution.ts b/solution/2200-2299/2244.Minimum Rounds to Complete All Tasks/Solution.ts new file mode 100644 index 0000000000000..8830dc79b9cc0 --- /dev/null +++ b/solution/2200-2299/2244.Minimum Rounds to Complete All Tasks/Solution.ts @@ -0,0 +1,14 @@ +function minimumRounds(tasks: number[]): number { + const cnt = new Map(); + for (const t of tasks) { + cnt.set(t, (cnt.get(t) || 0) + 1); + } + let ans = 0; + for (const v of cnt.values()) { + if (v == 1) { + return -1; + } + ans += Math.floor(v / 3) + (v % 3 === 0 ? 0 : 1); + } + return ans; +} diff --git a/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/Solution.cpp b/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/Solution.cpp index 8eab721ee939d..ac41c8175075c 100644 --- a/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/Solution.cpp +++ b/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/Solution.cpp @@ -1,24 +1,24 @@ -class Solution { -public: - int longestPath(vector& parent, string s) { - int n = parent.size(); - vector g[n]; - for (int i = 1; i < n; ++i) { - g[parent[i]].push_back(i); - } - int ans = 0; - function dfs = [&](int i) -> int { - int mx = 0; - for (int j : g[i]) { - int x = dfs(j) + 1; - if (s[i] != s[j]) { - ans = max(ans, mx + x); - mx = max(mx, x); - } - } - return mx; - }; - dfs(0); - return ans + 1; - } +class Solution { +public: + int longestPath(vector& parent, string s) { + int n = parent.size(); + vector g[n]; + for (int i = 1; i < n; ++i) { + g[parent[i]].push_back(i); + } + int ans = 0; + function dfs = [&](int i) -> int { + int mx = 0; + for (int j : g[i]) { + int x = dfs(j) + 1; + if (s[i] != s[j]) { + ans = max(ans, mx + x); + mx = max(mx, x); + } + } + return mx; + }; + dfs(0); + return ans + 1; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/Solution.java b/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/Solution.java index 7b9de3b4f96f5..48fb4543c64c1 100644 --- a/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/Solution.java +++ b/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/Solution.java @@ -1,29 +1,29 @@ -class Solution { - private List[] g; - private String s; - private int ans; - - public int longestPath(int[] parent, String s) { - int n = parent.length; - g = new List[n]; - this.s = s; - Arrays.setAll(g, k -> new ArrayList<>()); - for (int i = 1; i < n; ++i) { - g[parent[i]].add(i); - } - dfs(0); - return ans + 1; - } - - private int dfs(int i) { - int mx = 0; - for (int j : g[i]) { - int x = dfs(j) + 1; - if (s.charAt(i) != s.charAt(j)) { - ans = Math.max(ans, mx + x); - mx = Math.max(mx, x); - } - } - return mx; - } +class Solution { + private List[] g; + private String s; + private int ans; + + public int longestPath(int[] parent, String s) { + int n = parent.length; + g = new List[n]; + this.s = s; + Arrays.setAll(g, k -> new ArrayList<>()); + for (int i = 1; i < n; ++i) { + g[parent[i]].add(i); + } + dfs(0); + return ans + 1; + } + + private int dfs(int i) { + int mx = 0; + for (int j : g[i]) { + int x = dfs(j) + 1; + if (s.charAt(i) != s.charAt(j)) { + ans = Math.max(ans, mx + x); + mx = Math.max(mx, x); + } + } + return mx; + } } \ No newline at end of file diff --git a/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/Solution.py b/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/Solution.py index 030bc59014368..a2a595e032b9e 100644 --- a/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/Solution.py +++ b/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/Solution.py @@ -1,18 +1,18 @@ -class Solution: - def longestPath(self, parent: List[int], s: str) -> int: - def dfs(i: int) -> int: - mx = 0 - nonlocal ans - for j in g[i]: - x = dfs(j) + 1 - if s[i] != s[j]: - ans = max(ans, mx + x) - mx = max(mx, x) - return mx - - g = defaultdict(list) - for i in range(1, len(parent)): - g[parent[i]].append(i) - ans = 0 - dfs(0) - return ans + 1 +class Solution: + def longestPath(self, parent: List[int], s: str) -> int: + def dfs(i: int) -> int: + mx = 0 + nonlocal ans + for j in g[i]: + x = dfs(j) + 1 + if s[i] != s[j]: + ans = max(ans, mx + x) + mx = max(mx, x) + return mx + + g = defaultdict(list) + for i in range(1, len(parent)): + g[parent[i]].append(i) + ans = 0 + dfs(0) + return ans + 1 diff --git a/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/Solution.cpp b/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/Solution.cpp index 3405c2b3d9291..7c1b5bde144e3 100644 --- a/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/Solution.cpp +++ b/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/Solution.cpp @@ -1,35 +1,35 @@ -class Solution { -public: - int maximumCost(int n, vector>& highways, int k) { - if (k >= n) { - return -1; - } - vector> g[n]; - for (auto& h : highways) { - int a = h[0], b = h[1], cost = h[2]; - g[a].emplace_back(b, cost); - g[b].emplace_back(a, cost); - } - int f[1 << n][n]; - memset(f, -0x3f, sizeof(f)); - for (int i = 0; i < n; ++i) { - f[1 << i][i] = 0; - } - int ans = -1; - for (int i = 0; i < 1 << n; ++i) { - for (int j = 0; j < n; ++j) { - if (i >> j & 1) { - for (auto& [h, cost] : g[j]) { - if (i >> h & 1) { - f[i][j] = max(f[i][j], f[i ^ (1 << j)][h] + cost); - } - } - } - if (__builtin_popcount(i) == k + 1) { - ans = max(ans, f[i][j]); - } - } - } - return ans; - } +class Solution { +public: + int maximumCost(int n, vector>& highways, int k) { + if (k >= n) { + return -1; + } + vector> g[n]; + for (auto& h : highways) { + int a = h[0], b = h[1], cost = h[2]; + g[a].emplace_back(b, cost); + g[b].emplace_back(a, cost); + } + int f[1 << n][n]; + memset(f, -0x3f, sizeof(f)); + for (int i = 0; i < n; ++i) { + f[1 << i][i] = 0; + } + int ans = -1; + for (int i = 0; i < 1 << n; ++i) { + for (int j = 0; j < n; ++j) { + if (i >> j & 1) { + for (auto& [h, cost] : g[j]) { + if (i >> h & 1) { + f[i][j] = max(f[i][j], f[i ^ (1 << j)][h] + cost); + } + } + } + if (__builtin_popcount(i) == k + 1) { + ans = max(ans, f[i][j]); + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/Solution.java b/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/Solution.java index a9d6c1a000bf2..50499d7f434d4 100644 --- a/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/Solution.java +++ b/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/Solution.java @@ -1,38 +1,38 @@ -class Solution { - public int maximumCost(int n, int[][] highways, int k) { - if (k >= n) { - return -1; - } - List[] g = new List[n]; - Arrays.setAll(g, h -> new ArrayList<>()); - for (int[] h : highways) { - int a = h[0], b = h[1], cost = h[2]; - g[a].add(new int[] {b, cost}); - g[b].add(new int[] {a, cost}); - } - int[][] f = new int[1 << n][n]; - for (int[] e : f) { - Arrays.fill(e, -(1 << 30)); - } - for (int i = 0; i < n; ++i) { - f[1 << i][i] = 0; - } - int ans = -1; - for (int i = 0; i < 1 << n; ++i) { - for (int j = 0; j < n; ++j) { - if ((i >> j & 1) == 1) { - for (var e : g[j]) { - int h = e[0], cost = e[1]; - if ((i >> h & 1) == 1) { - f[i][j] = Math.max(f[i][j], f[i ^ (1 << j)][h] + cost); - } - } - } - if (Integer.bitCount(i) == k + 1) { - ans = Math.max(ans, f[i][j]); - } - } - } - return ans; - } +class Solution { + public int maximumCost(int n, int[][] highways, int k) { + if (k >= n) { + return -1; + } + List[] g = new List[n]; + Arrays.setAll(g, h -> new ArrayList<>()); + for (int[] h : highways) { + int a = h[0], b = h[1], cost = h[2]; + g[a].add(new int[] {b, cost}); + g[b].add(new int[] {a, cost}); + } + int[][] f = new int[1 << n][n]; + for (int[] e : f) { + Arrays.fill(e, -(1 << 30)); + } + for (int i = 0; i < n; ++i) { + f[1 << i][i] = 0; + } + int ans = -1; + for (int i = 0; i < 1 << n; ++i) { + for (int j = 0; j < n; ++j) { + if ((i >> j & 1) == 1) { + for (var e : g[j]) { + int h = e[0], cost = e[1]; + if ((i >> h & 1) == 1) { + f[i][j] = Math.max(f[i][j], f[i ^ (1 << j)][h] + cost); + } + } + } + if (Integer.bitCount(i) == k + 1) { + ans = Math.max(ans, f[i][j]); + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/Solution.py b/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/Solution.py index 291aed4b21630..9c9681473fa52 100644 --- a/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/Solution.py +++ b/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/Solution.py @@ -1,21 +1,21 @@ -class Solution: - def maximumCost(self, n: int, highways: List[List[int]], k: int) -> int: - if k >= n: - return -1 - g = defaultdict(list) - for a, b, cost in highways: - g[a].append((b, cost)) - g[b].append((a, cost)) - f = [[-inf] * n for _ in range(1 << n)] - for i in range(n): - f[1 << i][i] = 0 - ans = -1 - for i in range(1 << n): - for j in range(n): - if i >> j & 1: - for h, cost in g[j]: - if i >> h & 1: - f[i][j] = max(f[i][j], f[i ^ (1 << j)][h] + cost) - if i.bit_count() == k + 1: - ans = max(ans, f[i][j]) - return ans +class Solution: + def maximumCost(self, n: int, highways: List[List[int]], k: int) -> int: + if k >= n: + return -1 + g = defaultdict(list) + for a, b, cost in highways: + g[a].append((b, cost)) + g[b].append((a, cost)) + f = [[-inf] * n for _ in range(1 << n)] + for i in range(n): + f[1 << i][i] = 0 + ans = -1 + for i in range(1 << n): + for j in range(n): + if i >> j & 1: + for h, cost in g[j]: + if i >> h & 1: + f[i][j] = max(f[i][j], f[i ^ (1 << j)][h] + cost) + if i.bit_count() == k + 1: + ans = max(ans, f[i][j]) + return ans diff --git a/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution.php b/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution.php index de4643c5237ce..653de822097b7 100644 --- a/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution.php +++ b/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution.php @@ -16,4 +16,4 @@ function intersection($nums) { sort($rs); return $rs; } -} \ No newline at end of file +} diff --git a/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution2.cpp b/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution2.cpp new file mode 100644 index 0000000000000..98cf16ee0e4e1 --- /dev/null +++ b/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector intersection(vector>& nums) { + unordered_map cnt; + vector ans; + for (auto& arr : nums) { + for (int& x : arr) { + if (++cnt[x] == nums.size()) { + ans.push_back(x); + } + } + } + sort(ans.begin(), ans.end()); + return ans; + } +}; \ No newline at end of file diff --git a/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution2.go b/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution2.go new file mode 100644 index 0000000000000..553a3ef03806f --- /dev/null +++ b/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution2.go @@ -0,0 +1,13 @@ +func intersection(nums [][]int) (ans []int) { + cnt := map[int]int{} + for _, arr := range nums { + for _, x := range arr { + cnt[x]++ + if cnt[x] == len(nums) { + ans = append(ans, x) + } + } + } + sort.Ints(ans) + return +} \ No newline at end of file diff --git a/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution2.java b/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution2.java new file mode 100644 index 0000000000000..2988e67e26434 --- /dev/null +++ b/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public List intersection(int[][] nums) { + Map cnt = new HashMap<>(); + List ans = new ArrayList<>(); + for (var arr : nums) { + for (int x : arr) { + if (cnt.merge(x, 1, Integer::sum) == nums.length) { + ans.add(x); + } + } + } + Collections.sort(ans); + return ans; + } +} \ No newline at end of file diff --git a/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution2.py b/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution2.py new file mode 100644 index 0000000000000..a520bfb8ae7d0 --- /dev/null +++ b/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def intersection(self, nums: List[List[int]]) -> List[int]: + cnt = Counter() + ans = [] + for arr in nums: + for x in arr: + cnt[x] += 1 + if cnt[x] == len(nums): + ans.append(x) + ans.sort() + return ans diff --git a/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution2.ts b/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution2.ts new file mode 100644 index 0000000000000..1778add5a3831 --- /dev/null +++ b/solution/2200-2299/2248.Intersection of Multiple Arrays/Solution2.ts @@ -0,0 +1,13 @@ +function intersection(nums: number[][]): number[] { + const cnt = new Array(1001).fill(0); + const ans: number[] = []; + for (const arr of nums) { + for (const x of arr) { + if (++cnt[x] == nums.length) { + ans.push(x); + } + } + } + ans.sort((a, b) => a - b); + return ans; +} diff --git a/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution.py b/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution.py index 6e4d6eea10498..a3cd2e64d1095 100644 --- a/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution.py +++ b/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution.py @@ -1,6 +1,6 @@ class Solution: def fullBloomFlowers( - self, flowers: List[List[int]], persons: List[int] + self, flowers: List[List[int]], people: List[int] ) -> List[int]: start, end = sorted(a for a, _ in flowers), sorted(b for _, b in flowers) - return [bisect_right(start, p) - bisect_left(end, p) for p in persons] + return [bisect_right(start, p) - bisect_left(end, p) for p in people] diff --git a/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution2.cpp b/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution2.cpp new file mode 100644 index 0000000000000..c9080c7778cd3 --- /dev/null +++ b/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution2.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector fullBloomFlowers(vector>& flowers, vector& people) { + map d; + for (auto& f : flowers) { + d[f[0]]++; + d[f[1] + 1]--; + } + int m = people.size(); + vector idx(m); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { + return people[i] < people[j]; + }); + vector ans(m); + int s = 0; + for (int i : idx) { + int t = people[i]; + while (!d.empty() && d.begin()->first <= t) { + s += d.begin()->second; + d.erase(d.begin()); + } + ans[i] = s; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution2.go b/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution2.go new file mode 100644 index 0000000000000..93a3ce8b0c3bb --- /dev/null +++ b/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution2.go @@ -0,0 +1,29 @@ +func fullBloomFlowers(flowers [][]int, people []int) []int { + d := map[int]int{} + for _, f := range flowers { + d[f[0]]++ + d[f[1]+1]-- + } + ts := []int{} + for t := range d { + ts = append(ts, t) + } + sort.Ints(ts) + m := len(people) + idx := make([]int, m) + for i := range idx { + idx[i] = i + } + sort.Slice(idx, func(i, j int) bool { return people[idx[i]] < people[idx[j]] }) + ans := make([]int, m) + s, i := 0, 0 + for _, j := range idx { + t := people[j] + for i < len(ts) && ts[i] <= t { + s += d[ts[i]] + i++ + } + ans[j] = s + } + return ans +} \ No newline at end of file diff --git a/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution2.java b/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution2.java new file mode 100644 index 0000000000000..a78e074775730 --- /dev/null +++ b/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution2.java @@ -0,0 +1,25 @@ +class Solution { + public int[] fullBloomFlowers(int[][] flowers, int[] people) { + TreeMap d = new TreeMap<>(); + for (int[] f : flowers) { + d.merge(f[0], 1, Integer::sum); + d.merge(f[1] + 1, -1, Integer::sum); + } + int s = 0; + int m = people.length; + Integer[] idx = new Integer[m]; + for (int i = 0; i < m; i++) { + idx[i] = i; + } + Arrays.sort(idx, Comparator.comparingInt(i -> people[i])); + int[] ans = new int[m]; + for (int i : idx) { + int t = people[i]; + while (!d.isEmpty() && d.firstKey() <= t) { + s += d.pollFirstEntry().getValue(); + } + ans[i] = s; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution2.py b/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution2.py new file mode 100644 index 0000000000000..f344b1d79809b --- /dev/null +++ b/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def fullBloomFlowers( + self, flowers: List[List[int]], people: List[int] + ) -> List[int]: + d = defaultdict(int) + for st, ed in flowers: + d[st] += 1 + d[ed + 1] -= 1 + ts = sorted(d) + s = i = 0 + m = len(people) + ans = [0] * m + for t, j in sorted(zip(people, range(m))): + while i < len(ts) and ts[i] <= t: + s += d[ts[i]] + i += 1 + ans[j] = s + return ans diff --git a/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution2.ts b/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution2.ts new file mode 100644 index 0000000000000..f8f690e4639d5 --- /dev/null +++ b/solution/2200-2299/2251.Number of Flowers in Full Bloom/Solution2.ts @@ -0,0 +1,22 @@ +function fullBloomFlowers(flowers: number[][], people: number[]): number[] { + const d: Map = new Map(); + for (const [st, ed] of flowers) { + d.set(st, (d.get(st) || 0) + 1); + d.set(ed + 1, (d.get(ed + 1) || 0) - 1); + } + const ts = [...d.keys()].sort((a, b) => a - b); + let s = 0; + let i = 0; + const m = people.length; + const idx: number[] = [...Array(m)].map((_, i) => i).sort((a, b) => people[a] - people[b]); + const ans = Array(m).fill(0); + for (const j of idx) { + const t = people[j]; + while (i < ts.length && ts[i] <= t) { + s += d.get(ts[i])!; + ++i; + } + ans[j] = s; + } + return ans; +} diff --git a/solution/2200-2299/2252.Dynamic Pivoting of a Table/Solution.sql b/solution/2200-2299/2252.Dynamic Pivoting of a Table/Solution.sql index 679b71cf5a66e..1abb5f08ed518 100644 --- a/solution/2200-2299/2252.Dynamic Pivoting of a Table/Solution.sql +++ b/solution/2200-2299/2252.Dynamic Pivoting of a Table/Solution.sql @@ -3,9 +3,9 @@ BEGIN # Write your MySQL query statement below. SET group_concat_max_len = 5000; SELECT GROUP_CONCAT(DISTINCT 'MAX(CASE WHEN store = \'', - store, - '\' THEN price ELSE NULL END) AS ', - store + store, + '\' THEN price ELSE NULL END) AS ', + store ORDER BY store) INTO @sql FROM Products; SET @sql = CONCAT('SELECT product_id, ', @@ -14,4 +14,4 @@ BEGIN PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; -END \ No newline at end of file +END diff --git a/solution/2200-2299/2255.Count Prefixes of a Given String/Solution.cpp b/solution/2200-2299/2255.Count Prefixes of a Given String/Solution.cpp index 78b923c0e0953..60cfdb52f5787 100644 --- a/solution/2200-2299/2255.Count Prefixes of a Given String/Solution.cpp +++ b/solution/2200-2299/2255.Count Prefixes of a Given String/Solution.cpp @@ -1,10 +1,10 @@ -class Solution { -public: - int countPrefixes(vector& words, string s) { - int ans = 0; - for (auto& w : words) { - ans += s.starts_with(w); - } - return ans; - } +class Solution { +public: + int countPrefixes(vector& words, string s) { + int ans = 0; + for (auto& w : words) { + ans += s.starts_with(w); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2255.Count Prefixes of a Given String/Solution.java b/solution/2200-2299/2255.Count Prefixes of a Given String/Solution.java index 288ebf238ae67..d0c796ed5ff46 100644 --- a/solution/2200-2299/2255.Count Prefixes of a Given String/Solution.java +++ b/solution/2200-2299/2255.Count Prefixes of a Given String/Solution.java @@ -1,11 +1,11 @@ -class Solution { - public int countPrefixes(String[] words, String s) { - int ans = 0; - for (String w : words) { - if (s.startsWith(w)) { - ++ans; - } - } - return ans; - } +class Solution { + public int countPrefixes(String[] words, String s) { + int ans = 0; + for (String w : words) { + if (s.startsWith(w)) { + ++ans; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2200-2299/2255.Count Prefixes of a Given String/Solution.py b/solution/2200-2299/2255.Count Prefixes of a Given String/Solution.py index f3890e7945cc0..65639e3f61d35 100644 --- a/solution/2200-2299/2255.Count Prefixes of a Given String/Solution.py +++ b/solution/2200-2299/2255.Count Prefixes of a Given String/Solution.py @@ -1,3 +1,3 @@ -class Solution: - def countPrefixes(self, words: List[str], s: str) -> int: - return sum(s.startswith(w) for w in words) +class Solution: + def countPrefixes(self, words: List[str], s: str) -> int: + return sum(s.startswith(w) for w in words) diff --git a/solution/2200-2299/2256.Minimum Average Difference/Solution.cpp b/solution/2200-2299/2256.Minimum Average Difference/Solution.cpp index 6f7a6f4940c74..b1ae131c4d70a 100644 --- a/solution/2200-2299/2256.Minimum Average Difference/Solution.cpp +++ b/solution/2200-2299/2256.Minimum Average Difference/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - int minimumAverageDifference(vector& nums) { - int n = nums.size(); - using ll = long long; - ll pre = 0; - ll suf = accumulate(nums.begin(), nums.end(), 0LL); - int ans = 0; - ll mi = suf; - for (int i = 0; i < n; ++i) { - pre += nums[i]; - suf -= nums[i]; - ll a = pre / (i + 1); - ll b = n - i - 1 == 0 ? 0 : suf / (n - i - 1); - ll t = abs(a - b); - if (t < mi) { - ans = i; - mi = t; - } - } - return ans; - } +class Solution { +public: + int minimumAverageDifference(vector& nums) { + int n = nums.size(); + using ll = long long; + ll pre = 0; + ll suf = accumulate(nums.begin(), nums.end(), 0LL); + int ans = 0; + ll mi = suf; + for (int i = 0; i < n; ++i) { + pre += nums[i]; + suf -= nums[i]; + ll a = pre / (i + 1); + ll b = n - i - 1 == 0 ? 0 : suf / (n - i - 1); + ll t = abs(a - b); + if (t < mi) { + ans = i; + mi = t; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2256.Minimum Average Difference/Solution.java b/solution/2200-2299/2256.Minimum Average Difference/Solution.java index f112838facd57..a722d0654e484 100644 --- a/solution/2200-2299/2256.Minimum Average Difference/Solution.java +++ b/solution/2200-2299/2256.Minimum Average Difference/Solution.java @@ -1,23 +1,23 @@ -class Solution { - public int minimumAverageDifference(int[] nums) { - int n = nums.length; - long pre = 0, suf = 0; - for (int x : nums) { - suf += x; - } - int ans = 0; - long mi = Long.MAX_VALUE; - for (int i = 0; i < n; ++i) { - pre += nums[i]; - suf -= nums[i]; - long a = pre / (i + 1); - long b = n - i - 1 == 0 ? 0 : suf / (n - i - 1); - long t = Math.abs(a - b); - if (t < mi) { - ans = i; - mi = t; - } - } - return ans; - } +class Solution { + public int minimumAverageDifference(int[] nums) { + int n = nums.length; + long pre = 0, suf = 0; + for (int x : nums) { + suf += x; + } + int ans = 0; + long mi = Long.MAX_VALUE; + for (int i = 0; i < n; ++i) { + pre += nums[i]; + suf -= nums[i]; + long a = pre / (i + 1); + long b = n - i - 1 == 0 ? 0 : suf / (n - i - 1); + long t = Math.abs(a - b); + if (t < mi) { + ans = i; + mi = t; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2200-2299/2256.Minimum Average Difference/Solution.py b/solution/2200-2299/2256.Minimum Average Difference/Solution.py index fc4888f964cac..9124a6ada170e 100644 --- a/solution/2200-2299/2256.Minimum Average Difference/Solution.py +++ b/solution/2200-2299/2256.Minimum Average Difference/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def minimumAverageDifference(self, nums: List[int]) -> int: - pre, suf = 0, sum(nums) - n = len(nums) - ans, mi = 0, inf - for i, x in enumerate(nums): - pre += x - suf -= x - a = pre // (i + 1) - b = 0 if n - i - 1 == 0 else suf // (n - i - 1) - if (t := abs(a - b)) < mi: - ans = i - mi = t - return ans +class Solution: + def minimumAverageDifference(self, nums: List[int]) -> int: + pre, suf = 0, sum(nums) + n = len(nums) + ans, mi = 0, inf + for i, x in enumerate(nums): + pre += x + suf -= x + a = pre // (i + 1) + b = 0 if n - i - 1 == 0 else suf // (n - i - 1) + if (t := abs(a - b)) < mi: + ans = i + mi = t + return ans diff --git a/solution/2200-2299/2258.Escape the Spreading Fire/Solution.cpp b/solution/2200-2299/2258.Escape the Spreading Fire/Solution.cpp index bdb04d060ecea..8226baeb45776 100644 --- a/solution/2200-2299/2258.Escape the Spreading Fire/Solution.cpp +++ b/solution/2200-2299/2258.Escape the Spreading Fire/Solution.cpp @@ -1,76 +1,76 @@ -class Solution { -public: - int maximumMinutes(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - bool vis[m][n]; - bool fire[m][n]; - int dirs[5] = {-1, 0, 1, 0, -1}; - auto spread = [&](queue>& q) { - queue> nq; - while (q.size()) { - auto [i, j] = q.front(); - q.pop(); - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && !fire[x][y] && grid[x][y] == 0) { - fire[x][y] = true; - nq.emplace(x, y); - } - } - } - return nq; - }; - auto check = [&](int t) { - memset(vis, false, sizeof(vis)); - memset(fire, false, sizeof(fire)); - queue> q1; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == 1) { - q1.emplace(i, j); - fire[i][j] = true; - } - } - } - for (; t && q1.size(); --t) { - q1 = spread(q1); - } - if (fire[0][0]) { - return false; - } - queue> q2; - q2.emplace(0, 0); - vis[0][0] = true; - for (; q2.size(); q1 = spread(q1)) { - for (int d = q2.size(); d; --d) { - auto [i, j] = q2.front(); - q2.pop(); - if (fire[i][j]) { - continue; - } - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && !fire[x][y] && grid[x][y] == 0) { - if (x == m - 1 && y == n - 1) { - return true; - } - vis[x][y] = true; - q2.emplace(x, y); - } - } - } - } - return false; - }; - int l = -1, r = m * n; - while (l < r) { - int mid = (l + r + 1) >> 1; - if (check(mid)) { - l = mid; - } else { - r = mid - 1; - } - } - return l == m * n ? 1e9 : l; - } +class Solution { +public: + int maximumMinutes(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + bool vis[m][n]; + bool fire[m][n]; + int dirs[5] = {-1, 0, 1, 0, -1}; + auto spread = [&](queue>& q) { + queue> nq; + while (q.size()) { + auto [i, j] = q.front(); + q.pop(); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && !fire[x][y] && grid[x][y] == 0) { + fire[x][y] = true; + nq.emplace(x, y); + } + } + } + return nq; + }; + auto check = [&](int t) { + memset(vis, false, sizeof(vis)); + memset(fire, false, sizeof(fire)); + queue> q1; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 1) { + q1.emplace(i, j); + fire[i][j] = true; + } + } + } + for (; t && q1.size(); --t) { + q1 = spread(q1); + } + if (fire[0][0]) { + return false; + } + queue> q2; + q2.emplace(0, 0); + vis[0][0] = true; + for (; q2.size(); q1 = spread(q1)) { + for (int d = q2.size(); d; --d) { + auto [i, j] = q2.front(); + q2.pop(); + if (fire[i][j]) { + continue; + } + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && !fire[x][y] && grid[x][y] == 0) { + if (x == m - 1 && y == n - 1) { + return true; + } + vis[x][y] = true; + q2.emplace(x, y); + } + } + } + } + return false; + }; + int l = -1, r = m * n; + while (l < r) { + int mid = (l + r + 1) >> 1; + if (check(mid)) { + l = mid; + } else { + r = mid - 1; + } + } + return l == m * n ? 1e9 : l; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2258.Escape the Spreading Fire/Solution.java b/solution/2200-2299/2258.Escape the Spreading Fire/Solution.java index e32bfe2c83338..202219b6a91d3 100644 --- a/solution/2200-2299/2258.Escape the Spreading Fire/Solution.java +++ b/solution/2200-2299/2258.Escape the Spreading Fire/Solution.java @@ -1,86 +1,86 @@ -class Solution { - private int[][] grid; - private boolean[][] fire; - private boolean[][] vis; - private final int[] dirs = {-1, 0, 1, 0, -1}; - private int m; - private int n; - - public int maximumMinutes(int[][] grid) { - m = grid.length; - n = grid[0].length; - this.grid = grid; - fire = new boolean[m][n]; - vis = new boolean[m][n]; - int l = -1, r = m * n; - while (l < r) { - int mid = (l + r + 1) >> 1; - if (check(mid)) { - l = mid; - } else { - r = mid - 1; - } - } - return l == m * n ? 1000000000 : l; - } - - private boolean check(int t) { - for (int i = 0; i < m; ++i) { - Arrays.fill(fire[i], false); - Arrays.fill(vis[i], false); - } - Deque q1 = new ArrayDeque<>(); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == 1) { - q1.offer(new int[] {i, j}); - fire[i][j] = true; - } - } - } - for (; t > 0 && !q1.isEmpty(); --t) { - q1 = spread(q1); - } - if (fire[0][0]) { - return false; - } - Deque q2 = new ArrayDeque<>(); - q2.offer(new int[] {0, 0}); - vis[0][0] = true; - for (; !q2.isEmpty(); q1 = spread(q1)) { - for (int d = q2.size(); d > 0; --d) { - int[] p = q2.poll(); - if (fire[p[0]][p[1]]) { - continue; - } - for (int k = 0; k < 4; ++k) { - int x = p[0] + dirs[k], y = p[1] + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && !fire[x][y] && !vis[x][y] - && grid[x][y] == 0) { - if (x == m - 1 && y == n - 1) { - return true; - } - vis[x][y] = true; - q2.offer(new int[] {x, y}); - } - } - } - } - return false; - } - - private Deque spread(Deque q) { - Deque nq = new ArrayDeque<>(); - while (!q.isEmpty()) { - int[] p = q.poll(); - for (int k = 0; k < 4; ++k) { - int x = p[0] + dirs[k], y = p[1] + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && !fire[x][y] && grid[x][y] == 0) { - fire[x][y] = true; - nq.offer(new int[] {x, y}); - } - } - } - return nq; - } +class Solution { + private int[][] grid; + private boolean[][] fire; + private boolean[][] vis; + private final int[] dirs = {-1, 0, 1, 0, -1}; + private int m; + private int n; + + public int maximumMinutes(int[][] grid) { + m = grid.length; + n = grid[0].length; + this.grid = grid; + fire = new boolean[m][n]; + vis = new boolean[m][n]; + int l = -1, r = m * n; + while (l < r) { + int mid = (l + r + 1) >> 1; + if (check(mid)) { + l = mid; + } else { + r = mid - 1; + } + } + return l == m * n ? 1000000000 : l; + } + + private boolean check(int t) { + for (int i = 0; i < m; ++i) { + Arrays.fill(fire[i], false); + Arrays.fill(vis[i], false); + } + Deque q1 = new ArrayDeque<>(); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 1) { + q1.offer(new int[] {i, j}); + fire[i][j] = true; + } + } + } + for (; t > 0 && !q1.isEmpty(); --t) { + q1 = spread(q1); + } + if (fire[0][0]) { + return false; + } + Deque q2 = new ArrayDeque<>(); + q2.offer(new int[] {0, 0}); + vis[0][0] = true; + for (; !q2.isEmpty(); q1 = spread(q1)) { + for (int d = q2.size(); d > 0; --d) { + int[] p = q2.poll(); + if (fire[p[0]][p[1]]) { + continue; + } + for (int k = 0; k < 4; ++k) { + int x = p[0] + dirs[k], y = p[1] + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && !fire[x][y] && !vis[x][y] + && grid[x][y] == 0) { + if (x == m - 1 && y == n - 1) { + return true; + } + vis[x][y] = true; + q2.offer(new int[] {x, y}); + } + } + } + } + return false; + } + + private Deque spread(Deque q) { + Deque nq = new ArrayDeque<>(); + while (!q.isEmpty()) { + int[] p = q.poll(); + for (int k = 0; k < 4; ++k) { + int x = p[0] + dirs[k], y = p[1] + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && !fire[x][y] && grid[x][y] == 0) { + fire[x][y] = true; + nq.offer(new int[] {x, y}); + } + } + } + return nq; + } } \ No newline at end of file diff --git a/solution/2200-2299/2258.Escape the Spreading Fire/Solution.py b/solution/2200-2299/2258.Escape the Spreading Fire/Solution.py index 069f17c391083..e4a670697a0d4 100644 --- a/solution/2200-2299/2258.Escape the Spreading Fire/Solution.py +++ b/solution/2200-2299/2258.Escape the Spreading Fire/Solution.py @@ -1,63 +1,63 @@ -class Solution: - def maximumMinutes(self, grid: List[List[int]]) -> int: - def spread(q: Deque[int]) -> Deque[int]: - nq = deque() - while q: - i, j = q.popleft() - for a, b in pairwise(dirs): - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n and not fire[x][y] and grid[x][y] == 0: - fire[x][y] = True - nq.append((x, y)) - return nq - - def check(t: int) -> bool: - for i in range(m): - for j in range(n): - fire[i][j] = False - q1 = deque() - for i, row in enumerate(grid): - for j, x in enumerate(row): - if x == 1: - fire[i][j] = True - q1.append((i, j)) - while t and q1: - q1 = spread(q1) - t -= 1 - if fire[0][0]: - return False - q2 = deque([(0, 0)]) - vis = [[False] * n for _ in range(m)] - vis[0][0] = True - while q2: - for _ in range(len(q2)): - i, j = q2.popleft() - if fire[i][j]: - continue - for a, b in pairwise(dirs): - x, y = i + a, j + b - if ( - 0 <= x < m - and 0 <= y < n - and not vis[x][y] - and not fire[x][y] - and grid[x][y] == 0 - ): - if x == m - 1 and y == n - 1: - return True - vis[x][y] = True - q2.append((x, y)) - q1 = spread(q1) - return False - - m, n = len(grid), len(grid[0]) - l, r = -1, m * n - dirs = (-1, 0, 1, 0, -1) - fire = [[False] * n for _ in range(m)] - while l < r: - mid = (l + r + 1) >> 1 - if check(mid): - l = mid - else: - r = mid - 1 - return int(1e9) if l == m * n else l +class Solution: + def maximumMinutes(self, grid: List[List[int]]) -> int: + def spread(q: Deque[int]) -> Deque[int]: + nq = deque() + while q: + i, j = q.popleft() + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n and not fire[x][y] and grid[x][y] == 0: + fire[x][y] = True + nq.append((x, y)) + return nq + + def check(t: int) -> bool: + for i in range(m): + for j in range(n): + fire[i][j] = False + q1 = deque() + for i, row in enumerate(grid): + for j, x in enumerate(row): + if x == 1: + fire[i][j] = True + q1.append((i, j)) + while t and q1: + q1 = spread(q1) + t -= 1 + if fire[0][0]: + return False + q2 = deque([(0, 0)]) + vis = [[False] * n for _ in range(m)] + vis[0][0] = True + while q2: + for _ in range(len(q2)): + i, j = q2.popleft() + if fire[i][j]: + continue + for a, b in pairwise(dirs): + x, y = i + a, j + b + if ( + 0 <= x < m + and 0 <= y < n + and not vis[x][y] + and not fire[x][y] + and grid[x][y] == 0 + ): + if x == m - 1 and y == n - 1: + return True + vis[x][y] = True + q2.append((x, y)) + q1 = spread(q1) + return False + + m, n = len(grid), len(grid[0]) + l, r = -1, m * n + dirs = (-1, 0, 1, 0, -1) + fire = [[False] * n for _ in range(m)] + while l < r: + mid = (l + r + 1) >> 1 + if check(mid): + l = mid + else: + r = mid - 1 + return int(1e9) if l == m * n else l diff --git a/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.cpp b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.cpp index 359945807d1fd..54414ddf494b8 100644 --- a/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.cpp +++ b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.cpp @@ -1,17 +1,16 @@ class Solution { public: string removeDigit(string number, char digit) { - int n = number.size(); - int last = -1; - for (int i = 0; i < n; ++i) { + string ans = "0"; + for (int i = 0, n = number.size(); i < n; ++i) { char d = number[i]; if (d == digit) { - last = i; - if (i + 1 < n && number[i] < number[i + 1]) { - break; + string t = number.substr(0, i) + number.substr(i + 1, n - i); + if (ans < t) { + ans = t; } } } - return number.substr(0, last) + number.substr(last + 1); + return ans; } }; \ No newline at end of file diff --git a/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.go b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.go index 1dfb2a25e7902..377fbafdc93e2 100644 --- a/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.go +++ b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.go @@ -1,13 +1,12 @@ func removeDigit(number string, digit byte) string { - last := -1 - n := len(number) - for i := range number { - if number[i] == digit { - last = i - if i+1 < n && number[i] < number[i+1] { - break + ans := "0" + for i, d := range number { + if d == rune(digit) { + t := number[:i] + number[i+1:] + if strings.Compare(ans, t) < 0 { + ans = t } } } - return number[:last] + number[last+1:] + return ans } \ No newline at end of file diff --git a/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.java b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.java index 12419ed93f94d..9438077b6efd6 100644 --- a/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.java +++ b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.java @@ -1,16 +1,15 @@ class Solution { public String removeDigit(String number, char digit) { - int last = -1; - int n = number.length(); - for (int i = 0; i < n; ++i) { + String ans = "0"; + for (int i = 0, n = number.length(); i < n; ++i) { char d = number.charAt(i); if (d == digit) { - last = i; - if (i + 1 < n && d < number.charAt(i + 1)) { - break; + String t = number.substring(0, i) + number.substring(i + 1); + if (ans.compareTo(t) < 0) { + ans = t; } } } - return number.substring(0, last) + number.substring(last + 1); + return ans; } } \ No newline at end of file diff --git a/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.php b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.php index e7a510210c1aa..013e7bde636e0 100644 --- a/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.php +++ b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.php @@ -16,4 +16,4 @@ function removeDigit($number, $digit) { } return $max; } -} \ No newline at end of file +} diff --git a/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.py b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.py index 8db5c2aae385a..151f52425f567 100644 --- a/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.py +++ b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.py @@ -1,10 +1,5 @@ class Solution: def removeDigit(self, number: str, digit: str) -> str: - last = -1 - n = len(number) - for i, d in enumerate(number): - if d == digit: - last = i - if i + 1 < n and d < number[i + 1]: - break - return number[:last] + number[last + 1 :] + return max( + number[:i] + number[i + 1 :] for i, d in enumerate(number) if d == digit + ) diff --git a/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution2.cpp b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution2.cpp new file mode 100644 index 0000000000000..359945807d1fd --- /dev/null +++ b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + string removeDigit(string number, char digit) { + int n = number.size(); + int last = -1; + for (int i = 0; i < n; ++i) { + char d = number[i]; + if (d == digit) { + last = i; + if (i + 1 < n && number[i] < number[i + 1]) { + break; + } + } + } + return number.substr(0, last) + number.substr(last + 1); + } +}; \ No newline at end of file diff --git a/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution2.go b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution2.go new file mode 100644 index 0000000000000..1dfb2a25e7902 --- /dev/null +++ b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution2.go @@ -0,0 +1,13 @@ +func removeDigit(number string, digit byte) string { + last := -1 + n := len(number) + for i := range number { + if number[i] == digit { + last = i + if i+1 < n && number[i] < number[i+1] { + break + } + } + } + return number[:last] + number[last+1:] +} \ No newline at end of file diff --git a/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution2.java b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution2.java new file mode 100644 index 0000000000000..12419ed93f94d --- /dev/null +++ b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public String removeDigit(String number, char digit) { + int last = -1; + int n = number.length(); + for (int i = 0; i < n; ++i) { + char d = number.charAt(i); + if (d == digit) { + last = i; + if (i + 1 < n && d < number.charAt(i + 1)) { + break; + } + } + } + return number.substring(0, last) + number.substring(last + 1); + } +} \ No newline at end of file diff --git a/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution2.py b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution2.py new file mode 100644 index 0000000000000..8db5c2aae385a --- /dev/null +++ b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def removeDigit(self, number: str, digit: str) -> str: + last = -1 + n = len(number) + for i, d in enumerate(number): + if d == digit: + last = i + if i + 1 < n and d < number[i + 1]: + break + return number[:last] + number[last + 1 :] diff --git a/solution/2200-2299/2261.K Divisible Elements Subarrays/Solution.py b/solution/2200-2299/2261.K Divisible Elements Subarrays/Solution.py index e8d37001f1408..44b2164c5ee2c 100644 --- a/solution/2200-2299/2261.K Divisible Elements Subarrays/Solution.py +++ b/solution/2200-2299/2261.K Divisible Elements Subarrays/Solution.py @@ -4,11 +4,9 @@ def countDistinct(self, nums: List[int], k: int, p: int) -> int: s = set() for i in range(n): cnt = 0 - t = "" - for x in nums[i:]: - cnt += x % p == 0 + for j in range(i, n): + cnt += nums[j] % p == 0 if cnt > k: break - t += str(x) + "," - s.add(t) + s.add(tuple(nums[i : j + 1])) return len(s) diff --git a/solution/2200-2299/2261.K Divisible Elements Subarrays/Solution2.py b/solution/2200-2299/2261.K Divisible Elements Subarrays/Solution2.py new file mode 100644 index 0000000000000..e8d37001f1408 --- /dev/null +++ b/solution/2200-2299/2261.K Divisible Elements Subarrays/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def countDistinct(self, nums: List[int], k: int, p: int) -> int: + n = len(nums) + s = set() + for i in range(n): + cnt = 0 + t = "" + for x in nums[i:]: + cnt += x % p == 0 + if cnt > k: + break + t += str(x) + "," + s.add(t) + return len(s) diff --git a/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/Solution.cpp b/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/Solution.cpp index a1d09fbeccb36..06162eff79c23 100644 --- a/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/Solution.cpp +++ b/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/Solution.cpp @@ -1,12 +1,12 @@ -class Solution { -public: - string largestGoodInteger(string num) { - for (char i = '9'; i >= '0'; --i) { - string s(3, i); - if (num.find(s) != string::npos) { - return s; - } - } - return ""; - } +class Solution { +public: + string largestGoodInteger(string num) { + for (char i = '9'; i >= '0'; --i) { + string s(3, i); + if (num.find(s) != string::npos) { + return s; + } + } + return ""; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/Solution.java b/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/Solution.java index 49684a7168919..beefabfe87394 100644 --- a/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/Solution.java +++ b/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/Solution.java @@ -1,11 +1,11 @@ -class Solution { - public String largestGoodInteger(String num) { - for (int i = 9; i >= 0; i--) { - String s = String.valueOf(i).repeat(3); - if (num.contains(s)) { - return s; - } - } - return ""; - } -} +class Solution { + public String largestGoodInteger(String num) { + for (int i = 9; i >= 0; i--) { + String s = String.valueOf(i).repeat(3); + if (num.contains(s)) { + return s; + } + } + return ""; + } +} \ No newline at end of file diff --git a/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/Solution.py b/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/Solution.py index 30d2c88b8b4fc..d7d31829d019b 100644 --- a/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/Solution.py +++ b/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/Solution.py @@ -1,6 +1,6 @@ -class Solution: - def largestGoodInteger(self, num: str) -> str: - for i in range(9, -1, -1): - if (s := str(i) * 3) in num: - return s - return "" +class Solution: + def largestGoodInteger(self, num: str) -> str: + for i in range(9, -1, -1): + if (s := str(i) * 3) in num: + return s + return "" diff --git a/solution/2200-2299/2276.Count Integers in Intervals/Solution.cpp b/solution/2200-2299/2276.Count Integers in Intervals/Solution.cpp index bf28d4d3c6008..1444e1c594873 100644 --- a/solution/2200-2299/2276.Count Integers in Intervals/Solution.cpp +++ b/solution/2200-2299/2276.Count Integers in Intervals/Solution.cpp @@ -1,112 +1,112 @@ -class Node { -public: - Node(int l, int r) - : l(l) - , r(r) - , mid((l + r) / 2) - , v(0) - , add(0) - , left(nullptr) - , right(nullptr) {} - - int l, r, mid, v, add; - Node* left; - Node* right; -}; - -class SegmentTree { -public: - SegmentTree() - : root(new Node(1, 1000000001)) {} - - void modify(int l, int r, int v, Node* node = nullptr) { - if (node == nullptr) { - node = root; - } - if (l > r) { - return; - } - if (node->l >= l && node->r <= r) { - node->v = node->r - node->l + 1; - node->add = v; - return; - } - pushdown(node); - if (l <= node->mid) { - modify(l, r, v, node->left); - } - if (r > node->mid) { - modify(l, r, v, node->right); - } - pushup(node); - } - - int query(int l, int r, Node* node = nullptr) { - if (node == nullptr) { - node = root; - } - if (l > r) { - return 0; - } - if (node->l >= l && node->r <= r) { - return node->v; - } - pushdown(node); - int v = 0; - if (l <= node->mid) { - v += query(l, r, node->left); - } - if (r > node->mid) { - v += query(l, r, node->right); - } - return v; - } - -private: - Node* root; - - void pushup(Node* node) { - node->v = node->left->v + node->right->v; - } - - void pushdown(Node* node) { - if (node->left == nullptr) { - node->left = new Node(node->l, node->mid); - } - if (node->right == nullptr) { - node->right = new Node(node->mid + 1, node->r); - } - if (node->add != 0) { - Node* left = node->left; - Node* right = node->right; - left->add = node->add; - right->add = node->add; - left->v = left->r - left->l + 1; - right->v = right->r - right->l + 1; - node->add = 0; - } - } -}; - -class CountIntervals { -public: - CountIntervals() {} - - void add(int left, int right) { - tree.modify(left, right, 1); - } - - int count() { - return tree.query(1, 1000000000); - } - -private: - SegmentTree tree; -}; - -/** - * Your CountIntervals object will be instantiated and called as such: - * CountIntervals* obj = new CountIntervals(); - * obj->add(left,right); - * int param_2 = obj->count(); +class Node { +public: + Node(int l, int r) + : l(l) + , r(r) + , mid((l + r) / 2) + , v(0) + , add(0) + , left(nullptr) + , right(nullptr) {} + + int l, r, mid, v, add; + Node* left; + Node* right; +}; + +class SegmentTree { +public: + SegmentTree() + : root(new Node(1, 1000000001)) {} + + void modify(int l, int r, int v, Node* node = nullptr) { + if (node == nullptr) { + node = root; + } + if (l > r) { + return; + } + if (node->l >= l && node->r <= r) { + node->v = node->r - node->l + 1; + node->add = v; + return; + } + pushdown(node); + if (l <= node->mid) { + modify(l, r, v, node->left); + } + if (r > node->mid) { + modify(l, r, v, node->right); + } + pushup(node); + } + + int query(int l, int r, Node* node = nullptr) { + if (node == nullptr) { + node = root; + } + if (l > r) { + return 0; + } + if (node->l >= l && node->r <= r) { + return node->v; + } + pushdown(node); + int v = 0; + if (l <= node->mid) { + v += query(l, r, node->left); + } + if (r > node->mid) { + v += query(l, r, node->right); + } + return v; + } + +private: + Node* root; + + void pushup(Node* node) { + node->v = node->left->v + node->right->v; + } + + void pushdown(Node* node) { + if (node->left == nullptr) { + node->left = new Node(node->l, node->mid); + } + if (node->right == nullptr) { + node->right = new Node(node->mid + 1, node->r); + } + if (node->add != 0) { + Node* left = node->left; + Node* right = node->right; + left->add = node->add; + right->add = node->add; + left->v = left->r - left->l + 1; + right->v = right->r - right->l + 1; + node->add = 0; + } + } +}; + +class CountIntervals { +public: + CountIntervals() {} + + void add(int left, int right) { + tree.modify(left, right, 1); + } + + int count() { + return tree.query(1, 1000000000); + } + +private: + SegmentTree tree; +}; + +/** + * Your CountIntervals object will be instantiated and called as such: + * CountIntervals* obj = new CountIntervals(); + * obj->add(left,right); + * int param_2 = obj->count(); */ \ No newline at end of file diff --git a/solution/2200-2299/2276.Count Integers in Intervals/Solution.java b/solution/2200-2299/2276.Count Integers in Intervals/Solution.java index fe9e4cf1baecf..f48d08e6db3c8 100644 --- a/solution/2200-2299/2276.Count Integers in Intervals/Solution.java +++ b/solution/2200-2299/2276.Count Integers in Intervals/Solution.java @@ -107,4 +107,4 @@ public int count() { * CountIntervals obj = new CountIntervals(); * obj.add(left,right); * int param_2 = obj.count(); - */ + */ \ No newline at end of file diff --git a/solution/2200-2299/2276.Count Integers in Intervals/Solution.py b/solution/2200-2299/2276.Count Integers in Intervals/Solution.py index 03987aa885a51..0871b73b87a2e 100644 --- a/solution/2200-2299/2276.Count Integers in Intervals/Solution.py +++ b/solution/2200-2299/2276.Count Integers in Intervals/Solution.py @@ -1,80 +1,42 @@ -class Node: - __slots__ = ("left", "right", "l", "r", "mid", "v", "add") - - def __init__(self, l, r): - self.left = None - self.right = None - self.l = l - self.r = r - self.mid = (l + r) // 2 - self.v = 0 - self.add = 0 - - -class SegmentTree: - def __init__(self): - self.root = Node(1, int(1e9) + 1) - - def modify(self, l, r, v, node=None): - if node is None: - node = self.root - if l > r: - return - if node.l >= l and node.r <= r: - node.v = node.r - node.l + 1 - node.add = v - return - self.pushdown(node) - if l <= node.mid: - self.modify(l, r, v, node.left) - if r > node.mid: - self.modify(l, r, v, node.right) - self.pushup(node) - - def query(self, l, r, node=None): - if node is None: - node = self.root - if l > r: - return 0 - if node.l >= l and node.r <= r: - return node.v - self.pushdown(node) - v = 0 - if l <= node.mid: - v += self.query(l, r, node.left) - if r > node.mid: - v += self.query(l, r, node.right) - return v - - def pushup(self, node): - node.v = node.left.v + node.right.v - - def pushdown(self, node): - if node.left is None: - node.left = Node(node.l, node.mid) - if node.right is None: - node.right = Node(node.mid + 1, node.r) - if node.add != 0: - left, right = node.left, node.right - left.add = node.add - right.add = node.add - left.v = left.r - left.l + 1 - right.v = right.r - right.l + 1 - node.add = 0 - - -class CountIntervals: - def __init__(self): - self.tree = SegmentTree() - - def add(self, left, right): - self.tree.modify(left, right, 1) - - def count(self): - return self.tree.query(1, int(1e9)) - - -# Your CountIntervals object will be instantiated and called as such: -# obj = CountIntervals() -# obj.add(left, right) -# param_2 = obj.count() +class Node: + def __init__(self): + self.tag = 0 + self.tot = 0 + self.left = None + self.right = None + + def update(self, l, r, a, b): + if self.tag == 1: + return + mid = (a + b) >> 1 + if l == a and r == b: + self.tag = 1 + self.tot = b - a + 1 + return + if not self.left: + self.left = Node() + if not self.right: + self.right = Node() + if mid >= l: + self.left.update(l, min(mid, r), a, mid) + if mid + 1 <= r: + self.right.update(max(mid + 1, l), r, mid + 1, b) + self.tag = 0 + self.tot = self.left.tot + self.right.tot + + +class CountIntervals: + def __init__(self): + self.tree = Node() + + def add(self, left: int, right: int) -> None: + self.tree.update(left, right, 0, 1000000010) + + def count(self) -> int: + return self.tree.tot + + +# Your CountIntervals object will be instantiated and called as such: +# obj = CountIntervals() +# obj.add(left,right) +# param_2 = obj.count() diff --git a/solution/2200-2299/2276.Count Integers in Intervals/Solution2.py b/solution/2200-2299/2276.Count Integers in Intervals/Solution2.py new file mode 100644 index 0000000000000..d21aac9131109 --- /dev/null +++ b/solution/2200-2299/2276.Count Integers in Intervals/Solution2.py @@ -0,0 +1,80 @@ +class Node: + __slots__ = ("left", "right", "l", "r", "mid", "v", "add") + + def __init__(self, l, r): + self.left = None + self.right = None + self.l = l + self.r = r + self.mid = (l + r) // 2 + self.v = 0 + self.add = 0 + + +class SegmentTree: + def __init__(self): + self.root = Node(1, int(1e9) + 1) + + def modify(self, l, r, v, node=None): + if node is None: + node = self.root + if l > r: + return + if node.l >= l and node.r <= r: + node.v = node.r - node.l + 1 + node.add = v + return + self.pushdown(node) + if l <= node.mid: + self.modify(l, r, v, node.left) + if r > node.mid: + self.modify(l, r, v, node.right) + self.pushup(node) + + def query(self, l, r, node=None): + if node is None: + node = self.root + if l > r: + return 0 + if node.l >= l and node.r <= r: + return node.v + self.pushdown(node) + v = 0 + if l <= node.mid: + v += self.query(l, r, node.left) + if r > node.mid: + v += self.query(l, r, node.right) + return v + + def pushup(self, node): + node.v = node.left.v + node.right.v + + def pushdown(self, node): + if node.left is None: + node.left = Node(node.l, node.mid) + if node.right is None: + node.right = Node(node.mid + 1, node.r) + if node.add != 0: + left, right = node.left, node.right + left.add = node.add + right.add = node.add + left.v = left.r - left.l + 1 + right.v = right.r - right.l + 1 + node.add = 0 + + +class CountIntervals: + def __init__(self): + self.tree = SegmentTree() + + def add(self, left, right): + self.tree.modify(left, right, 1) + + def count(self): + return self.tree.query(1, int(1e9)) + + +# Your CountIntervals object will be instantiated and called as such: +# obj = CountIntervals() +# obj.add(left, right) +# param_2 = obj.count() diff --git a/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/Solution.cpp b/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/Solution.cpp index 625af4abf200c..84c035ce06a45 100644 --- a/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/Solution.cpp +++ b/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/Solution.cpp @@ -1,40 +1,40 @@ -class Solution { -public: - vector> seePeople(vector>& heights) { - int m = heights.size(), n = heights[0].size(); - auto f = [](vector& nums) { - int n = nums.size(); - vector ans(n); - stack stk; - for (int i = n - 1; ~i; --i) { - while (stk.size() && stk.top() < nums[i]) { - ++ans[i]; - stk.pop(); - } - if (stk.size()) { - ++ans[i]; - } - while (stk.size() && stk.top() == nums[i]) { - stk.pop(); - } - stk.push(nums[i]); - } - return ans; - }; - vector> ans; - for (auto& row : heights) { - ans.push_back(f(row)); - } - for (int j = 0; j < n; ++j) { - vector col; - for (int i = 0; i < m; ++i) { - col.push_back(heights[i][j]); - } - vector add = f(col); - for (int i = 0; i < m; ++i) { - ans[i][j] += add[i]; - } - } - return ans; - } +class Solution { +public: + vector> seePeople(vector>& heights) { + int m = heights.size(), n = heights[0].size(); + auto f = [](vector& nums) { + int n = nums.size(); + vector ans(n); + stack stk; + for (int i = n - 1; ~i; --i) { + while (stk.size() && stk.top() < nums[i]) { + ++ans[i]; + stk.pop(); + } + if (stk.size()) { + ++ans[i]; + } + while (stk.size() && stk.top() == nums[i]) { + stk.pop(); + } + stk.push(nums[i]); + } + return ans; + }; + vector> ans; + for (auto& row : heights) { + ans.push_back(f(row)); + } + for (int j = 0; j < n; ++j) { + vector col; + for (int i = 0; i < m; ++i) { + col.push_back(heights[i][j]); + } + vector add = f(col); + for (int i = 0; i < m; ++i) { + ans[i][j] += add[i]; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/Solution.java b/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/Solution.java index b2f104d13fe21..0dbc65a528831 100644 --- a/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/Solution.java +++ b/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/Solution.java @@ -1,40 +1,40 @@ -class Solution { - public int[][] seePeople(int[][] heights) { - int m = heights.length, n = heights[0].length; - int[][] ans = new int[m][0]; - for (int i = 0; i < m; ++i) { - ans[i] = f(heights[i]); - } - for (int j = 0; j < n; ++j) { - int[] nums = new int[m]; - for (int i = 0; i < m; ++i) { - nums[i] = heights[i][j]; - } - int[] add = f(nums); - for (int i = 0; i < m; ++i) { - ans[i][j] += add[i]; - } - } - return ans; - } - - private int[] f(int[] nums) { - int n = nums.length; - int[] ans = new int[n]; - Deque stk = new ArrayDeque<>(); - for (int i = n - 1; i >= 0; --i) { - while (!stk.isEmpty() && stk.peek() < nums[i]) { - stk.pop(); - ++ans[i]; - } - if (!stk.isEmpty()) { - ++ans[i]; - } - while (!stk.isEmpty() && stk.peek() == nums[i]) { - stk.pop(); - } - stk.push(nums[i]); - } - return ans; - } +class Solution { + public int[][] seePeople(int[][] heights) { + int m = heights.length, n = heights[0].length; + int[][] ans = new int[m][0]; + for (int i = 0; i < m; ++i) { + ans[i] = f(heights[i]); + } + for (int j = 0; j < n; ++j) { + int[] nums = new int[m]; + for (int i = 0; i < m; ++i) { + nums[i] = heights[i][j]; + } + int[] add = f(nums); + for (int i = 0; i < m; ++i) { + ans[i][j] += add[i]; + } + } + return ans; + } + + private int[] f(int[] nums) { + int n = nums.length; + int[] ans = new int[n]; + Deque stk = new ArrayDeque<>(); + for (int i = n - 1; i >= 0; --i) { + while (!stk.isEmpty() && stk.peek() < nums[i]) { + stk.pop(); + ++ans[i]; + } + if (!stk.isEmpty()) { + ++ans[i]; + } + while (!stk.isEmpty() && stk.peek() == nums[i]) { + stk.pop(); + } + stk.push(nums[i]); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/Solution.py b/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/Solution.py index aa4dce96638ca..b52954bbc70ec 100644 --- a/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/Solution.py +++ b/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/Solution.py @@ -1,24 +1,24 @@ -class Solution: - def seePeople(self, heights: List[List[int]]) -> List[List[int]]: - def f(nums: List[int]) -> List[int]: - n = len(nums) - stk = [] - ans = [0] * n - for i in range(n - 1, -1, -1): - while stk and stk[-1] < nums[i]: - ans[i] += 1 - stk.pop() - if stk: - ans[i] += 1 - while stk and stk[-1] == nums[i]: - stk.pop() - stk.append(nums[i]) - return ans - - ans = [f(row) for row in heights] - m, n = len(heights), len(heights[0]) - for j in range(n): - add = f([heights[i][j] for i in range(m)]) - for i in range(m): - ans[i][j] += add[i] - return ans +class Solution: + def seePeople(self, heights: List[List[int]]) -> List[List[int]]: + def f(nums: List[int]) -> List[int]: + n = len(nums) + stk = [] + ans = [0] * n + for i in range(n - 1, -1, -1): + while stk and stk[-1] < nums[i]: + ans[i] += 1 + stk.pop() + if stk: + ans[i] += 1 + while stk and stk[-1] == nums[i]: + stk.pop() + stk.append(nums[i]) + return ans + + ans = [f(row) for row in heights] + m, n = len(heights), len(heights[0]) + for j in range(n): + add = f([heights[i][j] for i in range(m)]) + for i in range(m): + ans[i][j] += add[i] + return ans diff --git a/solution/2200-2299/2283.Check if Number Has Equal Digit Count and Digit Value/Solution.c b/solution/2200-2299/2283.Check if Number Has Equal Digit Count and Digit Value/Solution.c index 8b48d24ab7ec0..1eaaa0c1c7129 100644 --- a/solution/2200-2299/2283.Check if Number Has Equal Digit Count and Digit Value/Solution.c +++ b/solution/2200-2299/2283.Check if Number Has Equal Digit Count and Digit Value/Solution.c @@ -12,4 +12,4 @@ bool digitCount(char* num) { } } return true; -} +} \ No newline at end of file diff --git a/solution/2200-2299/2287.Rearrange Characters to Make Target String/Solution.c b/solution/2200-2299/2287.Rearrange Characters to Make Target String/Solution.c index 63d894d2f17a5..7e24a2bce399c 100644 --- a/solution/2200-2299/2287.Rearrange Characters to Make Target String/Solution.c +++ b/solution/2200-2299/2287.Rearrange Characters to Make Target String/Solution.c @@ -16,4 +16,4 @@ int rearrangeCharacters(char* s, char* target) { } } return ans; -} +} \ No newline at end of file diff --git a/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution.cpp b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution.cpp index c39cc7b25449c..6d0021dca8143 100644 --- a/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution.cpp +++ b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution.cpp @@ -2,14 +2,16 @@ class Solution { public: int maximumProfit(vector& present, vector& future, int budget) { int n = present.size(); - int f[budget + 1]; + int f[n + 1][budget + 1]; memset(f, 0, sizeof f); - for (int i = 0; i < n; ++i) { - int a = present[i], b = future[i]; - for (int j = budget; j >= a; --j) { - f[j] = max(f[j], f[j - a] + b - a); + for (int i = 1; i <= n; ++i) { + for (int j = 0; j <= budget; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= present[i - 1]) { + f[i][j] = max(f[i][j], f[i - 1][j - present[i - 1]] + future[i - 1] - present[i - 1]); + } } } - return f[budget]; + return f[n][budget]; } }; \ No newline at end of file diff --git a/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution.go b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution.go index e8f827d11eac5..11005a6294e93 100644 --- a/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution.go +++ b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution.go @@ -1,9 +1,16 @@ func maximumProfit(present []int, future []int, budget int) int { - f := make([]int, budget+1) - for i, a := range present { - for j := budget; j >= a; j-- { - f[j] = max(f[j], f[j-a]+future[i]-a) + n := len(present) + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, budget+1) + } + for i := 1; i <= n; i++ { + for j := 0; j <= budget; j++ { + f[i][j] = f[i-1][j] + if j >= present[i-1] { + f[i][j] = max(f[i][j], f[i-1][j-present[i-1]]+future[i-1]-present[i-1]) + } } } - return f[budget] + return f[n][budget] } \ No newline at end of file diff --git a/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution.java b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution.java index 50e57000dd0ec..a78b65cf0f0d3 100644 --- a/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution.java +++ b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution.java @@ -1,13 +1,16 @@ class Solution { public int maximumProfit(int[] present, int[] future, int budget) { int n = present.length; - int[] f = new int[budget + 1]; - for (int i = 0; i < n; ++i) { - int a = present[i], b = future[i]; - for (int j = budget; j >= a; --j) { - f[j] = Math.max(f[j], f[j - a] + b - a); + int[][] f = new int[n + 1][budget + 1]; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j <= budget; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= present[i - 1]) { + f[i][j] = Math.max( + f[i][j], f[i - 1][j - present[i - 1]] + future[i - 1] - present[i - 1]); + } } } - return f[budget]; + return f[n][budget]; } } \ No newline at end of file diff --git a/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution.py b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution.py index 7384bff14c8ea..18c66d73e37e4 100644 --- a/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution.py +++ b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution.py @@ -1,7 +1,9 @@ class Solution: def maximumProfit(self, present: List[int], future: List[int], budget: int) -> int: - f = [0] * (budget + 1) - for a, b in zip(present, future): - for j in range(budget, a - 1, -1): - f[j] = max(f[j], f[j - a] + b - a) - return f[-1] + f = [[0] * (budget + 1) for _ in range(len(present) + 1)] + for i, w in enumerate(present, 1): + for j in range(budget + 1): + f[i][j] = f[i - 1][j] + if j >= w and future[i - 1] > w: + f[i][j] = max(f[i][j], f[i - 1][j - w] + future[i - 1] - w) + return f[-1][-1] diff --git a/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution2.cpp b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution2.cpp new file mode 100644 index 0000000000000..c39cc7b25449c --- /dev/null +++ b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int maximumProfit(vector& present, vector& future, int budget) { + int n = present.size(); + int f[budget + 1]; + memset(f, 0, sizeof f); + for (int i = 0; i < n; ++i) { + int a = present[i], b = future[i]; + for (int j = budget; j >= a; --j) { + f[j] = max(f[j], f[j - a] + b - a); + } + } + return f[budget]; + } +}; \ No newline at end of file diff --git a/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution2.go b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution2.go new file mode 100644 index 0000000000000..e8f827d11eac5 --- /dev/null +++ b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution2.go @@ -0,0 +1,9 @@ +func maximumProfit(present []int, future []int, budget int) int { + f := make([]int, budget+1) + for i, a := range present { + for j := budget; j >= a; j-- { + f[j] = max(f[j], f[j-a]+future[i]-a) + } + } + return f[budget] +} \ No newline at end of file diff --git a/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution2.java b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution2.java new file mode 100644 index 0000000000000..50e57000dd0ec --- /dev/null +++ b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution2.java @@ -0,0 +1,13 @@ +class Solution { + public int maximumProfit(int[] present, int[] future, int budget) { + int n = present.length; + int[] f = new int[budget + 1]; + for (int i = 0; i < n; ++i) { + int a = present[i], b = future[i]; + for (int j = budget; j >= a; --j) { + f[j] = Math.max(f[j], f[j - a] + b - a); + } + } + return f[budget]; + } +} \ No newline at end of file diff --git a/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution2.py b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution2.py new file mode 100644 index 0000000000000..7384bff14c8ea --- /dev/null +++ b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def maximumProfit(self, present: List[int], future: List[int], budget: int) -> int: + f = [0] * (budget + 1) + for a, b in zip(present, future): + for j in range(budget, a - 1, -1): + f[j] = max(f[j], f[j - a] + b - a) + return f[-1] diff --git a/solution/2200-2299/2292.Products With Three or More Orders in Two Consecutive Years/Solution.sql b/solution/2200-2299/2292.Products With Three or More Orders in Two Consecutive Years/Solution.sql index 683c145de576f..4b1a140d56eeb 100644 --- a/solution/2200-2299/2292.Products With Three or More Orders in Two Consecutive Years/Solution.sql +++ b/solution/2200-2299/2292.Products With Three or More Orders in Two Consecutive Years/Solution.sql @@ -1,12 +1,12 @@ # Write your MySQL query statement below WITH P AS ( - SELECT product_id, YEAR(purchase_date) AS y + SELECT product_id, YEAR(purchase_date) AS y, COUNT(1) >= 3 AS mark FROM Orders GROUP BY 1, 2 - HAVING COUNT(1) >= 3 ) SELECT DISTINCT p1.product_id FROM P AS p1 - JOIN P AS p2 ON p1.y = p2.y - 1 AND p1.product_id = p2.product_id; + JOIN P AS p2 ON p1.y = p2.y - 1 AND p1.product_id = p2.product_id +WHERE p1.mark AND p2.mark; diff --git a/solution/2200-2299/2292.Products With Three or More Orders in Two Consecutive Years/Solution2.sql b/solution/2200-2299/2292.Products With Three or More Orders in Two Consecutive Years/Solution2.sql new file mode 100644 index 0000000000000..683c145de576f --- /dev/null +++ b/solution/2200-2299/2292.Products With Three or More Orders in Two Consecutive Years/Solution2.sql @@ -0,0 +1,12 @@ +# Write your MySQL query statement below +WITH + P AS ( + SELECT product_id, YEAR(purchase_date) AS y + FROM Orders + GROUP BY 1, 2 + HAVING COUNT(1) >= 3 + ) +SELECT DISTINCT p1.product_id +FROM + P AS p1 + JOIN P AS p2 ON p1.y = p2.y - 1 AND p1.product_id = p2.product_id; diff --git a/solution/2200-2299/2293.Min Max Game/Solution.c b/solution/2200-2299/2293.Min Max Game/Solution.c index 885d134881f19..8136a6a5ea2ed 100644 --- a/solution/2200-2299/2293.Min Max Game/Solution.c +++ b/solution/2200-2299/2293.Min Max Game/Solution.c @@ -11,4 +11,4 @@ int minMaxGame(int* nums, int numsSize) { } } return nums[0]; -} +} \ No newline at end of file diff --git a/solution/2200-2299/2297.Jump Game VIII/Solution.cpp b/solution/2200-2299/2297.Jump Game VIII/Solution.cpp index 1f2df02107510..9931973e40403 100644 --- a/solution/2200-2299/2297.Jump Game VIII/Solution.cpp +++ b/solution/2200-2299/2297.Jump Game VIII/Solution.cpp @@ -1,35 +1,35 @@ -class Solution { -public: - long long minCost(vector& nums, vector& costs) { - int n = nums.size(); - vector g[n]; - stack stk; - for (int i = n - 1; ~i; --i) { - while (!stk.empty() && nums[stk.top()] < nums[i]) { - stk.pop(); - } - if (!stk.empty()) { - g[i].push_back(stk.top()); - } - stk.push(i); - } - stk = stack(); - for (int i = n - 1; ~i; --i) { - while (!stk.empty() && nums[stk.top()] >= nums[i]) { - stk.pop(); - } - if (!stk.empty()) { - g[i].push_back(stk.top()); - } - stk.push(i); - } - vector f(n, 1e18); - f[0] = 0; - for (int i = 0; i < n; ++i) { - for (int j : g[i]) { - f[j] = min(f[j], f[i] + costs[j]); - } - } - return f[n - 1]; - } +class Solution { +public: + long long minCost(vector& nums, vector& costs) { + int n = nums.size(); + vector g[n]; + stack stk; + for (int i = n - 1; ~i; --i) { + while (!stk.empty() && nums[stk.top()] < nums[i]) { + stk.pop(); + } + if (!stk.empty()) { + g[i].push_back(stk.top()); + } + stk.push(i); + } + stk = stack(); + for (int i = n - 1; ~i; --i) { + while (!stk.empty() && nums[stk.top()] >= nums[i]) { + stk.pop(); + } + if (!stk.empty()) { + g[i].push_back(stk.top()); + } + stk.push(i); + } + vector f(n, 1e18); + f[0] = 0; + for (int i = 0; i < n; ++i) { + for (int j : g[i]) { + f[j] = min(f[j], f[i] + costs[j]); + } + } + return f[n - 1]; + } }; \ No newline at end of file diff --git a/solution/2200-2299/2297.Jump Game VIII/Solution.java b/solution/2200-2299/2297.Jump Game VIII/Solution.java index 1723f8e76488e..bea9ead75a2cd 100644 --- a/solution/2200-2299/2297.Jump Game VIII/Solution.java +++ b/solution/2200-2299/2297.Jump Game VIII/Solution.java @@ -1,36 +1,36 @@ -class Solution { - public long minCost(int[] nums, int[] costs) { - int n = nums.length; - List[] g = new List[n]; - Arrays.setAll(g, k -> new ArrayList<>()); - Deque stk = new ArrayDeque<>(); - for (int i = n - 1; i >= 0; --i) { - while (!stk.isEmpty() && nums[stk.peek()] < nums[i]) { - stk.pop(); - } - if (!stk.isEmpty()) { - g[i].add(stk.peek()); - } - stk.push(i); - } - stk.clear(); - for (int i = n - 1; i >= 0; --i) { - while (!stk.isEmpty() && nums[stk.peek()] >= nums[i]) { - stk.pop(); - } - if (!stk.isEmpty()) { - g[i].add(stk.peek()); - } - stk.push(i); - } - long[] f = new long[n]; - Arrays.fill(f, 1L << 60); - f[0] = 0; - for (int i = 0; i < n; ++i) { - for (int j : g[i]) { - f[j] = Math.min(f[j], f[i] + costs[j]); - } - } - return f[n - 1]; - } +class Solution { + public long minCost(int[] nums, int[] costs) { + int n = nums.length; + List[] g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + Deque stk = new ArrayDeque<>(); + for (int i = n - 1; i >= 0; --i) { + while (!stk.isEmpty() && nums[stk.peek()] < nums[i]) { + stk.pop(); + } + if (!stk.isEmpty()) { + g[i].add(stk.peek()); + } + stk.push(i); + } + stk.clear(); + for (int i = n - 1; i >= 0; --i) { + while (!stk.isEmpty() && nums[stk.peek()] >= nums[i]) { + stk.pop(); + } + if (!stk.isEmpty()) { + g[i].add(stk.peek()); + } + stk.push(i); + } + long[] f = new long[n]; + Arrays.fill(f, 1L << 60); + f[0] = 0; + for (int i = 0; i < n; ++i) { + for (int j : g[i]) { + f[j] = Math.min(f[j], f[i] + costs[j]); + } + } + return f[n - 1]; + } } \ No newline at end of file diff --git a/solution/2200-2299/2297.Jump Game VIII/Solution.py b/solution/2200-2299/2297.Jump Game VIII/Solution.py index 0e71a0f3f30c0..461229d06a114 100644 --- a/solution/2200-2299/2297.Jump Game VIII/Solution.py +++ b/solution/2200-2299/2297.Jump Game VIII/Solution.py @@ -1,26 +1,26 @@ -class Solution: - def minCost(self, nums: List[int], costs: List[int]) -> int: - n = len(nums) - g = defaultdict(list) - stk = [] - for i in range(n - 1, -1, -1): - while stk and nums[stk[-1]] < nums[i]: - stk.pop() - if stk: - g[i].append(stk[-1]) - stk.append(i) - - stk = [] - for i in range(n - 1, -1, -1): - while stk and nums[stk[-1]] >= nums[i]: - stk.pop() - if stk: - g[i].append(stk[-1]) - stk.append(i) - - f = [inf] * n - f[0] = 0 - for i in range(n): - for j in g[i]: - f[j] = min(f[j], f[i] + costs[j]) - return f[n - 1] +class Solution: + def minCost(self, nums: List[int], costs: List[int]) -> int: + n = len(nums) + g = defaultdict(list) + stk = [] + for i in range(n - 1, -1, -1): + while stk and nums[stk[-1]] < nums[i]: + stk.pop() + if stk: + g[i].append(stk[-1]) + stk.append(i) + + stk = [] + for i in range(n - 1, -1, -1): + while stk and nums[stk[-1]] >= nums[i]: + stk.pop() + if stk: + g[i].append(stk[-1]) + stk.append(i) + + f = [inf] * n + f[0] = 0 + for i in range(n): + for j in g[i]: + f[j] = min(f[j], f[i] + costs[j]) + return f[n - 1] diff --git a/solution/2200-2299/2299.Strong Password Checker II/Solution.c b/solution/2200-2299/2299.Strong Password Checker II/Solution.c index 2ac3e6990efcd..05ff4fbf3643d 100644 --- a/solution/2200-2299/2299.Strong Password Checker II/Solution.c +++ b/solution/2200-2299/2299.Strong Password Checker II/Solution.c @@ -21,4 +21,4 @@ bool strongPasswordCheckerII(char* password) { prev = password[i]; } return mask == 0b1111; -} +} \ No newline at end of file diff --git a/solution/2300-2399/2301.Match Substring After Replacement/Solution.go b/solution/2300-2399/2301.Match Substring After Replacement/Solution.go index 3f9651c07cb29..e7982d8b3b2c7 100644 --- a/solution/2300-2399/2301.Match Substring After Replacement/Solution.go +++ b/solution/2300-2399/2301.Match Substring After Replacement/Solution.go @@ -1,6 +1,9 @@ func matchReplacement(s string, sub string, mappings [][]byte) bool { - d := [128][128]bool{} + d := map[byte]map[byte]bool{} for _, e := range mappings { + if d[e[0]] == nil { + d[e[0]] = map[byte]bool{} + } d[e[0]][e[1]] = true } for i := 0; i < len(s)-len(sub)+1; i++ { diff --git a/solution/2300-2399/2301.Match Substring After Replacement/Solution2.cpp b/solution/2300-2399/2301.Match Substring After Replacement/Solution2.cpp new file mode 100644 index 0000000000000..8702219d3ebd0 --- /dev/null +++ b/solution/2300-2399/2301.Match Substring After Replacement/Solution2.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + bool matchReplacement(string s, string sub, vector>& mappings) { + bool d[128][128]{}; + for (auto& e : mappings) { + d[e[0]][e[1]] = true; + } + int m = s.size(), n = sub.size(); + for (int i = 0; i < m - n + 1; ++i) { + bool ok = true; + for (int j = 0; j < n && ok; ++j) { + char a = s[i + j], b = sub[j]; + if (a != b && !d[b][a]) { + ok = false; + } + } + if (ok) { + return true; + } + } + return false; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2301.Match Substring After Replacement/Solution2.go b/solution/2300-2399/2301.Match Substring After Replacement/Solution2.go new file mode 100644 index 0000000000000..3f9651c07cb29 --- /dev/null +++ b/solution/2300-2399/2301.Match Substring After Replacement/Solution2.go @@ -0,0 +1,19 @@ +func matchReplacement(s string, sub string, mappings [][]byte) bool { + d := [128][128]bool{} + for _, e := range mappings { + d[e[0]][e[1]] = true + } + for i := 0; i < len(s)-len(sub)+1; i++ { + ok := true + for j := 0; j < len(sub) && ok; j++ { + a, b := s[i+j], sub[j] + if a != b && !d[b][a] { + ok = false + } + } + if ok { + return true + } + } + return false +} \ No newline at end of file diff --git a/solution/2300-2399/2301.Match Substring After Replacement/Solution2.java b/solution/2300-2399/2301.Match Substring After Replacement/Solution2.java new file mode 100644 index 0000000000000..b540dfb97dadc --- /dev/null +++ b/solution/2300-2399/2301.Match Substring After Replacement/Solution2.java @@ -0,0 +1,22 @@ +class Solution { + public boolean matchReplacement(String s, String sub, char[][] mappings) { + boolean[][] d = new boolean[128][128]; + for (var e : mappings) { + d[e[0]][e[1]] = true; + } + int m = s.length(), n = sub.length(); + for (int i = 0; i < m - n + 1; ++i) { + boolean ok = true; + for (int j = 0; j < n && ok; ++j) { + char a = s.charAt(i + j), b = sub.charAt(j); + if (a != b && !d[b][a]) { + ok = false; + } + } + if (ok) { + return true; + } + } + return false; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2301.Match Substring After Replacement/Solution2.py b/solution/2300-2399/2301.Match Substring After Replacement/Solution2.py new file mode 100644 index 0000000000000..633e8dc8e0671 --- /dev/null +++ b/solution/2300-2399/2301.Match Substring After Replacement/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: + d = [[False] * 128 for _ in range(128)] + for a, b in mappings: + d[ord(a)][ord(b)] = True + for i in range(len(s) - len(sub) + 1): + if all( + a == b or d[ord(b)][ord(a)] for a, b in zip(s[i : i + len(sub)], sub) + ): + return True + return False diff --git a/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution.cpp b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution.cpp index 5c7de427f37c4..0673135384f2a 100644 --- a/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution.cpp +++ b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution.cpp @@ -1,13 +1,24 @@ class Solution { public: long long countSubarrays(vector& nums, long long k) { - long long ans = 0, s = 0; - for (int i = 0, j = 0; i < nums.size(); ++i) { - s += nums[i]; - while (s * (i - j + 1) >= k) { - s -= nums[j++]; + int n = nums.size(); + long long s[n + 1]; + s[0] = 0; + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + long long ans = 0; + for (int i = 1; i <= n; ++i) { + int left = 0, right = i; + while (left < right) { + int mid = (left + right + 1) >> 1; + if ((s[i] - s[i - mid]) * mid < k) { + left = mid; + } else { + right = mid - 1; + } } - ans += i - j + 1; + ans += left; } return ans; } diff --git a/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution.go b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution.go index 7be9ee8f94c85..e59cbbb249a6f 100644 --- a/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution.go +++ b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution.go @@ -1,12 +1,20 @@ func countSubarrays(nums []int, k int64) (ans int64) { - s, j := 0, 0 + n := len(nums) + s := make([]int64, n+1) for i, v := range nums { - s += v - for int64(s*(i-j+1)) >= k { - s -= nums[j] - j++ + s[i+1] = s[i] + int64(v) + } + for i := 1; i <= n; i++ { + left, right := 0, i + for left < right { + mid := (left + right + 1) >> 1 + if (s[i]-s[i-mid])*int64(mid) < k { + left = mid + } else { + right = mid - 1 + } } - ans += int64(i - j + 1) + ans += int64(left) } return } \ No newline at end of file diff --git a/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution.java b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution.java index 4d0687db6b070..55c7d46b32883 100644 --- a/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution.java +++ b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution.java @@ -1,12 +1,22 @@ class Solution { public long countSubarrays(int[] nums, long k) { - long ans = 0, s = 0; - for (int i = 0, j = 0; i < nums.length; ++i) { - s += nums[i]; - while (s * (i - j + 1) >= k) { - s -= nums[j++]; + int n = nums.length; + long[] s = new long[n + 1]; + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + long ans = 0; + for (int i = 1; i <= n; ++i) { + int left = 0, right = i; + while (left < right) { + int mid = (left + right + 1) >> 1; + if ((s[i] - s[i - mid]) * mid < k) { + left = mid; + } else { + right = mid - 1; + } } - ans += i - j + 1; + ans += left; } return ans; } diff --git a/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution.py b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution.py index 7b4fb98c0c857..1040f8d2bf60c 100644 --- a/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution.py +++ b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution.py @@ -1,10 +1,14 @@ class Solution: def countSubarrays(self, nums: List[int], k: int) -> int: - ans = s = j = 0 - for i, v in enumerate(nums): - s += v - while s * (i - j + 1) >= k: - s -= nums[j] - j += 1 - ans += i - j + 1 + s = list(accumulate(nums, initial=0)) + ans = 0 + for i in range(1, len(s)): + left, right = 0, i + while left < right: + mid = (left + right + 1) >> 1 + if (s[i] - s[i - mid]) * mid < k: + left = mid + else: + right = mid - 1 + ans += left return ans diff --git a/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution2.cpp b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution2.cpp new file mode 100644 index 0000000000000..5c7de427f37c4 --- /dev/null +++ b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + long long countSubarrays(vector& nums, long long k) { + long long ans = 0, s = 0; + for (int i = 0, j = 0; i < nums.size(); ++i) { + s += nums[i]; + while (s * (i - j + 1) >= k) { + s -= nums[j++]; + } + ans += i - j + 1; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution2.go b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution2.go new file mode 100644 index 0000000000000..7be9ee8f94c85 --- /dev/null +++ b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution2.go @@ -0,0 +1,12 @@ +func countSubarrays(nums []int, k int64) (ans int64) { + s, j := 0, 0 + for i, v := range nums { + s += v + for int64(s*(i-j+1)) >= k { + s -= nums[j] + j++ + } + ans += int64(i - j + 1) + } + return +} \ No newline at end of file diff --git a/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution2.java b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution2.java new file mode 100644 index 0000000000000..4d0687db6b070 --- /dev/null +++ b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution2.java @@ -0,0 +1,13 @@ +class Solution { + public long countSubarrays(int[] nums, long k) { + long ans = 0, s = 0; + for (int i = 0, j = 0; i < nums.length; ++i) { + s += nums[i]; + while (s * (i - j + 1) >= k) { + s -= nums[j++]; + } + ans += i - j + 1; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution2.py b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution2.py new file mode 100644 index 0000000000000..7b4fb98c0c857 --- /dev/null +++ b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def countSubarrays(self, nums: List[int], k: int) -> int: + ans = s = j = 0 + for i, v in enumerate(nums): + s += v + while s * (i - j + 1) >= k: + s -= nums[j] + j += 1 + ans += i - j + 1 + return ans diff --git a/solution/2300-2399/2305.Fair Distribution of Cookies/Solution.java b/solution/2300-2399/2305.Fair Distribution of Cookies/Solution.java index 298404df116e0..dcd7fad4a5dee 100644 --- a/solution/2300-2399/2305.Fair Distribution of Cookies/Solution.java +++ b/solution/2300-2399/2305.Fair Distribution of Cookies/Solution.java @@ -8,9 +8,11 @@ class Solution { public int distributeCookies(int[] cookies, int k) { n = cookies.length; cnt = new int[k]; + // 升序排列 Arrays.sort(cookies); this.cookies = cookies; this.k = k; + // 这里搜索顺序是 n-1, n-2,...0 dfs(n - 1); return ans; } diff --git a/solution/2300-2399/2306.Naming a Company/Solution.cpp b/solution/2300-2399/2306.Naming a Company/Solution.cpp index 9c28d4c6f452d..631c6cfb6bc41 100644 --- a/solution/2300-2399/2306.Naming a Company/Solution.cpp +++ b/solution/2300-2399/2306.Naming a Company/Solution.cpp @@ -1,27 +1,27 @@ -class Solution { -public: - long long distinctNames(vector& ideas) { - unordered_set s(ideas.begin(), ideas.end()); - int f[26][26]{}; - for (auto v : ideas) { - int i = v[0] - 'a'; - for (int j = 0; j < 26; ++j) { - v[0] = j + 'a'; - if (!s.count(v)) { - ++f[i][j]; - } - } - } - long long ans = 0; - for (auto& v : ideas) { - int i = v[0] - 'a'; - for (int j = 0; j < 26; ++j) { - v[0] = j + 'a'; - if (!s.count(v)) { - ans += f[j][i]; - } - } - } - return ans; - } +class Solution { +public: + long long distinctNames(vector& ideas) { + unordered_set s(ideas.begin(), ideas.end()); + int f[26][26]{}; + for (auto v : ideas) { + int i = v[0] - 'a'; + for (int j = 0; j < 26; ++j) { + v[0] = j + 'a'; + if (!s.count(v)) { + ++f[i][j]; + } + } + } + long long ans = 0; + for (auto& v : ideas) { + int i = v[0] - 'a'; + for (int j = 0; j < 26; ++j) { + v[0] = j + 'a'; + if (!s.count(v)) { + ans += f[j][i]; + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2300-2399/2307.Check for Contradictions in Equations/Solution.cpp b/solution/2300-2399/2307.Check for Contradictions in Equations/Solution.cpp index a1b32bad6b049..203493e3ac0a3 100644 --- a/solution/2300-2399/2307.Check for Contradictions in Equations/Solution.cpp +++ b/solution/2300-2399/2307.Check for Contradictions in Equations/Solution.cpp @@ -1,37 +1,37 @@ -class Solution { -public: - bool checkContradictions(vector>& equations, vector& values) { - unordered_map d; - int n = 0; - for (auto& e : equations) { - for (auto& s : e) { - if (!d.count(s)) { - d[s] = n++; - } - } - } - vector p(n); - iota(p.begin(), p.end(), 0); - vector w(n, 1.0); - function find = [&](int x) -> int { - if (p[x] != x) { - int root = find(p[x]); - w[x] *= w[p[x]]; - p[x] = root; - } - return p[x]; - }; - for (int i = 0; i < equations.size(); ++i) { - int a = d[equations[i][0]], b = d[equations[i][1]]; - double v = values[i]; - int pa = find(a), pb = find(b); - if (pa != pb) { - p[pb] = pa; - w[pb] = v * w[a] / w[b]; - } else if (fabs(v * w[a] - w[b]) >= 1e-5) { - return true; - } - } - return false; - } +class Solution { +public: + bool checkContradictions(vector>& equations, vector& values) { + unordered_map d; + int n = 0; + for (auto& e : equations) { + for (auto& s : e) { + if (!d.count(s)) { + d[s] = n++; + } + } + } + vector p(n); + iota(p.begin(), p.end(), 0); + vector w(n, 1.0); + function find = [&](int x) -> int { + if (p[x] != x) { + int root = find(p[x]); + w[x] *= w[p[x]]; + p[x] = root; + } + return p[x]; + }; + for (int i = 0; i < equations.size(); ++i) { + int a = d[equations[i][0]], b = d[equations[i][1]]; + double v = values[i]; + int pa = find(a), pb = find(b); + if (pa != pb) { + p[pb] = pa; + w[pb] = v * w[a] / w[b]; + } else if (fabs(v * w[a] - w[b]) >= 1e-5) { + return true; + } + } + return false; + } }; \ No newline at end of file diff --git a/solution/2300-2399/2307.Check for Contradictions in Equations/Solution.java b/solution/2300-2399/2307.Check for Contradictions in Equations/Solution.java index 7dc0d11483793..30af89f6cc552 100644 --- a/solution/2300-2399/2307.Check for Contradictions in Equations/Solution.java +++ b/solution/2300-2399/2307.Check for Contradictions in Equations/Solution.java @@ -1,44 +1,44 @@ -class Solution { - private int[] p; - private double[] w; - - public boolean checkContradictions(List> equations, double[] values) { - Map d = new HashMap<>(); - int n = 0; - for (var e : equations) { - for (var s : e) { - if (!d.containsKey(s)) { - d.put(s, n++); - } - } - } - p = new int[n]; - w = new double[n]; - for (int i = 0; i < n; ++i) { - p[i] = i; - w[i] = 1.0; - } - final double eps = 1e-5; - for (int i = 0; i < equations.size(); ++i) { - int a = d.get(equations.get(i).get(0)), b = d.get(equations.get(i).get(1)); - int pa = find(a), pb = find(b); - double v = values[i]; - if (pa != pb) { - p[pb] = pa; - w[pb] = v * w[a] / w[b]; - } else if (Math.abs(v * w[a] - w[b]) >= eps) { - return true; - } - } - return false; - } - - private int find(int x) { - if (p[x] != x) { - int root = find(p[x]); - w[x] *= w[p[x]]; - p[x] = root; - } - return p[x]; - } +class Solution { + private int[] p; + private double[] w; + + public boolean checkContradictions(List> equations, double[] values) { + Map d = new HashMap<>(); + int n = 0; + for (var e : equations) { + for (var s : e) { + if (!d.containsKey(s)) { + d.put(s, n++); + } + } + } + p = new int[n]; + w = new double[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + w[i] = 1.0; + } + final double eps = 1e-5; + for (int i = 0; i < equations.size(); ++i) { + int a = d.get(equations.get(i).get(0)), b = d.get(equations.get(i).get(1)); + int pa = find(a), pb = find(b); + double v = values[i]; + if (pa != pb) { + p[pb] = pa; + w[pb] = v * w[a] / w[b]; + } else if (Math.abs(v * w[a] - w[b]) >= eps) { + return true; + } + } + return false; + } + + private int find(int x) { + if (p[x] != x) { + int root = find(p[x]); + w[x] *= w[p[x]]; + p[x] = root; + } + return p[x]; + } } \ No newline at end of file diff --git a/solution/2300-2399/2307.Check for Contradictions in Equations/Solution.py b/solution/2300-2399/2307.Check for Contradictions in Equations/Solution.py index 218b3d7efeb74..9f8fa87abd30f 100644 --- a/solution/2300-2399/2307.Check for Contradictions in Equations/Solution.py +++ b/solution/2300-2399/2307.Check for Contradictions in Equations/Solution.py @@ -1,30 +1,30 @@ -class Solution: - def checkContradictions( - self, equations: List[List[str]], values: List[float] - ) -> bool: - def find(x: int) -> int: - if p[x] != x: - root = find(p[x]) - w[x] *= w[p[x]] - p[x] = root - return p[x] - - d = defaultdict(int) - n = 0 - for e in equations: - for s in e: - if s not in d: - d[s] = n - n += 1 - p = list(range(n)) - w = [1.0] * n - eps = 1e-5 - for (a, b), v in zip(equations, values): - a, b = d[a], d[b] - pa, pb = find(a), find(b) - if pa != pb: - p[pb] = pa - w[pb] = v * w[a] / w[b] - elif abs(v * w[a] - w[b]) >= eps: - return True - return False +class Solution: + def checkContradictions( + self, equations: List[List[str]], values: List[float] + ) -> bool: + def find(x: int) -> int: + if p[x] != x: + root = find(p[x]) + w[x] *= w[p[x]] + p[x] = root + return p[x] + + d = defaultdict(int) + n = 0 + for e in equations: + for s in e: + if s not in d: + d[s] = n + n += 1 + p = list(range(n)) + w = [1.0] * n + eps = 1e-5 + for (a, b), v in zip(equations, values): + a, b = d[a], d[b] + pa, pb = find(a), find(b) + if pa != pb: + p[pb] = pa + w[pb] = v * w[a] / w[b] + elif abs(v * w[a] - w[b]) >= eps: + return True + return False diff --git a/solution/2300-2399/2308.Arrange Table by Gender/Solution2.sql b/solution/2300-2399/2308.Arrange Table by Gender/Solution2.sql new file mode 100644 index 0000000000000..1619d9c537b7f --- /dev/null +++ b/solution/2300-2399/2308.Arrange Table by Gender/Solution2.sql @@ -0,0 +1,12 @@ +SELECT + user_id, + gender +FROM Genders +ORDER BY + ( + RANK() OVER ( + PARTITION BY gender + ORDER BY user_id + ) + ), + 2; diff --git a/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution.cpp b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution.cpp index 428ffe94c9c31..2575015135615 100644 --- a/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution.cpp +++ b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution.cpp @@ -1,15 +1,12 @@ class Solution { public: string greatestLetter(string s) { - int mask1 = 0, mask2 = 0; - for (char& c : s) { - if (islower(c)) { - mask1 |= 1 << (c - 'a'); - } else { - mask2 |= 1 << (c - 'A'); + unordered_set ss(s.begin(), s.end()); + for (char c = 'Z'; c >= 'A'; --c) { + if (ss.count(c) && ss.count(char(c + 32))) { + return string(1, c); } } - int mask = mask1 & mask2; - return mask ? string(1, 31 - __builtin_clz(mask) + 'A') : ""; + return ""; } }; \ No newline at end of file diff --git a/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution.go b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution.go index ff51325cf1977..cc79dc5cb5331 100644 --- a/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution.go +++ b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution.go @@ -1,15 +1,12 @@ func greatestLetter(s string) string { - mask1, mask2 := 0, 0 + ss := map[rune]bool{} for _, c := range s { - if unicode.IsLower(c) { - mask1 |= 1 << (c - 'a') - } else { - mask2 |= 1 << (c - 'A') - } + ss[c] = true } - mask := mask1 & mask2 - if mask == 0 { - return "" + for c := 'Z'; c >= 'A'; c-- { + if ss[c] && ss[rune(c+32)] { + return string(c) + } } - return string(byte(bits.Len(uint(mask))-1) + 'A') + return "" } \ No newline at end of file diff --git a/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution.java b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution.java index a3194968e2af6..0b332b6eb27ec 100644 --- a/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution.java +++ b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution.java @@ -1,16 +1,14 @@ class Solution { public String greatestLetter(String s) { - int mask1 = 0, mask2 = 0; - for (int i = 0; i < s.length(); ++i) { - char c = s.charAt(i); - if (Character.isLowerCase(c)) { - mask1 |= 1 << (c - 'a'); - } else { - mask2 |= 1 << (c - 'A'); + Set ss = new HashSet<>(); + for (char c : s.toCharArray()) { + ss.add(c); + } + for (char a = 'Z'; a >= 'A'; --a) { + if (ss.contains(a) && ss.contains((char) (a + 32))) { + return String.valueOf(a); } } - int mask = mask1 & mask2; - return mask > 0 ? String.valueOf((char) (31 - Integer.numberOfLeadingZeros(mask) + 'A')) - : ""; + return ""; } } \ No newline at end of file diff --git a/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution.py b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution.py index ce99cba237570..5ea722808d1ef 100644 --- a/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution.py +++ b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution.py @@ -1,10 +1,7 @@ class Solution: def greatestLetter(self, s: str) -> str: - mask1 = mask2 = 0 - for c in s: - if c.islower(): - mask1 |= 1 << (ord(c) - ord("a")) - else: - mask2 |= 1 << (ord(c) - ord("A")) - mask = mask1 & mask2 - return chr(mask.bit_length() - 1 + ord("A")) if mask else "" + ss = set(s) + for c in ascii_uppercase[::-1]: + if c in ss and c.lower() in ss: + return c + return '' diff --git a/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution2.cpp b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution2.cpp new file mode 100644 index 0000000000000..428ffe94c9c31 --- /dev/null +++ b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + string greatestLetter(string s) { + int mask1 = 0, mask2 = 0; + for (char& c : s) { + if (islower(c)) { + mask1 |= 1 << (c - 'a'); + } else { + mask2 |= 1 << (c - 'A'); + } + } + int mask = mask1 & mask2; + return mask ? string(1, 31 - __builtin_clz(mask) + 'A') : ""; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution2.go b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution2.go new file mode 100644 index 0000000000000..ff51325cf1977 --- /dev/null +++ b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution2.go @@ -0,0 +1,15 @@ +func greatestLetter(s string) string { + mask1, mask2 := 0, 0 + for _, c := range s { + if unicode.IsLower(c) { + mask1 |= 1 << (c - 'a') + } else { + mask2 |= 1 << (c - 'A') + } + } + mask := mask1 & mask2 + if mask == 0 { + return "" + } + return string(byte(bits.Len(uint(mask))-1) + 'A') +} \ No newline at end of file diff --git a/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution2.java b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution2.java new file mode 100644 index 0000000000000..a3194968e2af6 --- /dev/null +++ b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public String greatestLetter(String s) { + int mask1 = 0, mask2 = 0; + for (int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if (Character.isLowerCase(c)) { + mask1 |= 1 << (c - 'a'); + } else { + mask2 |= 1 << (c - 'A'); + } + } + int mask = mask1 & mask2; + return mask > 0 ? String.valueOf((char) (31 - Integer.numberOfLeadingZeros(mask) + 'A')) + : ""; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution2.py b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution2.py new file mode 100644 index 0000000000000..ce99cba237570 --- /dev/null +++ b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def greatestLetter(self, s: str) -> str: + mask1 = mask2 = 0 + for c in s: + if c.islower(): + mask1 |= 1 << (ord(c) - ord("a")) + else: + mask2 |= 1 << (ord(c) - ord("A")) + mask = mask1 & mask2 + return chr(mask.bit_length() - 1 + ord("A")) if mask else "" diff --git a/solution/2300-2399/2310.Sum of Numbers With Units Digit K/Solution2.cpp b/solution/2300-2399/2310.Sum of Numbers With Units Digit K/Solution2.cpp new file mode 100644 index 0000000000000..99773cca46fa7 --- /dev/null +++ b/solution/2300-2399/2310.Sum of Numbers With Units Digit K/Solution2.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + int minimumNumbers(int num, int k) { + if (!num) return 0; + for (int i = 1; i <= 10; ++i) + if ((k * i) % 10 == num % 10 && k * i <= num) + return i; + return -1; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2310.Sum of Numbers With Units Digit K/Solution2.go b/solution/2300-2399/2310.Sum of Numbers With Units Digit K/Solution2.go new file mode 100644 index 0000000000000..9470eacdc4229 --- /dev/null +++ b/solution/2300-2399/2310.Sum of Numbers With Units Digit K/Solution2.go @@ -0,0 +1,11 @@ +func minimumNumbers(num int, k int) int { + if num == 0 { + return 0 + } + for i := 1; i <= 10; i++ { + if (k*i)%10 == num%10 && k*i <= num { + return i + } + } + return -1 +} \ No newline at end of file diff --git a/solution/2300-2399/2310.Sum of Numbers With Units Digit K/Solution2.java b/solution/2300-2399/2310.Sum of Numbers With Units Digit K/Solution2.java new file mode 100644 index 0000000000000..123f6f14b8728 --- /dev/null +++ b/solution/2300-2399/2310.Sum of Numbers With Units Digit K/Solution2.java @@ -0,0 +1,13 @@ +class Solution { + public int minimumNumbers(int num, int k) { + if (num == 0) { + return 0; + } + for (int i = 1; i <= 10; ++i) { + if ((k * i) % 10 == num % 10 && k * i <= num) { + return i; + } + } + return -1; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2310.Sum of Numbers With Units Digit K/Solution2.py b/solution/2300-2399/2310.Sum of Numbers With Units Digit K/Solution2.py new file mode 100644 index 0000000000000..d9ab66347d946 --- /dev/null +++ b/solution/2300-2399/2310.Sum of Numbers With Units Digit K/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def minimumNumbers(self, num: int, k: int) -> int: + if num == 0: + return 0 + for i in range(1, 11): + if (k * i) % 10 == num % 10 and k * i <= num: + return i + return -1 diff --git a/solution/2300-2399/2310.Sum of Numbers With Units Digit K/Solution3.py b/solution/2300-2399/2310.Sum of Numbers With Units Digit K/Solution3.py new file mode 100644 index 0000000000000..3f77f3accf089 --- /dev/null +++ b/solution/2300-2399/2310.Sum of Numbers With Units Digit K/Solution3.py @@ -0,0 +1,21 @@ +class Solution: + def minimumNumbers(self, num: int, k: int) -> int: + @cache + def dfs(v): + if v == 0: + return 0 + if v < 10 and v % k: + return inf + i = 0 + t = inf + while (x := i * 10 + k) <= v: + t = min(t, dfs(v - x)) + i += 1 + return t + 1 + + if num == 0: + return 0 + if k == 0: + return -1 if num % 10 else 1 + ans = dfs(num) + return -1 if ans >= inf else ans diff --git a/solution/2300-2399/2311.Longest Binary Subsequence Less Than or Equal to K/Solution.cs b/solution/2300-2399/2311.Longest Binary Subsequence Less Than or Equal to K/Solution.cs new file mode 100644 index 0000000000000..3c833903527e2 --- /dev/null +++ b/solution/2300-2399/2311.Longest Binary Subsequence Less Than or Equal to K/Solution.cs @@ -0,0 +1,14 @@ +public class Solution { + public int LongestSubsequence(string s, int k) { + int ans = 0, v = 0; + for (int i = s.Length - 1; i >= 0; --i) { + if (s[i] == '0') { + ++ans; + } else if (ans < 30 && (v | 1 << ans) <= k) { + v |= 1 << ans; + ++ans; + } + } + return ans; + } +} diff --git a/solution/2300-2399/2312.Selling Pieces of Wood/Solution2.cpp b/solution/2300-2399/2312.Selling Pieces of Wood/Solution2.cpp new file mode 100644 index 0000000000000..1260d3b2898b1 --- /dev/null +++ b/solution/2300-2399/2312.Selling Pieces of Wood/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + long long sellingWood(int m, int n, vector>& prices) { + vector> d(m + 1, vector(n + 1)); + vector> dp(m + 1, vector(n + 1)); + for (auto& p : prices) d[p[0]][p[1]] = p[2]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + dp[i][j] = d[i][j]; + for (int k = 1; k < i; ++k) dp[i][j] = max(dp[i][j], dp[k][j] + dp[i - k][j]); + for (int k = 1; k < j; ++k) dp[i][j] = max(dp[i][j], dp[i][k] + dp[i][j - k]); + } + } + return dp[m][n]; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2312.Selling Pieces of Wood/Solution2.go b/solution/2300-2399/2312.Selling Pieces of Wood/Solution2.go new file mode 100644 index 0000000000000..9e9078e19579f --- /dev/null +++ b/solution/2300-2399/2312.Selling Pieces of Wood/Solution2.go @@ -0,0 +1,23 @@ +func sellingWood(m int, n int, prices [][]int) int64 { + d := make([][]int, m+1) + dp := make([][]int, m+1) + for i := range d { + d[i] = make([]int, n+1) + dp[i] = make([]int, n+1) + } + for _, p := range prices { + d[p[0]][p[1]] = p[2] + } + for i := 1; i <= m; i++ { + for j := 1; j <= n; j++ { + dp[i][j] = d[i][j] + for k := 1; k < i; k++ { + dp[i][j] = max(dp[i][j], dp[k][j]+dp[i-k][j]) + } + for k := 1; k < j; k++ { + dp[i][j] = max(dp[i][j], dp[i][k]+dp[i][j-k]) + } + } + } + return int64(dp[m][n]) +} \ No newline at end of file diff --git a/solution/2300-2399/2312.Selling Pieces of Wood/Solution2.java b/solution/2300-2399/2312.Selling Pieces of Wood/Solution2.java new file mode 100644 index 0000000000000..7881421d3c5a6 --- /dev/null +++ b/solution/2300-2399/2312.Selling Pieces of Wood/Solution2.java @@ -0,0 +1,21 @@ +class Solution { + public long sellingWood(int m, int n, int[][] prices) { + int[][] d = new int[m + 1][n + 1]; + long[][] dp = new long[m + 1][n + 1]; + for (int[] p : prices) { + d[p[0]][p[1]] = p[2]; + } + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + dp[i][j] = d[i][j]; + for (int k = 1; k < i; ++k) { + dp[i][j] = Math.max(dp[i][j], dp[k][j] + dp[i - k][j]); + } + for (int k = 1; k < j; ++k) { + dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[i][j - k]); + } + } + } + return dp[m][n]; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2312.Selling Pieces of Wood/Solution2.py b/solution/2300-2399/2312.Selling Pieces of Wood/Solution2.py new file mode 100644 index 0000000000000..8fe92e5b9be73 --- /dev/null +++ b/solution/2300-2399/2312.Selling Pieces of Wood/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int: + d = defaultdict(dict) + for h, w, p in prices: + d[h][w] = p + dp = [[0] * (n + 1) for _ in range(m + 1)] + for i in range(1, m + 1): + for j in range(1, n + 1): + dp[i][j] = d[i].get(j, 0) + for k in range(1, i): + dp[i][j] = max(dp[i][j], dp[k][j] + dp[i - k][j]) + for k in range(1, j): + dp[i][j] = max(dp[i][j], dp[i][k] + dp[i][j - k]) + return dp[-1][-1] diff --git a/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/Solution.cpp b/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/Solution.cpp index d7036193d7c43..e8287c399ecb9 100644 --- a/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/Solution.cpp +++ b/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/Solution.cpp @@ -1,44 +1,44 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int minimumFlips(TreeNode* root, bool result) { - function(TreeNode*)> dfs = [&](TreeNode* root) -> pair { - if (!root) { - return {1 << 30, 1 << 30}; - } - int x = root->val; - if (x < 2) { - return {x, x ^ 1}; - } - auto [l0, l1] = dfs(root->left); - auto [r0, r1] = dfs(root->right); - int a = 0, b = 0; - if (x == 2) { - a = l0 + r0; - b = min({l0 + r1, l1 + r0, l1 + r1}); - } else if (x == 3) { - a = min({l0 + r0, l0 + r1, l1 + r0}); - b = l1 + r1; - } else if (x == 4) { - a = min(l0 + r0, l1 + r1); - b = min(l0 + r1, l1 + r0); - } else { - a = min(l1, r1); - b = min(l0, r0); - } - return {a, b}; - }; - auto [a, b] = dfs(root); - return result ? b : a; - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int minimumFlips(TreeNode* root, bool result) { + function(TreeNode*)> dfs = [&](TreeNode* root) -> pair { + if (!root) { + return {1 << 30, 1 << 30}; + } + int x = root->val; + if (x < 2) { + return {x, x ^ 1}; + } + auto [l0, l1] = dfs(root->left); + auto [r0, r1] = dfs(root->right); + int a = 0, b = 0; + if (x == 2) { + a = l0 + r0; + b = min({l0 + r1, l1 + r0, l1 + r1}); + } else if (x == 3) { + a = min({l0 + r0, l0 + r1, l1 + r0}); + b = l1 + r1; + } else if (x == 4) { + a = min(l0 + r0, l1 + r1); + b = min(l0 + r1, l1 + r0); + } else { + a = min(l1, r1); + b = min(l0, r0); + } + return {a, b}; + }; + auto [a, b] = dfs(root); + return result ? b : a; + } }; \ No newline at end of file diff --git a/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/Solution.java b/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/Solution.java index 34d48c0feb361..fc8d64b618614 100644 --- a/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/Solution.java +++ b/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/Solution.java @@ -1,47 +1,47 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public int minimumFlips(TreeNode root, boolean result) { - return dfs(root)[result ? 1 : 0]; - } - - private int[] dfs(TreeNode root) { - if (root == null) { - return new int[] {1 << 30, 1 << 30}; - } - int x = root.val; - if (x < 2) { - return new int[] {x, x ^ 1}; - } - var l = dfs(root.left); - var r = dfs(root.right); - int a = 0, b = 0; - if (x == 2) { - a = l[0] + r[0]; - b = Math.min(l[0] + r[1], Math.min(l[1] + r[0], l[1] + r[1])); - } else if (x == 3) { - a = Math.min(l[0] + r[0], Math.min(l[0] + r[1], l[1] + r[0])); - b = l[1] + r[1]; - } else if (x == 4) { - a = Math.min(l[0] + r[0], l[1] + r[1]); - b = Math.min(l[0] + r[1], l[1] + r[0]); - } else { - a = Math.min(l[1], r[1]); - b = Math.min(l[0], r[0]); - } - return new int[] {a, b}; - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int minimumFlips(TreeNode root, boolean result) { + return dfs(root)[result ? 1 : 0]; + } + + private int[] dfs(TreeNode root) { + if (root == null) { + return new int[] {1 << 30, 1 << 30}; + } + int x = root.val; + if (x < 2) { + return new int[] {x, x ^ 1}; + } + var l = dfs(root.left); + var r = dfs(root.right); + int a = 0, b = 0; + if (x == 2) { + a = l[0] + r[0]; + b = Math.min(l[0] + r[1], Math.min(l[1] + r[0], l[1] + r[1])); + } else if (x == 3) { + a = Math.min(l[0] + r[0], Math.min(l[0] + r[1], l[1] + r[0])); + b = l[1] + r[1]; + } else if (x == 4) { + a = Math.min(l[0] + r[0], l[1] + r[1]); + b = Math.min(l[0] + r[1], l[1] + r[0]); + } else { + a = Math.min(l[1], r[1]); + b = Math.min(l[0], r[0]); + } + return new int[] {a, b}; + } } \ No newline at end of file diff --git a/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/Solution.py b/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/Solution.py index c15b2837a3330..0746aabc5a772 100644 --- a/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/Solution.py +++ b/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/Solution.py @@ -1,24 +1,24 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def minimumFlips(self, root: Optional[TreeNode], result: bool) -> int: - def dfs(root: Optional[TreeNode]) -> (int, int): - if root is None: - return inf, inf - x = root.val - if x in (0, 1): - return x, x ^ 1 - l, r = dfs(root.left), dfs(root.right) - if x == 2: - return l[0] + r[0], min(l[0] + r[1], l[1] + r[0], l[1] + r[1]) - if x == 3: - return min(l[0] + r[0], l[0] + r[1], l[1] + r[0]), l[1] + r[1] - if x == 4: - return min(l[0] + r[0], l[1] + r[1]), min(l[0] + r[1], l[1] + r[0]) - return min(l[1], r[1]), min(l[0], r[0]) - - return dfs(root)[int(result)] +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def minimumFlips(self, root: Optional[TreeNode], result: bool) -> int: + def dfs(root: Optional[TreeNode]) -> (int, int): + if root is None: + return inf, inf + x = root.val + if x in (0, 1): + return x, x ^ 1 + l, r = dfs(root.left), dfs(root.right) + if x == 2: + return l[0] + r[0], min(l[0] + r[1], l[1] + r[0], l[1] + r[1]) + if x == 3: + return min(l[0] + r[0], l[0] + r[1], l[1] + r[0]), l[1] + r[1] + if x == 4: + return min(l[0] + r[0], l[1] + r[1]), min(l[0] + r[1], l[1] + r[0]) + return min(l[1], r[1]), min(l[0], r[0]) + + return dfs(root)[int(result)] diff --git a/solution/2300-2399/2315.Count Asterisks/Solution.cs b/solution/2300-2399/2315.Count Asterisks/Solution.cs index 7f1490aaea18d..32f7f5bf81b8f 100644 --- a/solution/2300-2399/2315.Count Asterisks/Solution.cs +++ b/solution/2300-2399/2315.Count Asterisks/Solution.cs @@ -10,4 +10,4 @@ public int CountAsterisks(string s) { } return ans; } -} \ No newline at end of file +} diff --git a/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/Solution.cpp b/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/Solution.cpp index e4446ae8e875e..a746599a6e45b 100644 --- a/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/Solution.cpp +++ b/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/Solution.cpp @@ -1,31 +1,31 @@ -class Solution { -public: - long long countPairs(int n, vector>& edges) { - vector g[n]; - for (auto& e : edges) { - int a = e[0], b = e[1]; - g[a].push_back(b); - g[b].push_back(a); - } - bool vis[n]; - memset(vis, 0, sizeof(vis)); - function dfs = [&](int i) { - if (vis[i]) { - return 0; - } - vis[i] = true; - int cnt = 1; - for (int j : g[i]) { - cnt += dfs(j); - } - return cnt; - }; - long long ans = 0, s = 0; - for (int i = 0; i < n; ++i) { - int t = dfs(i); - ans += s * t; - s += t; - } - return ans; - } +class Solution { +public: + long long countPairs(int n, vector>& edges) { + vector g[n]; + for (auto& e : edges) { + int a = e[0], b = e[1]; + g[a].push_back(b); + g[b].push_back(a); + } + bool vis[n]; + memset(vis, 0, sizeof(vis)); + function dfs = [&](int i) { + if (vis[i]) { + return 0; + } + vis[i] = true; + int cnt = 1; + for (int j : g[i]) { + cnt += dfs(j); + } + return cnt; + }; + long long ans = 0, s = 0; + for (int i = 0; i < n; ++i) { + int t = dfs(i); + ans += s * t; + s += t; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/Solution.java b/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/Solution.java index 4081734f4c439..232e9cf9de599 100644 --- a/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/Solution.java +++ b/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/Solution.java @@ -1,34 +1,34 @@ -class Solution { - private List[] g; - private boolean[] vis; - - public long countPairs(int n, int[][] edges) { - g = new List[n]; - vis = new boolean[n]; - Arrays.setAll(g, i -> new ArrayList<>()); - for (var e : edges) { - int a = e[0], b = e[1]; - g[a].add(b); - g[b].add(a); - } - long ans = 0, s = 0; - for (int i = 0; i < n; ++i) { - int t = dfs(i); - ans += s * t; - s += t; - } - return ans; - } - - private int dfs(int i) { - if (vis[i]) { - return 0; - } - vis[i] = true; - int cnt = 1; - for (int j : g[i]) { - cnt += dfs(j); - } - return cnt; - } +class Solution { + private List[] g; + private boolean[] vis; + + public long countPairs(int n, int[][] edges) { + g = new List[n]; + vis = new boolean[n]; + Arrays.setAll(g, i -> new ArrayList<>()); + for (var e : edges) { + int a = e[0], b = e[1]; + g[a].add(b); + g[b].add(a); + } + long ans = 0, s = 0; + for (int i = 0; i < n; ++i) { + int t = dfs(i); + ans += s * t; + s += t; + } + return ans; + } + + private int dfs(int i) { + if (vis[i]) { + return 0; + } + vis[i] = true; + int cnt = 1; + for (int j : g[i]) { + cnt += dfs(j); + } + return cnt; + } } \ No newline at end of file diff --git a/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/Solution.py b/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/Solution.py index 074b9cabb7a9f..4a038ce31d7ba 100644 --- a/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/Solution.py +++ b/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/Solution.py @@ -1,19 +1,19 @@ -class Solution: - def countPairs(self, n: int, edges: List[List[int]]) -> int: - def dfs(i: int) -> int: - if vis[i]: - return 0 - vis[i] = True - return 1 + sum(dfs(j) for j in g[i]) - - g = [[] for _ in range(n)] - for a, b in edges: - g[a].append(b) - g[b].append(a) - vis = [False] * n - ans = s = 0 - for i in range(n): - t = dfs(i) - ans += s * t - s += t - return ans +class Solution: + def countPairs(self, n: int, edges: List[List[int]]) -> int: + def dfs(i: int) -> int: + if vis[i]: + return 0 + vis[i] = True + return 1 + sum(dfs(j) for j in g[i]) + + g = [[] for _ in range(n)] + for a, b in edges: + g[a].append(b) + g[b].append(a) + vis = [False] * n + ans = s = 0 + for i in range(n): + t = dfs(i) + ans += s * t + s += t + return ans diff --git a/solution/2300-2399/2319.Check if Matrix Is X-Matrix/Solution.c b/solution/2300-2399/2319.Check if Matrix Is X-Matrix/Solution.c index e7465ac5f8fef..7d4f307d05aee 100644 --- a/solution/2300-2399/2319.Check if Matrix Is X-Matrix/Solution.c +++ b/solution/2300-2399/2319.Check if Matrix Is X-Matrix/Solution.c @@ -11,4 +11,4 @@ bool checkXMatrix(int** grid, int gridSize, int* gridColSize) { } } return true; -} +} \ No newline at end of file diff --git a/solution/2300-2399/2319.Check if Matrix Is X-Matrix/Solution.cs b/solution/2300-2399/2319.Check if Matrix Is X-Matrix/Solution.cs index 32420f688e0e2..f77c58675d92c 100644 --- a/solution/2300-2399/2319.Check if Matrix Is X-Matrix/Solution.cs +++ b/solution/2300-2399/2319.Check if Matrix Is X-Matrix/Solution.cs @@ -14,4 +14,4 @@ public bool CheckXMatrix(int[][] grid) { } return true; } -} \ No newline at end of file +} diff --git a/solution/2300-2399/2320.Count Number of Ways to Place Houses/Solution.cs b/solution/2300-2399/2320.Count Number of Ways to Place Houses/Solution.cs index 8fe2a31f161e3..3e4474c131990 100644 --- a/solution/2300-2399/2320.Count Number of Ways to Place Houses/Solution.cs +++ b/solution/2300-2399/2320.Count Number of Ways to Place Houses/Solution.cs @@ -11,4 +11,4 @@ public int CountHousePlacements(int n) { long v = (f[n - 1] + g[n - 1]) % mod; return (int) (v * v % mod); } -} \ No newline at end of file +} diff --git a/solution/2300-2399/2325.Decode the Message/Solution.c b/solution/2300-2399/2325.Decode the Message/Solution.c index b1328f87da271..e19d30bcc6205 100644 --- a/solution/2300-2399/2325.Decode the Message/Solution.c +++ b/solution/2300-2399/2325.Decode the Message/Solution.c @@ -15,4 +15,4 @@ char* decodeMessage(char* key, char* message) { } ans[n] = '\0'; return ans; -} +} \ No newline at end of file diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.c b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.c index b701070bb39ff..e370424f70ce5 100644 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.c +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.c @@ -14,4 +14,4 @@ bool evaluateTree(struct TreeNode* root) { return evaluateTree(root->left) || evaluateTree(root->right); } return evaluateTree(root->left) && evaluateTree(root->right); -} +} \ No newline at end of file diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.cpp b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.cpp index fe76cf937ecbc..7904ca8733341 100644 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.cpp +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.cpp @@ -12,11 +12,13 @@ class Solution { public: bool evaluateTree(TreeNode* root) { - if (!root->left) { - return root->val; - } - bool l = evaluateTree(root->left); - bool r = evaluateTree(root->right); - return root->val == 2 ? l or r : l and r; + return dfs(root); + } + + bool dfs(TreeNode* root) { + if (!root->left && !root->right) return root->val; + bool l = dfs(root->left), r = dfs(root->right); + if (root->val == 2) return l || r; + return l && r; } }; \ No newline at end of file diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.go b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.go index 3acf50ef352a3..e9e16ce2f3801 100644 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.go +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.go @@ -7,12 +7,16 @@ * } */ func evaluateTree(root *TreeNode) bool { - if root.Left == nil { - return root.Val == 1 + var dfs func(*TreeNode) bool + dfs = func(root *TreeNode) bool { + if root.Left == nil && root.Right == nil { + return root.Val == 1 + } + l, r := dfs(root.Left), dfs(root.Right) + if root.Val == 2 { + return l || r + } + return l && r } - l, r := evaluateTree(root.Left), evaluateTree(root.Right) - if root.Val == 2 { - return l || r - } - return l && r + return dfs(root) } \ No newline at end of file diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.java b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.java index ce00b11f767d8..f39e3671d451b 100644 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.java +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.java @@ -15,11 +15,17 @@ */ class Solution { public boolean evaluateTree(TreeNode root) { - if (root.left == null) { + return dfs(root); + } + + private boolean dfs(TreeNode root) { + if (root.left == null && root.right == null) { return root.val == 1; } - boolean l = evaluateTree(root.left); - boolean r = evaluateTree(root.right); - return root.val == 2 ? l || r : l && r; + boolean l = dfs(root.left), r = dfs(root.right); + if (root.val == 2) { + return l || r; + } + return l && r; } } \ No newline at end of file diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.py b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.py index 3fdfcb7659bb1..75b51b5a7a707 100644 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.py +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.py @@ -6,8 +6,10 @@ # self.right = right class Solution: def evaluateTree(self, root: Optional[TreeNode]) -> bool: - if root.left is None: - return bool(root.val) - l = self.evaluateTree(root.left) - r = self.evaluateTree(root.right) - return l or r if root.val == 2 else l and r + def dfs(root): + if root.left is None and root.right is None: + return bool(root.val) + l, r = dfs(root.left), dfs(root.right) + return (l or r) if root.val == 2 else (l and r) + + return dfs(root) diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.cpp b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.cpp new file mode 100644 index 0000000000000..fe76cf937ecbc --- /dev/null +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.cpp @@ -0,0 +1,22 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool evaluateTree(TreeNode* root) { + if (!root->left) { + return root->val; + } + bool l = evaluateTree(root->left); + bool r = evaluateTree(root->right); + return root->val == 2 ? l or r : l and r; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.go b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.go new file mode 100644 index 0000000000000..3acf50ef352a3 --- /dev/null +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.go @@ -0,0 +1,18 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func evaluateTree(root *TreeNode) bool { + if root.Left == nil { + return root.Val == 1 + } + l, r := evaluateTree(root.Left), evaluateTree(root.Right) + if root.Val == 2 { + return l || r + } + return l && r +} \ No newline at end of file diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.java b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.java new file mode 100644 index 0000000000000..ce00b11f767d8 --- /dev/null +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.java @@ -0,0 +1,25 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean evaluateTree(TreeNode root) { + if (root.left == null) { + return root.val == 1; + } + boolean l = evaluateTree(root.left); + boolean r = evaluateTree(root.right); + return root.val == 2 ? l || r : l && r; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.py b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.py new file mode 100644 index 0000000000000..3fdfcb7659bb1 --- /dev/null +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.py @@ -0,0 +1,13 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def evaluateTree(self, root: Optional[TreeNode]) -> bool: + if root.left is None: + return bool(root.val) + l = self.evaluateTree(root.left) + r = self.evaluateTree(root.right) + return l or r if root.val == 2 else l and r diff --git a/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution.cpp b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution.cpp index 965c1914abe79..f4ec6bc9791c7 100644 --- a/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution.cpp +++ b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution.cpp @@ -1,28 +1,38 @@ +using pii = pair; + class Solution { public: + vector p; + vector size; + int validSubarraySize(vector& nums, int threshold) { int n = nums.size(); - vector left(n, -1); - vector right(n, n); - stack stk; - for (int i = 0; i < n; ++i) { - int v = nums[i]; - while (!stk.empty() && nums[stk.top()] >= v) stk.pop(); - if (!stk.empty()) left[i] = stk.top(); - stk.push(i); - } - stk = stack(); - for (int i = n - 1; ~i; --i) { - int v = nums[i]; - while (!stk.empty() && nums[stk.top()] >= v) stk.pop(); - if (!stk.empty()) right[i] = stk.top(); - stk.push(i); - } - for (int i = 0; i < n; ++i) { - int v = nums[i]; - int k = right[i] - left[i] - 1; - if (v > threshold / k) return k; + p.resize(n); + for (int i = 0; i < n; ++i) p[i] = i; + size.assign(n, 1); + vector arr(n); + for (int i = 0; i < n; ++i) arr[i] = {nums[i], i}; + sort(arr.begin(), arr.end()); + vector vis(n); + for (int j = n - 1; ~j; --j) { + int v = arr[j].first, i = arr[j].second; + if (i && vis[i - 1]) merge(i, i - 1); + if (j < n - 1 && vis[i + 1]) merge(i, i + 1); + if (v > threshold / size[find(i)]) return size[find(i)]; + vis[i] = true; } return -1; } + + int find(int x) { + if (p[x] != x) p[x] = find(p[x]); + return p[x]; + } + + void merge(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) return; + p[pa] = pb; + size[pb] += size[pa]; + } }; \ No newline at end of file diff --git a/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution.go b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution.go index 63da8f0af12e6..8e3aa49f9116f 100644 --- a/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution.go +++ b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution.go @@ -1,37 +1,47 @@ func validSubarraySize(nums []int, threshold int) int { n := len(nums) - left := make([]int, n) - right := make([]int, n) - for i := range left { - left[i] = -1 - right[i] = n + p := make([]int, n) + size := make([]int, n) + for i := range p { + p[i] = i + size[i] = 1 } - var stk []int - for i, v := range nums { - for len(stk) > 0 && nums[stk[len(stk)-1]] >= v { - stk = stk[:len(stk)-1] - } - if len(stk) > 0 { - left[i] = stk[len(stk)-1] + var find func(int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) } - stk = append(stk, i) + return p[x] } - stk = []int{} - for i := n - 1; i >= 0; i-- { - v := nums[i] - for len(stk) > 0 && nums[stk[len(stk)-1]] >= v { - stk = stk[:len(stk)-1] - } - if len(stk) > 0 { - right[i] = stk[len(stk)-1] + merge := func(a, b int) { + pa, pb := find(a), find(b) + if pa == pb { + return } - stk = append(stk, i) + p[pa] = pb + size[pb] += size[pa] } + + arr := make([][]int, n) for i, v := range nums { - k := right[i] - left[i] - 1 - if v > threshold/k { - return k + arr[i] = []int{v, i} + } + sort.Slice(arr, func(i, j int) bool { + return arr[i][0] > arr[j][0] + }) + vis := make([]bool, n) + for _, e := range arr { + v, i := e[0], e[1] + if i > 0 && vis[i-1] { + merge(i, i-1) + } + if i < n-1 && vis[i+1] { + merge(i, i+1) + } + if v > threshold/size[find(i)] { + return size[find(i)] } + vis[i] = true } return -1 } \ No newline at end of file diff --git a/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution.java b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution.java index c0a36e4e5402f..19db4e2e79213 100644 --- a/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution.java +++ b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution.java @@ -1,39 +1,51 @@ class Solution { + private int[] p; + private int[] size; + public int validSubarraySize(int[] nums, int threshold) { int n = nums.length; - int[] left = new int[n]; - int[] right = new int[n]; - Arrays.fill(left, -1); - Arrays.fill(right, n); - Deque stk = new ArrayDeque<>(); + p = new int[n]; + size = new int[n]; for (int i = 0; i < n; ++i) { - int v = nums[i]; - while (!stk.isEmpty() && nums[stk.peek()] >= v) { - stk.pop(); - } - if (!stk.isEmpty()) { - left[i] = stk.peek(); - } - stk.push(i); + p[i] = i; + size[i] = 1; } - stk.clear(); - for (int i = n - 1; i >= 0; --i) { - int v = nums[i]; - while (!stk.isEmpty() && nums[stk.peek()] >= v) { - stk.pop(); + int[][] arr = new int[n][2]; + for (int i = 0; i < n; ++i) { + arr[i][0] = nums[i]; + arr[i][1] = i; + } + Arrays.sort(arr, (a, b) -> b[0] - a[0]); + boolean[] vis = new boolean[n]; + for (int[] e : arr) { + int v = e[0], i = e[1]; + if (i > 0 && vis[i - 1]) { + merge(i, i - 1); } - if (!stk.isEmpty()) { - right[i] = stk.peek(); + if (i < n - 1 && vis[i + 1]) { + merge(i, i + 1); } - stk.push(i); - } - for (int i = 0; i < n; ++i) { - int v = nums[i]; - int k = right[i] - left[i] - 1; - if (v > threshold / k) { - return k; + if (v > threshold / size[find(i)]) { + return size[find(i)]; } + vis[i] = true; } return -1; } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + + private void merge(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) { + return; + } + p[pa] = pb; + size[pb] += size[pa]; + } } \ No newline at end of file diff --git a/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution.py b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution.py index dfb26e345eff4..df6c2c2b42230 100644 --- a/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution.py +++ b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution.py @@ -1,24 +1,28 @@ class Solution: def validSubarraySize(self, nums: List[int], threshold: int) -> int: + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + def merge(a, b): + pa, pb = find(a), find(b) + if pa == pb: + return + p[pa] = pb + size[pb] += size[pa] + n = len(nums) - left = [-1] * n - right = [n] * n - stk = [] - for i, v in enumerate(nums): - while stk and nums[stk[-1]] >= v: - stk.pop() - if stk: - left[i] = stk[-1] - stk.append(i) - stk = [] - for i in range(n - 1, -1, -1): - while stk and nums[stk[-1]] >= nums[i]: - stk.pop() - if stk: - right[i] = stk[-1] - stk.append(i) - for i, v in enumerate(nums): - k = right[i] - left[i] - 1 - if v > threshold // k: - return k + p = list(range(n)) + size = [1] * n + arr = sorted(zip(nums, range(n)), reverse=True) + vis = [False] * n + for v, i in arr: + if i and vis[i - 1]: + merge(i, i - 1) + if i < n - 1 and vis[i + 1]: + merge(i, i + 1) + if v > threshold // size[find(i)]: + return size[find(i)] + vis[i] = True return -1 diff --git a/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution2.cpp b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution2.cpp new file mode 100644 index 0000000000000..965c1914abe79 --- /dev/null +++ b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution2.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int validSubarraySize(vector& nums, int threshold) { + int n = nums.size(); + vector left(n, -1); + vector right(n, n); + stack stk; + for (int i = 0; i < n; ++i) { + int v = nums[i]; + while (!stk.empty() && nums[stk.top()] >= v) stk.pop(); + if (!stk.empty()) left[i] = stk.top(); + stk.push(i); + } + stk = stack(); + for (int i = n - 1; ~i; --i) { + int v = nums[i]; + while (!stk.empty() && nums[stk.top()] >= v) stk.pop(); + if (!stk.empty()) right[i] = stk.top(); + stk.push(i); + } + for (int i = 0; i < n; ++i) { + int v = nums[i]; + int k = right[i] - left[i] - 1; + if (v > threshold / k) return k; + } + return -1; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution2.go b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution2.go new file mode 100644 index 0000000000000..63da8f0af12e6 --- /dev/null +++ b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution2.go @@ -0,0 +1,37 @@ +func validSubarraySize(nums []int, threshold int) int { + n := len(nums) + left := make([]int, n) + right := make([]int, n) + for i := range left { + left[i] = -1 + right[i] = n + } + var stk []int + for i, v := range nums { + for len(stk) > 0 && nums[stk[len(stk)-1]] >= v { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + left[i] = stk[len(stk)-1] + } + stk = append(stk, i) + } + stk = []int{} + for i := n - 1; i >= 0; i-- { + v := nums[i] + for len(stk) > 0 && nums[stk[len(stk)-1]] >= v { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + right[i] = stk[len(stk)-1] + } + stk = append(stk, i) + } + for i, v := range nums { + k := right[i] - left[i] - 1 + if v > threshold/k { + return k + } + } + return -1 +} \ No newline at end of file diff --git a/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution2.java b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution2.java new file mode 100644 index 0000000000000..c0a36e4e5402f --- /dev/null +++ b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution2.java @@ -0,0 +1,39 @@ +class Solution { + public int validSubarraySize(int[] nums, int threshold) { + int n = nums.length; + int[] left = new int[n]; + int[] right = new int[n]; + Arrays.fill(left, -1); + Arrays.fill(right, n); + Deque stk = new ArrayDeque<>(); + for (int i = 0; i < n; ++i) { + int v = nums[i]; + while (!stk.isEmpty() && nums[stk.peek()] >= v) { + stk.pop(); + } + if (!stk.isEmpty()) { + left[i] = stk.peek(); + } + stk.push(i); + } + stk.clear(); + for (int i = n - 1; i >= 0; --i) { + int v = nums[i]; + while (!stk.isEmpty() && nums[stk.peek()] >= v) { + stk.pop(); + } + if (!stk.isEmpty()) { + right[i] = stk.peek(); + } + stk.push(i); + } + for (int i = 0; i < n; ++i) { + int v = nums[i]; + int k = right[i] - left[i] - 1; + if (v > threshold / k) { + return k; + } + } + return -1; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution2.py b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution2.py new file mode 100644 index 0000000000000..dfb26e345eff4 --- /dev/null +++ b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution2.py @@ -0,0 +1,24 @@ +class Solution: + def validSubarraySize(self, nums: List[int], threshold: int) -> int: + n = len(nums) + left = [-1] * n + right = [n] * n + stk = [] + for i, v in enumerate(nums): + while stk and nums[stk[-1]] >= v: + stk.pop() + if stk: + left[i] = stk[-1] + stk.append(i) + stk = [] + for i in range(n - 1, -1, -1): + while stk and nums[stk[-1]] >= nums[i]: + stk.pop() + if stk: + right[i] = stk[-1] + stk.append(i) + for i, v in enumerate(nums): + k = right[i] - left[i] - 1 + if v > threshold // k: + return k + return -1 diff --git a/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution.cpp b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution.cpp index 49423d00ddd39..f44bf38f0f8f3 100644 --- a/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution.cpp +++ b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution.cpp @@ -1,10 +1,13 @@ class Solution { public: int fillCups(vector& amount) { - sort(amount.begin(), amount.end()); - if (amount[0] + amount[1] <= amount[2]) { - return amount[2]; + int ans = 0; + while (amount[0] + amount[1] + amount[2]) { + sort(amount.begin(), amount.end()); + ++ans; + amount[2]--; + amount[1] = max(0, amount[1] - 1); } - return (amount[0] + amount[1] + amount[2] + 1) / 2; + return ans; } }; \ No newline at end of file diff --git a/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution.go b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution.go index 6ce34cf1443f0..e4baeb6fca107 100644 --- a/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution.go +++ b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution.go @@ -1,7 +1,12 @@ func fillCups(amount []int) int { - sort.Ints(amount) - if amount[0]+amount[1] <= amount[2] { - return amount[2] + ans := 0 + for amount[0]+amount[1]+amount[2] > 0 { + sort.Ints(amount) + ans++ + amount[2]-- + if amount[1] > 0 { + amount[1]-- + } } - return (amount[0] + amount[1] + amount[2] + 1) / 2 + return ans } \ No newline at end of file diff --git a/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution.java b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution.java index c50283712aa2e..218aa9d536a0d 100644 --- a/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution.java +++ b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution.java @@ -1,9 +1,12 @@ class Solution { public int fillCups(int[] amount) { - Arrays.sort(amount); - if (amount[0] + amount[1] <= amount[2]) { - return amount[2]; + int ans = 0; + while (amount[0] + amount[1] + amount[2] > 0) { + Arrays.sort(amount); + ++ans; + amount[2]--; + amount[1] = Math.max(0, amount[1] - 1); } - return (amount[0] + amount[1] + amount[2] + 1) / 2; + return ans; } } \ No newline at end of file diff --git a/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution.py b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution.py index 6df1bcf664cea..8064e45f42401 100644 --- a/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution.py +++ b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution.py @@ -1,6 +1,9 @@ class Solution: def fillCups(self, amount: List[int]) -> int: - amount.sort() - if amount[0] + amount[1] <= amount[2]: - return amount[2] - return (sum(amount) + 1) // 2 + ans = 0 + while sum(amount): + amount.sort() + ans += 1 + amount[2] -= 1 + amount[1] = max(0, amount[1] - 1) + return ans diff --git a/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution2.cpp b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution2.cpp new file mode 100644 index 0000000000000..49423d00ddd39 --- /dev/null +++ b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution2.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + int fillCups(vector& amount) { + sort(amount.begin(), amount.end()); + if (amount[0] + amount[1] <= amount[2]) { + return amount[2]; + } + return (amount[0] + amount[1] + amount[2] + 1) / 2; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution2.go b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution2.go new file mode 100644 index 0000000000000..6ce34cf1443f0 --- /dev/null +++ b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution2.go @@ -0,0 +1,7 @@ +func fillCups(amount []int) int { + sort.Ints(amount) + if amount[0]+amount[1] <= amount[2] { + return amount[2] + } + return (amount[0] + amount[1] + amount[2] + 1) / 2 +} \ No newline at end of file diff --git a/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution2.java b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution2.java new file mode 100644 index 0000000000000..c50283712aa2e --- /dev/null +++ b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution2.java @@ -0,0 +1,9 @@ +class Solution { + public int fillCups(int[] amount) { + Arrays.sort(amount); + if (amount[0] + amount[1] <= amount[2]) { + return amount[2]; + } + return (amount[0] + amount[1] + amount[2] + 1) / 2; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution2.py b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution2.py new file mode 100644 index 0000000000000..6df1bcf664cea --- /dev/null +++ b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/Solution2.py @@ -0,0 +1,6 @@ +class Solution: + def fillCups(self, amount: List[int]) -> int: + amount.sort() + if amount[0] + amount[1] <= amount[2]: + return amount[2] + return (sum(amount) + 1) // 2 diff --git a/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution.cpp b/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution.cpp index e371130bb3422..77013521ea8a7 100644 --- a/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution.cpp +++ b/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution.cpp @@ -1,28 +1,28 @@ -class SmallestInfiniteSet { -public: - SmallestInfiniteSet() { - for (int i = 1; i <= 1000; ++i) { - s.insert(i); - } - } - - int popSmallest() { - int x = *s.begin(); - s.erase(s.begin()); - return x; - } - - void addBack(int num) { - s.insert(num); - } - -private: - set s; -}; - -/** - * Your SmallestInfiniteSet object will be instantiated and called as such: - * SmallestInfiniteSet* obj = new SmallestInfiniteSet(); - * int param_1 = obj->popSmallest(); - * obj->addBack(num); +class SmallestInfiniteSet { +public: + SmallestInfiniteSet() { + for (int i = 1; i <= 1000; ++i) { + s.insert(i); + } + } + + int popSmallest() { + int x = *s.begin(); + s.erase(s.begin()); + return x; + } + + void addBack(int num) { + s.insert(num); + } + +private: + set s; +}; + +/** + * Your SmallestInfiniteSet object will be instantiated and called as such: + * SmallestInfiniteSet* obj = new SmallestInfiniteSet(); + * int param_1 = obj->popSmallest(); + * obj->addBack(num); */ \ No newline at end of file diff --git a/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution.java b/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution.java index 3b6adca8cc209..093893642b465 100644 --- a/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution.java +++ b/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution.java @@ -1,24 +1,24 @@ -class SmallestInfiniteSet { - private TreeSet s = new TreeSet<>(); - - public SmallestInfiniteSet() { - for (int i = 1; i <= 1000; ++i) { - s.add(i); - } - } - - public int popSmallest() { - return s.pollFirst(); - } - - public void addBack(int num) { - s.add(num); - } -} - -/** - * Your SmallestInfiniteSet object will be instantiated and called as such: - * SmallestInfiniteSet obj = new SmallestInfiniteSet(); - * int param_1 = obj.popSmallest(); - * obj.addBack(num); +class SmallestInfiniteSet { + private TreeSet s = new TreeSet<>(); + + public SmallestInfiniteSet() { + for (int i = 1; i <= 1000; ++i) { + s.add(i); + } + } + + public int popSmallest() { + return s.pollFirst(); + } + + public void addBack(int num) { + s.add(num); + } +} + +/** + * Your SmallestInfiniteSet object will be instantiated and called as such: + * SmallestInfiniteSet obj = new SmallestInfiniteSet(); + * int param_1 = obj.popSmallest(); + * obj.addBack(num); */ \ No newline at end of file diff --git a/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution.py b/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution.py index cb78e926aa7c3..e6be6e00ce732 100644 --- a/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution.py +++ b/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution.py @@ -1,20 +1,20 @@ -from sortedcontainers import SortedSet - - -class SmallestInfiniteSet: - def __init__(self): - self.s = SortedSet(range(1, 1001)) - - def popSmallest(self) -> int: - x = self.s[0] - self.s.remove(x) - return x - - def addBack(self, num: int) -> None: - self.s.add(num) - - -# Your SmallestInfiniteSet object will be instantiated and called as such: -# obj = SmallestInfiniteSet() -# param_1 = obj.popSmallest() -# obj.addBack(num) +from sortedcontainers import SortedSet + + +class SmallestInfiniteSet: + def __init__(self): + self.s = SortedSet(range(1, 1001)) + + def popSmallest(self) -> int: + x = self.s[0] + self.s.remove(x) + return x + + def addBack(self, num: int) -> None: + self.s.add(num) + + +# Your SmallestInfiniteSet object will be instantiated and called as such: +# obj = SmallestInfiniteSet() +# param_1 = obj.popSmallest() +# obj.addBack(num) diff --git a/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution.ts b/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution.ts index 1643b51cff370..aa3c0d59b5612 100644 --- a/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution.ts +++ b/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution.ts @@ -1,27 +1,659 @@ class SmallestInfiniteSet { - private pq: typeof MinPriorityQueue; - private s: Set; + private s: TreeSet; constructor() { - this.pq = new MinPriorityQueue(); - this.s = new Set(); - for (let i = 1; i <= 1000; i++) { - this.pq.enqueue(i, i); + this.s = new TreeSet(); + for (let i = 1; i <= 1000; ++i) { this.s.add(i); } } popSmallest(): number { - const x = this.pq.dequeue()?.element; - this.s.delete(x); - return x; + return this.s.shift()!; } addBack(num: number): void { - if (!this.s.has(num)) { - this.pq.enqueue(num, num); - this.s.add(num); + this.s.add(num); + } +} + +type Compare = (lhs: T, rhs: T) => number; + +class RBTreeNode { + data: T; + count: number; + left: RBTreeNode | null; + right: RBTreeNode | null; + parent: RBTreeNode | null; + color: number; + constructor(data: T) { + this.data = data; + this.left = this.right = this.parent = null; + this.color = 0; + this.count = 1; + } + + sibling(): RBTreeNode | null { + if (!this.parent) return null; // sibling null if no parent + return this.isOnLeft() ? this.parent.right : this.parent.left; + } + + isOnLeft(): boolean { + return this === this.parent!.left; + } + + hasRedChild(): boolean { + return ( + Boolean(this.left && this.left.color === 0) || + Boolean(this.right && this.right.color === 0) + ); + } +} + +class RBTree { + root: RBTreeNode | null; + lt: (l: T, r: T) => boolean; + constructor(compare: Compare = (l: T, r: T) => (l < r ? -1 : l > r ? 1 : 0)) { + this.root = null; + this.lt = (l: T, r: T) => compare(l, r) < 0; + } + + rotateLeft(pt: RBTreeNode): void { + const right = pt.right!; + pt.right = right.left; + + if (pt.right) pt.right.parent = pt; + right.parent = pt.parent; + + if (!pt.parent) this.root = right; + else if (pt === pt.parent.left) pt.parent.left = right; + else pt.parent.right = right; + + right.left = pt; + pt.parent = right; + } + + rotateRight(pt: RBTreeNode): void { + const left = pt.left!; + pt.left = left.right; + + if (pt.left) pt.left.parent = pt; + left.parent = pt.parent; + + if (!pt.parent) this.root = left; + else if (pt === pt.parent.left) pt.parent.left = left; + else pt.parent.right = left; + + left.right = pt; + pt.parent = left; + } + + swapColor(p1: RBTreeNode, p2: RBTreeNode): void { + const tmp = p1.color; + p1.color = p2.color; + p2.color = tmp; + } + + swapData(p1: RBTreeNode, p2: RBTreeNode): void { + const tmp = p1.data; + p1.data = p2.data; + p2.data = tmp; + } + + fixAfterInsert(pt: RBTreeNode): void { + let parent = null; + let grandParent = null; + + while (pt !== this.root && pt.color !== 1 && pt.parent?.color === 0) { + parent = pt.parent; + grandParent = pt.parent.parent; + + /* Case : A + Parent of pt is left child of Grand-parent of pt */ + if (parent === grandParent?.left) { + const uncle = grandParent.right; + + /* Case : 1 + The uncle of pt is also red + Only Recoloring required */ + if (uncle && uncle.color === 0) { + grandParent.color = 0; + parent.color = 1; + uncle.color = 1; + pt = grandParent; + } else { + /* Case : 2 + pt is right child of its parent + Left-rotation required */ + if (pt === parent.right) { + this.rotateLeft(parent); + pt = parent; + parent = pt.parent; + } + + /* Case : 3 + pt is left child of its parent + Right-rotation required */ + this.rotateRight(grandParent); + this.swapColor(parent!, grandParent); + pt = parent!; + } + } else { + /* Case : B + Parent of pt is right child of Grand-parent of pt */ + const uncle = grandParent!.left; + + /* Case : 1 + The uncle of pt is also red + Only Recoloring required */ + if (uncle != null && uncle.color === 0) { + grandParent!.color = 0; + parent.color = 1; + uncle.color = 1; + pt = grandParent!; + } else { + /* Case : 2 + pt is left child of its parent + Right-rotation required */ + if (pt === parent.left) { + this.rotateRight(parent); + pt = parent; + parent = pt.parent; + } + + /* Case : 3 + pt is right child of its parent + Left-rotation required */ + this.rotateLeft(grandParent!); + this.swapColor(parent!, grandParent!); + pt = parent!; + } + } + } + this.root!.color = 1; + } + + delete(val: T): boolean { + const node = this.find(val); + if (!node) return false; + node.count--; + if (!node.count) this.deleteNode(node); + return true; + } + + deleteAll(val: T): boolean { + const node = this.find(val); + if (!node) return false; + this.deleteNode(node); + return true; + } + + deleteNode(v: RBTreeNode): void { + const u = BSTreplace(v); + + // True when u and v are both black + const uvBlack = (u === null || u.color === 1) && v.color === 1; + const parent = v.parent!; + + if (!u) { + // u is null therefore v is leaf + if (v === this.root) this.root = null; + // v is root, making root null + else { + if (uvBlack) { + // u and v both black + // v is leaf, fix double black at v + this.fixDoubleBlack(v); + } else { + // u or v is red + if (v.sibling()) { + // sibling is not null, make it red" + v.sibling()!.color = 0; + } + } + // delete v from the tree + if (v.isOnLeft()) parent.left = null; + else parent.right = null; + } + return; + } + + if (!v.left || !v.right) { + // v has 1 child + if (v === this.root) { + // v is root, assign the value of u to v, and delete u + v.data = u.data; + v.left = v.right = null; + } else { + // Detach v from tree and move u up + if (v.isOnLeft()) parent.left = u; + else parent.right = u; + u.parent = parent; + if (uvBlack) this.fixDoubleBlack(u); + // u and v both black, fix double black at u + else u.color = 1; // u or v red, color u black + } + return; + } + + // v has 2 children, swap data with successor and recurse + this.swapData(u, v); + this.deleteNode(u); + + // find node that replaces a deleted node in BST + function BSTreplace(x: RBTreeNode): RBTreeNode | null { + // when node have 2 children + if (x.left && x.right) return successor(x.right); + // when leaf + if (!x.left && !x.right) return null; + // when single child + return x.left ?? x.right; + } + // find node that do not have a left child + // in the subtree of the given node + function successor(x: RBTreeNode): RBTreeNode { + let temp = x; + while (temp.left) temp = temp.left; + return temp; + } + } + + fixDoubleBlack(x: RBTreeNode): void { + if (x === this.root) return; // Reached root + + const sibling = x.sibling(); + const parent = x.parent!; + if (!sibling) { + // No sibiling, double black pushed up + this.fixDoubleBlack(parent); + } else { + if (sibling.color === 0) { + // Sibling red + parent.color = 0; + sibling.color = 1; + if (sibling.isOnLeft()) this.rotateRight(parent); + // left case + else this.rotateLeft(parent); // right case + this.fixDoubleBlack(x); + } else { + // Sibling black + if (sibling.hasRedChild()) { + // at least 1 red children + if (sibling.left && sibling.left.color === 0) { + if (sibling.isOnLeft()) { + // left left + sibling.left.color = sibling.color; + sibling.color = parent.color; + this.rotateRight(parent); + } else { + // right left + sibling.left.color = parent.color; + this.rotateRight(sibling); + this.rotateLeft(parent); + } + } else { + if (sibling.isOnLeft()) { + // left right + sibling.right!.color = parent.color; + this.rotateLeft(sibling); + this.rotateRight(parent); + } else { + // right right + sibling.right!.color = sibling.color; + sibling.color = parent.color; + this.rotateLeft(parent); + } + } + parent.color = 1; + } else { + // 2 black children + sibling.color = 0; + if (parent.color === 1) this.fixDoubleBlack(parent); + else parent.color = 1; + } + } + } + } + + insert(data: T): boolean { + // search for a position to insert + let parent = this.root; + while (parent) { + if (this.lt(data, parent.data)) { + if (!parent.left) break; + else parent = parent.left; + } else if (this.lt(parent.data, data)) { + if (!parent.right) break; + else parent = parent.right; + } else break; + } + + // insert node into parent + const node = new RBTreeNode(data); + if (!parent) this.root = node; + else if (this.lt(node.data, parent.data)) parent.left = node; + else if (this.lt(parent.data, node.data)) parent.right = node; + else { + parent.count++; + return false; + } + node.parent = parent; + this.fixAfterInsert(node); + return true; + } + + find(data: T): RBTreeNode | null { + let p = this.root; + while (p) { + if (this.lt(data, p.data)) { + p = p.left; + } else if (this.lt(p.data, data)) { + p = p.right; + } else break; + } + return p ?? null; + } + + *inOrder(root: RBTreeNode = this.root!): Generator { + if (!root) return; + for (const v of this.inOrder(root.left!)) yield v; + yield root.data; + for (const v of this.inOrder(root.right!)) yield v; + } + + *reverseInOrder(root: RBTreeNode = this.root!): Generator { + if (!root) return; + for (const v of this.reverseInOrder(root.right!)) yield v; + yield root.data; + for (const v of this.reverseInOrder(root.left!)) yield v; + } +} + +class TreeSet { + _size: number; + tree: RBTree; + compare: Compare; + constructor( + collection: T[] | Compare = [], + compare: Compare = (l: T, r: T) => (l < r ? -1 : l > r ? 1 : 0), + ) { + if (typeof collection === 'function') { + compare = collection; + collection = []; + } + this._size = 0; + this.compare = compare; + this.tree = new RBTree(compare); + for (const val of collection) this.add(val); + } + + size(): number { + return this._size; + } + + has(val: T): boolean { + return !!this.tree.find(val); + } + + add(val: T): boolean { + const successful = this.tree.insert(val); + this._size += successful ? 1 : 0; + return successful; + } + + delete(val: T): boolean { + const deleted = this.tree.deleteAll(val); + this._size -= deleted ? 1 : 0; + return deleted; + } + + ceil(val: T): T | undefined { + let p = this.tree.root; + let higher = null; + while (p) { + if (this.compare(p.data, val) >= 0) { + higher = p; + p = p.left; + } else { + p = p.right; + } + } + return higher?.data; + } + + floor(val: T): T | undefined { + let p = this.tree.root; + let lower = null; + while (p) { + if (this.compare(val, p.data) >= 0) { + lower = p; + p = p.right; + } else { + p = p.left; + } + } + return lower?.data; + } + + higher(val: T): T | undefined { + let p = this.tree.root; + let higher = null; + while (p) { + if (this.compare(val, p.data) < 0) { + higher = p; + p = p.left; + } else { + p = p.right; + } + } + return higher?.data; + } + + lower(val: T): T | undefined { + let p = this.tree.root; + let lower = null; + while (p) { + if (this.compare(p.data, val) < 0) { + lower = p; + p = p.right; + } else { + p = p.left; + } + } + return lower?.data; + } + + first(): T | undefined { + return this.tree.inOrder().next().value; + } + + last(): T | undefined { + return this.tree.reverseInOrder().next().value; + } + + shift(): T | undefined { + const first = this.first(); + if (first === undefined) return undefined; + this.delete(first); + return first; + } + + pop(): T | undefined { + const last = this.last(); + if (last === undefined) return undefined; + this.delete(last); + return last; + } + + *[Symbol.iterator](): Generator { + for (const val of this.values()) yield val; + } + + *keys(): Generator { + for (const val of this.values()) yield val; + } + + *values(): Generator { + for (const val of this.tree.inOrder()) yield val; + return undefined; + } + + /** + * Return a generator for reverse order traversing the set + */ + *rvalues(): Generator { + for (const val of this.tree.reverseInOrder()) yield val; + return undefined; + } +} + +class TreeMultiSet { + _size: number; + tree: RBTree; + compare: Compare; + constructor( + collection: T[] | Compare = [], + compare: Compare = (l: T, r: T) => (l < r ? -1 : l > r ? 1 : 0), + ) { + if (typeof collection === 'function') { + compare = collection; + collection = []; + } + this._size = 0; + this.compare = compare; + this.tree = new RBTree(compare); + for (const val of collection) this.add(val); + } + + size(): number { + return this._size; + } + + has(val: T): boolean { + return !!this.tree.find(val); + } + + add(val: T): boolean { + const successful = this.tree.insert(val); + this._size++; + return successful; + } + + delete(val: T): boolean { + const successful = this.tree.delete(val); + if (!successful) return false; + this._size--; + return true; + } + + count(val: T): number { + const node = this.tree.find(val); + return node ? node.count : 0; + } + + ceil(val: T): T | undefined { + let p = this.tree.root; + let higher = null; + while (p) { + if (this.compare(p.data, val) >= 0) { + higher = p; + p = p.left; + } else { + p = p.right; + } + } + return higher?.data; + } + + floor(val: T): T | undefined { + let p = this.tree.root; + let lower = null; + while (p) { + if (this.compare(val, p.data) >= 0) { + lower = p; + p = p.right; + } else { + p = p.left; + } + } + return lower?.data; + } + + higher(val: T): T | undefined { + let p = this.tree.root; + let higher = null; + while (p) { + if (this.compare(val, p.data) < 0) { + higher = p; + p = p.left; + } else { + p = p.right; + } + } + return higher?.data; + } + + lower(val: T): T | undefined { + let p = this.tree.root; + let lower = null; + while (p) { + if (this.compare(p.data, val) < 0) { + lower = p; + p = p.right; + } else { + p = p.left; + } + } + return lower?.data; + } + + first(): T | undefined { + return this.tree.inOrder().next().value; + } + + last(): T | undefined { + return this.tree.reverseInOrder().next().value; + } + + shift(): T | undefined { + const first = this.first(); + if (first === undefined) return undefined; + this.delete(first); + return first; + } + + pop(): T | undefined { + const last = this.last(); + if (last === undefined) return undefined; + this.delete(last); + return last; + } + + *[Symbol.iterator](): Generator { + yield* this.values(); + } + + *keys(): Generator { + for (const val of this.values()) yield val; + } + + *values(): Generator { + for (const val of this.tree.inOrder()) { + let count = this.count(val); + while (count--) yield val; + } + return undefined; + } + + /** + * Return a generator for reverse order traversing the multi-set + */ + *rvalues(): Generator { + for (const val of this.tree.reverseInOrder()) { + let count = this.count(val); + while (count--) yield val; } + return undefined; } } diff --git a/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution2.ts b/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution2.ts new file mode 100644 index 0000000000000..1643b51cff370 --- /dev/null +++ b/solution/2300-2399/2336.Smallest Number in Infinite Set/Solution2.ts @@ -0,0 +1,33 @@ +class SmallestInfiniteSet { + private pq: typeof MinPriorityQueue; + private s: Set; + + constructor() { + this.pq = new MinPriorityQueue(); + this.s = new Set(); + for (let i = 1; i <= 1000; i++) { + this.pq.enqueue(i, i); + this.s.add(i); + } + } + + popSmallest(): number { + const x = this.pq.dequeue()?.element; + this.s.delete(x); + return x; + } + + addBack(num: number): void { + if (!this.s.has(num)) { + this.pq.enqueue(num, num); + this.s.add(num); + } + } +} + +/** + * Your SmallestInfiniteSet object will be instantiated and called as such: + * var obj = new SmallestInfiniteSet() + * var param_1 = obj.popSmallest() + * obj.addBack(num) + */ diff --git a/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution.ts b/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution.ts index f3157db2eb662..99e230550beb0 100644 --- a/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution.ts +++ b/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution.ts @@ -1,23 +1,31 @@ function canChange(start: string, target: string): boolean { + if ( + [...start].filter(c => c !== '_').join('') !== [...target].filter(c => c !== '_').join('') + ) { + return false; + } const n = start.length; - let [i, j] = [0, 0]; - while (1) { - while (i < n && start[i] === '_') { - ++i; - } - while (j < n && target[j] === '_') { - ++j; + let i = 0; + let j = 0; + while (i < n || j < n) { + while (start[i] === '_') { + i++; } - if (i === n && j === n) { - return true; + while (target[j] === '_') { + j++; } - if (i === n || j === n || start[i] !== target[j]) { - return false; + if (start[i] === 'R') { + if (i > j) { + return false; + } } - if ((start[i] === 'L' && i < j) || (start[i] === 'R' && i > j)) { - return false; + if (start[i] === 'L') { + if (i < j) { + return false; + } } - ++i; - ++j; + i++; + j++; } + return true; } diff --git a/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution2.cpp b/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution2.cpp new file mode 100644 index 0000000000000..67da01e342db5 --- /dev/null +++ b/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool canChange(string start, string target) { + int n = start.size(); + int i = 0, j = 0; + while (true) { + while (i < n && start[i] == '_') ++i; + while (j < n && target[j] == '_') ++j; + if (i == n && j == n) return true; + if (i == n || j == n || start[i] != target[j]) return false; + if (start[i] == 'L' && i < j) return false; + if (start[i] == 'R' && i > j) return false; + ++i; + ++j; + } + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution2.go b/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution2.go new file mode 100644 index 0000000000000..db1ce3befeca6 --- /dev/null +++ b/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution2.go @@ -0,0 +1,25 @@ +func canChange(start string, target string) bool { + n := len(start) + i, j := 0, 0 + for { + for i < n && start[i] == '_' { + i++ + } + for j < n && target[j] == '_' { + j++ + } + if i == n && j == n { + return true + } + if i == n || j == n || start[i] != target[j] { + return false + } + if start[i] == 'L' && i < j { + return false + } + if start[i] == 'R' && i > j { + return false + } + i, j = i+1, j+1 + } +} \ No newline at end of file diff --git a/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution2.java b/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution2.java new file mode 100644 index 0000000000000..c5f2349360a9d --- /dev/null +++ b/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution2.java @@ -0,0 +1,25 @@ +class Solution { + public boolean canChange(String start, String target) { + int n = start.length(); + int i = 0, j = 0; + while (true) { + while (i < n && start.charAt(i) == '_') { + ++i; + } + while (j < n && target.charAt(j) == '_') { + ++j; + } + if (i == n && j == n) { + return true; + } + if (i == n || j == n || start.charAt(i) != target.charAt(j)) { + return false; + } + if (start.charAt(i) == 'L' && i < j || start.charAt(i) == 'R' && i > j) { + return false; + } + ++i; + ++j; + } + } +} \ No newline at end of file diff --git a/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution2.py b/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution2.py new file mode 100644 index 0000000000000..f74f4a69d7114 --- /dev/null +++ b/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def canChange(self, start: str, target: str) -> bool: + n = len(start) + i = j = 0 + while 1: + while i < n and start[i] == '_': + i += 1 + while j < n and target[j] == '_': + j += 1 + if i >= n and j >= n: + return True + if i >= n or j >= n or start[i] != target[j]: + return False + if start[i] == 'L' and i < j: + return False + if start[i] == 'R' and i > j: + return False + i, j = i + 1, j + 1 diff --git a/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution2.ts b/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution2.ts new file mode 100644 index 0000000000000..f3157db2eb662 --- /dev/null +++ b/solution/2300-2399/2337.Move Pieces to Obtain a String/Solution2.ts @@ -0,0 +1,23 @@ +function canChange(start: string, target: string): boolean { + const n = start.length; + let [i, j] = [0, 0]; + while (1) { + while (i < n && start[i] === '_') { + ++i; + } + while (j < n && target[j] === '_') { + ++j; + } + if (i === n && j === n) { + return true; + } + if (i === n || j === n || start[i] !== target[j]) { + return false; + } + if ((start[i] === 'L' && i < j) || (start[i] === 'R' && i > j)) { + return false; + } + ++i; + ++j; + } +} diff --git a/solution/2300-2399/2338.Count the Number of Ideal Arrays/Solution2.cpp b/solution/2300-2399/2338.Count the Number of Ideal Arrays/Solution2.cpp new file mode 100644 index 0000000000000..df0cf26cd2fe6 --- /dev/null +++ b/solution/2300-2399/2338.Count the Number of Ideal Arrays/Solution2.cpp @@ -0,0 +1,26 @@ +using ll = long long; + +class Solution { +public: + const int mod = 1e9 + 7; + + int idealArrays(int n, int maxValue) { + vector> c(n, vector(16)); + for (int i = 0; i < n; ++i) + for (int j = 0; j <= i && j < 16; ++j) + c[i][j] = j == 0 ? 1 : (c[i - 1][j] + c[i - 1][j - 1]) % mod; + vector> dp(maxValue + 1, vector(16)); + for (int i = 1; i <= maxValue; ++i) dp[i][1] = 1; + for (int j = 1; j < 15; ++j) { + for (int i = 1; i <= maxValue; ++i) { + int k = 2; + for (; k * i <= maxValue; ++k) dp[k * i][j + 1] = (dp[k * i][j + 1] + dp[i][j]) % mod; + } + } + ll ans = 0; + for (int i = 1; i <= maxValue; ++i) + for (int j = 1; j < 16; ++j) + ans = (ans + dp[i][j] * c[n - 1][j - 1]) % mod; + return (int) ans; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2338.Count the Number of Ideal Arrays/Solution2.go b/solution/2300-2399/2338.Count the Number of Ideal Arrays/Solution2.go new file mode 100644 index 0000000000000..0765f8b4411b3 --- /dev/null +++ b/solution/2300-2399/2338.Count the Number of Ideal Arrays/Solution2.go @@ -0,0 +1,36 @@ +func idealArrays(n int, maxValue int) int { + mod := int(1e9) + 7 + c := make([][]int, n) + for i := range c { + c[i] = make([]int, 16) + } + for i := 0; i < n; i++ { + for j := 0; j <= i && j < 16; j++ { + if j == 0 { + c[i][j] = 1 + } else { + c[i][j] = (c[i-1][j] + c[i-1][j-1]) % mod + } + } + } + dp := make([][]int, maxValue+1) + for i := range dp { + dp[i] = make([]int, 16) + dp[i][1] = 1 + } + for j := 1; j < 15; j++ { + for i := 1; i <= maxValue; i++ { + k := 2 + for ; k*i <= maxValue; k++ { + dp[k*i][j+1] = (dp[k*i][j+1] + dp[i][j]) % mod + } + } + } + ans := 0 + for i := 1; i <= maxValue; i++ { + for j := 1; j < 16; j++ { + ans = (ans + dp[i][j]*c[n-1][j-1]) % mod + } + } + return ans +} \ No newline at end of file diff --git a/solution/2300-2399/2338.Count the Number of Ideal Arrays/Solution2.java b/solution/2300-2399/2338.Count the Number of Ideal Arrays/Solution2.java new file mode 100644 index 0000000000000..3f8c9315b4356 --- /dev/null +++ b/solution/2300-2399/2338.Count the Number of Ideal Arrays/Solution2.java @@ -0,0 +1,31 @@ +class Solution { + private static final int MOD = (int) 1e9 + 7; + + public int idealArrays(int n, int maxValue) { + int[][] c = new int[n][16]; + for (int i = 0; i < n; ++i) { + for (int j = 0; j <= i && j < 16; ++j) { + c[i][j] = j == 0 ? 1 : (c[i - 1][j] + c[i - 1][j - 1]) % MOD; + } + } + long[][] dp = new long[maxValue + 1][16]; + for (int i = 1; i <= maxValue; ++i) { + dp[i][1] = 1; + } + for (int j = 1; j < 15; ++j) { + for (int i = 1; i <= maxValue; ++i) { + int k = 2; + for (; k * i <= maxValue; ++k) { + dp[k * i][j + 1] = (dp[k * i][j + 1] + dp[i][j]) % MOD; + } + } + } + long ans = 0; + for (int i = 1; i <= maxValue; ++i) { + for (int j = 1; j < 16; ++j) { + ans = (ans + dp[i][j] * c[n - 1][j - 1]) % MOD; + } + } + return (int) ans; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2338.Count the Number of Ideal Arrays/Solution2.py b/solution/2300-2399/2338.Count the Number of Ideal Arrays/Solution2.py new file mode 100644 index 0000000000000..de720e4b85941 --- /dev/null +++ b/solution/2300-2399/2338.Count the Number of Ideal Arrays/Solution2.py @@ -0,0 +1,21 @@ +class Solution: + def idealArrays(self, n: int, maxValue: int) -> int: + c = [[0] * 16 for _ in range(n)] + mod = 10**9 + 7 + for i in range(n): + for j in range(min(16, i + 1)): + c[i][j] = 1 if j == 0 else (c[i - 1][j] + c[i - 1][j - 1]) % mod + dp = [[0] * 16 for _ in range(maxValue + 1)] + for i in range(1, maxValue + 1): + dp[i][1] = 1 + for j in range(1, 15): + for i in range(1, maxValue + 1): + k = 2 + while k * i <= maxValue: + dp[k * i][j + 1] = (dp[k * i][j + 1] + dp[i][j]) % mod + k += 1 + ans = 0 + for i in range(1, maxValue + 1): + for j in range(1, 16): + ans = (ans + dp[i][j] * c[-1][j - 1]) % mod + return ans diff --git a/solution/2300-2399/2341.Maximum Number of Pairs in Array/Solution.c b/solution/2300-2399/2341.Maximum Number of Pairs in Array/Solution.c index 3b4f1b6cbf49a..2ddca1a35bba0 100644 --- a/solution/2300-2399/2341.Maximum Number of Pairs in Array/Solution.c +++ b/solution/2300-2399/2341.Maximum Number of Pairs in Array/Solution.c @@ -15,4 +15,4 @@ int* numberOfPairs(int* nums, int numsSize, int* returnSize) { ans[1] = numsSize - sum * 2; *returnSize = 2; return ans; -} +} \ No newline at end of file diff --git a/solution/2300-2399/2341.Maximum Number of Pairs in Array/Solution.cs b/solution/2300-2399/2341.Maximum Number of Pairs in Array/Solution.cs index 37e0ca29835d0..f27f52b227257 100644 --- a/solution/2300-2399/2341.Maximum Number of Pairs in Array/Solution.cs +++ b/solution/2300-2399/2341.Maximum Number of Pairs in Array/Solution.cs @@ -10,4 +10,4 @@ public int[] NumberOfPairs(int[] nums) { } return new int[] {s, nums.Length - s * 2}; } -} \ No newline at end of file +} diff --git a/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/Solution.cpp b/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/Solution.cpp index 8ad7e8c03824f..a365690942fa1 100644 --- a/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/Solution.cpp +++ b/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/Solution.cpp @@ -1,18 +1,18 @@ -class Solution { -public: - int maximumSum(vector& nums) { - int d[100]{}; - int ans = -1; - for (int v : nums) { - int x = 0; - for (int y = v; y; y /= 10) { - x += y % 10; - } - if (d[x]) { - ans = max(ans, d[x] + v); - } - d[x] = max(d[x], v); - } - return ans; - } +class Solution { +public: + int maximumSum(vector& nums) { + int d[100]{}; + int ans = -1; + for (int v : nums) { + int x = 0; + for (int y = v; y; y /= 10) { + x += y % 10; + } + if (d[x]) { + ans = max(ans, d[x] + v); + } + d[x] = max(d[x], v); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/Solution.java b/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/Solution.java index 413dcfbc94cb8..1d1e9a2f2c5ce 100644 --- a/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/Solution.java +++ b/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public int maximumSum(int[] nums) { - int[] d = new int[100]; - int ans = -1; - for (int v : nums) { - int x = 0; - for (int y = v; y > 0; y /= 10) { - x += y % 10; - } - if (d[x] > 0) { - ans = Math.max(ans, d[x] + v); - } - d[x] = Math.max(d[x], v); - } - return ans; - } +class Solution { + public int maximumSum(int[] nums) { + int[] d = new int[100]; + int ans = -1; + for (int v : nums) { + int x = 0; + for (int y = v; y > 0; y /= 10) { + x += y % 10; + } + if (d[x] > 0) { + ans = Math.max(ans, d[x] + v); + } + d[x] = Math.max(d[x], v); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/Solution.py b/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/Solution.py index 033a5a95b49ca..69e3b84d4bbea 100644 --- a/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/Solution.py +++ b/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def maximumSum(self, nums: List[int]) -> int: - d = defaultdict(int) - ans = -1 - for v in nums: - x, y = 0, v - while y: - x += y % 10 - y //= 10 - if x in d: - ans = max(ans, d[x] + v) - d[x] = max(d[x], v) - return ans +class Solution: + def maximumSum(self, nums: List[int]) -> int: + d = defaultdict(int) + ans = -1 + for v in nums: + x, y = 0, v + while y: + x += y % 10 + y //= 10 + if x in d: + ans = max(ans, d[x] + v) + d[x] = max(d[x], v) + return ans diff --git a/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution.cpp b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution.cpp index f6604e8a217a1..2a4bd0b2c399f 100644 --- a/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution.cpp +++ b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution.cpp @@ -5,19 +5,12 @@ class Solution { for (int& v : numsDivide) { x = gcd(x, v); } - int y = 1 << 30; - for (int& v : nums) { - if (x % v == 0) { - y = min(y, v); + sort(nums.begin(), nums.end()); + for (int i = 0; i < nums.size(); ++i) { + if (x % nums[i] == 0) { + return i; } } - if (y == 1 << 30) { - return -1; - } - int ans = 0; - for (int& v : nums) { - ans += v < y; - } - return ans; + return -1; } }; \ No newline at end of file diff --git a/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution.go b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution.go index 4667010a0a171..389be4c6741cb 100644 --- a/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution.go +++ b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution.go @@ -3,22 +3,13 @@ func minOperations(nums []int, numsDivide []int) int { for _, v := range numsDivide { x = gcd(x, v) } - y := 1 << 30 - for _, v := range nums { + sort.Ints(nums) + for i, v := range nums { if x%v == 0 { - y = min(y, v) + return i } } - if y == 1<<30 { - return -1 - } - ans := 0 - for _, v := range nums { - if v < y { - ans++ - } - } - return ans + return -1 } func gcd(a, b int) int { diff --git a/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution.java b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution.java index eca6879905efc..dd3786f04ecdc 100644 --- a/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution.java +++ b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution.java @@ -4,22 +4,13 @@ public int minOperations(int[] nums, int[] numsDivide) { for (int v : numsDivide) { x = gcd(x, v); } - int y = 1 << 30; - for (int v : nums) { - if (x % v == 0) { - y = Math.min(y, v); + Arrays.sort(nums); + for (int i = 0; i < nums.length; ++i) { + if (x % nums[i] == 0) { + return i; } } - if (y == 1 << 30) { - return -1; - } - int ans = 0; - for (int v : nums) { - if (v < y) { - ++ans; - } - } - return ans; + return -1; } private int gcd(int a, int b) { diff --git a/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution.py b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution.py index 744a5eb82329c..0827a18b7d4f4 100644 --- a/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution.py +++ b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution.py @@ -1,5 +1,10 @@ class Solution: def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: - x = gcd(*numsDivide) - y = min((v for v in nums if x % v == 0), default=0) - return sum(v < y for v in nums) if y else -1 + x = numsDivide[0] + for v in numsDivide[1:]: + x = gcd(x, v) + nums.sort() + for i, v in enumerate(nums): + if x % v == 0: + return i + return -1 diff --git a/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution2.cpp b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution2.cpp new file mode 100644 index 0000000000000..f6604e8a217a1 --- /dev/null +++ b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution2.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int minOperations(vector& nums, vector& numsDivide) { + int x = 0; + for (int& v : numsDivide) { + x = gcd(x, v); + } + int y = 1 << 30; + for (int& v : nums) { + if (x % v == 0) { + y = min(y, v); + } + } + if (y == 1 << 30) { + return -1; + } + int ans = 0; + for (int& v : nums) { + ans += v < y; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution2.go b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution2.go new file mode 100644 index 0000000000000..4667010a0a171 --- /dev/null +++ b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution2.go @@ -0,0 +1,29 @@ +func minOperations(nums []int, numsDivide []int) int { + x := 0 + for _, v := range numsDivide { + x = gcd(x, v) + } + y := 1 << 30 + for _, v := range nums { + if x%v == 0 { + y = min(y, v) + } + } + if y == 1<<30 { + return -1 + } + ans := 0 + for _, v := range nums { + if v < y { + ans++ + } + } + return ans +} + +func gcd(a, b int) int { + if b == 0 { + return a + } + return gcd(b, a%b) +} \ No newline at end of file diff --git a/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution2.java b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution2.java new file mode 100644 index 0000000000000..eca6879905efc --- /dev/null +++ b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution2.java @@ -0,0 +1,28 @@ +class Solution { + public int minOperations(int[] nums, int[] numsDivide) { + int x = 0; + for (int v : numsDivide) { + x = gcd(x, v); + } + int y = 1 << 30; + for (int v : nums) { + if (x % v == 0) { + y = Math.min(y, v); + } + } + if (y == 1 << 30) { + return -1; + } + int ans = 0; + for (int v : nums) { + if (v < y) { + ++ans; + } + } + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} \ No newline at end of file diff --git a/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution2.py b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution2.py new file mode 100644 index 0000000000000..cc3ac3189a539 --- /dev/null +++ b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution2.py @@ -0,0 +1,5 @@ +class Solution: + def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: + x = gcd(*numsDivide) + nums.sort() + return next((i for i, v in enumerate(nums) if x % v == 0), -1) diff --git a/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution3.py b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution3.py new file mode 100644 index 0000000000000..744a5eb82329c --- /dev/null +++ b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution3.py @@ -0,0 +1,5 @@ +class Solution: + def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: + x = gcd(*numsDivide) + y = min((v for v in nums if x % v == 0), default=0) + return sum(v < y for v in nums) if y else -1 diff --git a/solution/2300-2399/2345.Finding the Number of Visible Mountains/Solution2.java b/solution/2300-2399/2345.Finding the Number of Visible Mountains/Solution2.java new file mode 100644 index 0000000000000..52771483480e4 --- /dev/null +++ b/solution/2300-2399/2345.Finding the Number of Visible Mountains/Solution2.java @@ -0,0 +1,24 @@ +class Solution { + public int visibleMountains(int[][] peaks) { + int n = peaks.length; + int[][] arr = new int[n][2]; + for (int i = 0; i < n; ++i) { + int x = peaks[i][0], y = peaks[i][1]; + arr[i] = new int[] {x - y, x + y}; + } + Arrays.sort(arr, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); + int ans = 0; + int cur = Integer.MIN_VALUE; + for (int i = 0; i < n; ++i) { + int l = arr[i][0], r = arr[i][1]; + if (r <= cur) { + continue; + } + cur = r; + if (!(i < n - 1 && arr[i][0] == arr[i + 1][0] && arr[i][1] == arr[i + 1][1])) { + ++ans; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2347.Best Poker Hand/Solution.c b/solution/2300-2399/2347.Best Poker Hand/Solution.c index abfba3084ad94..dbb81174c9d45 100644 --- a/solution/2300-2399/2347.Best Poker Hand/Solution.c +++ b/solution/2300-2399/2347.Best Poker Hand/Solution.c @@ -21,4 +21,4 @@ char* bestHand(int* ranks, int ranksSize, char* suits, int suitsSize) { return "Pair"; } return "High Card"; -} +} \ No newline at end of file diff --git a/solution/2300-2399/2351.First Letter to Appear Twice/Solution.c b/solution/2300-2399/2351.First Letter to Appear Twice/Solution.c index 8e5003999b7a5..e7d6ce7312ba1 100644 --- a/solution/2300-2399/2351.First Letter to Appear Twice/Solution.c +++ b/solution/2300-2399/2351.First Letter to Appear Twice/Solution.c @@ -1,10 +1,10 @@ char repeatedCharacter(char* s) { - int mask = 0; + int vis[26] = {0}; for (int i = 0; s[i]; i++) { - if (mask & (1 << s[i] - 'a')) { + if (vis[s[i] - 'a']) { return s[i]; } - mask |= 1 << s[i] - 'a'; + vis[s[i] - 'a']++; } return ' '; -} +} \ No newline at end of file diff --git a/solution/2300-2399/2351.First Letter to Appear Twice/Solution.cpp b/solution/2300-2399/2351.First Letter to Appear Twice/Solution.cpp index e434445962bec..42e22adaad65d 100644 --- a/solution/2300-2399/2351.First Letter to Appear Twice/Solution.cpp +++ b/solution/2300-2399/2351.First Letter to Appear Twice/Solution.cpp @@ -1,12 +1,11 @@ class Solution { public: char repeatedCharacter(string s) { - int mask = 0; + int cnt[26]{}; for (int i = 0;; ++i) { - if (mask >> (s[i] - 'a') & 1) { + if (++cnt[s[i] - 'a'] == 2) { return s[i]; } - mask |= 1 << (s[i] - 'a'); } } }; \ No newline at end of file diff --git a/solution/2300-2399/2351.First Letter to Appear Twice/Solution.go b/solution/2300-2399/2351.First Letter to Appear Twice/Solution.go index 2df97a5b5e358..a1643e99ec1ee 100644 --- a/solution/2300-2399/2351.First Letter to Appear Twice/Solution.go +++ b/solution/2300-2399/2351.First Letter to Appear Twice/Solution.go @@ -1,9 +1,9 @@ func repeatedCharacter(s string) byte { - mask := 0 + cnt := [26]int{} for i := 0; ; i++ { - if mask>>(s[i]-'a')&1 == 1 { + cnt[s[i]-'a']++ + if cnt[s[i]-'a'] == 2 { return s[i] } - mask |= 1 << (s[i] - 'a') } } \ No newline at end of file diff --git a/solution/2300-2399/2351.First Letter to Appear Twice/Solution.java b/solution/2300-2399/2351.First Letter to Appear Twice/Solution.java index ea4f9a194e58c..ff120ccf45216 100644 --- a/solution/2300-2399/2351.First Letter to Appear Twice/Solution.java +++ b/solution/2300-2399/2351.First Letter to Appear Twice/Solution.java @@ -1,12 +1,11 @@ class Solution { public char repeatedCharacter(String s) { - int mask = 0; + int[] cnt = new int[26]; for (int i = 0;; ++i) { char c = s.charAt(i); - if ((mask >> (c - 'a') & 1) == 1) { + if (++cnt[c - 'a'] == 2) { return c; } - mask |= 1 << (c - 'a'); } } } \ No newline at end of file diff --git a/solution/2300-2399/2351.First Letter to Appear Twice/Solution.php b/solution/2300-2399/2351.First Letter to Appear Twice/Solution.php index 4eb1e5effa35f..346c1f6767cb0 100644 --- a/solution/2300-2399/2351.First Letter to Appear Twice/Solution.php +++ b/solution/2300-2399/2351.First Letter to Appear Twice/Solution.php @@ -11,4 +11,4 @@ function repeatedCharacter($s) { } } } -} \ No newline at end of file +} diff --git a/solution/2300-2399/2351.First Letter to Appear Twice/Solution.py b/solution/2300-2399/2351.First Letter to Appear Twice/Solution.py index 0bd8cd781a72b..655ef838c98d8 100644 --- a/solution/2300-2399/2351.First Letter to Appear Twice/Solution.py +++ b/solution/2300-2399/2351.First Letter to Appear Twice/Solution.py @@ -1,8 +1,7 @@ class Solution: def repeatedCharacter(self, s: str) -> str: - mask = 0 + cnt = Counter() for c in s: - i = ord(c) - ord('a') - if mask >> i & 1: + cnt[c] += 1 + if cnt[c] == 2: return c - mask |= 1 << i diff --git a/solution/2300-2399/2351.First Letter to Appear Twice/Solution.rs b/solution/2300-2399/2351.First Letter to Appear Twice/Solution.rs index 623858843b9d3..dc8a1473d3be0 100644 --- a/solution/2300-2399/2351.First Letter to Appear Twice/Solution.rs +++ b/solution/2300-2399/2351.First Letter to Appear Twice/Solution.rs @@ -1,11 +1,11 @@ impl Solution { pub fn repeated_character(s: String) -> char { - let mut mask = 0; + let mut vis = [false; 26]; for &c in s.as_bytes() { - if (mask & (1 << ((c - b'a') as i32))) != 0 { + if vis[(c - b'a') as usize] { return c as char; } - mask |= 1 << ((c - b'a') as i32); + vis[(c - b'a') as usize] = true; } ' ' } diff --git a/solution/2300-2399/2351.First Letter to Appear Twice/Solution.ts b/solution/2300-2399/2351.First Letter to Appear Twice/Solution.ts index b1f8b03aaf5e8..238a5412703b1 100644 --- a/solution/2300-2399/2351.First Letter to Appear Twice/Solution.ts +++ b/solution/2300-2399/2351.First Letter to Appear Twice/Solution.ts @@ -1,11 +1,11 @@ function repeatedCharacter(s: string): string { - let mask = 0; + const vis = new Array(26).fill(false); for (const c of s) { const i = c.charCodeAt(0) - 'a'.charCodeAt(0); - if (mask & (1 << i)) { + if (vis[i]) { return c; } - mask |= 1 << i; + vis[i] = true; } return ' '; } diff --git a/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.c b/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.c new file mode 100644 index 0000000000000..a87d82b29165e --- /dev/null +++ b/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.c @@ -0,0 +1,10 @@ +char repeatedCharacter(char* s) { + int mask = 0; + for (int i = 0; s[i]; i++) { + if (mask & (1 << s[i] - 'a')) { + return s[i]; + } + mask |= 1 << s[i] - 'a'; + } + return ' '; +} \ No newline at end of file diff --git a/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.cpp b/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.cpp new file mode 100644 index 0000000000000..e434445962bec --- /dev/null +++ b/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + char repeatedCharacter(string s) { + int mask = 0; + for (int i = 0;; ++i) { + if (mask >> (s[i] - 'a') & 1) { + return s[i]; + } + mask |= 1 << (s[i] - 'a'); + } + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.go b/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.go new file mode 100644 index 0000000000000..2df97a5b5e358 --- /dev/null +++ b/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.go @@ -0,0 +1,9 @@ +func repeatedCharacter(s string) byte { + mask := 0 + for i := 0; ; i++ { + if mask>>(s[i]-'a')&1 == 1 { + return s[i] + } + mask |= 1 << (s[i] - 'a') + } +} \ No newline at end of file diff --git a/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.java b/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.java new file mode 100644 index 0000000000000..ea4f9a194e58c --- /dev/null +++ b/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.java @@ -0,0 +1,12 @@ +class Solution { + public char repeatedCharacter(String s) { + int mask = 0; + for (int i = 0;; ++i) { + char c = s.charAt(i); + if ((mask >> (c - 'a') & 1) == 1) { + return c; + } + mask |= 1 << (c - 'a'); + } + } +} \ No newline at end of file diff --git a/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.py b/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.py new file mode 100644 index 0000000000000..0bd8cd781a72b --- /dev/null +++ b/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def repeatedCharacter(self, s: str) -> str: + mask = 0 + for c in s: + i = ord(c) - ord('a') + if mask >> i & 1: + return c + mask |= 1 << i diff --git a/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.rs b/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.rs new file mode 100644 index 0000000000000..623858843b9d3 --- /dev/null +++ b/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.rs @@ -0,0 +1,12 @@ +impl Solution { + pub fn repeated_character(s: String) -> char { + let mut mask = 0; + for &c in s.as_bytes() { + if (mask & (1 << ((c - b'a') as i32))) != 0 { + return c as char; + } + mask |= 1 << ((c - b'a') as i32); + } + ' ' + } +} diff --git a/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.ts b/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.ts new file mode 100644 index 0000000000000..b1f8b03aaf5e8 --- /dev/null +++ b/solution/2300-2399/2351.First Letter to Appear Twice/Solution2.ts @@ -0,0 +1,11 @@ +function repeatedCharacter(s: string): string { + let mask = 0; + for (const c of s) { + const i = c.charCodeAt(0) - 'a'.charCodeAt(0); + if (mask & (1 << i)) { + return c; + } + mask |= 1 << i; + } + return ' '; +} diff --git a/solution/2300-2399/2352.Equal Row and Column Pairs/Solution2.cpp b/solution/2300-2399/2352.Equal Row and Column Pairs/Solution2.cpp new file mode 100644 index 0000000000000..e30202743e20f --- /dev/null +++ b/solution/2300-2399/2352.Equal Row and Column Pairs/Solution2.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int equalPairs(vector>& grid) { + int n = grid.size(); + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + int ok = 1; + for (int k = 0; k < n; ++k) { + if (grid[i][k] != grid[k][j]) { + ok = 0; + break; + } + } + ans += ok; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2352.Equal Row and Column Pairs/Solution2.go b/solution/2300-2399/2352.Equal Row and Column Pairs/Solution2.go new file mode 100644 index 0000000000000..701a032e800fe --- /dev/null +++ b/solution/2300-2399/2352.Equal Row and Column Pairs/Solution2.go @@ -0,0 +1,15 @@ +func equalPairs(grid [][]int) (ans int) { + for i := range grid { + for j := range grid { + ok := 1 + for k := range grid { + if grid[i][k] != grid[k][j] { + ok = 0 + break + } + } + ans += ok + } + } + return +} \ No newline at end of file diff --git a/solution/2300-2399/2352.Equal Row and Column Pairs/Solution2.java b/solution/2300-2399/2352.Equal Row and Column Pairs/Solution2.java new file mode 100644 index 0000000000000..ecb4a96deae18 --- /dev/null +++ b/solution/2300-2399/2352.Equal Row and Column Pairs/Solution2.java @@ -0,0 +1,19 @@ +class Solution { + public int equalPairs(int[][] grid) { + int n = grid.length; + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + int ok = 1; + for (int k = 0; k < n; ++k) { + if (grid[i][k] != grid[k][j]) { + ok = 0; + break; + } + } + ans += ok; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2352.Equal Row and Column Pairs/Solution2.py b/solution/2300-2399/2352.Equal Row and Column Pairs/Solution2.py new file mode 100644 index 0000000000000..92506a67f1cc0 --- /dev/null +++ b/solution/2300-2399/2352.Equal Row and Column Pairs/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def equalPairs(self, grid: List[List[int]]) -> int: + n = len(grid) + ans = 0 + for i in range(n): + for j in range(n): + ans += all(grid[i][k] == grid[k][j] for k in range(n)) + return ans diff --git a/solution/2300-2399/2352.Equal Row and Column Pairs/Solution2.ts b/solution/2300-2399/2352.Equal Row and Column Pairs/Solution2.ts new file mode 100644 index 0000000000000..ab3851ce0bc9d --- /dev/null +++ b/solution/2300-2399/2352.Equal Row and Column Pairs/Solution2.ts @@ -0,0 +1,17 @@ +function equalPairs(grid: number[][]): number { + const n = grid.length; + let ans = 0; + for (let i = 0; i < n; ++i) { + for (let j = 0; j < n; ++j) { + let ok = 1; + for (let k = 0; k < n; ++k) { + if (grid[i][k] !== grid[k][j]) { + ok = 0; + break; + } + } + ans += ok; + } + } + return ans; +} diff --git a/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/Solution.c b/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/Solution.c index 40d7b1e791db9..3b44eba625a13 100644 --- a/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/Solution.c +++ b/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/Solution.c @@ -10,4 +10,4 @@ int minimumOperations(int* nums, int numsSize) { ans++; } return ans; -} +} \ No newline at end of file diff --git a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.cpp b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.cpp new file mode 100644 index 0000000000000..626e5e2feb064 --- /dev/null +++ b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + int closestMeetingNode(vector& edges, int node1, int node2) { + int n = edges.size(); + vector> g(n); + for (int i = 0; i < n; ++i) { + if (edges[i] != -1) { + g[i].push_back(edges[i]); + } + } + const int inf = 1 << 30; + using pii = pair; + auto f = [&](int i) { + vector dist(n, inf); + dist[i] = 0; + queue q{{i}}; + while (!q.empty()) { + i = q.front(); + q.pop(); + for (int j : g[i]) { + if (dist[j] == inf) { + dist[j] = dist[i] + 1; + q.push(j); + } + } + } + return dist; + }; + vector d1 = f(node1); + vector d2 = f(node2); + int ans = -1, d = inf; + for (int i = 0; i < n; ++i) { + int t = max(d1[i], d2[i]); + if (t < d) { + d = t; + ans = i; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.go b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.go new file mode 100644 index 0000000000000..2942464df6754 --- /dev/null +++ b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.go @@ -0,0 +1,41 @@ +func closestMeetingNode(edges []int, node1 int, node2 int) int { + n := len(edges) + g := make([][]int, n) + for i, j := range edges { + if j != -1 { + g[i] = append(g[i], j) + } + } + const inf int = 1 << 30 + f := func(i int) []int { + dist := make([]int, n) + for j := range dist { + dist[j] = inf + } + dist[i] = 0 + q := []int{i} + for len(q) > 0 { + i = q[0] + q = q[1:] + for _, j := range g[i] { + if dist[j] == inf { + dist[j] = dist[i] + 1 + q = append(q, j) + } + } + } + return dist + } + d1 := f(node1) + d2 := f(node2) + ans, d := -1, inf + for i, a := range d1 { + b := d2[i] + t := max(a, b) + if t < d { + d = t + ans = i + } + } + return ans +} \ No newline at end of file diff --git a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.java b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.java new file mode 100644 index 0000000000000..6cb9c23907765 --- /dev/null +++ b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.java @@ -0,0 +1,45 @@ +class Solution { + private int n; + private List[] g; + + public int closestMeetingNode(int[] edges, int node1, int node2) { + n = edges.length; + g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (int i = 0; i < n; ++i) { + if (edges[i] != -1) { + g[i].add(edges[i]); + } + } + int[] d1 = f(node1); + int[] d2 = f(node2); + int d = 1 << 30; + int ans = -1; + for (int i = 0; i < n; ++i) { + int t = Math.max(d1[i], d2[i]); + if (t < d) { + d = t; + ans = i; + } + } + return ans; + } + + private int[] f(int i) { + int[] dist = new int[n]; + Arrays.fill(dist, 1 << 30); + dist[i] = 0; + Deque q = new ArrayDeque<>(); + q.offer(i); + while (!q.isEmpty()) { + i = q.poll(); + for (int j : g[i]) { + if (dist[j] == 1 << 30) { + dist[j] = dist[i] + 1; + q.offer(j); + } + } + } + return dist; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.py b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.py new file mode 100644 index 0000000000000..d6b338ca128d3 --- /dev/null +++ b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.py @@ -0,0 +1,27 @@ +class Solution: + def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: + def f(i): + dist = [inf] * n + dist[i] = 0 + q = deque([i]) + while q: + i = q.popleft() + for j in g[i]: + if dist[j] == inf: + dist[j] = dist[i] + 1 + q.append(j) + return dist + + g = defaultdict(list) + for i, j in enumerate(edges): + if j != -1: + g[i].append(j) + n = len(edges) + d1 = f(node1) + d2 = f(node2) + ans, d = -1, inf + for i, (a, b) in enumerate(zip(d1, d2)): + if (t := max(a, b)) < d: + d = t + ans = i + return ans diff --git a/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.cpp b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.cpp index 03352c3fee184..54e5daa26cb41 100644 --- a/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.cpp +++ b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.cpp @@ -1,19 +1,19 @@ -class Solution { -public: - vector minimumCosts(vector& regular, vector& express, int expressCost) { - int n = regular.size(); - long long f = 0; - long long g = 1 << 30; - vector cost(n); - for (int i = 0; i < n; ++i) { - int a = regular[i]; - int b = express[i]; - long long ff = min(f + a, g + a); - long long gg = min(f + expressCost + b, g + b); - f = ff; - g = gg; - cost[i] = min(f, g); - } - return cost; - } +class Solution { +public: + vector minimumCosts(vector& regular, vector& express, int expressCost) { + int n = regular.size(); + long long f[n + 1]; + long long g[n + 1]; + f[0] = 0; + g[0] = 1 << 30; + vector cost(n); + for (int i = 1; i <= n; ++i) { + int a = regular[i - 1]; + int b = express[i - 1]; + f[i] = min(f[i - 1] + a, g[i - 1] + a); + g[i] = min(f[i - 1] + expressCost + b, g[i - 1] + b); + cost[i - 1] = min(f[i], g[i]); + } + return cost; + } }; \ No newline at end of file diff --git a/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.go b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.go index 114916f9a6319..4e9840d7da365 100644 --- a/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.go +++ b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.go @@ -1,12 +1,14 @@ func minimumCosts(regular []int, express []int, expressCost int) []int64 { - f, g := 0, 1<<30 - cost := make([]int64, len(regular)) - for i, a := range regular { - b := express[i] - ff := min(f+a, g+a) - gg := min(f+expressCost+b, g+b) - f, g = ff, gg - cost[i] = int64(min(f, g)) + n := len(regular) + f := make([]int, n+1) + g := make([]int, n+1) + g[0] = 1 << 30 + cost := make([]int64, n) + for i := 1; i <= n; i++ { + a, b := regular[i-1], express[i-1] + f[i] = min(f[i-1]+a, g[i-1]+a) + g[i] = min(f[i-1]+expressCost+b, g[i-1]+b) + cost[i-1] = int64(min(f[i], g[i])) } return cost } \ No newline at end of file diff --git a/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.java b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.java index f179409857c2f..da4bbf4d590da 100644 --- a/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.java +++ b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.java @@ -1,18 +1,17 @@ -class Solution { - public long[] minimumCosts(int[] regular, int[] express, int expressCost) { - int n = regular.length; - long f = 0; - long g = 1 << 30; - long[] cost = new long[n]; - for (int i = 0; i < n; ++i) { - int a = regular[i]; - int b = express[i]; - long ff = Math.min(f + a, g + a); - long gg = Math.min(f + expressCost + b, g + b); - f = ff; - g = gg; - cost[i] = Math.min(f, g); - } - return cost; - } +class Solution { + public long[] minimumCosts(int[] regular, int[] express, int expressCost) { + int n = regular.length; + long[] f = new long[n + 1]; + long[] g = new long[n + 1]; + g[0] = 1 << 30; + long[] cost = new long[n]; + for (int i = 1; i <= n; ++i) { + int a = regular[i - 1]; + int b = express[i - 1]; + f[i] = Math.min(f[i - 1] + a, g[i - 1] + a); + g[i] = Math.min(f[i - 1] + expressCost + b, g[i - 1] + b); + cost[i - 1] = Math.min(f[i], g[i]); + } + return cost; + } } \ No newline at end of file diff --git a/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.py b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.py index d0edb3f44383d..4c34212ac18f4 100644 --- a/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.py +++ b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def minimumCosts( - self, regular: List[int], express: List[int], expressCost: int - ) -> List[int]: - n = len(regular) - f, g = 0, inf - cost = [0] * n - for i, (a, b) in enumerate(zip(regular, express), 1): - ff = min(f + a, g + a) - gg = min(f + expressCost + b, g + b) - f, g = ff, gg - cost[i - 1] = min(f, g) - return cost +class Solution: + def minimumCosts( + self, regular: List[int], express: List[int], expressCost: int + ) -> List[int]: + n = len(regular) + f = [0] * (n + 1) + g = [inf] * (n + 1) + cost = [0] * n + for i, (a, b) in enumerate(zip(regular, express), 1): + f[i] = min(f[i - 1] + a, g[i - 1] + a) + g[i] = min(f[i - 1] + expressCost + b, g[i - 1] + b) + cost[i - 1] = min(f[i], g[i]) + return cost diff --git a/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.ts b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.ts index e374726152b0f..14a7febd0cb0d 100644 --- a/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.ts +++ b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution.ts @@ -1,14 +1,14 @@ function minimumCosts(regular: number[], express: number[], expressCost: number): number[] { const n = regular.length; - let f = 0; - let g = 1 << 30; + const f: number[] = new Array(n + 1).fill(0); + const g: number[] = new Array(n + 1).fill(0); + g[0] = 1 << 30; const cost: number[] = new Array(n).fill(0); - for (let i = 0; i < n; ++i) { - const [a, b] = [regular[i], express[i]]; - const ff = Math.min(f + a, g + a); - const gg = Math.min(f + expressCost + b, g + b); - [f, g] = [ff, gg]; - cost[i] = Math.min(f, g); + for (let i = 1; i <= n; ++i) { + const [a, b] = [regular[i - 1], express[i - 1]]; + f[i] = Math.min(f[i - 1] + a, g[i - 1] + a); + g[i] = Math.min(f[i - 1] + expressCost + b, g[i - 1] + b); + cost[i - 1] = Math.min(f[i], g[i]); } return cost; } diff --git a/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution2.cpp b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution2.cpp new file mode 100644 index 0000000000000..2da1b7c5bca7b --- /dev/null +++ b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + vector minimumCosts(vector& regular, vector& express, int expressCost) { + int n = regular.size(); + long long f = 0; + long long g = 1 << 30; + vector cost(n); + for (int i = 0; i < n; ++i) { + int a = regular[i]; + int b = express[i]; + long long ff = min(f + a, g + a); + long long gg = min(f + expressCost + b, g + b); + f = ff; + g = gg; + cost[i] = min(f, g); + } + return cost; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution2.go b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution2.go new file mode 100644 index 0000000000000..114916f9a6319 --- /dev/null +++ b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution2.go @@ -0,0 +1,12 @@ +func minimumCosts(regular []int, express []int, expressCost int) []int64 { + f, g := 0, 1<<30 + cost := make([]int64, len(regular)) + for i, a := range regular { + b := express[i] + ff := min(f+a, g+a) + gg := min(f+expressCost+b, g+b) + f, g = ff, gg + cost[i] = int64(min(f, g)) + } + return cost +} \ No newline at end of file diff --git a/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution2.java b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution2.java new file mode 100644 index 0000000000000..bc3f891f660a1 --- /dev/null +++ b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution2.java @@ -0,0 +1,18 @@ +class Solution { + public long[] minimumCosts(int[] regular, int[] express, int expressCost) { + int n = regular.length; + long f = 0; + long g = 1 << 30; + long[] cost = new long[n]; + for (int i = 0; i < n; ++i) { + int a = regular[i]; + int b = express[i]; + long ff = Math.min(f + a, g + a); + long gg = Math.min(f + expressCost + b, g + b); + f = ff; + g = gg; + cost[i] = Math.min(f, g); + } + return cost; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution2.py b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution2.py new file mode 100644 index 0000000000000..48ef46bafe88d --- /dev/null +++ b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def minimumCosts( + self, regular: List[int], express: List[int], expressCost: int + ) -> List[int]: + n = len(regular) + f, g = 0, inf + cost = [0] * n + for i, (a, b) in enumerate(zip(regular, express), 1): + ff = min(f + a, g + a) + gg = min(f + expressCost + b, g + b) + f, g = ff, gg + cost[i - 1] = min(f, g) + return cost diff --git a/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution2.ts b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution2.ts new file mode 100644 index 0000000000000..e374726152b0f --- /dev/null +++ b/solution/2300-2399/2361.Minimum Costs Using the Train Line/Solution2.ts @@ -0,0 +1,14 @@ +function minimumCosts(regular: number[], express: number[], expressCost: number): number[] { + const n = regular.length; + let f = 0; + let g = 1 << 30; + const cost: number[] = new Array(n).fill(0); + for (let i = 0; i < n; ++i) { + const [a, b] = [regular[i], express[i]]; + const ff = Math.min(f + a, g + a); + const gg = Math.min(f + expressCost + b, g + b); + [f, g] = [ff, gg]; + cost[i] = Math.min(f, g); + } + return cost; +} diff --git a/solution/2300-2399/2363.Merge Similar Items/Solution.c b/solution/2300-2399/2363.Merge Similar Items/Solution.c index c7a72736b023e..9d3543ec5ea0c 100644 --- a/solution/2300-2399/2363.Merge Similar Items/Solution.c +++ b/solution/2300-2399/2363.Merge Similar Items/Solution.c @@ -26,4 +26,4 @@ int** mergeSimilarItems(int** items1, int items1Size, int* items1ColSize, int** } *returnSize = size; return ans; -} +} \ No newline at end of file diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.cpp b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.cpp index d0a2779abb874..6720e0119d6a5 100644 --- a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.cpp +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.cpp @@ -1,13 +1,16 @@ class Solution { public: int arithmeticTriplets(vector& nums, int diff) { - bitset<301> vis; - for (int x : nums) { - vis[x] = 1; - } int ans = 0; - for (int x : nums) { - ans += vis[x + diff] && vis[x + diff + diff]; + int n = nums.size(); + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + for (int k = j + 1; k < n; ++k) { + if (nums[j] - nums[i] == diff && nums[k] - nums[j] == diff) { + ++ans; + } + } + } } return ans; } diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.go b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.go index c8abb142e55ad..8ab67bc98a0e3 100644 --- a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.go +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.go @@ -1,11 +1,12 @@ func arithmeticTriplets(nums []int, diff int) (ans int) { - vis := [301]bool{} - for _, x := range nums { - vis[x] = true - } - for _, x := range nums { - if vis[x+diff] && vis[x+diff+diff] { - ans++ + n := len(nums) + for i := 0; i < n; i++ { + for j := i + 1; j < n; j++ { + for k := j + 1; k < n; k++ { + if nums[j]-nums[i] == diff && nums[k]-nums[j] == diff { + ans++ + } + } } } return diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.java b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.java index 5312b45e468b2..357301ffba53f 100644 --- a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.java +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.java @@ -1,13 +1,14 @@ class Solution { public int arithmeticTriplets(int[] nums, int diff) { - boolean[] vis = new boolean[301]; - for (int x : nums) { - vis[x] = true; - } int ans = 0; - for (int x : nums) { - if (vis[x + diff] && vis[x + diff + diff]) { - ++ans; + int n = nums.length; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + for (int k = j + 1; k < n; ++k) { + if (nums[j] - nums[i] == diff && nums[k] - nums[j] == diff) { + ++ans; + } + } } } return ans; diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.py b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.py index fb70b11a3fbd5..eedbd2da48fc5 100644 --- a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.py +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.py @@ -1,4 +1,3 @@ class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: - vis = set(nums) - return sum(x + diff in vis and x + diff * 2 in vis for x in nums) + return sum(b - a == diff and c - b == diff for a, b, c in combinations(nums, 3)) diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.ts b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.ts index 220955cc46501..e9a4fcff6199d 100644 --- a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.ts +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.ts @@ -1,12 +1,13 @@ function arithmeticTriplets(nums: number[], diff: number): number { - const vis: boolean[] = new Array(301).fill(false); - for (const x of nums) { - vis[x] = true; - } + const n = nums.length; let ans = 0; - for (const x of nums) { - if (vis[x + diff] && vis[x + diff + diff]) { - ++ans; + for (let i = 0; i < n; ++i) { + for (let j = i + 1; j < n; ++j) { + for (let k = j + 1; k < n; ++k) { + if (nums[j] - nums[i] === diff && nums[k] - nums[j] === diff) { + ++ans; + } + } } } return ans; diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution2.cpp b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution2.cpp new file mode 100644 index 0000000000000..d0a2779abb874 --- /dev/null +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int arithmeticTriplets(vector& nums, int diff) { + bitset<301> vis; + for (int x : nums) { + vis[x] = 1; + } + int ans = 0; + for (int x : nums) { + ans += vis[x + diff] && vis[x + diff + diff]; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution2.go b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution2.go new file mode 100644 index 0000000000000..c8abb142e55ad --- /dev/null +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution2.go @@ -0,0 +1,12 @@ +func arithmeticTriplets(nums []int, diff int) (ans int) { + vis := [301]bool{} + for _, x := range nums { + vis[x] = true + } + for _, x := range nums { + if vis[x+diff] && vis[x+diff+diff] { + ans++ + } + } + return +} \ No newline at end of file diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution2.java b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution2.java new file mode 100644 index 0000000000000..5312b45e468b2 --- /dev/null +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public int arithmeticTriplets(int[] nums, int diff) { + boolean[] vis = new boolean[301]; + for (int x : nums) { + vis[x] = true; + } + int ans = 0; + for (int x : nums) { + if (vis[x + diff] && vis[x + diff + diff]) { + ++ans; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution2.py b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution2.py new file mode 100644 index 0000000000000..fb70b11a3fbd5 --- /dev/null +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution2.py @@ -0,0 +1,4 @@ +class Solution: + def arithmeticTriplets(self, nums: List[int], diff: int) -> int: + vis = set(nums) + return sum(x + diff in vis and x + diff * 2 in vis for x in nums) diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution2.ts b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution2.ts new file mode 100644 index 0000000000000..220955cc46501 --- /dev/null +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution2.ts @@ -0,0 +1,13 @@ +function arithmeticTriplets(nums: number[], diff: number): number { + const vis: boolean[] = new Array(301).fill(false); + for (const x of nums) { + vis[x] = true; + } + let ans = 0; + for (const x of nums) { + if (vis[x + diff] && vis[x + diff + diff]) { + ++ans; + } + } + return ans; +} diff --git a/solution/2300-2399/2368.Reachable Nodes With Restrictions/Solution2.cpp b/solution/2300-2399/2368.Reachable Nodes With Restrictions/Solution2.cpp new file mode 100644 index 0000000000000..7f8cc379830af --- /dev/null +++ b/solution/2300-2399/2368.Reachable Nodes With Restrictions/Solution2.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int reachableNodes(int n, vector>& edges, vector& restricted) { + vector> g(n); + vector vis(n); + for (auto& e : edges) { + int a = e[0], b = e[1]; + g[a].push_back(b); + g[b].push_back(a); + } + for (int v : restricted) vis[v] = true; + queue q{{0}}; + int ans = 0; + while (!q.empty()) { + int i = q.front(); + q.pop(); + ++ans; + vis[i] = true; + for (int j : g[i]) + if (!vis[j]) q.push(j); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2368.Reachable Nodes With Restrictions/Solution2.go b/solution/2300-2399/2368.Reachable Nodes With Restrictions/Solution2.go new file mode 100644 index 0000000000000..ef07ff2bc0ad3 --- /dev/null +++ b/solution/2300-2399/2368.Reachable Nodes With Restrictions/Solution2.go @@ -0,0 +1,26 @@ +func reachableNodes(n int, edges [][]int, restricted []int) int { + g := make([][]int, n) + vis := make([]bool, n) + for _, e := range edges { + a, b := e[0], e[1] + g[a] = append(g[a], b) + g[b] = append(g[b], a) + } + for _, v := range restricted { + vis[v] = true + } + q := []int{0} + ans := 0 + for len(q) > 0 { + i := q[0] + q = q[1:] + ans++ + vis[i] = true + for _, j := range g[i] { + if !vis[j] { + q = append(q, j) + } + } + } + return ans +} \ No newline at end of file diff --git a/solution/2300-2399/2368.Reachable Nodes With Restrictions/Solution2.java b/solution/2300-2399/2368.Reachable Nodes With Restrictions/Solution2.java new file mode 100644 index 0000000000000..5412ac3698a71 --- /dev/null +++ b/solution/2300-2399/2368.Reachable Nodes With Restrictions/Solution2.java @@ -0,0 +1,29 @@ +class Solution { + public int reachableNodes(int n, int[][] edges, int[] restricted) { + List[] g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (int[] e : edges) { + int a = e[0], b = e[1]; + g[a].add(b); + g[b].add(a); + } + boolean[] vis = new boolean[n]; + for (int v : restricted) { + vis[v] = true; + } + Deque q = new ArrayDeque<>(); + q.offer(0); + int ans = 0; + while (!q.isEmpty()) { + int i = q.pollFirst(); + ++ans; + vis[i] = true; + for (int j : g[i]) { + if (!vis[j]) { + q.offer(j); + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2368.Reachable Nodes With Restrictions/Solution2.py b/solution/2300-2399/2368.Reachable Nodes With Restrictions/Solution2.py new file mode 100644 index 0000000000000..ddc97aa2e24f4 --- /dev/null +++ b/solution/2300-2399/2368.Reachable Nodes With Restrictions/Solution2.py @@ -0,0 +1,22 @@ +class Solution: + def reachableNodes( + self, n: int, edges: List[List[int]], restricted: List[int] + ) -> int: + s = set(restricted) + g = defaultdict(list) + for a, b in edges: + g[a].append(b) + g[b].append(a) + q = deque([0]) + vis = [False] * n + for v in restricted: + vis[v] = True + ans = 0 + while q: + i = q.popleft() + ans += 1 + vis[i] = True + for j in g[i]: + if not vis[j]: + q.append(j) + return ans diff --git a/solution/2300-2399/2368.Reachable Nodes With Restrictions/Solution2.ts b/solution/2300-2399/2368.Reachable Nodes With Restrictions/Solution2.ts new file mode 100644 index 0000000000000..c79fcc69ed42d --- /dev/null +++ b/solution/2300-2399/2368.Reachable Nodes With Restrictions/Solution2.ts @@ -0,0 +1,24 @@ +function reachableNodes(n: number, edges: number[][], restricted: number[]): number { + const g = Array.from({ length: n }, () => []); + const vis = new Array(n).fill(false); + for (const [a, b] of edges) { + g[a].push(b); + g[b].push(a); + } + for (const v of restricted) { + vis[v] = true; + } + const q = [0]; + let ans = 0; + while (q.length) { + const i = q.shift(); + ++ans; + vis[i] = true; + for (const j of g[i]) { + if (!vis[j]) { + q.push(j); + } + } + } + return ans; +} diff --git a/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/Solution2.cpp b/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/Solution2.cpp new file mode 100644 index 0000000000000..39ba7173b09d7 --- /dev/null +++ b/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + bool validPartition(vector& nums) { + int n = nums.size(); + vector dp(n + 1); + dp[0] = true; + for (int i = 2; i <= n; ++i) { + if (nums[i - 1] == nums[i - 2]) dp[i] = dp[i] || dp[i - 2]; + if (i > 2 && nums[i - 1] == nums[i - 2] && nums[i - 2] == nums[i - 3]) dp[i] = dp[i] || dp[i - 3]; + if (i > 2 && nums[i - 1] - nums[i - 2] == 1 && nums[i - 2] - nums[i - 3] == 1) dp[i] = dp[i] || dp[i - 3]; + } + return dp[n]; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/Solution2.go b/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/Solution2.go new file mode 100644 index 0000000000000..55b5a87ab8535 --- /dev/null +++ b/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/Solution2.go @@ -0,0 +1,17 @@ +func validPartition(nums []int) bool { + n := len(nums) + dp := make([]bool, n+1) + dp[0] = true + for i := 2; i <= n; i++ { + if nums[i-1] == nums[i-2] { + dp[i] = dp[i] || dp[i-2] + } + if i > 2 && nums[i-1] == nums[i-2] && nums[i-2] == nums[i-3] { + dp[i] = dp[i] || dp[i-3] + } + if i > 2 && nums[i-1]-nums[i-2] == 1 && nums[i-2]-nums[i-3] == 1 { + dp[i] = dp[i] || dp[i-3] + } + } + return dp[n] +} \ No newline at end of file diff --git a/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/Solution2.java b/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/Solution2.java new file mode 100644 index 0000000000000..e3dd5a644db3a --- /dev/null +++ b/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/Solution2.java @@ -0,0 +1,19 @@ +class Solution { + public boolean validPartition(int[] nums) { + int n = nums.length; + boolean[] dp = new boolean[n + 1]; + dp[0] = true; + for (int i = 2; i <= n; ++i) { + if (nums[i - 1] == nums[i - 2]) { + dp[i] = dp[i] || dp[i - 2]; + } + if (i > 2 && nums[i - 1] == nums[i - 2] && nums[i - 2] == nums[i - 3]) { + dp[i] = dp[i] || dp[i - 3]; + } + if (i > 2 && nums[i - 1] - nums[i - 2] == 1 && nums[i - 2] - nums[i - 3] == 1) { + dp[i] = dp[i] || dp[i - 3]; + } + } + return dp[n]; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/Solution2.py b/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/Solution2.py new file mode 100644 index 0000000000000..abaed229c4e96 --- /dev/null +++ b/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def validPartition(self, nums: List[int]) -> bool: + n = len(nums) + dp = [False] * (n + 1) + dp[0] = True + for i in range(2, n + 1): + if nums[i - 1] == nums[i - 2]: + dp[i] = dp[i] or dp[i - 2] + if i > 2 and nums[i - 1] == nums[i - 2] == nums[i - 3]: + dp[i] = dp[i] or dp[i - 3] + if ( + i > 2 + and nums[i - 1] - nums[i - 2] == 1 + and nums[i - 2] - nums[i - 3] == 1 + ): + dp[i] = dp[i] or dp[i - 3] + return dp[-1] diff --git a/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/Solution2.ts b/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/Solution2.ts new file mode 100644 index 0000000000000..de81ef1cee936 --- /dev/null +++ b/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/Solution2.ts @@ -0,0 +1,17 @@ +function validPartition(nums: number[]): boolean { + const n = nums.length; + const dp = new Array(n + 1).fill(false); + dp[0] = true; + for (let i = 2; i <= n; ++i) { + if (nums[i - 1] == nums[i - 2]) { + dp[i] = dp[i] || dp[i - 2]; + } + if (i > 2 && nums[i - 1] == nums[i - 2] && nums[i - 2] == nums[i - 3]) { + dp[i] = dp[i] || dp[i - 3]; + } + if (i > 2 && nums[i - 1] - nums[i - 2] == 1 && nums[i - 2] - nums[i - 3] == 1) { + dp[i] = dp[i] || dp[i - 3]; + } + } + return dp[n]; +} diff --git a/solution/2300-2399/2376.Count Special Integers/Solution2.cpp b/solution/2300-2399/2376.Count Special Integers/Solution2.cpp new file mode 100644 index 0000000000000..07c5fb7b7be9c --- /dev/null +++ b/solution/2300-2399/2376.Count Special Integers/Solution2.cpp @@ -0,0 +1,42 @@ +class Solution { +public: + int a[11]; + int dp[11][1 << 11]; + + int countSpecialNumbers(int n) { + return f(n); + } + + int f(int n) { + memset(dp, -1, sizeof dp); + int len = 0; + while (n) { + a[++len] = n % 10; + n /= 10; + } + return dfs(len, 0, true, true); + } + + int dfs(int pos, int mask, bool lead, bool limit) { + if (pos <= 0) { + return lead ? 0 : 1; + } + if (!lead && !limit && dp[pos][mask] != -1) { + return dp[pos][mask]; + } + int up = limit ? a[pos] : 9; + int ans = 0; + for (int i = 0; i <= up; ++i) { + if ((mask >> i) & 1) continue; + if (i == 0 && lead) { + ans += dfs(pos - 1, mask, lead, limit && i == up); + } else { + ans += dfs(pos - 1, mask | 1 << i, false, limit && i == up); + } + } + if (!lead && !limit) { + dp[pos][mask] = ans; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2376.Count Special Integers/Solution2.go b/solution/2300-2399/2376.Count Special Integers/Solution2.go new file mode 100644 index 0000000000000..a0bbbd03fe603 --- /dev/null +++ b/solution/2300-2399/2376.Count Special Integers/Solution2.go @@ -0,0 +1,53 @@ +func countSpecialNumbers(n int) int { + return f(n) +} + +func f(n int) int { + a := make([]int, 11) + dp := make([][]int, 11) + for i := range dp { + dp[i] = make([]int, 1<<11) + for j := range dp[i] { + dp[i][j] = -1 + } + } + l := 0 + for n > 0 { + l++ + a[l] = n % 10 + n /= 10 + } + var dfs func(int, int, bool, bool) int + dfs = func(pos, mask int, lead, limit bool) int { + if pos <= 0 { + if lead { + return 0 + } + return 1 + } + if !lead && !limit && dp[pos][mask] != -1 { + return dp[pos][mask] + } + ans := 0 + up := 9 + if limit { + up = a[pos] + } + for i := 0; i <= up; i++ { + if ((mask >> i) & 1) == 1 { + continue + } + if i == 0 && lead { + ans += dfs(pos-1, mask, lead, limit && i == up) + } else { + ans += dfs(pos-1, mask|1< 0) { + a[++len] = n % 10; + n /= 10; + } + return dfs(len, 0, true, true); + } + + private int dfs(int pos, int mask, boolean lead, boolean limit) { + if (pos <= 0) { + return lead ? 0 : 1; + } + if (!lead && !limit && dp[pos][mask] != -1) { + return dp[pos][mask]; + } + int up = limit ? a[pos] : 9; + int ans = 0; + for (int i = 0; i <= up; ++i) { + if (((mask >> i) & 1) == 1) { + continue; + } + if (i == 0 && lead) { + ans += dfs(pos - 1, mask, lead, limit && i == up); + } else { + ans += dfs(pos - 1, mask | 1 << i, false, limit && i == up); + } + } + if (!lead && !limit) { + dp[pos][mask] = ans; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2376.Count Special Integers/Solution2.py b/solution/2300-2399/2376.Count Special Integers/Solution2.py new file mode 100644 index 0000000000000..b40be7d0fa4ee --- /dev/null +++ b/solution/2300-2399/2376.Count Special Integers/Solution2.py @@ -0,0 +1,27 @@ +class Solution: + def countSpecialNumbers(self, n: int) -> int: + return self.f(n) + + def f(self, n): + @cache + def dfs(pos, mask, lead, limit): + if pos <= 0: + return lead ^ 1 + up = a[pos] if limit else 9 + ans = 0 + for i in range(up + 1): + if (mask >> i) & 1: + continue + if i == 0 and lead: + ans += dfs(pos - 1, mask, lead, limit and i == up) + else: + ans += dfs(pos - 1, mask | 1 << i, False, limit and i == up) + return ans + + a = [0] * 11 + l = 0 + while n: + l += 1 + a[l] = n % 10 + n //= 10 + return dfs(l, 0, True, True) diff --git a/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/Solution.c b/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/Solution.c index 8f11fcc24b25d..139338eb41c57 100644 --- a/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/Solution.c +++ b/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/Solution.c @@ -13,4 +13,4 @@ int minimumRecolors(char* blocks, int k) { ans = min(ans, k - count); } return ans; -} +} \ No newline at end of file diff --git a/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/Solution.php b/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/Solution.php index 0a3da5a855f97..0b664e028b904 100644 --- a/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/Solution.php +++ b/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/Solution.php @@ -23,4 +23,4 @@ function minimumRecolors($blocks, $k) { } return $min; } -} \ No newline at end of file +} diff --git a/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution.cpp b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution.cpp index 053fe7a5cd292..b66dd449704de 100644 --- a/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution.cpp +++ b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution.cpp @@ -1,12 +1,19 @@ class Solution { public: int secondsToRemoveOccurrences(string s) { - int ans = 0, cnt = 0; - for (char c : s) { - if (c == '0') { - ++cnt; - } else if (cnt) { - ans = max(ans + 1, cnt); + bool find = true; + int ans = 0; + while (find) { + find = false; + for (int i = 0; i < s.size() - 1; ++i) { + if (s[i] == '0' && s[i + 1] == '1') { + swap(s[i], s[i + 1]); + ++i; + find = true; + } + } + if (find) { + ++ans; } } return ans; diff --git a/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution.go b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution.go index 62739ffc4d4cb..92d5e232c3ea9 100644 --- a/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution.go +++ b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution.go @@ -1,10 +1,18 @@ func secondsToRemoveOccurrences(s string) int { - ans, cnt := 0, 0 - for _, c := range s { - if c == '0' { - cnt++ - } else if cnt > 0 { - ans = max(ans+1, cnt) + cs := []byte(s) + ans := 0 + find := true + for find { + find = false + for i := 0; i < len(cs)-1; i++ { + if cs[i] == '0' && cs[i+1] == '1' { + cs[i], cs[i+1] = cs[i+1], cs[i] + i++ + find = true + } + } + if find { + ans++ } } return ans diff --git a/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution.java b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution.java index 7ea7bd09c25a7..9493888b561f1 100644 --- a/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution.java +++ b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution.java @@ -1,11 +1,21 @@ class Solution { public int secondsToRemoveOccurrences(String s) { - int ans = 0, cnt = 0; - for (char c : s.toCharArray()) { - if (c == '0') { - ++cnt; - } else if (cnt > 0) { - ans = Math.max(ans + 1, cnt); + char[] cs = s.toCharArray(); + boolean find = true; + int ans = 0; + while (find) { + find = false; + for (int i = 0; i < cs.length - 1; ++i) { + if (cs[i] == '0' && cs[i + 1] == '1') { + char t = cs[i]; + cs[i] = cs[i + 1]; + cs[i + 1] = t; + ++i; + find = true; + } + } + if (find) { + ++ans; } } return ans; diff --git a/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution.py b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution.py index 40606076b7ab4..ead2a13da6c3d 100644 --- a/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution.py +++ b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution.py @@ -1,9 +1,7 @@ class Solution: def secondsToRemoveOccurrences(self, s: str) -> int: - ans = cnt = 0 - for c in s: - if c == '0': - cnt += 1 - elif cnt: - ans = max(ans + 1, cnt) + ans = 0 + while s.count('01'): + s = s.replace('01', '10') + ans += 1 return ans diff --git a/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution2.cpp b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution2.cpp new file mode 100644 index 0000000000000..053fe7a5cd292 --- /dev/null +++ b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int secondsToRemoveOccurrences(string s) { + int ans = 0, cnt = 0; + for (char c : s) { + if (c == '0') { + ++cnt; + } else if (cnt) { + ans = max(ans + 1, cnt); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution2.go b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution2.go new file mode 100644 index 0000000000000..62739ffc4d4cb --- /dev/null +++ b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution2.go @@ -0,0 +1,11 @@ +func secondsToRemoveOccurrences(s string) int { + ans, cnt := 0, 0 + for _, c := range s { + if c == '0' { + cnt++ + } else if cnt > 0 { + ans = max(ans+1, cnt) + } + } + return ans +} \ No newline at end of file diff --git a/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution2.java b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution2.java new file mode 100644 index 0000000000000..7ea7bd09c25a7 --- /dev/null +++ b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution2.java @@ -0,0 +1,13 @@ +class Solution { + public int secondsToRemoveOccurrences(String s) { + int ans = 0, cnt = 0; + for (char c : s.toCharArray()) { + if (c == '0') { + ++cnt; + } else if (cnt > 0) { + ans = Math.max(ans + 1, cnt); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution2.py b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution2.py new file mode 100644 index 0000000000000..40606076b7ab4 --- /dev/null +++ b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def secondsToRemoveOccurrences(self, s: str) -> int: + ans = cnt = 0 + for c in s: + if c == '0': + cnt += 1 + elif cnt: + ans = max(ans + 1, cnt) + return ans diff --git a/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution.c b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution.c index 68676066911aa..2999a43c188a0 100644 --- a/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution.c +++ b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution.c @@ -13,4 +13,4 @@ int minNumberOfHours(int initialEnergy, int initialExperience, int* energy, int initialExperience += experience[i]; } return res; -} +} \ No newline at end of file diff --git a/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution2.cpp b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution2.cpp new file mode 100644 index 0000000000000..5e1b0b1512698 --- /dev/null +++ b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int minNumberOfHours(int initialEnergy, int initialExperience, vector& energy, vector& experience) { + int s = accumulate(energy.begin(), energy.end(), 0); + int ans = max(0, s - initialEnergy + 1); + for (int x : experience) { + if (initialExperience <= x) { + ans += x - initialExperience + 1; + initialExperience = x + 1; + } + initialExperience += x; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution2.go b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution2.go new file mode 100644 index 0000000000000..0a825ce7e48a0 --- /dev/null +++ b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution2.go @@ -0,0 +1,17 @@ +func minNumberOfHours(initialEnergy int, initialExperience int, energy []int, experience []int) (ans int) { + s := 0 + for _, x := range energy { + s += x + } + if y := s - initialEnergy + 1; y > 0 { + ans = y + } + for _, x := range experience { + if initialExperience <= x { + ans += x - initialExperience + 1 + initialExperience = x + 1 + } + initialExperience += x + } + return +} \ No newline at end of file diff --git a/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution2.java b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution2.java new file mode 100644 index 0000000000000..38ba1c11d64fd --- /dev/null +++ b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution2.java @@ -0,0 +1,18 @@ +class Solution { + public int minNumberOfHours( + int initialEnergy, int initialExperience, int[] energy, int[] experience) { + int s = 0; + for (int x : energy) { + s += x; + } + int ans = Math.max(0, s - initialEnergy + 1); + for (int x : experience) { + if (initialExperience <= x) { + ans += x - initialExperience + 1; + initialExperience = x + 1; + } + initialExperience += x; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution2.py b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution2.py new file mode 100644 index 0000000000000..86828c02fcdc1 --- /dev/null +++ b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution2.py @@ -0,0 +1,15 @@ +class Solution: + def minNumberOfHours( + self, + initialEnergy: int, + initialExperience: int, + energy: List[int], + experience: List[int], + ) -> int: + ans = max(0, sum(energy) - initialEnergy + 1) + for x in experience: + if initialExperience <= x: + ans += x - initialExperience + 1 + initialExperience = x + 1 + initialExperience += x + return ans diff --git a/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution2.ts b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution2.ts new file mode 100644 index 0000000000000..4566665224eb0 --- /dev/null +++ b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution2.ts @@ -0,0 +1,23 @@ +function minNumberOfHours( + initialEnergy: number, + initialExperience: number, + energy: number[], + experience: number[], +): number { + let res = 0; + for (const v of experience) { + if (initialExperience <= v) { + res += v - initialExperience + 1; + initialExperience = v + 1; + } + initialExperience += v; + } + for (const v of energy) { + if (initialEnergy <= v) { + res += v - initialEnergy + 1; + initialEnergy = v + 1; + } + initialEnergy -= v; + } + return res; +} diff --git a/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution3.ts b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution3.ts new file mode 100644 index 0000000000000..56d6aa8a12803 --- /dev/null +++ b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution3.ts @@ -0,0 +1,17 @@ +function minNumberOfHours( + initialEnergy: number, + initialExperience: number, + energy: number[], + experience: number[], +): number { + const s = energy.reduce((a, b) => a + b, 0); + let ans = Math.max(0, s - initialEnergy + 1); + for (const x of experience) { + if (initialExperience <= x) { + ans += x - initialExperience + 1; + initialExperience = x + 1; + } + initialExperience += x; + } + return ans; +} diff --git a/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/Solution2.cpp b/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/Solution2.cpp new file mode 100644 index 0000000000000..b691c178657e1 --- /dev/null +++ b/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/Solution2.cpp @@ -0,0 +1,44 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + unordered_map> g; + + int amountOfTime(TreeNode* root, int start) { + dfs(root); + return dfs(start, -1); + } + + int dfs(int i, int fa) { + int ans = 0; + for (int& j : g[i]) { + if (j != fa) { + ans = max(ans, 1 + dfs(j, i)); + } + } + return ans; + } + + void dfs(TreeNode* root) { + if (!root) return; + if (root->left) { + g[root->val].push_back(root->left->val); + g[root->left->val].push_back(root->val); + } + if (root->right) { + g[root->val].push_back(root->right->val); + g[root->right->val].push_back(root->val); + } + dfs(root->left); + dfs(root->right); + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/Solution2.go b/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/Solution2.go new file mode 100644 index 0000000000000..8782cad108de8 --- /dev/null +++ b/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/Solution2.go @@ -0,0 +1,41 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func amountOfTime(root *TreeNode, start int) int { + g := map[int][]int{} + var dfs func(*TreeNode) + dfs = func(root *TreeNode) { + if root == nil { + return + } + if root.Left != nil { + g[root.Val] = append(g[root.Val], root.Left.Val) + g[root.Left.Val] = append(g[root.Left.Val], root.Val) + } + if root.Right != nil { + g[root.Val] = append(g[root.Val], root.Right.Val) + g[root.Right.Val] = append(g[root.Right.Val], root.Val) + } + dfs(root.Left) + dfs(root.Right) + } + + var dfs2 func(int, int) int + dfs2 = func(i, fa int) int { + ans := 0 + for _, j := range g[i] { + if j != fa { + ans = max(ans, 1+dfs2(j, i)) + } + } + return ans + } + + dfs(root) + return dfs2(start, -1) +} \ No newline at end of file diff --git a/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/Solution2.java b/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/Solution2.java new file mode 100644 index 0000000000000..3d0bd2f470fbc --- /dev/null +++ b/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/Solution2.java @@ -0,0 +1,49 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private Map> g = new HashMap<>(); + + public int amountOfTime(TreeNode root, int start) { + dfs(root); + return dfs(start, -1); + } + + private int dfs(int i, int fa) { + int ans = 0; + for (int j : g.getOrDefault(i, Collections.emptyList())) { + if (j != fa) { + ans = Math.max(ans, 1 + dfs(j, i)); + } + } + return ans; + } + + private void dfs(TreeNode root) { + if (root == null) { + return; + } + if (root.left != null) { + g.computeIfAbsent(root.left.val, k -> new ArrayList<>()).add(root.val); + g.computeIfAbsent(root.val, k -> new ArrayList<>()).add(root.left.val); + } + if (root.right != null) { + g.computeIfAbsent(root.right.val, k -> new ArrayList<>()).add(root.val); + g.computeIfAbsent(root.val, k -> new ArrayList<>()).add(root.right.val); + } + dfs(root.left); + dfs(root.right); + } +} \ No newline at end of file diff --git a/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/Solution2.py b/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/Solution2.py new file mode 100644 index 0000000000000..5e211bc04b974 --- /dev/null +++ b/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/Solution2.py @@ -0,0 +1,30 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def amountOfTime(self, root: Optional[TreeNode], start: int) -> int: + def dfs(root): + if root is None: + return + if root.left: + g[root.val].append(root.left.val) + g[root.left.val].append(root.val) + if root.right: + g[root.val].append(root.right.val) + g[root.right.val].append(root.val) + dfs(root.left) + dfs(root.right) + + def dfs2(i, fa): + ans = 0 + for j in g[i]: + if j != fa: + ans = max(ans, 1 + dfs2(j, i)) + return ans + + g = defaultdict(list) + dfs(root) + return dfs2(start, -1) diff --git a/solution/2300-2399/2388.Change Null Values in a Table to the Previous Value/Solution.sql b/solution/2300-2399/2388.Change Null Values in a Table to the Previous Value/Solution.sql index 778703af00efe..7c4ef3c207f66 100644 --- a/solution/2300-2399/2388.Change Null Values in a Table to the Previous Value/Solution.sql +++ b/solution/2300-2399/2388.Change Null Values in a Table to the Previous Value/Solution.sql @@ -1,24 +1,8 @@ # Write your MySQL query statement below -WITH - S AS ( - SELECT *, ROW_NUMBER() OVER () AS rk - FROM CoffeeShop - ), - T AS ( - SELECT - *, - SUM( - CASE - WHEN drink IS NULL THEN 0 - ELSE 1 - END - ) OVER (ORDER BY rk) AS gid - FROM S - ) SELECT id, - MAX(drink) OVER ( - PARTITION BY gid - ORDER BY rk - ) AS drink -FROM T; + CASE + WHEN drink IS NOT NULL THEN @cur := drink + ELSE @cur + END AS drink +FROM CoffeeShop; diff --git a/solution/2300-2399/2388.Change Null Values in a Table to the Previous Value/Solution2.sql b/solution/2300-2399/2388.Change Null Values in a Table to the Previous Value/Solution2.sql new file mode 100644 index 0000000000000..778703af00efe --- /dev/null +++ b/solution/2300-2399/2388.Change Null Values in a Table to the Previous Value/Solution2.sql @@ -0,0 +1,24 @@ +# Write your MySQL query statement below +WITH + S AS ( + SELECT *, ROW_NUMBER() OVER () AS rk + FROM CoffeeShop + ), + T AS ( + SELECT + *, + SUM( + CASE + WHEN drink IS NULL THEN 0 + ELSE 1 + END + ) OVER (ORDER BY rk) AS gid + FROM S + ) +SELECT + id, + MAX(drink) OVER ( + PARTITION BY gid + ORDER BY rk + ) AS drink +FROM T; diff --git a/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution.cs b/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution.cs new file mode 100644 index 0000000000000..17a35674faffb --- /dev/null +++ b/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution.cs @@ -0,0 +1,22 @@ +public class Solution { + public int[] AnswerQueries(int[] nums, int[] queries) { + int[] result = new int[queries.Length]; + Array.Sort(nums); + for (int i = 0; i < queries.Length; i++) { + result[i] = getSubsequent(nums, queries[i]); + } + return result; + + } + + public int getSubsequent(int[] nums,int query) { + int sum = 0; + for (int i = 0; i < nums.Length; i++) { + sum += nums[i]; + if (sum > query) { + return i; + } + } + return nums.Length; + } +} diff --git a/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution2.cpp b/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution2.cpp new file mode 100644 index 0000000000000..ad779204e65ec --- /dev/null +++ b/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution2.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + vector answerQueries(vector& nums, vector& queries) { + sort(nums.begin(), nums.end()); + int m = queries.size(); + vector idx(m); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { + return queries[i] < queries[j]; + }); + vector ans(m); + int s = 0, j = 0; + for (int i : idx) { + while (j < nums.size() && s + nums[j] <= queries[i]) { + s += nums[j++]; + } + ans[i] = j; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution2.go b/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution2.go new file mode 100644 index 0000000000000..d18a9b282d2fb --- /dev/null +++ b/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution2.go @@ -0,0 +1,19 @@ +func answerQueries(nums []int, queries []int) (ans []int) { + sort.Ints(nums) + m := len(queries) + idx := make([]int, m) + for i := range idx { + idx[i] = i + } + sort.Slice(idx, func(i, j int) bool { return queries[idx[i]] < queries[idx[j]] }) + ans = make([]int, m) + s, j := 0, 0 + for _, i := range idx { + for j < len(nums) && s+nums[j] <= queries[i] { + s += nums[j] + j++ + } + ans[i] = j + } + return +} \ No newline at end of file diff --git a/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution2.java b/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution2.java new file mode 100644 index 0000000000000..9100703fc5f9a --- /dev/null +++ b/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution2.java @@ -0,0 +1,20 @@ +class Solution { + public int[] answerQueries(int[] nums, int[] queries) { + Arrays.sort(nums); + int m = queries.length; + Integer[] idx = new Integer[m]; + for (int i = 0; i < m; ++i) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> queries[i] - queries[j]); + int[] ans = new int[m]; + int s = 0, j = 0; + for (int i : idx) { + while (j < nums.length && s + nums[j] <= queries[i]) { + s += nums[j++]; + } + ans[i] = j; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution2.py b/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution2.py new file mode 100644 index 0000000000000..2573d74eee85a --- /dev/null +++ b/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]: + nums.sort() + m = len(queries) + ans = [0] * m + idx = sorted(range(m), key=lambda i: queries[i]) + s = j = 0 + for i in idx: + while j < len(nums) and s + nums[j] <= queries[i]: + s += nums[j] + j += 1 + ans[i] = j + return ans diff --git a/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution2.ts b/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution2.ts new file mode 100644 index 0000000000000..d0fae1c618392 --- /dev/null +++ b/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution2.ts @@ -0,0 +1,19 @@ +function answerQueries(nums: number[], queries: number[]): number[] { + nums.sort((a, b) => a - b); + const m = queries.length; + const idx: number[] = new Array(m); + for (let i = 0; i < m; i++) { + idx[i] = i; + } + idx.sort((i, j) => queries[i] - queries[j]); + const ans: number[] = new Array(m); + let s = 0; + let j = 0; + for (const i of idx) { + while (j < nums.length && s + nums[j] <= queries[i]) { + s += nums[j++]; + } + ans[i] = j; + } + return ans; +} diff --git a/solution/2300-2399/2390.Removing Stars From a String/Solution.php b/solution/2300-2399/2390.Removing Stars From a String/Solution.php index 57d8b1a0088d1..dc1ba3e286738 100644 --- a/solution/2300-2399/2390.Removing Stars From a String/Solution.php +++ b/solution/2300-2399/2390.Removing Stars From a String/Solution.php @@ -14,4 +14,4 @@ function removeStars($s) { } return join($rs); } -} \ No newline at end of file +} diff --git a/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/Solution2.cpp b/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/Solution2.cpp new file mode 100644 index 0000000000000..3f7b423287e7c --- /dev/null +++ b/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/Solution2.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int garbageCollection(vector& garbage, vector& travel) { + auto f = [&](char x) { + int ans = 0, st = 0; + for (int i = 0; i < garbage.size(); ++i) { + int cnt = 0; + for (char& c : garbage[i]) { + if (c == x) { + ++cnt; + } + } + if (cnt > 0) { + ans += cnt + st; + st = 0; + } + if (i < travel.size()) { + st += travel[i]; + } + } + return ans; + }; + return f('M') + f('P') + f('G'); + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/Solution2.go b/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/Solution2.go new file mode 100644 index 0000000000000..ac166b7c10b12 --- /dev/null +++ b/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/Solution2.go @@ -0,0 +1,17 @@ +func garbageCollection(garbage []string, travel []int) (ans int) { + f := func(x rune) int { + ans, st := 0, 0 + for i, s := range garbage { + cnt := strings.Count(s, string(x)) + if cnt > 0 { + ans += cnt + st + st = 0 + } + if i < len(travel) { + st += travel[i] + } + } + return ans + } + return f('M') + f('P') + f('G') +} \ No newline at end of file diff --git a/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/Solution2.java b/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/Solution2.java new file mode 100644 index 0000000000000..e26aad4fd64b3 --- /dev/null +++ b/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/Solution2.java @@ -0,0 +1,31 @@ +class Solution { + private String[] garbage; + private int[] travel; + + public int garbageCollection(String[] garbage, int[] travel) { + this.garbage = garbage; + this.travel = travel; + return f('M') + f('P') + f('G'); + } + + private int f(char c) { + int ans = 0; + int st = 0; + for (int i = 0; i < garbage.length; ++i) { + int cnt = 0; + for (int j = 0; j < garbage[i].length(); ++j) { + if (garbage[i].charAt(j) == c) { + ++cnt; + } + } + if (cnt > 0) { + ans += cnt + st; + st = 0; + } + if (i < travel.length) { + st += travel[i]; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/Solution2.py b/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/Solution2.py new file mode 100644 index 0000000000000..a3f5846d99c12 --- /dev/null +++ b/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def garbageCollection(self, garbage: List[str], travel: List[int]) -> int: + def f(x: str) -> int: + ans = 0 + st = 0 + for i, s in enumerate(garbage): + if t := s.count(x): + ans += t + st + st = 0 + if i < len(travel): + st += travel[i] + return ans + + return f('M') + f('P') + f('G') diff --git a/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/Solution2.ts b/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/Solution2.ts new file mode 100644 index 0000000000000..dc154c3b49e14 --- /dev/null +++ b/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/Solution2.ts @@ -0,0 +1,23 @@ +function garbageCollection(garbage: string[], travel: number[]): number { + const f = (x: string) => { + let ans = 0; + let st = 0; + for (let i = 0; i < garbage.length; ++i) { + let cnt = 0; + for (const c of garbage[i]) { + if (c === x) { + ++cnt; + } + } + if (cnt > 0) { + ans += cnt + st; + st = 0; + } + if (i < travel.length) { + st += travel[i]; + } + } + return ans; + }; + return f('M') + f('P') + f('G'); +} diff --git a/solution/2300-2399/2393.Count Strictly Increasing Subarrays/Solution2.cpp b/solution/2300-2399/2393.Count Strictly Increasing Subarrays/Solution2.cpp new file mode 100644 index 0000000000000..1184da8ebe6e0 --- /dev/null +++ b/solution/2300-2399/2393.Count Strictly Increasing Subarrays/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + long long countSubarrays(vector& nums) { + long long ans = 0; + int pre = 0, cnt = 0; + for (int x : nums) { + if (pre < x) { + ++cnt; + } else { + cnt = 1; + } + ans += cnt; + pre = x; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2300-2399/2393.Count Strictly Increasing Subarrays/Solution2.go b/solution/2300-2399/2393.Count Strictly Increasing Subarrays/Solution2.go new file mode 100644 index 0000000000000..9bb112f931827 --- /dev/null +++ b/solution/2300-2399/2393.Count Strictly Increasing Subarrays/Solution2.go @@ -0,0 +1,13 @@ +func countSubarrays(nums []int) (ans int64) { + pre, cnt := 0, 0 + for _, x := range nums { + if pre < x { + cnt++ + } else { + cnt = 1 + } + ans += int64(cnt) + pre = x + } + return +} \ No newline at end of file diff --git a/solution/2300-2399/2393.Count Strictly Increasing Subarrays/Solution2.java b/solution/2300-2399/2393.Count Strictly Increasing Subarrays/Solution2.java new file mode 100644 index 0000000000000..bbbcf80b74a99 --- /dev/null +++ b/solution/2300-2399/2393.Count Strictly Increasing Subarrays/Solution2.java @@ -0,0 +1,16 @@ +class Solution { + public long countSubarrays(int[] nums) { + long ans = 0; + int pre = 0, cnt = 0; + for (int x : nums) { + if (pre < x) { + ++cnt; + } else { + cnt = 1; + } + pre = x; + ans += cnt; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2300-2399/2393.Count Strictly Increasing Subarrays/Solution2.py b/solution/2300-2399/2393.Count Strictly Increasing Subarrays/Solution2.py new file mode 100644 index 0000000000000..1b3afbb15fa1d --- /dev/null +++ b/solution/2300-2399/2393.Count Strictly Increasing Subarrays/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def countSubarrays(self, nums: List[int]) -> int: + ans = pre = cnt = 0 + for x in nums: + if pre < x: + cnt += 1 + else: + cnt = 1 + pre = x + ans += cnt + return ans diff --git a/solution/2300-2399/2393.Count Strictly Increasing Subarrays/Solution2.ts b/solution/2300-2399/2393.Count Strictly Increasing Subarrays/Solution2.ts new file mode 100644 index 0000000000000..d5107e1620cc2 --- /dev/null +++ b/solution/2300-2399/2393.Count Strictly Increasing Subarrays/Solution2.ts @@ -0,0 +1,15 @@ +function countSubarrays(nums: number[]): number { + let ans = 0; + let pre = 0; + let cnt = 0; + for (const x of nums) { + if (pre < x) { + ++cnt; + } else { + cnt = 1; + } + ans += cnt; + pre = x; + } + return ans; +} diff --git a/solution/2300-2399/2395.Find Subarrays With Equal Sum/Solution.c b/solution/2300-2399/2395.Find Subarrays With Equal Sum/Solution.c index 62be149a9da11..2f05c0acddc41 100644 --- a/solution/2300-2399/2395.Find Subarrays With Equal Sum/Solution.c +++ b/solution/2300-2399/2395.Find Subarrays With Equal Sum/Solution.c @@ -1,5 +1,5 @@ bool findSubarrays(int* nums, int numsSize) { - for (int i = 1; i < numsSize - 2; i++) { + for (int i = 1; i < numsSize - 1; i++) { for (int j = i + 1; j < numsSize; j++) { if (nums[i - 1] + nums[i] == nums[j - 1] + nums[j]) { return true; @@ -7,4 +7,4 @@ bool findSubarrays(int* nums, int numsSize) { } } return false; -} +} \ No newline at end of file diff --git a/solution/2300-2399/2396.Strictly Palindromic Number/Solution.c b/solution/2300-2399/2396.Strictly Palindromic Number/Solution.c index ef19e560c485d..cddd64b3d3caf 100644 --- a/solution/2300-2399/2396.Strictly Palindromic Number/Solution.c +++ b/solution/2300-2399/2396.Strictly Palindromic Number/Solution.c @@ -1,3 +1,3 @@ bool isStrictlyPalindromic(int n) { return 0; -} +} \ No newline at end of file diff --git a/solution/2300-2399/2398.Maximum Number of Robots Within Budget/Solution.py b/solution/2300-2399/2398.Maximum Number of Robots Within Budget/Solution.py index aafdc27a364ea..122f1522c478d 100644 --- a/solution/2300-2399/2398.Maximum Number of Robots Within Budget/Solution.py +++ b/solution/2300-2399/2398.Maximum Number of Robots Within Budget/Solution.py @@ -1,18 +1,18 @@ -class Solution: - def maximumRobots( - self, chargeTimes: List[int], runningCosts: List[int], budget: int - ) -> int: - q = deque() - ans = j = s = 0 - for i, (a, b) in enumerate(zip(chargeTimes, runningCosts)): - while q and chargeTimes[q[-1]] <= a: - q.pop() - q.append(i) - s += b - while q and chargeTimes[q[0]] + (i - j + 1) * s > budget: - if q[0] == j: - q.popleft() - s -= runningCosts[j] - j += 1 - ans = max(ans, i - j + 1) - return ans +class Solution: + def maximumRobots( + self, chargeTimes: List[int], runningCosts: List[int], budget: int + ) -> int: + q = deque() + ans = j = s = 0 + for i, (a, b) in enumerate(zip(chargeTimes, runningCosts)): + while q and chargeTimes[q[-1]] <= a: + q.pop() + q.append(i) + s += b + while q and chargeTimes[q[0]] + (i - j + 1) * s > budget: + if q[0] == j: + q.popleft() + s -= runningCosts[j] + j += 1 + ans = max(ans, i - j + 1) + return ans diff --git a/solution/2300-2399/2399.Check Distances Between Same Letters/Solution.c b/solution/2300-2399/2399.Check Distances Between Same Letters/Solution.c index 28ba1607fe6f7..502ccb7a8deff 100644 --- a/solution/2300-2399/2399.Check Distances Between Same Letters/Solution.c +++ b/solution/2300-2399/2399.Check Distances Between Same Letters/Solution.c @@ -9,4 +9,4 @@ bool checkDistances(char* s, int* distance, int distanceSize) { d[j] = i + 1; } return true; -} +} \ No newline at end of file diff --git a/solution/2400-2499/2403.Minimum Time to Kill All Monsters/Solution2.cpp b/solution/2400-2499/2403.Minimum Time to Kill All Monsters/Solution2.cpp new file mode 100644 index 0000000000000..5c874a7ea9ff0 --- /dev/null +++ b/solution/2400-2499/2403.Minimum Time to Kill All Monsters/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + long long minimumTime(vector& power) { + int n = power.size(); + vector dp(1 << n, LONG_MAX); + dp[0] = 0; + for (int mask = 1; mask < 1 << n; ++mask) { + int cnt = __builtin_popcount(mask); + for (int i = 0; i < n; ++i) { + if ((mask >> i) & 1) { + dp[mask] = min(dp[mask], dp[mask ^ (1 << i)] + (power[i] + cnt - 1) / cnt); + } + } + } + return dp[(1 << n) - 1]; + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2403.Minimum Time to Kill All Monsters/Solution2.go b/solution/2400-2499/2403.Minimum Time to Kill All Monsters/Solution2.go new file mode 100644 index 0000000000000..3dc312425acd6 --- /dev/null +++ b/solution/2400-2499/2403.Minimum Time to Kill All Monsters/Solution2.go @@ -0,0 +1,17 @@ +func minimumTime(power []int) int64 { + n := len(power) + dp := make([]int64, 1<> i) & 1) == 1 { + dp[mask] = min(dp[mask], dp[mask^(1<> i) & 1) == 1) { + dp[mask] = Math.min(dp[mask], dp[mask ^ (1 << i)] + (power[i] + cnt - 1) / cnt); + } + } + } + return dp[(1 << n) - 1]; + } +} \ No newline at end of file diff --git a/solution/2400-2499/2403.Minimum Time to Kill All Monsters/Solution2.py b/solution/2400-2499/2403.Minimum Time to Kill All Monsters/Solution2.py new file mode 100644 index 0000000000000..56b4872e6e9b2 --- /dev/null +++ b/solution/2400-2499/2403.Minimum Time to Kill All Monsters/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def minimumTime(self, power: List[int]) -> int: + n = len(power) + dp = [inf] * (1 << n) + dp[0] = 0 + for mask in range(1, 1 << n): + cnt = mask.bit_count() + for i, v in enumerate(power): + if (mask >> i) & 1: + dp[mask] = min(dp[mask], dp[mask ^ (1 << i)] + (v + cnt - 1) // cnt) + return dp[-1] diff --git a/solution/2400-2499/2403.Minimum Time to Kill All Monsters/Solution2.ts b/solution/2400-2499/2403.Minimum Time to Kill All Monsters/Solution2.ts new file mode 100644 index 0000000000000..7b6084915b180 --- /dev/null +++ b/solution/2400-2499/2403.Minimum Time to Kill All Monsters/Solution2.ts @@ -0,0 +1,24 @@ +function minimumTime(power: number[]): number { + const n = power.length; + const dp = new Array(1 << n).fill(Infinity); + dp[0] = 0; + for (let mask = 1; mask < 1 << n; ++mask) { + const cnt = bitCount(mask); + for (let i = 0; i < n; ++i) { + if ((mask >> i) & 1) { + dp[mask] = Math.min(dp[mask], dp[mask ^ (1 << i)] + Math.ceil(power[i] / cnt)); + } + } + } + return dp[dp.length - 1]; +} + +function bitCount(x) { + let cnt = 0; + for (let i = 0; i < 32; ++i) { + if ((x >> i) & 1) { + ++cnt; + } + } + return cnt; +} diff --git a/solution/2400-2499/2404.Most Frequent Even Element/Solution.php b/solution/2400-2499/2404.Most Frequent Even Element/Solution.php index 160dc924b339f..19af6a689274d 100644 --- a/solution/2400-2499/2404.Most Frequent Even Element/Solution.php +++ b/solution/2400-2499/2404.Most Frequent Even Element/Solution.php @@ -19,4 +19,4 @@ function mostFrequentEven($nums) { } return $rs; } -} \ No newline at end of file +} diff --git a/solution/2400-2499/2405.Optimal Partition of String/Solution.cpp b/solution/2400-2499/2405.Optimal Partition of String/Solution.cpp index a0bef78cd437d..b3f1fbbdc92d0 100644 --- a/solution/2400-2499/2405.Optimal Partition of String/Solution.cpp +++ b/solution/2400-2499/2405.Optimal Partition of String/Solution.cpp @@ -1,15 +1,14 @@ class Solution { public: int partitionString(string s) { + unordered_set ss; int ans = 1; - int v = 0; for (char c : s) { - int i = c - 'a'; - if ((v >> i) & 1) { - v = 0; + if (ss.count(c)) { ++ans; + ss.clear(); } - v |= 1 << i; + ss.insert(c); } return ans; } diff --git a/solution/2400-2499/2405.Optimal Partition of String/Solution.go b/solution/2400-2499/2405.Optimal Partition of String/Solution.go index 0ed4084c4d890..0550d6e0fc7ab 100644 --- a/solution/2400-2499/2405.Optimal Partition of String/Solution.go +++ b/solution/2400-2499/2405.Optimal Partition of String/Solution.go @@ -1,12 +1,12 @@ func partitionString(s string) int { - ans, v := 1, 0 + ss := map[rune]bool{} + ans := 1 for _, c := range s { - i := int(c - 'a') - if v>>i&1 == 1 { - v = 0 + if ss[c] { ans++ + ss = map[rune]bool{} } - v |= 1 << i + ss[c] = true } return ans } \ No newline at end of file diff --git a/solution/2400-2499/2405.Optimal Partition of String/Solution.java b/solution/2400-2499/2405.Optimal Partition of String/Solution.java index 89683b1b9fe16..ddca7d757fbd9 100644 --- a/solution/2400-2499/2405.Optimal Partition of String/Solution.java +++ b/solution/2400-2499/2405.Optimal Partition of String/Solution.java @@ -1,14 +1,13 @@ class Solution { public int partitionString(String s) { - int v = 0; + Set ss = new HashSet<>(); int ans = 1; for (char c : s.toCharArray()) { - int i = c - 'a'; - if (((v >> i) & 1) == 1) { - v = 0; + if (ss.contains(c)) { ++ans; + ss.clear(); } - v |= 1 << i; + ss.add(c); } return ans; } diff --git a/solution/2400-2499/2405.Optimal Partition of String/Solution.py b/solution/2400-2499/2405.Optimal Partition of String/Solution.py index df3265ccba350..44f216c5ad84a 100644 --- a/solution/2400-2499/2405.Optimal Partition of String/Solution.py +++ b/solution/2400-2499/2405.Optimal Partition of String/Solution.py @@ -1,10 +1,10 @@ class Solution: def partitionString(self, s: str) -> int: - ans, v = 1, 0 + ss = set() + ans = 1 for c in s: - i = ord(c) - ord('a') - if (v >> i) & 1: - v = 0 + if c in ss: ans += 1 - v |= 1 << i + ss = set() + ss.add(c) return ans diff --git a/solution/2400-2499/2405.Optimal Partition of String/Solution2.cpp b/solution/2400-2499/2405.Optimal Partition of String/Solution2.cpp new file mode 100644 index 0000000000000..a0bef78cd437d --- /dev/null +++ b/solution/2400-2499/2405.Optimal Partition of String/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int partitionString(string s) { + int ans = 1; + int v = 0; + for (char c : s) { + int i = c - 'a'; + if ((v >> i) & 1) { + v = 0; + ++ans; + } + v |= 1 << i; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2405.Optimal Partition of String/Solution2.go b/solution/2400-2499/2405.Optimal Partition of String/Solution2.go new file mode 100644 index 0000000000000..0ed4084c4d890 --- /dev/null +++ b/solution/2400-2499/2405.Optimal Partition of String/Solution2.go @@ -0,0 +1,12 @@ +func partitionString(s string) int { + ans, v := 1, 0 + for _, c := range s { + i := int(c - 'a') + if v>>i&1 == 1 { + v = 0 + ans++ + } + v |= 1 << i + } + return ans +} \ No newline at end of file diff --git a/solution/2400-2499/2405.Optimal Partition of String/Solution2.java b/solution/2400-2499/2405.Optimal Partition of String/Solution2.java new file mode 100644 index 0000000000000..89683b1b9fe16 --- /dev/null +++ b/solution/2400-2499/2405.Optimal Partition of String/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public int partitionString(String s) { + int v = 0; + int ans = 1; + for (char c : s.toCharArray()) { + int i = c - 'a'; + if (((v >> i) & 1) == 1) { + v = 0; + ++ans; + } + v |= 1 << i; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2400-2499/2405.Optimal Partition of String/Solution2.py b/solution/2400-2499/2405.Optimal Partition of String/Solution2.py new file mode 100644 index 0000000000000..df3265ccba350 --- /dev/null +++ b/solution/2400-2499/2405.Optimal Partition of String/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def partitionString(self, s: str) -> int: + ans, v = 1, 0 + for c in s: + i = ord(c) - ord('a') + if (v >> i) & 1: + v = 0 + ans += 1 + v |= 1 << i + return ans diff --git a/solution/2400-2499/2413.Smallest Even Multiple/Solution.c b/solution/2400-2499/2413.Smallest Even Multiple/Solution.c index 11155d0c3c1c2..532f4d1a75c02 100644 --- a/solution/2400-2499/2413.Smallest Even Multiple/Solution.c +++ b/solution/2400-2499/2413.Smallest Even Multiple/Solution.c @@ -1,3 +1,3 @@ int smallestEvenMultiple(int n) { return n % 2 == 0 ? n : n * 2; -} +} \ No newline at end of file diff --git a/solution/2400-2499/2414.Length of the Longest Alphabetical Continuous Substring/Solution.c b/solution/2400-2499/2414.Length of the Longest Alphabetical Continuous Substring/Solution.c index fd4c7a8a7ebde..3539ddbb3e57c 100644 --- a/solution/2400-2499/2414.Length of the Longest Alphabetical Continuous Substring/Solution.c +++ b/solution/2400-2499/2414.Length of the Longest Alphabetical Continuous Substring/Solution.c @@ -11,4 +11,4 @@ int longestContinuousSubstring(char* s) { } } return max(res, n - i); -} +} \ No newline at end of file diff --git a/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/Solution.cpp b/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/Solution.cpp index 1aba662067d62..04f1fdc0c3536 100644 --- a/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/Solution.cpp +++ b/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/Solution.cpp @@ -1,35 +1,35 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* reverseOddLevels(TreeNode* root) { - queue q{{root}}; - for (int i = 0; q.size(); ++i) { - vector t; - for (int k = q.size(); k; --k) { - TreeNode* node = q.front(); - q.pop(); - if (i & 1) { - t.push_back(node); - } - if (node->left) { - q.push(node->left); - q.push(node->right); - } - } - for (int l = 0, r = t.size() - 1; l < r; ++l, --r) { - swap(t[l]->val, t[r]->val); - } - } - return root; - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* reverseOddLevels(TreeNode* root) { + queue q{{root}}; + for (int i = 0; q.size(); ++i) { + vector t; + for (int k = q.size(); k; --k) { + TreeNode* node = q.front(); + q.pop(); + if (i & 1) { + t.push_back(node); + } + if (node->left) { + q.push(node->left); + q.push(node->right); + } + } + for (int l = 0, r = t.size() - 1; l < r; ++l, --r) { + swap(t[l]->val, t[r]->val); + } + } + return root; + } }; \ No newline at end of file diff --git a/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/Solution.java b/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/Solution.java index 3be6bc67f81b7..49a095d520cbb 100644 --- a/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/Solution.java +++ b/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/Solution.java @@ -1,40 +1,40 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public TreeNode reverseOddLevels(TreeNode root) { - Deque q = new ArrayDeque<>(); - q.offer(root); - for (int i = 0; !q.isEmpty(); ++i) { - List t = new ArrayList<>(); - for (int k = q.size(); k > 0; --k) { - var node = q.poll(); - if (i % 2 == 1) { - t.add(node); - } - if (node.left != null) { - q.offer(node.left); - q.offer(node.right); - } - } - for (int l = 0, r = t.size() - 1; l < r; ++l, --r) { - var x = t.get(l).val; - t.get(l).val = t.get(r).val; - t.get(r).val = x; - } - } - return root; - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode reverseOddLevels(TreeNode root) { + Deque q = new ArrayDeque<>(); + q.offer(root); + for (int i = 0; !q.isEmpty(); ++i) { + List t = new ArrayList<>(); + for (int k = q.size(); k > 0; --k) { + var node = q.poll(); + if (i % 2 == 1) { + t.add(node); + } + if (node.left != null) { + q.offer(node.left); + q.offer(node.right); + } + } + for (int l = 0, r = t.size() - 1; l < r; ++l, --r) { + var x = t.get(l).val; + t.get(l).val = t.get(r).val; + t.get(r).val = x; + } + } + return root; + } } \ No newline at end of file diff --git a/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/Solution.py b/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/Solution.py index de4660157f546..3e6a7567ec2b6 100644 --- a/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/Solution.py +++ b/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/Solution.py @@ -1,23 +1,23 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]: - q = deque([root]) - i = 0 - while q: - if i & 1: - l, r = 0, len(q) - 1 - while l < r: - q[l].val, q[r].val = q[r].val, q[l].val - l, r = l + 1, r - 1 - for _ in range(len(q)): - node = q.popleft() - if node.left: - q.append(node.left) - q.append(node.right) - i += 1 - return root +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + q = deque([root]) + i = 0 + while q: + if i & 1: + l, r = 0, len(q) - 1 + while l < r: + q[l].val, q[r].val = q[r].val, q[l].val + l, r = l + 1, r - 1 + for _ in range(len(q)): + node = q.popleft() + if node.left: + q.append(node.left) + q.append(node.right) + i += 1 + return root diff --git a/solution/2400-2499/2416.Sum of Prefix Scores of Strings/Solution.ts b/solution/2400-2499/2416.Sum of Prefix Scores of Strings/Solution.ts index fa8217675a44e..8dbbaf5a2ff83 100644 --- a/solution/2400-2499/2416.Sum of Prefix Scores of Strings/Solution.ts +++ b/solution/2400-2499/2416.Sum of Prefix Scores of Strings/Solution.ts @@ -1,47 +1,21 @@ -class Trie { - children: Array; - cnt: number; - - constructor() { - this.children = Array(26); - this.cnt = 0; - } +function sumPrefixScores(words: string[]): number[] { + const map = new Map(); - insert(w: string): void { - let node = this; - for (const c of w) { - const idx = c.charCodeAt(0) - 'a'.charCodeAt(0); - if (!node.children[idx]) { - node.children[idx] = new Trie(); - } - node = node.children[idx]; - node.cnt++; + for (const word of words) { + const n = word.length; + for (let i = 1; i <= n; i++) { + const s = word.slice(0, i); + map.set(s, (map.get(s) ?? 0) + 1); } } - search(w: string): number { - let node = this; - let ans = 0; - for (const c of w) { - const idx = c.charCodeAt(0) - 'a'.charCodeAt(0); - if (!node.children[idx]) { - return ans; - } - node = node.children[idx]; - ans += node.cnt; + return words.map(word => { + const n = word.length; + let count = 0; + for (let i = 1; i <= n; i++) { + const s = word.slice(0, i); + count += map.get(s); } - return ans; - } -} - -function sumPrefixScores(words: string[]): number[] { - const trie = new Trie(); - for (const w of words) { - trie.insert(w); - } - let ans = []; - for (const w of words) { - ans.push(trie.search(w)); - } - return ans; + return count; + }); } diff --git a/solution/2400-2499/2416.Sum of Prefix Scores of Strings/Solution2.ts b/solution/2400-2499/2416.Sum of Prefix Scores of Strings/Solution2.ts new file mode 100644 index 0000000000000..fa8217675a44e --- /dev/null +++ b/solution/2400-2499/2416.Sum of Prefix Scores of Strings/Solution2.ts @@ -0,0 +1,47 @@ +class Trie { + children: Array; + cnt: number; + + constructor() { + this.children = Array(26); + this.cnt = 0; + } + + insert(w: string): void { + let node = this; + for (const c of w) { + const idx = c.charCodeAt(0) - 'a'.charCodeAt(0); + if (!node.children[idx]) { + node.children[idx] = new Trie(); + } + node = node.children[idx]; + node.cnt++; + } + } + + search(w: string): number { + let node = this; + let ans = 0; + for (const c of w) { + const idx = c.charCodeAt(0) - 'a'.charCodeAt(0); + if (!node.children[idx]) { + return ans; + } + node = node.children[idx]; + ans += node.cnt; + } + return ans; + } +} + +function sumPrefixScores(words: string[]): number[] { + const trie = new Trie(); + for (const w of words) { + trie.insert(w); + } + let ans = []; + for (const w of words) { + ans.push(trie.search(w)); + } + return ans; +} diff --git a/solution/2400-2499/2418.Sort the People/Solution2.cpp b/solution/2400-2499/2418.Sort the People/Solution2.cpp new file mode 100644 index 0000000000000..762a55c479186 --- /dev/null +++ b/solution/2400-2499/2418.Sort the People/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector sortPeople(vector& names, vector& heights) { + int n = names.size(); + vector> arr; + for (int i = 0; i < n; ++i) { + arr.emplace_back(-heights[i], i); + } + sort(arr.begin(), arr.end()); + vector ans; + for (int i = 0; i < n; ++i) { + ans.emplace_back(names[arr[i].second]); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2418.Sort the People/Solution2.go b/solution/2400-2499/2418.Sort the People/Solution2.go new file mode 100644 index 0000000000000..30d9ff0857b08 --- /dev/null +++ b/solution/2400-2499/2418.Sort the People/Solution2.go @@ -0,0 +1,13 @@ +func sortPeople(names []string, heights []int) []string { + n := len(names) + arr := make([][2]int, n) + for i, h := range heights { + arr[i] = [2]int{h, i} + } + sort.Slice(arr, func(i, j int) bool { return arr[i][0] > arr[j][0] }) + ans := make([]string, n) + for i, x := range arr { + ans[i] = names[x[1]] + } + return ans +} \ No newline at end of file diff --git a/solution/2400-2499/2418.Sort the People/Solution2.java b/solution/2400-2499/2418.Sort the People/Solution2.java new file mode 100644 index 0000000000000..232b6f4c169a5 --- /dev/null +++ b/solution/2400-2499/2418.Sort the People/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public String[] sortPeople(String[] names, int[] heights) { + int n = names.length; + int[][] arr = new int[n][2]; + for (int i = 0; i < n; ++i) { + arr[i] = new int[] {heights[i], i}; + } + Arrays.sort(arr, (a, b) -> b[0] - a[0]); + String[] ans = new String[n]; + for (int i = 0; i < n; ++i) { + ans[i] = names[arr[i][1]]; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2400-2499/2418.Sort the People/Solution2.py b/solution/2400-2499/2418.Sort the People/Solution2.py new file mode 100644 index 0000000000000..1f83705b79187 --- /dev/null +++ b/solution/2400-2499/2418.Sort the People/Solution2.py @@ -0,0 +1,3 @@ +class Solution: + def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: + return [name for _, name in sorted(zip(heights, names), reverse=True)] diff --git a/solution/2400-2499/2418.Sort the People/Solution2.ts b/solution/2400-2499/2418.Sort the People/Solution2.ts new file mode 100644 index 0000000000000..f1a7bfa268212 --- /dev/null +++ b/solution/2400-2499/2418.Sort the People/Solution2.ts @@ -0,0 +1,6 @@ +function sortPeople(names: string[], heights: number[]): string[] { + return names + .map<[string, number]>((s, i) => [s, heights[i]]) + .sort((a, b) => b[1] - a[1]) + .map(([v]) => v); +} diff --git a/solution/2400-2499/2426.Number of Pairs Satisfying Inequality/Solution.py b/solution/2400-2499/2426.Number of Pairs Satisfying Inequality/Solution.py index af677d3588028..68cbe34954fa4 100644 --- a/solution/2400-2499/2426.Number of Pairs Satisfying Inequality/Solution.py +++ b/solution/2400-2499/2426.Number of Pairs Satisfying Inequality/Solution.py @@ -8,13 +8,11 @@ def lowbit(x): return x & -x def update(self, x, delta): - x += 40000 while x <= self.n: self.c[x] += delta x += BinaryIndexedTree.lowbit(x) def query(self, x): - x += 40000 s = 0 while x: s += self.c[x] @@ -28,6 +26,6 @@ def numberOfPairs(self, nums1: List[int], nums2: List[int], diff: int) -> int: ans = 0 for a, b in zip(nums1, nums2): v = a - b - ans += tree.query(v + diff) - tree.update(v, 1) + ans += tree.query(v + diff + 40000) + tree.update(v + 40000, 1) return ans diff --git a/solution/2400-2499/2427.Number of Common Factors/Solution.go b/solution/2400-2499/2427.Number of Common Factors/Solution.go index 0803454c57b71..099c75c937a4a 100644 --- a/solution/2400-2499/2427.Number of Common Factors/Solution.go +++ b/solution/2400-2499/2427.Number of Common Factors/Solution.go @@ -1,11 +1,8 @@ func commonFactors(a int, b int) (ans int) { g := gcd(a, b) - for x := 1; x*x <= g; x++ { + for x := 1; x <= g; x++ { if g%x == 0 { ans++ - if x*x < g { - ans++ - } } } return diff --git a/solution/2400-2499/2427.Number of Common Factors/Solution.java b/solution/2400-2499/2427.Number of Common Factors/Solution.java index c0adcfd041c37..3ad3aaa80c02b 100644 --- a/solution/2400-2499/2427.Number of Common Factors/Solution.java +++ b/solution/2400-2499/2427.Number of Common Factors/Solution.java @@ -2,12 +2,9 @@ class Solution { public int commonFactors(int a, int b) { int g = gcd(a, b); int ans = 0; - for (int x = 1; x * x <= g; ++x) { + for (int x = 1; x <= g; ++x) { if (g % x == 0) { ++ans; - if (x * x < g) { - ++ans; - } } } return ans; diff --git a/solution/2400-2499/2427.Number of Common Factors/Solution.py b/solution/2400-2499/2427.Number of Common Factors/Solution.py index 9398ffcff6b6c..c1f5e06716e56 100644 --- a/solution/2400-2499/2427.Number of Common Factors/Solution.py +++ b/solution/2400-2499/2427.Number of Common Factors/Solution.py @@ -1,10 +1,4 @@ class Solution: def commonFactors(self, a: int, b: int) -> int: g = gcd(a, b) - ans, x = 0, 1 - while x * x <= g: - if g % x == 0: - ans += 1 - ans += x * x < g - x += 1 - return ans + return sum(g % x == 0 for x in range(1, g + 1)) diff --git a/solution/2400-2499/2427.Number of Common Factors/Solution.ts b/solution/2400-2499/2427.Number of Common Factors/Solution.ts index ba416e12ad436..c10e2f4ea7a0a 100644 --- a/solution/2400-2499/2427.Number of Common Factors/Solution.ts +++ b/solution/2400-2499/2427.Number of Common Factors/Solution.ts @@ -1,12 +1,9 @@ function commonFactors(a: number, b: number): number { const g = gcd(a, b); let ans = 0; - for (let x = 1; x * x <= g; ++x) { + for (let x = 1; x <= g; ++x) { if (g % x === 0) { ++ans; - if (x * x < g) { - ++ans; - } } } return ans; diff --git a/solution/2400-2499/2427.Number of Common Factors/Solution2.cpp b/solution/2400-2499/2427.Number of Common Factors/Solution2.cpp new file mode 100644 index 0000000000000..4cf01a6cb29f5 --- /dev/null +++ b/solution/2400-2499/2427.Number of Common Factors/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int commonFactors(int a, int b) { + int g = gcd(a, b); + int ans = 0; + for (int x = 1; x * x <= g; ++x) { + if (g % x == 0) { + ans++; + ans += x * x < g; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2427.Number of Common Factors/Solution2.go b/solution/2400-2499/2427.Number of Common Factors/Solution2.go new file mode 100644 index 0000000000000..0803454c57b71 --- /dev/null +++ b/solution/2400-2499/2427.Number of Common Factors/Solution2.go @@ -0,0 +1,19 @@ +func commonFactors(a int, b int) (ans int) { + g := gcd(a, b) + for x := 1; x*x <= g; x++ { + if g%x == 0 { + ans++ + if x*x < g { + ans++ + } + } + } + return +} + +func gcd(a int, b int) int { + if b == 0 { + return a + } + return gcd(b, a%b) +} \ No newline at end of file diff --git a/solution/2400-2499/2427.Number of Common Factors/Solution2.java b/solution/2400-2499/2427.Number of Common Factors/Solution2.java new file mode 100644 index 0000000000000..c0adcfd041c37 --- /dev/null +++ b/solution/2400-2499/2427.Number of Common Factors/Solution2.java @@ -0,0 +1,19 @@ +class Solution { + public int commonFactors(int a, int b) { + int g = gcd(a, b); + int ans = 0; + for (int x = 1; x * x <= g; ++x) { + if (g % x == 0) { + ++ans; + if (x * x < g) { + ++ans; + } + } + } + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} \ No newline at end of file diff --git a/solution/2400-2499/2427.Number of Common Factors/Solution2.py b/solution/2400-2499/2427.Number of Common Factors/Solution2.py new file mode 100644 index 0000000000000..9398ffcff6b6c --- /dev/null +++ b/solution/2400-2499/2427.Number of Common Factors/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def commonFactors(self, a: int, b: int) -> int: + g = gcd(a, b) + ans, x = 0, 1 + while x * x <= g: + if g % x == 0: + ans += 1 + ans += x * x < g + x += 1 + return ans diff --git a/solution/2400-2499/2427.Number of Common Factors/Solution2.ts b/solution/2400-2499/2427.Number of Common Factors/Solution2.ts new file mode 100644 index 0000000000000..ba416e12ad436 --- /dev/null +++ b/solution/2400-2499/2427.Number of Common Factors/Solution2.ts @@ -0,0 +1,17 @@ +function commonFactors(a: number, b: number): number { + const g = gcd(a, b); + let ans = 0; + for (let x = 1; x * x <= g; ++x) { + if (g % x === 0) { + ++ans; + if (x * x < g) { + ++ans; + } + } + } + return ans; +} + +function gcd(a: number, b: number): number { + return b === 0 ? a : gcd(b, a % b); +} diff --git a/solution/2400-2499/2429.Minimize XOR/Solution.cpp b/solution/2400-2499/2429.Minimize XOR/Solution.cpp index d0e507aa2b528..32aeca3e929ce 100644 --- a/solution/2400-2499/2429.Minimize XOR/Solution.cpp +++ b/solution/2400-2499/2429.Minimize XOR/Solution.cpp @@ -1,14 +1,20 @@ class Solution { public: int minimizeXor(int num1, int num2) { - int cnt1 = __builtin_popcount(num1); - int cnt2 = __builtin_popcount(num2); - for (; cnt1 > cnt2; --cnt1) { - num1 &= (num1 - 1); + int cnt = __builtin_popcount(num2); + int x = 0; + for (int i = 30; ~i && cnt; --i) { + if (num1 >> i & 1) { + x |= 1 << i; + --cnt; + } } - for (; cnt1 < cnt2; ++cnt1) { - num1 |= (num1 + 1); + for (int i = 0; cnt; ++i) { + if (num1 >> i & 1 ^ 1) { + x |= 1 << i; + --cnt; + } } - return num1; + return x; } }; \ No newline at end of file diff --git a/solution/2400-2499/2429.Minimize XOR/Solution.go b/solution/2400-2499/2429.Minimize XOR/Solution.go index 94eb188121ea3..5c7194620cfeb 100644 --- a/solution/2400-2499/2429.Minimize XOR/Solution.go +++ b/solution/2400-2499/2429.Minimize XOR/Solution.go @@ -1,11 +1,17 @@ func minimizeXor(num1 int, num2 int) int { - cnt1 := bits.OnesCount(uint(num1)) - cnt2 := bits.OnesCount(uint(num2)) - for ; cnt1 > cnt2; cnt1-- { - num1 &= (num1 - 1) + cnt := bits.OnesCount(uint(num2)) + x := 0 + for i := 30; i >= 0 && cnt > 0; i-- { + if num1>>i&1 == 1 { + x |= 1 << i + cnt-- + } } - for ; cnt1 < cnt2; cnt1++ { - num1 |= (num1 + 1) + for i := 0; cnt > 0; i++ { + if num1>>i&1 == 0 { + x |= 1 << i + cnt-- + } } - return num1 + return x } \ No newline at end of file diff --git a/solution/2400-2499/2429.Minimize XOR/Solution.java b/solution/2400-2499/2429.Minimize XOR/Solution.java index 7e5636a6eaf87..d3f02a314cf3d 100644 --- a/solution/2400-2499/2429.Minimize XOR/Solution.java +++ b/solution/2400-2499/2429.Minimize XOR/Solution.java @@ -1,13 +1,19 @@ class Solution { public int minimizeXor(int num1, int num2) { - int cnt1 = Integer.bitCount(num1); - int cnt2 = Integer.bitCount(num2); - for (; cnt1 > cnt2; --cnt1) { - num1 &= (num1 - 1); + int cnt = Integer.bitCount(num2); + int x = 0; + for (int i = 30; i >= 0 && cnt > 0; --i) { + if ((num1 >> i & 1) == 1) { + x |= 1 << i; + --cnt; + } } - for (; cnt1 < cnt2; ++cnt1) { - num1 |= (num1 + 1); + for (int i = 0; cnt > 0; ++i) { + if ((num1 >> i & 1) == 0) { + x |= 1 << i; + --cnt; + } } - return num1; + return x; } } \ No newline at end of file diff --git a/solution/2400-2499/2429.Minimize XOR/Solution.py b/solution/2400-2499/2429.Minimize XOR/Solution.py index bd07409846075..3f68aa57149bf 100644 --- a/solution/2400-2499/2429.Minimize XOR/Solution.py +++ b/solution/2400-2499/2429.Minimize XOR/Solution.py @@ -1,11 +1,13 @@ class Solution: def minimizeXor(self, num1: int, num2: int) -> int: - cnt1 = num1.bit_count() - cnt2 = num2.bit_count() - while cnt1 > cnt2: - num1 &= num1 - 1 - cnt1 -= 1 - while cnt1 < cnt2: - num1 |= num1 + 1 - cnt1 += 1 - return num1 + cnt = num2.bit_count() + x = 0 + for i in range(30, -1, -1): + if num1 >> i & 1 and cnt: + x |= 1 << i + cnt -= 1 + for i in range(30): + if num1 >> i & 1 ^ 1 and cnt: + x |= 1 << i + cnt -= 1 + return x diff --git a/solution/2400-2499/2429.Minimize XOR/Solution.ts b/solution/2400-2499/2429.Minimize XOR/Solution.ts index 64d948aa6871b..7b06416d00b64 100644 --- a/solution/2400-2499/2429.Minimize XOR/Solution.ts +++ b/solution/2400-2499/2429.Minimize XOR/Solution.ts @@ -1,20 +1,21 @@ function minimizeXor(num1: number, num2: number): number { - let cnt1 = bitCount(num1); - let cnt2 = bitCount(num2); - for (; cnt1 > cnt2; --cnt1) { - num1 &= num1 - 1; + let cnt = 0; + while (num2) { + num2 &= num2 - 1; + ++cnt; } - for (; cnt1 < cnt2; ++cnt1) { - num1 |= num1 + 1; + let x = 0; + for (let i = 30; i >= 0 && cnt > 0; --i) { + if ((num1 >> i) & 1) { + x |= 1 << i; + --cnt; + } } - return num1; -} - -function bitCount(i: number): number { - i = i - ((i >>> 1) & 0x55555555); - i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); - i = (i + (i >>> 4)) & 0x0f0f0f0f; - i = i + (i >>> 8); - i = i + (i >>> 16); - return i & 0x3f; + for (let i = 0; cnt > 0; ++i) { + if (!((num1 >> i) & 1)) { + x |= 1 << i; + --cnt; + } + } + return x; } diff --git a/solution/2400-2499/2429.Minimize XOR/Solution2.cpp b/solution/2400-2499/2429.Minimize XOR/Solution2.cpp new file mode 100644 index 0000000000000..d0e507aa2b528 --- /dev/null +++ b/solution/2400-2499/2429.Minimize XOR/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int minimizeXor(int num1, int num2) { + int cnt1 = __builtin_popcount(num1); + int cnt2 = __builtin_popcount(num2); + for (; cnt1 > cnt2; --cnt1) { + num1 &= (num1 - 1); + } + for (; cnt1 < cnt2; ++cnt1) { + num1 |= (num1 + 1); + } + return num1; + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2429.Minimize XOR/Solution2.go b/solution/2400-2499/2429.Minimize XOR/Solution2.go new file mode 100644 index 0000000000000..94eb188121ea3 --- /dev/null +++ b/solution/2400-2499/2429.Minimize XOR/Solution2.go @@ -0,0 +1,11 @@ +func minimizeXor(num1 int, num2 int) int { + cnt1 := bits.OnesCount(uint(num1)) + cnt2 := bits.OnesCount(uint(num2)) + for ; cnt1 > cnt2; cnt1-- { + num1 &= (num1 - 1) + } + for ; cnt1 < cnt2; cnt1++ { + num1 |= (num1 + 1) + } + return num1 +} \ No newline at end of file diff --git a/solution/2400-2499/2429.Minimize XOR/Solution2.java b/solution/2400-2499/2429.Minimize XOR/Solution2.java new file mode 100644 index 0000000000000..7e5636a6eaf87 --- /dev/null +++ b/solution/2400-2499/2429.Minimize XOR/Solution2.java @@ -0,0 +1,13 @@ +class Solution { + public int minimizeXor(int num1, int num2) { + int cnt1 = Integer.bitCount(num1); + int cnt2 = Integer.bitCount(num2); + for (; cnt1 > cnt2; --cnt1) { + num1 &= (num1 - 1); + } + for (; cnt1 < cnt2; ++cnt1) { + num1 |= (num1 + 1); + } + return num1; + } +} \ No newline at end of file diff --git a/solution/2400-2499/2429.Minimize XOR/Solution2.py b/solution/2400-2499/2429.Minimize XOR/Solution2.py new file mode 100644 index 0000000000000..bd07409846075 --- /dev/null +++ b/solution/2400-2499/2429.Minimize XOR/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def minimizeXor(self, num1: int, num2: int) -> int: + cnt1 = num1.bit_count() + cnt2 = num2.bit_count() + while cnt1 > cnt2: + num1 &= num1 - 1 + cnt1 -= 1 + while cnt1 < cnt2: + num1 |= num1 + 1 + cnt1 += 1 + return num1 diff --git a/solution/2400-2499/2429.Minimize XOR/Solution2.ts b/solution/2400-2499/2429.Minimize XOR/Solution2.ts new file mode 100644 index 0000000000000..64d948aa6871b --- /dev/null +++ b/solution/2400-2499/2429.Minimize XOR/Solution2.ts @@ -0,0 +1,20 @@ +function minimizeXor(num1: number, num2: number): number { + let cnt1 = bitCount(num1); + let cnt2 = bitCount(num2); + for (; cnt1 > cnt2; --cnt1) { + num1 &= num1 - 1; + } + for (; cnt1 < cnt2; ++cnt1) { + num1 |= num1 + 1; + } + return num1; +} + +function bitCount(i: number): number { + i = i - ((i >>> 1) & 0x55555555); + i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); + i = (i + (i >>> 4)) & 0x0f0f0f0f; + i = i + (i >>> 8); + i = i + (i >>> 16); + return i & 0x3f; +} diff --git a/solution/2400-2499/2430.Maximum Deletions on a String/Solution.cpp b/solution/2400-2499/2430.Maximum Deletions on a String/Solution.cpp index f54c62bdcd8d3..7036bb6bbbedf 100644 --- a/solution/2400-2499/2430.Maximum Deletions on a String/Solution.cpp +++ b/solution/2400-2499/2430.Maximum Deletions on a String/Solution.cpp @@ -12,14 +12,22 @@ class Solution { } } int f[n]; - for (int i = n - 1; ~i; --i) { + memset(f, 0, sizeof(f)); + function dfs = [&](int i) -> int { + if (i == n) { + return 0; + } + if (f[i]) { + return f[i]; + } f[i] = 1; for (int j = 1; j <= (n - i) / 2; ++j) { if (g[i][i + j] >= j) { - f[i] = max(f[i], f[i + j] + 1); + f[i] = max(f[i], 1 + dfs(i + j)); } } - } - return f[0]; + return f[i]; + }; + return dfs(0); } }; \ No newline at end of file diff --git a/solution/2400-2499/2430.Maximum Deletions on a String/Solution.go b/solution/2400-2499/2430.Maximum Deletions on a String/Solution.go index 254859224e278..9264630fedab9 100644 --- a/solution/2400-2499/2430.Maximum Deletions on a String/Solution.go +++ b/solution/2400-2499/2430.Maximum Deletions on a String/Solution.go @@ -12,13 +12,21 @@ func deleteString(s string) int { } } f := make([]int, n) - for i := n - 1; i >= 0; i-- { + var dfs func(int) int + dfs = func(i int) int { + if i == n { + return 0 + } + if f[i] > 0 { + return f[i] + } f[i] = 1 for j := 1; j <= (n-i)/2; j++ { if g[i][i+j] >= j { - f[i] = max(f[i], f[i+j]+1) + f[i] = max(f[i], dfs(i+j)+1) } } + return f[i] } - return f[0] + return dfs(0) } \ No newline at end of file diff --git a/solution/2400-2499/2430.Maximum Deletions on a String/Solution.java b/solution/2400-2499/2430.Maximum Deletions on a String/Solution.java index de472713882ae..4c439accf5d58 100644 --- a/solution/2400-2499/2430.Maximum Deletions on a String/Solution.java +++ b/solution/2400-2499/2430.Maximum Deletions on a String/Solution.java @@ -1,7 +1,12 @@ class Solution { + private int n; + private Integer[] f; + private int[][] g; + public int deleteString(String s) { - int n = s.length(); - int[][] g = new int[n + 1][n + 1]; + n = s.length(); + f = new Integer[n]; + g = new int[n + 1][n + 1]; for (int i = n - 1; i >= 0; --i) { for (int j = i + 1; j < n; ++j) { if (s.charAt(i) == s.charAt(j)) { @@ -9,15 +14,22 @@ public int deleteString(String s) { } } } - int[] f = new int[n]; - for (int i = n - 1; i >= 0; --i) { - f[i] = 1; - for (int j = 1; j <= (n - i) / 2; ++j) { - if (g[i][i + j] >= j) { - f[i] = Math.max(f[i], f[i + j] + 1); - } + return dfs(0); + } + + private int dfs(int i) { + if (i == n) { + return 0; + } + if (f[i] != null) { + return f[i]; + } + f[i] = 1; + for (int j = 1; j <= (n - i) / 2; ++j) { + if (g[i][i + j] >= j) { + f[i] = Math.max(f[i], 1 + dfs(i + j)); } } - return f[0]; + return f[i]; } } \ No newline at end of file diff --git a/solution/2400-2499/2430.Maximum Deletions on a String/Solution.ts b/solution/2400-2499/2430.Maximum Deletions on a String/Solution.ts index 96dd088381142..e509ce8cc293b 100644 --- a/solution/2400-2499/2430.Maximum Deletions on a String/Solution.ts +++ b/solution/2400-2499/2430.Maximum Deletions on a String/Solution.ts @@ -1,12 +1,20 @@ function deleteString(s: string): number { const n = s.length; - const f: number[] = new Array(n).fill(1); - for (let i = n - 1; i >= 0; --i) { + const f: number[] = new Array(n).fill(0); + const dfs = (i: number): number => { + if (i == n) { + return 0; + } + if (f[i] > 0) { + return f[i]; + } + f[i] = 1; for (let j = 1; j <= (n - i) >> 1; ++j) { - if (s.slice(i, i + j) === s.slice(i + j, i + j + j)) { - f[i] = Math.max(f[i], f[i + j] + 1); + if (s.slice(i, i + j) == s.slice(i + j, i + j + j)) { + f[i] = Math.max(f[i], dfs(i + j) + 1); } } - } - return f[0]; + return f[i]; + }; + return dfs(0); } diff --git a/solution/2400-2499/2430.Maximum Deletions on a String/Solution2.cpp b/solution/2400-2499/2430.Maximum Deletions on a String/Solution2.cpp new file mode 100644 index 0000000000000..f54c62bdcd8d3 --- /dev/null +++ b/solution/2400-2499/2430.Maximum Deletions on a String/Solution2.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int deleteString(string s) { + int n = s.size(); + int g[n + 1][n + 1]; + memset(g, 0, sizeof(g)); + for (int i = n - 1; ~i; --i) { + for (int j = i + 1; j < n; ++j) { + if (s[i] == s[j]) { + g[i][j] = g[i + 1][j + 1] + 1; + } + } + } + int f[n]; + for (int i = n - 1; ~i; --i) { + f[i] = 1; + for (int j = 1; j <= (n - i) / 2; ++j) { + if (g[i][i + j] >= j) { + f[i] = max(f[i], f[i + j] + 1); + } + } + } + return f[0]; + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2430.Maximum Deletions on a String/Solution2.go b/solution/2400-2499/2430.Maximum Deletions on a String/Solution2.go new file mode 100644 index 0000000000000..254859224e278 --- /dev/null +++ b/solution/2400-2499/2430.Maximum Deletions on a String/Solution2.go @@ -0,0 +1,24 @@ +func deleteString(s string) int { + n := len(s) + g := make([][]int, n+1) + for i := range g { + g[i] = make([]int, n+1) + } + for i := n - 1; i >= 0; i-- { + for j := i + 1; j < n; j++ { + if s[i] == s[j] { + g[i][j] = g[i+1][j+1] + 1 + } + } + } + f := make([]int, n) + for i := n - 1; i >= 0; i-- { + f[i] = 1 + for j := 1; j <= (n-i)/2; j++ { + if g[i][i+j] >= j { + f[i] = max(f[i], f[i+j]+1) + } + } + } + return f[0] +} \ No newline at end of file diff --git a/solution/2400-2499/2430.Maximum Deletions on a String/Solution2.java b/solution/2400-2499/2430.Maximum Deletions on a String/Solution2.java new file mode 100644 index 0000000000000..de472713882ae --- /dev/null +++ b/solution/2400-2499/2430.Maximum Deletions on a String/Solution2.java @@ -0,0 +1,23 @@ +class Solution { + public int deleteString(String s) { + int n = s.length(); + int[][] g = new int[n + 1][n + 1]; + for (int i = n - 1; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + if (s.charAt(i) == s.charAt(j)) { + g[i][j] = g[i + 1][j + 1] + 1; + } + } + } + int[] f = new int[n]; + for (int i = n - 1; i >= 0; --i) { + f[i] = 1; + for (int j = 1; j <= (n - i) / 2; ++j) { + if (g[i][i + j] >= j) { + f[i] = Math.max(f[i], f[i + j] + 1); + } + } + } + return f[0]; + } +} \ No newline at end of file diff --git a/solution/2400-2499/2430.Maximum Deletions on a String/Solution2.py b/solution/2400-2499/2430.Maximum Deletions on a String/Solution2.py new file mode 100644 index 0000000000000..5ddc1102d6d58 --- /dev/null +++ b/solution/2400-2499/2430.Maximum Deletions on a String/Solution2.py @@ -0,0 +1,15 @@ +class Solution: + def deleteString(self, s: str) -> int: + n = len(s) + g = [[0] * (n + 1) for _ in range(n + 1)] + for i in range(n - 1, -1, -1): + for j in range(i + 1, n): + if s[i] == s[j]: + g[i][j] = g[i + 1][j + 1] + 1 + + f = [1] * n + for i in range(n - 1, -1, -1): + for j in range(1, (n - i) // 2 + 1): + if g[i][i + j] >= j: + f[i] = max(f[i], f[i + j] + 1) + return f[0] diff --git a/solution/2400-2499/2430.Maximum Deletions on a String/Solution2.ts b/solution/2400-2499/2430.Maximum Deletions on a String/Solution2.ts new file mode 100644 index 0000000000000..96dd088381142 --- /dev/null +++ b/solution/2400-2499/2430.Maximum Deletions on a String/Solution2.ts @@ -0,0 +1,12 @@ +function deleteString(s: string): number { + const n = s.length; + const f: number[] = new Array(n).fill(1); + for (let i = n - 1; i >= 0; --i) { + for (let j = 1; j <= (n - i) >> 1; ++j) { + if (s.slice(i, i + j) === s.slice(i + j, i + j + j)) { + f[i] = Math.max(f[i], f[i + j] + 1); + } + } + } + return f[0]; +} diff --git a/solution/2400-2499/2432.The Employee That Worked on the Longest Task/Solution.c b/solution/2400-2499/2432.The Employee That Worked on the Longest Task/Solution.c index 84688bd244287..a75fdd9a99d04 100644 --- a/solution/2400-2499/2432.The Employee That Worked on the Longest Task/Solution.c +++ b/solution/2400-2499/2432.The Employee That Worked on the Longest Task/Solution.c @@ -13,4 +13,4 @@ int hardestWorker(int n, int** logs, int logsSize, int* logsColSize) { pre = logs[i][1]; } return res; -} +} \ No newline at end of file diff --git a/solution/2400-2499/2432.The Employee That Worked on the Longest Task/Solution2.rs b/solution/2400-2499/2432.The Employee That Worked on the Longest Task/Solution2.rs new file mode 100644 index 0000000000000..9accc154eaaee --- /dev/null +++ b/solution/2400-2499/2432.The Employee That Worked on the Longest Task/Solution2.rs @@ -0,0 +1,22 @@ +impl Solution { + pub fn hardest_worker(n: i32, logs: Vec>) -> i32 { + let mut ans = 0; + let mut mx = 0; + let mut last = 0; + + for log in logs { + let uid = log[0]; + let t = log[1]; + + let diff = t - last; + last = t; + + if diff > mx || (diff == mx && uid < ans) { + ans = uid; + mx = diff; + } + } + + ans + } +} diff --git a/solution/2400-2499/2433.Find The Original Array of Prefix Xor/Solution.c b/solution/2400-2499/2433.Find The Original Array of Prefix Xor/Solution.c index 0cab4ee16268c..67970a807675e 100644 --- a/solution/2400-2499/2433.Find The Original Array of Prefix Xor/Solution.c +++ b/solution/2400-2499/2433.Find The Original Array of Prefix Xor/Solution.c @@ -9,4 +9,4 @@ int* findArray(int* pref, int prefSize, int* returnSize) { } *returnSize = prefSize; return res; -} +} \ No newline at end of file diff --git a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution2.cpp b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution2.cpp new file mode 100644 index 0000000000000..52342943adfa6 --- /dev/null +++ b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution2.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + string robotWithString(string s) { + int n = s.size(); + vector right(n, n - 1); + for (int i = n - 2; i >= 0; --i) { + right[i] = s[i] < s[right[i + 1]] ? i : right[i + 1]; + } + string ans; + string stk; + for (int i = 0; i < n; ++i) { + stk += s[i]; + while (!stk.empty() && (stk.back() <= (i > n - 2 ? 'z' + 1 : s[right[i + 1]]))) { + ans += stk.back(); + stk.pop_back(); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution2.java b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution2.java new file mode 100644 index 0000000000000..fb44e686de474 --- /dev/null +++ b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution2.java @@ -0,0 +1,20 @@ +class Solution { + public String robotWithString(String s) { + int n = s.length(); + int[] right = new int[n]; + right[n - 1] = n - 1; + for (int i = n - 2; i >= 0; --i) { + right[i] = s.charAt(i) < s.charAt(right[i + 1]) ? i : right[i + 1]; + } + StringBuilder ans = new StringBuilder(); + Deque stk = new ArrayDeque<>(); + for (int i = 0; i < n; ++i) { + stk.push(s.charAt(i)); + while ( + !stk.isEmpty() && (stk.peek() <= (i > n - 2 ? 'z' + 1 : s.charAt(right[i + 1])))) { + ans.append(stk.pop()); + } + } + return ans.toString(); + } +} \ No newline at end of file diff --git a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution2.py b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution2.py new file mode 100644 index 0000000000000..2765d7590b32f --- /dev/null +++ b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def robotWithString(self, s: str) -> str: + n = len(s) + right = [chr(ord('z') + 1)] * (n + 1) + for i in range(n - 1, -1, -1): + right[i] = min(s[i], right[i + 1]) + ans = [] + stk = [] + for i, c in enumerate(s): + stk.append(c) + while stk and stk[-1] <= right[i + 1]: + ans.append(stk.pop()) + return ''.join(ans) diff --git a/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution.java b/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution.java index 34e67bba122c2..2493a1990a396 100644 --- a/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution.java +++ b/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution.java @@ -1,24 +1,39 @@ class Solution { + private int m; + private int n; + private int k; private static final int MOD = (int) 1e9 + 7; + private int[][] grid; + private int[][][] f; public int numberOfPaths(int[][] grid, int k) { - int m = grid.length, n = grid[0].length; - int[][][] dp = new int[m][n][k]; - dp[0][0][grid[0][0] % k] = 1; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - for (int s = 0; s < k; ++s) { - int t = ((s - grid[i][j] % k) + k) % k; - if (i > 0) { - dp[i][j][s] += dp[i - 1][j][t]; - } - if (j > 0) { - dp[i][j][s] += dp[i][j - 1][t]; - } - dp[i][j][s] %= MOD; - } + this.grid = grid; + this.k = k; + m = grid.length; + n = grid[0].length; + f = new int[m][n][k]; + for (var a : f) { + for (var b : a) { + Arrays.fill(b, -1); } } - return dp[m - 1][n - 1][0]; + return dfs(0, 0, 0); } -} + + private int dfs(int i, int j, int s) { + if (i < 0 || i >= m || j < 0 || j >= n) { + return 0; + } + s = (s + grid[i][j]) % k; + if (f[i][j][s] != -1) { + return f[i][j][s]; + } + if (i == m - 1 && j == n - 1) { + return s == 0 ? 1 : 0; + } + int ans = dfs(i + 1, j, s) + dfs(i, j + 1, s); + ans %= MOD; + f[i][j][s] = ans; + return ans; + } +} \ No newline at end of file diff --git a/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution.py b/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution.py index 9efd47563808a..6233faa28ca8e 100644 --- a/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution.py +++ b/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution.py @@ -1,16 +1,17 @@ class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: + @cache + def dfs(i, j, s): + if i < 0 or i >= m or j < 0 or j >= n: + return 0 + s = (s + grid[i][j]) % k + if i == m - 1 and j == n - 1: + return int(s == 0) + ans = dfs(i + 1, j, s) + dfs(i, j + 1, s) + return ans % mod + m, n = len(grid), len(grid[0]) - dp = [[[0] * k for _ in range(n)] for _ in range(m)] - dp[0][0][grid[0][0] % k] = 1 mod = 10**9 + 7 - for i in range(m): - for j in range(n): - for s in range(k): - t = ((s - grid[i][j] % k) + k) % k - if i: - dp[i][j][s] += dp[i - 1][j][t] - if j: - dp[i][j][s] += dp[i][j - 1][t] - dp[i][j][s] %= mod - return dp[-1][-1][0] + ans = dfs(0, 0, 0) + dfs.cache_clear() + return ans diff --git a/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution2.cpp b/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution2.cpp new file mode 100644 index 0000000000000..0dbc288bb2028 --- /dev/null +++ b/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution2.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + const int mod = 1e9 + 7; + + int numberOfPaths(vector>& grid, int k) { + int m = grid.size(), n = grid[0].size(); + vector>> dp(m, vector>(n, vector(k))); + dp[0][0][grid[0][0] % k] = 1; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int s = 0; s < k; ++s) { + int t = ((s - grid[i][j] % k) + k) % k; + if (i) dp[i][j][s] += dp[i - 1][j][t]; + if (j) dp[i][j][s] += dp[i][j - 1][t]; + dp[i][j][s] %= mod; + } + } + } + return dp[m - 1][n - 1][0]; + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution2.go b/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution2.go new file mode 100644 index 0000000000000..bce9d55db7107 --- /dev/null +++ b/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution2.go @@ -0,0 +1,27 @@ +func numberOfPaths(grid [][]int, k int) int { + m, n := len(grid), len(grid[0]) + var mod int = 1e9 + 7 + dp := make([][][]int, m) + for i := range dp { + dp[i] = make([][]int, n) + for j := range dp[i] { + dp[i][j] = make([]int, k) + } + } + dp[0][0][grid[0][0]%k] = 1 + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + for s := 0; s < k; s++ { + t := ((s - grid[i][j]%k) + k) % k + if i > 0 { + dp[i][j][s] += dp[i-1][j][t] + } + if j > 0 { + dp[i][j][s] += dp[i][j-1][t] + } + dp[i][j][s] %= mod + } + } + } + return dp[m-1][n-1][0] +} \ No newline at end of file diff --git a/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution2.java b/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution2.java new file mode 100644 index 0000000000000..a914f76e5cb4e --- /dev/null +++ b/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution2.java @@ -0,0 +1,24 @@ +class Solution { + private static final int MOD = (int) 1e9 + 7; + + public int numberOfPaths(int[][] grid, int k) { + int m = grid.length, n = grid[0].length; + int[][][] dp = new int[m][n][k]; + dp[0][0][grid[0][0] % k] = 1; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int s = 0; s < k; ++s) { + int t = ((s - grid[i][j] % k) + k) % k; + if (i > 0) { + dp[i][j][s] += dp[i - 1][j][t]; + } + if (j > 0) { + dp[i][j][s] += dp[i][j - 1][t]; + } + dp[i][j][s] %= MOD; + } + } + } + return dp[m - 1][n - 1][0]; + } +} \ No newline at end of file diff --git a/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution2.py b/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution2.py new file mode 100644 index 0000000000000..9efd47563808a --- /dev/null +++ b/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/Solution2.py @@ -0,0 +1,16 @@ +class Solution: + def numberOfPaths(self, grid: List[List[int]], k: int) -> int: + m, n = len(grid), len(grid[0]) + dp = [[[0] * k for _ in range(n)] for _ in range(m)] + dp[0][0][grid[0][0] % k] = 1 + mod = 10**9 + 7 + for i in range(m): + for j in range(n): + for s in range(k): + t = ((s - grid[i][j] % k) + k) % k + if i: + dp[i][j][s] += dp[i - 1][j][t] + if j: + dp[i][j][s] += dp[i][j - 1][t] + dp[i][j][s] %= mod + return dp[-1][-1][0] diff --git a/solution/2400-2499/2437.Number of Valid Clock Times/Solution.cpp b/solution/2400-2499/2437.Number of Valid Clock Times/Solution.cpp index 7a5e96733fa51..1d182625558b8 100644 --- a/solution/2400-2499/2437.Number of Valid Clock Times/Solution.cpp +++ b/solution/2400-2499/2437.Number of Valid Clock Times/Solution.cpp @@ -1,15 +1,21 @@ class Solution { public: int countTime(string time) { - auto f = [](string s, int m) { - int cnt = 0; - for (int i = 0; i < m; ++i) { - bool a = s[0] == '?' || s[0] - '0' == i / 10; - bool b = s[1] == '?' || s[1] - '0' == i % 10; - cnt += a && b; + int ans = 0; + for (int h = 0; h < 24; ++h) { + for (int m = 0; m < 60; ++m) { + char s[20]; + sprintf(s, "%02d:%02d", h, m); + int ok = 1; + for (int i = 0; i < 5; ++i) { + if (s[i] != time[i] && time[i] != '?') { + ok = 0; + break; + } + } + ans += ok; } - return cnt; - }; - return f(time.substr(0, 2), 24) * f(time.substr(3, 2), 60); + } + return ans; } }; \ No newline at end of file diff --git a/solution/2400-2499/2437.Number of Valid Clock Times/Solution.go b/solution/2400-2499/2437.Number of Valid Clock Times/Solution.go index 829de4d068611..437b682691410 100644 --- a/solution/2400-2499/2437.Number of Valid Clock Times/Solution.go +++ b/solution/2400-2499/2437.Number of Valid Clock Times/Solution.go @@ -1,13 +1,17 @@ func countTime(time string) int { - f := func(s string, m int) (cnt int) { - for i := 0; i < m; i++ { - a := s[0] == '?' || int(s[0]-'0') == i/10 - b := s[1] == '?' || int(s[1]-'0') == i%10 - if a && b { - cnt++ + ans := 0 + for h := 0; h < 24; h++ { + for m := 0; m < 60; m++ { + s := fmt.Sprintf("%02d:%02d", h, m) + ok := 1 + for i := 0; i < 5; i++ { + if s[i] != time[i] && time[i] != '?' { + ok = 0 + break + } } + ans += ok } - return } - return f(time[:2], 24) * f(time[3:], 60) + return ans } \ No newline at end of file diff --git a/solution/2400-2499/2437.Number of Valid Clock Times/Solution.java b/solution/2400-2499/2437.Number of Valid Clock Times/Solution.java index f495ab66ffdd1..08a836030426d 100644 --- a/solution/2400-2499/2437.Number of Valid Clock Times/Solution.java +++ b/solution/2400-2499/2437.Number of Valid Clock Times/Solution.java @@ -1,15 +1,19 @@ class Solution { public int countTime(String time) { - return f(time.substring(0, 2), 24) * f(time.substring(3), 60); - } - - private int f(String s, int m) { - int cnt = 0; - for (int i = 0; i < m; ++i) { - boolean a = s.charAt(0) == '?' || s.charAt(0) - '0' == i / 10; - boolean b = s.charAt(1) == '?' || s.charAt(1) - '0' == i % 10; - cnt += a && b ? 1 : 0; + int ans = 0; + for (int h = 0; h < 24; ++h) { + for (int m = 0; m < 60; ++m) { + String s = String.format("%02d:%02d", h, m); + int ok = 1; + for (int i = 0; i < 5; ++i) { + if (s.charAt(i) != time.charAt(i) && time.charAt(i) != '?') { + ok = 0; + break; + } + } + ans += ok; + } } - return cnt; + return ans; } } \ No newline at end of file diff --git a/solution/2400-2499/2437.Number of Valid Clock Times/Solution.py b/solution/2400-2499/2437.Number of Valid Clock Times/Solution.py index 60856eb2cfbbb..508fab65fce58 100644 --- a/solution/2400-2499/2437.Number of Valid Clock Times/Solution.py +++ b/solution/2400-2499/2437.Number of Valid Clock Times/Solution.py @@ -1,11 +1,8 @@ class Solution: def countTime(self, time: str) -> int: - def f(s: str, m: int) -> int: - cnt = 0 - for i in range(m): - a = s[0] == "?" or (int(s[0]) == i // 10) - b = s[1] == "?" or (int(s[1]) == i % 10) - cnt += a and b - return cnt + def check(s: str, t: str) -> bool: + return all(a == b or b == '?' for a, b in zip(s, t)) - return f(time[:2], 24) * f(time[3:], 60) + return sum( + check(f'{h:02d}:{m:02d}', time) for h in range(24) for m in range(60) + ) diff --git a/solution/2400-2499/2437.Number of Valid Clock Times/Solution.rs b/solution/2400-2499/2437.Number of Valid Clock Times/Solution.rs index 6e5b779edc37c..0a4df5276df25 100644 --- a/solution/2400-2499/2437.Number of Valid Clock Times/Solution.rs +++ b/solution/2400-2499/2437.Number of Valid Clock Times/Solution.rs @@ -1,23 +1,24 @@ impl Solution { pub fn count_time(time: String) -> i32 { - let f = |s: &str, m: usize| -> i32 { - let mut cnt = 0; - let first = s.chars().nth(0).unwrap(); - let second = s.chars().nth(1).unwrap(); + let mut ans = 0; - for i in 0..m { - let a = first == '?' || (first.to_digit(10).unwrap() as usize) == i / 10; + for i in 0..24 { + for j in 0..60 { + let mut ok = true; + let t = format!("{:02}:{:02}", i, j); - let b = second == '?' || (second.to_digit(10).unwrap() as usize) == i % 10; + for (k, ch) in time.chars().enumerate() { + if ch != '?' && ch != t.chars().nth(k).unwrap() { + ok = false; + } + } - if a && b { - cnt += 1; + if ok { + ans += 1; } } + } - cnt - }; - - f(&time[..2], 24) * f(&time[3..], 60) + ans } } diff --git a/solution/2400-2499/2437.Number of Valid Clock Times/Solution.ts b/solution/2400-2499/2437.Number of Valid Clock Times/Solution.ts index 3662b76b845c9..4824674347c4e 100644 --- a/solution/2400-2499/2437.Number of Valid Clock Times/Solution.ts +++ b/solution/2400-2499/2437.Number of Valid Clock Times/Solution.ts @@ -1,14 +1,17 @@ function countTime(time: string): number { - const f = (s: string, m: number): number => { - let cnt = 0; - for (let i = 0; i < m; ++i) { - const a = s[0] === '?' || s[0] === Math.floor(i / 10).toString(); - const b = s[1] === '?' || s[1] === (i % 10).toString(); - if (a && b) { - ++cnt; + let ans = 0; + for (let h = 0; h < 24; ++h) { + for (let m = 0; m < 60; ++m) { + const s = `${h}`.padStart(2, '0') + ':' + `${m}`.padStart(2, '0'); + let ok = 1; + for (let i = 0; i < 5; ++i) { + if (s[i] !== time[i] && time[i] !== '?') { + ok = 0; + break; + } } + ans += ok; } - return cnt; - }; - return f(time.slice(0, 2), 24) * f(time.slice(3), 60); + } + return ans; } diff --git a/solution/2400-2499/2437.Number of Valid Clock Times/Solution2.cpp b/solution/2400-2499/2437.Number of Valid Clock Times/Solution2.cpp new file mode 100644 index 0000000000000..7a5e96733fa51 --- /dev/null +++ b/solution/2400-2499/2437.Number of Valid Clock Times/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int countTime(string time) { + auto f = [](string s, int m) { + int cnt = 0; + for (int i = 0; i < m; ++i) { + bool a = s[0] == '?' || s[0] - '0' == i / 10; + bool b = s[1] == '?' || s[1] - '0' == i % 10; + cnt += a && b; + } + return cnt; + }; + return f(time.substr(0, 2), 24) * f(time.substr(3, 2), 60); + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2437.Number of Valid Clock Times/Solution2.go b/solution/2400-2499/2437.Number of Valid Clock Times/Solution2.go new file mode 100644 index 0000000000000..829de4d068611 --- /dev/null +++ b/solution/2400-2499/2437.Number of Valid Clock Times/Solution2.go @@ -0,0 +1,13 @@ +func countTime(time string) int { + f := func(s string, m int) (cnt int) { + for i := 0; i < m; i++ { + a := s[0] == '?' || int(s[0]-'0') == i/10 + b := s[1] == '?' || int(s[1]-'0') == i%10 + if a && b { + cnt++ + } + } + return + } + return f(time[:2], 24) * f(time[3:], 60) +} \ No newline at end of file diff --git a/solution/2400-2499/2437.Number of Valid Clock Times/Solution2.java b/solution/2400-2499/2437.Number of Valid Clock Times/Solution2.java new file mode 100644 index 0000000000000..f495ab66ffdd1 --- /dev/null +++ b/solution/2400-2499/2437.Number of Valid Clock Times/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public int countTime(String time) { + return f(time.substring(0, 2), 24) * f(time.substring(3), 60); + } + + private int f(String s, int m) { + int cnt = 0; + for (int i = 0; i < m; ++i) { + boolean a = s.charAt(0) == '?' || s.charAt(0) - '0' == i / 10; + boolean b = s.charAt(1) == '?' || s.charAt(1) - '0' == i % 10; + cnt += a && b ? 1 : 0; + } + return cnt; + } +} \ No newline at end of file diff --git a/solution/2400-2499/2437.Number of Valid Clock Times/Solution2.py b/solution/2400-2499/2437.Number of Valid Clock Times/Solution2.py new file mode 100644 index 0000000000000..7c138812872db --- /dev/null +++ b/solution/2400-2499/2437.Number of Valid Clock Times/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def countTime(self, time: str) -> int: + def f(s: str, m: int) -> int: + cnt = 0 + for i in range(m): + a = s[0] == '?' or (int(s[0]) == i // 10) + b = s[1] == '?' or (int(s[1]) == i % 10) + cnt += a and b + return cnt + + return f(time[:2], 24) * f(time[3:], 60) diff --git a/solution/2400-2499/2437.Number of Valid Clock Times/Solution2.rs b/solution/2400-2499/2437.Number of Valid Clock Times/Solution2.rs new file mode 100644 index 0000000000000..6e5b779edc37c --- /dev/null +++ b/solution/2400-2499/2437.Number of Valid Clock Times/Solution2.rs @@ -0,0 +1,23 @@ +impl Solution { + pub fn count_time(time: String) -> i32 { + let f = |s: &str, m: usize| -> i32 { + let mut cnt = 0; + let first = s.chars().nth(0).unwrap(); + let second = s.chars().nth(1).unwrap(); + + for i in 0..m { + let a = first == '?' || (first.to_digit(10).unwrap() as usize) == i / 10; + + let b = second == '?' || (second.to_digit(10).unwrap() as usize) == i % 10; + + if a && b { + cnt += 1; + } + } + + cnt + }; + + f(&time[..2], 24) * f(&time[3..], 60) + } +} diff --git a/solution/2400-2499/2437.Number of Valid Clock Times/Solution2.ts b/solution/2400-2499/2437.Number of Valid Clock Times/Solution2.ts new file mode 100644 index 0000000000000..3662b76b845c9 --- /dev/null +++ b/solution/2400-2499/2437.Number of Valid Clock Times/Solution2.ts @@ -0,0 +1,14 @@ +function countTime(time: string): number { + const f = (s: string, m: number): number => { + let cnt = 0; + for (let i = 0; i < m; ++i) { + const a = s[0] === '?' || s[0] === Math.floor(i / 10).toString(); + const b = s[1] === '?' || s[1] === (i % 10).toString(); + if (a && b) { + ++cnt; + } + } + return cnt; + }; + return f(time.slice(0, 2), 24) * f(time.slice(3), 60); +} diff --git a/solution/2400-2499/2441.Largest Positive Integer That Exists With Its Negative/Solution2.rs b/solution/2400-2499/2441.Largest Positive Integer That Exists With Its Negative/Solution2.rs new file mode 100644 index 0000000000000..bb457ca3a2dfd --- /dev/null +++ b/solution/2400-2499/2441.Largest Positive Integer That Exists With Its Negative/Solution2.rs @@ -0,0 +1,20 @@ +use std::collections::HashSet; + +impl Solution { + pub fn find_max_k(nums: Vec) -> i32 { + let mut ans = -1; + let mut h = HashSet::new(); + + for &n in &nums { + h.insert(n); + } + + for &n in &nums { + if h.contains(&-n) && n > ans { + ans = n; + } + } + + ans + } +} diff --git a/solution/2400-2499/2443.Sum of Number and Its Reverse/Solution.c b/solution/2400-2499/2443.Sum of Number and Its Reverse/Solution.c index e8691eabafad6..bdb0f87b1792d 100644 --- a/solution/2400-2499/2443.Sum of Number and Its Reverse/Solution.c +++ b/solution/2400-2499/2443.Sum of Number and Its Reverse/Solution.c @@ -11,4 +11,4 @@ bool sumOfNumberAndReverse(int num) { } } return 0; -} +} \ No newline at end of file diff --git a/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.c b/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.c index 478c48080a3ea..79b6e9f914c78 100644 --- a/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.c +++ b/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.c @@ -20,4 +20,4 @@ long long countSubarrays(int* nums, int numsSize, int minK, int maxK) { res += max(min(minIndex, maxIndex) - k, 0); } return res; -} +} \ No newline at end of file diff --git a/solution/2400-2499/2448.Minimum Cost to Make Array Equal/Solution2.cpp b/solution/2400-2499/2448.Minimum Cost to Make Array Equal/Solution2.cpp new file mode 100644 index 0000000000000..f116aefeab1ab --- /dev/null +++ b/solution/2400-2499/2448.Minimum Cost to Make Array Equal/Solution2.cpp @@ -0,0 +1,23 @@ +using ll = long long; + +class Solution { +public: + long long minCost(vector& nums, vector& cost) { + int n = nums.size(); + vector> arr(n); + for (int i = 0; i < n; ++i) arr[i] = {nums[i], cost[i]}; + sort(arr.begin(), arr.end()); + ll mid = accumulate(cost.begin(), cost.end(), 0ll) / 2; + ll s = 0, ans = 0; + for (auto [x, c] : arr) { + s += c; + if (s > mid) { + for (auto [v, d] : arr) { + ans += 1ll * abs(v - x) * d; + } + break; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2448.Minimum Cost to Make Array Equal/Solution2.go b/solution/2400-2499/2448.Minimum Cost to Make Array Equal/Solution2.go new file mode 100644 index 0000000000000..252c06bae9750 --- /dev/null +++ b/solution/2400-2499/2448.Minimum Cost to Make Array Equal/Solution2.go @@ -0,0 +1,33 @@ +func minCost(nums []int, cost []int) int64 { + n := len(nums) + type pair struct{ a, b int } + arr := make([]pair, n) + mid := 0 + for i, a := range nums { + b := cost[i] + mid += b + arr[i] = pair{a, b} + } + mid /= 2 + sort.Slice(arr, func(i, j int) bool { return arr[i].a < arr[j].a }) + s, ans := 0, 0 + for _, e := range arr { + x, c := e.a, e.b + s += c + if s > mid { + for _, t := range arr { + ans += abs(t.a-x) * t.b + } + break + } + } + return int64(ans) + +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} \ No newline at end of file diff --git a/solution/2400-2499/2448.Minimum Cost to Make Array Equal/Solution2.java b/solution/2400-2499/2448.Minimum Cost to Make Array Equal/Solution2.java new file mode 100644 index 0000000000000..fa5b7a28a2f42 --- /dev/null +++ b/solution/2400-2499/2448.Minimum Cost to Make Array Equal/Solution2.java @@ -0,0 +1,31 @@ +class Solution { + public long minCost(int[] nums, int[] cost) { + int n = nums.length; + int[][] arr = new int[n][2]; + for (int i = 0; i < n; ++i) { + arr[i] = new int[] {nums[i], cost[i]}; + } + Arrays.sort(arr, (a, b) -> a[0] - b[0]); + long mid = sum(cost) / 2; + long s = 0, ans = 0; + for (var e : arr) { + int x = e[0], c = e[1]; + s += c; + if (s > mid) { + for (var t : arr) { + ans += (long) Math.abs(t[0] - x) * t[1]; + } + break; + } + } + return ans; + } + + private long sum(int[] arr) { + long s = 0; + for (int v : arr) { + s += v; + } + return s; + } +} \ No newline at end of file diff --git a/solution/2400-2499/2448.Minimum Cost to Make Array Equal/Solution2.py b/solution/2400-2499/2448.Minimum Cost to Make Array Equal/Solution2.py new file mode 100644 index 0000000000000..63ad846d76ff2 --- /dev/null +++ b/solution/2400-2499/2448.Minimum Cost to Make Array Equal/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def minCost(self, nums: List[int], cost: List[int]) -> int: + arr = sorted(zip(nums, cost)) + mid = sum(cost) // 2 + s = 0 + for x, c in arr: + s += c + if s > mid: + return sum(abs(v - x) * c for v, c in arr) diff --git a/solution/2400-2499/2451.Odd String Difference/Solution.cpp b/solution/2400-2499/2451.Odd String Difference/Solution.cpp index bc580ff7abd75..9158e0ceb77e9 100644 --- a/solution/2400-2499/2451.Odd String Difference/Solution.cpp +++ b/solution/2400-2499/2451.Odd String Difference/Solution.cpp @@ -1,18 +1,18 @@ class Solution { public: string oddString(vector& words) { - unordered_map> d; - for (auto& s : words) { - int m = s.size(); - string t(m - 1, 0); - for (int i = 0; i < m - 1; ++i) { - t[i] = s[i + 1] - s[i]; + unordered_map> cnt; + for (auto& w : words) { + string d; + for (int i = 0; i < w.size() - 1; ++i) { + d += (char) (w[i + 1] - w[i]); + d += ','; } - d[t].push_back(s); + cnt[d].emplace_back(w); } - for (auto& [_, ss] : d) { - if (ss.size() == 1) { - return ss[0]; + for (auto& [_, v] : cnt) { + if (v.size() == 1) { + return v[0]; } } return ""; diff --git a/solution/2400-2499/2451.Odd String Difference/Solution2.rs b/solution/2400-2499/2451.Odd String Difference/Solution2.rs new file mode 100644 index 0000000000000..7c34c996a806a --- /dev/null +++ b/solution/2400-2499/2451.Odd String Difference/Solution2.rs @@ -0,0 +1,32 @@ +use std::collections::HashMap; + +impl Solution { + pub fn odd_string(words: Vec) -> String { + let mut h = HashMap::new(); + + for w in words { + let bytes: Vec = w + .bytes() + .zip(w.bytes().skip(1)) + .map(|(current, next)| (next - current) as i32) + .collect(); + + let s: String = bytes + .iter() + .map(|&b| char::from(b as u8)) + .collect(); + + h.entry(s) + .or_insert(vec![]) + .push(w); + } + + for strs in h.values() { + if strs.len() == 1 { + return strs[0].clone(); + } + } + + String::from("") + } +} diff --git a/solution/2400-2499/2454.Next Greater Element IV/Solution.cpp b/solution/2400-2499/2454.Next Greater Element IV/Solution.cpp index 1f6c24bb54184..65114c564d96c 100644 --- a/solution/2400-2499/2454.Next Greater Element IV/Solution.cpp +++ b/solution/2400-2499/2454.Next Greater Element IV/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - vector secondGreaterElement(vector& nums) { - int n = nums.size(); - vector ans(n, -1); - vector> arr(n); - for (int i = 0; i < n; ++i) { - arr[i] = {-nums[i], i}; - } - sort(arr.begin(), arr.end()); - set ts; - for (auto& [_, i] : arr) { - auto it = ts.upper_bound(i); - if (it != ts.end() && ts.upper_bound(*it) != ts.end()) { - ans[i] = nums[*ts.upper_bound(*it)]; - } - ts.insert(i); - } - return ans; - } -}; +class Solution { +public: + vector secondGreaterElement(vector& nums) { + int n = nums.size(); + vector ans(n, -1); + vector> arr(n); + for (int i = 0; i < n; ++i) { + arr[i] = {-nums[i], i}; + } + sort(arr.begin(), arr.end()); + set ts; + for (auto& [_, i] : arr) { + auto it = ts.upper_bound(i); + if (it != ts.end() && ts.upper_bound(*it) != ts.end()) { + ans[i] = nums[*ts.upper_bound(*it)]; + } + ts.insert(i); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2454.Next Greater Element IV/Solution.java b/solution/2400-2499/2454.Next Greater Element IV/Solution.java index df8365bb3bab1..e39bc21d90221 100644 --- a/solution/2400-2499/2454.Next Greater Element IV/Solution.java +++ b/solution/2400-2499/2454.Next Greater Element IV/Solution.java @@ -1,22 +1,22 @@ -class Solution { - public int[] secondGreaterElement(int[] nums) { - int n = nums.length; - int[] ans = new int[n]; - Arrays.fill(ans, -1); - int[][] arr = new int[n][0]; - for (int i = 0; i < n; ++i) { - arr[i] = new int[] {nums[i], i}; - } - Arrays.sort(arr, (a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]); - TreeSet ts = new TreeSet<>(); - for (int[] pair : arr) { - int i = pair[1]; - Integer j = ts.higher(i); - if (j != null && ts.higher(j) != null) { - ans[i] = nums[ts.higher(j)]; - } - ts.add(i); - } - return ans; - } +class Solution { + public int[] secondGreaterElement(int[] nums) { + int n = nums.length; + int[] ans = new int[n]; + Arrays.fill(ans, -1); + int[][] arr = new int[n][0]; + for (int i = 0; i < n; ++i) { + arr[i] = new int[] {nums[i], i}; + } + Arrays.sort(arr, (a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]); + TreeSet ts = new TreeSet<>(); + for (int[] pair : arr) { + int i = pair[1]; + Integer j = ts.higher(i); + if (j != null && ts.higher(j) != null) { + ans[i] = nums[ts.higher(j)]; + } + ts.add(i); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2400-2499/2454.Next Greater Element IV/Solution.py b/solution/2400-2499/2454.Next Greater Element IV/Solution.py index 8596b7950b61f..e0da6506e11fe 100644 --- a/solution/2400-2499/2454.Next Greater Element IV/Solution.py +++ b/solution/2400-2499/2454.Next Greater Element IV/Solution.py @@ -1,16 +1,16 @@ -from sortedcontainers import SortedList - - -class Solution: - def secondGreaterElement(self, nums: List[int]) -> List[int]: - arr = [(x, i) for i, x in enumerate(nums)] - arr.sort(key=lambda x: -x[0]) - sl = SortedList() - n = len(nums) - ans = [-1] * n - for _, i in arr: - j = sl.bisect_right(i) - if j + 1 < len(sl): - ans[i] = nums[sl[j + 1]] - sl.add(i) - return ans +from sortedcontainers import SortedList + + +class Solution: + def secondGreaterElement(self, nums: List[int]) -> List[int]: + arr = [(x, i) for i, x in enumerate(nums)] + arr.sort(key=lambda x: -x[0]) + sl = SortedList() + n = len(nums) + ans = [-1] * n + for _, i in arr: + j = sl.bisect_right(i) + if j + 1 < len(sl): + ans[i] = nums[sl[j + 1]] + sl.add(i) + return ans diff --git a/solution/2400-2499/2455.Average Value of Even Numbers That Are Divisible by Three/Solution2.rs b/solution/2400-2499/2455.Average Value of Even Numbers That Are Divisible by Three/Solution2.rs new file mode 100644 index 0000000000000..d7ba0d1a73556 --- /dev/null +++ b/solution/2400-2499/2455.Average Value of Even Numbers That Are Divisible by Three/Solution2.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn average_value(nums: Vec) -> i32 { + let filtered_nums: Vec = nums + .iter() + .cloned() + .filter(|&n| n % 6 == 0) + .collect(); + + if filtered_nums.is_empty() { + return 0; + } + + filtered_nums.iter().sum::() / (filtered_nums.len() as i32) + } +} diff --git a/solution/2400-2499/2461.Maximum Sum of Distinct Subarrays With Length K/Solution.cpp b/solution/2400-2499/2461.Maximum Sum of Distinct Subarrays With Length K/Solution.cpp index f2be2192b5217..5103bc82a519b 100644 --- a/solution/2400-2499/2461.Maximum Sum of Distinct Subarrays With Length K/Solution.cpp +++ b/solution/2400-2499/2461.Maximum Sum of Distinct Subarrays With Length K/Solution.cpp @@ -3,7 +3,7 @@ class Solution { long long maximumSubarraySum(vector& nums, int k) { using ll = long long; int n = nums.size(); - unordered_map cnt; + unordered_map cnt; ll s = 0; for (int i = 0; i < k; ++i) { cnt[nums[i]]++; diff --git a/solution/2400-2499/2465.Number of Distinct Averages/Solution.cpp b/solution/2400-2499/2465.Number of Distinct Averages/Solution.cpp index dbf52c19b1f91..fa7c8b83c16dd 100644 --- a/solution/2400-2499/2465.Number of Distinct Averages/Solution.cpp +++ b/solution/2400-2499/2465.Number of Distinct Averages/Solution.cpp @@ -2,14 +2,11 @@ class Solution { public: int distinctAverages(vector& nums) { sort(nums.begin(), nums.end()); - int cnt[201]{}; + unordered_set s; int n = nums.size(); - int ans = 0; for (int i = 0; i < n >> 1; ++i) { - if (++cnt[nums[i] + nums[n - i - 1]] == 1) { - ++ans; - } + s.insert(nums[i] + nums[n - i - 1]); } - return ans; + return s.size(); } }; \ No newline at end of file diff --git a/solution/2400-2499/2465.Number of Distinct Averages/Solution.go b/solution/2400-2499/2465.Number of Distinct Averages/Solution.go index 6cab76c85af84..da93a9aa4d747 100644 --- a/solution/2400-2499/2465.Number of Distinct Averages/Solution.go +++ b/solution/2400-2499/2465.Number of Distinct Averages/Solution.go @@ -1,13 +1,9 @@ func distinctAverages(nums []int) (ans int) { sort.Ints(nums) n := len(nums) - cnt := [201]int{} + s := map[int]struct{}{} for i := 0; i < n>>1; i++ { - x := nums[i] + nums[n-i-1] - cnt[x]++ - if cnt[x] == 1 { - ans++ - } + s[nums[i]+nums[n-i-1]] = struct{}{} } - return + return len(s) } \ No newline at end of file diff --git a/solution/2400-2499/2465.Number of Distinct Averages/Solution.java b/solution/2400-2499/2465.Number of Distinct Averages/Solution.java index 51d9007723c38..54c1da59dcd6b 100644 --- a/solution/2400-2499/2465.Number of Distinct Averages/Solution.java +++ b/solution/2400-2499/2465.Number of Distinct Averages/Solution.java @@ -1,14 +1,11 @@ class Solution { public int distinctAverages(int[] nums) { Arrays.sort(nums); - int[] cnt = new int[201]; + Set s = new HashSet<>(); int n = nums.length; - int ans = 0; for (int i = 0; i < n >> 1; ++i) { - if (++cnt[nums[i] + nums[n - i - 1]] == 1) { - ++ans; - } + s.add(nums[i] + nums[n - i - 1]); } - return ans; + return s.size(); } } \ No newline at end of file diff --git a/solution/2400-2499/2465.Number of Distinct Averages/Solution.rs b/solution/2400-2499/2465.Number of Distinct Averages/Solution.rs index 49ff2acb2eeb9..ced481e6ab1bf 100644 --- a/solution/2400-2499/2465.Number of Distinct Averages/Solution.rs +++ b/solution/2400-2499/2465.Number of Distinct Averages/Solution.rs @@ -1,22 +1,18 @@ -use std::collections::HashSet; - impl Solution { pub fn distinct_averages(nums: Vec) -> i32 { - let mut set = HashSet::new(); - let mut ans = 0; - let n = nums.len(); let mut nums = nums; nums.sort(); + let n = nums.len(); + let mut cnt = vec![0; 201]; + let mut ans = 0; for i in 0..n >> 1 { - let x = nums[i] + nums[n - i - 1]; + let x = (nums[i] + nums[n - i - 1]) as usize; + cnt[x] += 1; - if set.contains(&x) { - continue; + if cnt[x] == 1 { + ans += 1; } - - set.insert(x); - ans += 1; } ans diff --git a/solution/2400-2499/2465.Number of Distinct Averages/Solution.ts b/solution/2400-2499/2465.Number of Distinct Averages/Solution.ts index ac3c93ff9d906..12c7379f7e89f 100644 --- a/solution/2400-2499/2465.Number of Distinct Averages/Solution.ts +++ b/solution/2400-2499/2465.Number of Distinct Averages/Solution.ts @@ -1,12 +1,9 @@ function distinctAverages(nums: number[]): number { nums.sort((a, b) => a - b); - const cnt: number[] = Array(201).fill(0); - let ans = 0; + const s: Set = new Set(); const n = nums.length; for (let i = 0; i < n >> 1; ++i) { - if (++cnt[nums[i] + nums[n - i - 1]] === 1) { - ++ans; - } + s.add(nums[i] + nums[n - i - 1]); } - return ans; + return s.size; } diff --git a/solution/2400-2499/2465.Number of Distinct Averages/Solution2.cpp b/solution/2400-2499/2465.Number of Distinct Averages/Solution2.cpp new file mode 100644 index 0000000000000..dbf52c19b1f91 --- /dev/null +++ b/solution/2400-2499/2465.Number of Distinct Averages/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int distinctAverages(vector& nums) { + sort(nums.begin(), nums.end()); + int cnt[201]{}; + int n = nums.size(); + int ans = 0; + for (int i = 0; i < n >> 1; ++i) { + if (++cnt[nums[i] + nums[n - i - 1]] == 1) { + ++ans; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2465.Number of Distinct Averages/Solution2.go b/solution/2400-2499/2465.Number of Distinct Averages/Solution2.go new file mode 100644 index 0000000000000..6cab76c85af84 --- /dev/null +++ b/solution/2400-2499/2465.Number of Distinct Averages/Solution2.go @@ -0,0 +1,13 @@ +func distinctAverages(nums []int) (ans int) { + sort.Ints(nums) + n := len(nums) + cnt := [201]int{} + for i := 0; i < n>>1; i++ { + x := nums[i] + nums[n-i-1] + cnt[x]++ + if cnt[x] == 1 { + ans++ + } + } + return +} \ No newline at end of file diff --git a/solution/2400-2499/2465.Number of Distinct Averages/Solution2.java b/solution/2400-2499/2465.Number of Distinct Averages/Solution2.java new file mode 100644 index 0000000000000..51d9007723c38 --- /dev/null +++ b/solution/2400-2499/2465.Number of Distinct Averages/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public int distinctAverages(int[] nums) { + Arrays.sort(nums); + int[] cnt = new int[201]; + int n = nums.length; + int ans = 0; + for (int i = 0; i < n >> 1; ++i) { + if (++cnt[nums[i] + nums[n - i - 1]] == 1) { + ++ans; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2400-2499/2465.Number of Distinct Averages/Solution2.py b/solution/2400-2499/2465.Number of Distinct Averages/Solution2.py new file mode 100644 index 0000000000000..807068cb5120c --- /dev/null +++ b/solution/2400-2499/2465.Number of Distinct Averages/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def distinctAverages(self, nums: List[int]) -> int: + nums.sort() + ans = 0 + cnt = Counter() + for i in range(len(nums) >> 1): + x = nums[i] + nums[-i - 1] + cnt[x] += 1 + if cnt[x] == 1: + ans += 1 + return ans diff --git a/solution/2400-2499/2465.Number of Distinct Averages/Solution2.rs b/solution/2400-2499/2465.Number of Distinct Averages/Solution2.rs new file mode 100644 index 0000000000000..e92389982a7c9 --- /dev/null +++ b/solution/2400-2499/2465.Number of Distinct Averages/Solution2.rs @@ -0,0 +1,22 @@ +use std::collections::HashMap; + +impl Solution { + pub fn distinct_averages(nums: Vec) -> i32 { + let mut h = HashMap::new(); + let mut nums = nums; + let mut ans = 0; + let n = nums.len(); + nums.sort(); + + for i in 0..n >> 1 { + let x = nums[i] + nums[n - i - 1]; + *h.entry(x).or_insert(0) += 1; + + if *h.get(&x).unwrap() == 1 { + ans += 1; + } + } + + ans + } +} diff --git a/solution/2400-2499/2465.Number of Distinct Averages/Solution2.ts b/solution/2400-2499/2465.Number of Distinct Averages/Solution2.ts new file mode 100644 index 0000000000000..ac3c93ff9d906 --- /dev/null +++ b/solution/2400-2499/2465.Number of Distinct Averages/Solution2.ts @@ -0,0 +1,12 @@ +function distinctAverages(nums: number[]): number { + nums.sort((a, b) => a - b); + const cnt: number[] = Array(201).fill(0); + let ans = 0; + const n = nums.length; + for (let i = 0; i < n >> 1; ++i) { + if (++cnt[nums[i] + nums[n - i - 1]] === 1) { + ++ans; + } + } + return ans; +} diff --git a/solution/2400-2499/2465.Number of Distinct Averages/Solution3.rs b/solution/2400-2499/2465.Number of Distinct Averages/Solution3.rs new file mode 100644 index 0000000000000..49ff2acb2eeb9 --- /dev/null +++ b/solution/2400-2499/2465.Number of Distinct Averages/Solution3.rs @@ -0,0 +1,24 @@ +use std::collections::HashSet; + +impl Solution { + pub fn distinct_averages(nums: Vec) -> i32 { + let mut set = HashSet::new(); + let mut ans = 0; + let n = nums.len(); + let mut nums = nums; + nums.sort(); + + for i in 0..n >> 1 { + let x = nums[i] + nums[n - i - 1]; + + if set.contains(&x) { + continue; + } + + set.insert(x); + ans += 1; + } + + ans + } +} diff --git a/solution/2400-2499/2469.Convert the Temperature/Solution.c b/solution/2400-2499/2469.Convert the Temperature/Solution.c index 08d6a9321fbe2..7c8de56d3060f 100644 --- a/solution/2400-2499/2469.Convert the Temperature/Solution.c +++ b/solution/2400-2499/2469.Convert the Temperature/Solution.c @@ -7,4 +7,4 @@ double* convertTemperature(double celsius, int* returnSize) { ans[1] = celsius * 1.8 + 32; *returnSize = 2; return ans; -} +} \ No newline at end of file diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.cpp b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.cpp index 5fd27f8920d9a..74f60d9e309ef 100644 --- a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.cpp +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.cpp @@ -1,16 +1,16 @@ class Solution { public: int unequalTriplets(vector& nums) { - unordered_map cnt; - for (int& v : nums) { - ++cnt[v]; - } - int ans = 0, a = 0; int n = nums.size(); - for (auto& [_, b] : cnt) { - int c = n - a - b; - ans += a * b * c; - a += b; + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + for (int k = j + 1; k < n; ++k) { + if (nums[i] != nums[j] && nums[j] != nums[k] && nums[i] != nums[k]) { + ++ans; + } + } + } } return ans; } diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.go b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.go index fb99aa06c32e4..2b47db60a463b 100644 --- a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.go +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.go @@ -1,13 +1,13 @@ func unequalTriplets(nums []int) (ans int) { - cnt := map[int]int{} - for _, v := range nums { - cnt[v]++ - } - a, n := 0, len(nums) - for _, b := range cnt { - c := n - a - b - ans += a * b * c - a += b + n := len(nums) + for i := 0; i < n; i++ { + for j := i + 1; j < n; j++ { + for k := j + 1; k < n; k++ { + if nums[i] != nums[j] && nums[j] != nums[k] && nums[i] != nums[k] { + ans++ + } + } + } } return } \ No newline at end of file diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.java b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.java index 1d02081ba9b95..15b10fcd7092a 100644 --- a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.java +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.java @@ -1,15 +1,15 @@ class Solution { public int unequalTriplets(int[] nums) { - Map cnt = new HashMap<>(); - for (int v : nums) { - cnt.merge(v, 1, Integer::sum); - } - int ans = 0, a = 0; int n = nums.length; - for (int b : cnt.values()) { - int c = n - a - b; - ans += a * b * c; - a += b; + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + for (int k = j + 1; k < n; ++k) { + if (nums[i] != nums[j] && nums[j] != nums[k] && nums[i] != nums[k]) { + ++ans; + } + } + } } return ans; } diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.py b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.py index cfeb2c4a2d781..ca339b7aff069 100644 --- a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.py +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.py @@ -1,10 +1,11 @@ class Solution: def unequalTriplets(self, nums: List[int]) -> int: - cnt = Counter(nums) n = len(nums) - ans = a = 0 - for b in cnt.values(): - c = n - a - b - ans += a * b * c - a += b + ans = 0 + for i in range(n): + for j in range(i + 1, n): + for k in range(j + 1, n): + ans += ( + nums[i] != nums[j] and nums[j] != nums[k] and nums[i] != nums[k] + ) return ans diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.rs b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.rs index f748b86a1e3cf..23e95738cabd9 100644 --- a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.rs +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.rs @@ -1,18 +1,16 @@ -use std::collections::HashMap; impl Solution { pub fn unequal_triplets(nums: Vec) -> i32 { - let mut cnt = HashMap::new(); - for num in nums.iter() { - *cnt.entry(num).or_insert(0) += 1; - } let n = nums.len(); let mut ans = 0; - let mut a = 0; - for v in cnt.values() { - let b = n - a - v; - ans += v * a * b; - a += v; + for i in 0..n - 2 { + for j in i + 1..n - 1 { + for k in j + 1..n { + if nums[i] != nums[j] && nums[j] != nums[k] && nums[i] != nums[k] { + ans += 1; + } + } + } } - ans as i32 + ans } } diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.ts b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.ts index 83254bd029c90..36e4e75c9607e 100644 --- a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.ts +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution.ts @@ -1,15 +1,14 @@ function unequalTriplets(nums: number[]): number { const n = nums.length; - const cnt = new Map(); - for (const num of nums) { - cnt.set(num, (cnt.get(num) ?? 0) + 1); - } let ans = 0; - let a = 0; - for (const b of cnt.values()) { - const c = n - a - b; - ans += a * b * c; - a += b; + for (let i = 0; i < n - 2; i++) { + for (let j = i + 1; j < n - 1; j++) { + for (let k = j + 1; k < n; k++) { + if (nums[i] !== nums[j] && nums[j] !== nums[k] && nums[i] !== nums[k]) { + ans++; + } + } + } } return ans; } diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution2.cpp b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution2.cpp new file mode 100644 index 0000000000000..abb7d8fa8f739 --- /dev/null +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int unequalTriplets(vector& nums) { + sort(nums.begin(), nums.end()); + int ans = 0, n = nums.size(); + for (int j = 1; j < n - 1; ++j) { + int i = lower_bound(nums.begin(), nums.begin() + j, nums[j]) - nums.begin() - 1; + int k = upper_bound(nums.begin() + j + 1, nums.end(), nums[j]) - nums.begin(); + if (i >= 0 && k < n) { + ans += (i + 1) * (n - k); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution2.go b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution2.go new file mode 100644 index 0000000000000..fe73c5cc8da9b --- /dev/null +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution2.go @@ -0,0 +1,12 @@ +func unequalTriplets(nums []int) (ans int) { + sort.Ints(nums) + n := len(nums) + for j := 1; j < n-1; j++ { + i := sort.Search(j, func(h int) bool { return nums[h] >= nums[j] }) - 1 + k := sort.Search(n, func(h int) bool { return h > j && nums[h] > nums[j] }) + if i >= 0 && k < n { + ans += (i + 1) * (n - k) + } + } + return +} \ No newline at end of file diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution2.java b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution2.java new file mode 100644 index 0000000000000..aaec94fdea81e --- /dev/null +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution2.java @@ -0,0 +1,26 @@ +class Solution { + public int unequalTriplets(int[] nums) { + Arrays.sort(nums); + int ans = 0, n = nums.length; + for (int j = 1; j < n - 1; ++j) { + int i = search(nums, nums[j], 0, j) - 1; + int k = search(nums, nums[j] + 1, j + 1, n); + if (i >= 0 && k < n) { + ans += (i + 1) * (n - k); + } + } + return ans; + } + + private int search(int[] nums, int x, int left, int right) { + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} \ No newline at end of file diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution2.py b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution2.py new file mode 100644 index 0000000000000..6a68cb6a93bbe --- /dev/null +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def unequalTriplets(self, nums: List[int]) -> int: + nums.sort() + ans, n = 0, len(nums) + for j in range(1, n - 1): + i = bisect_left(nums, nums[j], hi=j) - 1 + k = bisect_right(nums, nums[j], lo=j + 1) + ans += (i >= 0 and k < n) * (i + 1) * (n - k) + return ans diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution2.rs b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution2.rs new file mode 100644 index 0000000000000..f748b86a1e3cf --- /dev/null +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution2.rs @@ -0,0 +1,18 @@ +use std::collections::HashMap; +impl Solution { + pub fn unequal_triplets(nums: Vec) -> i32 { + let mut cnt = HashMap::new(); + for num in nums.iter() { + *cnt.entry(num).or_insert(0) += 1; + } + let n = nums.len(); + let mut ans = 0; + let mut a = 0; + for v in cnt.values() { + let b = n - a - v; + ans += v * a * b; + a += v; + } + ans as i32 + } +} diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution2.ts b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution2.ts new file mode 100644 index 0000000000000..83254bd029c90 --- /dev/null +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution2.ts @@ -0,0 +1,15 @@ +function unequalTriplets(nums: number[]): number { + const n = nums.length; + const cnt = new Map(); + for (const num of nums) { + cnt.set(num, (cnt.get(num) ?? 0) + 1); + } + let ans = 0; + let a = 0; + for (const b of cnt.values()) { + const c = n - a - b; + ans += a * b * c; + a += b; + } + return ans; +} diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution3.cpp b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution3.cpp new file mode 100644 index 0000000000000..5fd27f8920d9a --- /dev/null +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution3.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int unequalTriplets(vector& nums) { + unordered_map cnt; + for (int& v : nums) { + ++cnt[v]; + } + int ans = 0, a = 0; + int n = nums.size(); + for (auto& [_, b] : cnt) { + int c = n - a - b; + ans += a * b * c; + a += b; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution3.go b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution3.go new file mode 100644 index 0000000000000..fb99aa06c32e4 --- /dev/null +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution3.go @@ -0,0 +1,13 @@ +func unequalTriplets(nums []int) (ans int) { + cnt := map[int]int{} + for _, v := range nums { + cnt[v]++ + } + a, n := 0, len(nums) + for _, b := range cnt { + c := n - a - b + ans += a * b * c + a += b + } + return +} \ No newline at end of file diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution3.java b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution3.java new file mode 100644 index 0000000000000..1d02081ba9b95 --- /dev/null +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution3.java @@ -0,0 +1,16 @@ +class Solution { + public int unequalTriplets(int[] nums) { + Map cnt = new HashMap<>(); + for (int v : nums) { + cnt.merge(v, 1, Integer::sum); + } + int ans = 0, a = 0; + int n = nums.length; + for (int b : cnt.values()) { + int c = n - a - b; + ans += a * b * c; + a += b; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution3.py b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution3.py new file mode 100644 index 0000000000000..cfeb2c4a2d781 --- /dev/null +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution3.py @@ -0,0 +1,10 @@ +class Solution: + def unequalTriplets(self, nums: List[int]) -> int: + cnt = Counter(nums) + n = len(nums) + ans = a = 0 + for b in cnt.values(): + c = n - a - b + ans += a * b * c + a += b + return ans diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution3.rs b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution3.rs new file mode 100644 index 0000000000000..9d5ac48ba5659 --- /dev/null +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution3.rs @@ -0,0 +1,21 @@ +use std::collections::HashMap; + +impl Solution { + pub fn unequal_triplets(nums: Vec) -> i32 { + let cnt = nums.iter().fold(HashMap::new(), |mut map, &n| { + *map.entry(n).or_insert(0) += 1; + map + }); + + let mut ans = 0; + let n = nums.len(); + let mut a = 0; + for &b in cnt.values() { + let c = n - a - b; + ans += a * b * c; + a += b; + } + + ans as i32 + } +} diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution4.rs b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution4.rs new file mode 100644 index 0000000000000..b2457b248503e --- /dev/null +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/Solution4.rs @@ -0,0 +1,38 @@ +impl Solution { + pub fn unequal_triplets(nums: Vec) -> i32 { + let mut ans = 0; + let mut nums = nums; + nums.sort(); + let n = nums.len(); + + for i in 1..n - 1 { + let mut l = 0; + let mut r = i; + while l < r { + let mid = (l + r) >> 1; + if nums[mid] >= nums[i] { + r = mid; + } else { + l = mid + 1; + } + } + let j = r; + + let mut l = i + 1; + let mut r = n; + while l < r { + let mid = (l + r) >> 1; + if nums[mid] > nums[i] { + r = mid; + } else { + l = mid + 1; + } + } + let k = r; + + ans += j * (n - k); + } + + ans as i32 + } +} diff --git a/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/Solution.cpp b/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/Solution.cpp index 5f35e90689986..044fd5fbd9b3c 100644 --- a/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/Solution.cpp +++ b/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/Solution.cpp @@ -1,36 +1,36 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - vector> closestNodes(TreeNode* root, vector& queries) { - vector nums; - function dfs = [&](TreeNode* root) { - if (!root) { - return; - } - dfs(root->left); - nums.push_back(root->val); - dfs(root->right); - }; - dfs(root); - vector> ans; - int n = nums.size(); - for (int& x : queries) { - int i = lower_bound(nums.begin(), nums.end(), x + 1) - nums.begin() - 1; - int j = lower_bound(nums.begin(), nums.end(), x) - nums.begin(); - int mi = i >= 0 && i < n ? nums[i] : -1; - int mx = j >= 0 && j < n ? nums[j] : -1; - ans.push_back({mi, mx}); - } - return ans; - } +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> closestNodes(TreeNode* root, vector& queries) { + vector nums; + function dfs = [&](TreeNode* root) { + if (!root) { + return; + } + dfs(root->left); + nums.push_back(root->val); + dfs(root->right); + }; + dfs(root); + vector> ans; + int n = nums.size(); + for (int& x : queries) { + int i = lower_bound(nums.begin(), nums.end(), x + 1) - nums.begin() - 1; + int j = lower_bound(nums.begin(), nums.end(), x) - nums.begin(); + int mi = i >= 0 && i < n ? nums[i] : -1; + int mx = j >= 0 && j < n ? nums[j] : -1; + ans.push_back({mi, mx}); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/Solution.java b/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/Solution.java index 283fee814605d..7bd9391a03c4b 100644 --- a/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/Solution.java +++ b/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/Solution.java @@ -1,42 +1,42 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private List nums = new ArrayList<>(); - - public List> closestNodes(TreeNode root, List queries) { - dfs(root); - List> ans = new ArrayList<>(); - for (int x : queries) { - int i = Collections.binarySearch(nums, x + 1); - int j = Collections.binarySearch(nums, x); - i = i < 0 ? -i - 2 : i - 1; - j = j < 0 ? -j - 1 : j; - int mi = i >= 0 && i < nums.size() ? nums.get(i) : -1; - int mx = j >= 0 && j < nums.size() ? nums.get(j) : -1; - ans.add(List.of(mi, mx)); - } - return ans; - } - - private void dfs(TreeNode root) { - if (root == null) { - return; - } - dfs(root.left); - nums.add(root.val); - dfs(root.right); - } +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private List nums = new ArrayList<>(); + + public List> closestNodes(TreeNode root, List queries) { + dfs(root); + List> ans = new ArrayList<>(); + for (int x : queries) { + int i = Collections.binarySearch(nums, x + 1); + int j = Collections.binarySearch(nums, x); + i = i < 0 ? -i - 2 : i - 1; + j = j < 0 ? -j - 1 : j; + int mi = i >= 0 && i < nums.size() ? nums.get(i) : -1; + int mx = j >= 0 && j < nums.size() ? nums.get(j) : -1; + ans.add(List.of(mi, mx)); + } + return ans; + } + + private void dfs(TreeNode root) { + if (root == null) { + return; + } + dfs(root.left); + nums.add(root.val); + dfs(root.right); + } } \ No newline at end of file diff --git a/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/Solution.py b/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/Solution.py index cceef6ba52988..77f686f0ae2e7 100644 --- a/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/Solution.py +++ b/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/Solution.py @@ -1,27 +1,27 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def closestNodes( - self, root: Optional[TreeNode], queries: List[int] - ) -> List[List[int]]: - def dfs(root: Optional[TreeNode]): - if root is None: - return - dfs(root.left) - nums.append(root.val) - dfs(root.right) - - nums = [] - dfs(root) - ans = [] - for x in queries: - i = bisect_left(nums, x + 1) - 1 - j = bisect_left(nums, x) - mi = nums[i] if 0 <= i < len(nums) else -1 - mx = nums[j] if 0 <= j < len(nums) else -1 - ans.append([mi, mx]) - return ans +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def closestNodes( + self, root: Optional[TreeNode], queries: List[int] + ) -> List[List[int]]: + def dfs(root: Optional[TreeNode]): + if root is None: + return + dfs(root.left) + nums.append(root.val) + dfs(root.right) + + nums = [] + dfs(root) + ans = [] + for x in queries: + i = bisect_left(nums, x + 1) - 1 + j = bisect_left(nums, x) + mi = nums[i] if 0 <= i < len(nums) else -1 + mx = nums[j] if 0 <= j < len(nums) else -1 + ans.append([mi, mx]) + return ans diff --git a/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/Solution.cpp b/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/Solution.cpp index d2c78524b2cc3..4a73629bd11b6 100644 --- a/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/Solution.cpp +++ b/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/Solution.cpp @@ -1,26 +1,26 @@ -class Solution { -public: - long long minimumFuelCost(vector>& roads, int seats) { - int n = roads.size() + 1; - vector g[n]; - for (auto& e : roads) { - int a = e[0], b = e[1]; - g[a].emplace_back(b); - g[b].emplace_back(a); - } - long long ans = 0; - function dfs = [&](int a, int fa) { - int sz = 1; - for (int b : g[a]) { - if (b != fa) { - int t = dfs(b, a); - ans += (t + seats - 1) / seats; - sz += t; - } - } - return sz; - }; - dfs(0, -1); - return ans; - } +class Solution { +public: + long long minimumFuelCost(vector>& roads, int seats) { + int n = roads.size() + 1; + vector g[n]; + for (auto& e : roads) { + int a = e[0], b = e[1]; + g[a].emplace_back(b); + g[b].emplace_back(a); + } + long long ans = 0; + function dfs = [&](int a, int fa) { + int sz = 1; + for (int b : g[a]) { + if (b != fa) { + int t = dfs(b, a); + ans += (t + seats - 1) / seats; + sz += t; + } + } + return sz; + }; + dfs(0, -1); + return ans; + } }; \ No newline at end of file diff --git a/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/Solution.java b/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/Solution.java index e5eaf7d67cec7..9c489ed9f98cc 100644 --- a/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/Solution.java +++ b/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/Solution.java @@ -1,31 +1,31 @@ -class Solution { - private List[] g; - private int seats; - private long ans; - - public long minimumFuelCost(int[][] roads, int seats) { - int n = roads.length + 1; - g = new List[n]; - Arrays.setAll(g, k -> new ArrayList<>()); - this.seats = seats; - for (var e : roads) { - int a = e[0], b = e[1]; - g[a].add(b); - g[b].add(a); - } - dfs(0, -1); - return ans; - } - - private int dfs(int a, int fa) { - int sz = 1; - for (int b : g[a]) { - if (b != fa) { - int t = dfs(b, a); - ans += (t + seats - 1) / seats; - sz += t; - } - } - return sz; - } +class Solution { + private List[] g; + private int seats; + private long ans; + + public long minimumFuelCost(int[][] roads, int seats) { + int n = roads.length + 1; + g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + this.seats = seats; + for (var e : roads) { + int a = e[0], b = e[1]; + g[a].add(b); + g[b].add(a); + } + dfs(0, -1); + return ans; + } + + private int dfs(int a, int fa) { + int sz = 1; + for (int b : g[a]) { + if (b != fa) { + int t = dfs(b, a); + ans += (t + seats - 1) / seats; + sz += t; + } + } + return sz; + } } \ No newline at end of file diff --git a/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/Solution.py b/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/Solution.py index d12b46f1943f8..ce9263c33ad1f 100644 --- a/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/Solution.py +++ b/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/Solution.py @@ -1,19 +1,19 @@ -class Solution: - def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int: - def dfs(a: int, fa: int) -> int: - nonlocal ans - sz = 1 - for b in g[a]: - if b != fa: - t = dfs(b, a) - ans += ceil(t / seats) - sz += t - return sz - - g = defaultdict(list) - for a, b in roads: - g[a].append(b) - g[b].append(a) - ans = 0 - dfs(0, -1) - return ans +class Solution: + def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int: + def dfs(a: int, fa: int) -> int: + nonlocal ans + sz = 1 + for b in g[a]: + if b != fa: + t = dfs(b, a) + ans += ceil(t / seats) + sz += t + return sz + + g = defaultdict(list) + for a, b in roads: + g[a].append(b) + g[b].append(a) + ans = 0 + dfs(0, -1) + return ans diff --git a/solution/2400-2499/2481.Minimum Cuts to Divide a Circle/Solution.cs b/solution/2400-2499/2481.Minimum Cuts to Divide a Circle/Solution.cs index 90d7087a53981..135734df5783d 100644 --- a/solution/2400-2499/2481.Minimum Cuts to Divide a Circle/Solution.cs +++ b/solution/2400-2499/2481.Minimum Cuts to Divide a Circle/Solution.cs @@ -1,5 +1,5 @@ -public class Solution { - public int NumberOfCuts(int n) { - return n > 1 && n % 2 == 1 ? n : n >> 1; - } -} \ No newline at end of file +public class Solution { + public int NumberOfCuts(int n) { + return n > 1 && n % 2 == 1 ? n : n >> 1; + } +} diff --git a/solution/2400-2499/2481.Minimum Cuts to Divide a Circle/Solution.py b/solution/2400-2499/2481.Minimum Cuts to Divide a Circle/Solution.py index 1fe9d433bfc59..b4a3e3ebae188 100644 --- a/solution/2400-2499/2481.Minimum Cuts to Divide a Circle/Solution.py +++ b/solution/2400-2499/2481.Minimum Cuts to Divide a Circle/Solution.py @@ -1,3 +1,3 @@ -class Solution: - def numberOfCuts(self, n: int) -> int: - return n if (n > 1 and n & 1) else n >> 1 +class Solution: + def numberOfCuts(self, n: int) -> int: + return n if (n > 1 and n & 1) else n >> 1 diff --git a/solution/2400-2499/2482.Difference Between Ones and Zeros in Row and Column/Solution.c b/solution/2400-2499/2482.Difference Between Ones and Zeros in Row and Column/Solution.c index 966c134ae2d5d..2e00b74ffe5ec 100644 --- a/solution/2400-2499/2482.Difference Between Ones and Zeros in Row and Column/Solution.c +++ b/solution/2400-2499/2482.Difference Between Ones and Zeros in Row and Column/Solution.c @@ -26,4 +26,4 @@ int** onesMinusZeros(int** grid, int gridSize, int* gridColSize, int* returnSize *returnSize = gridSize; *returnColumnSizes = gridColSize; return ans; -} +} \ No newline at end of file diff --git a/solution/2400-2499/2485.Find the Pivot Integer/Solution.cpp b/solution/2400-2499/2485.Find the Pivot Integer/Solution.cpp index bcfcb277ac5f4..1663fc7addde1 100644 --- a/solution/2400-2499/2485.Find the Pivot Integer/Solution.cpp +++ b/solution/2400-2499/2485.Find the Pivot Integer/Solution.cpp @@ -1,8 +1,11 @@ -class Solution { -public: - int pivotInteger(int n) { - int y = n * (n + 1) / 2; - int x = sqrt(y); - return x * x == y ? x : -1; - } +class Solution { +public: + int pivotInteger(int n) { + for (int x = 1; x <= n; ++x) { + if ((1 + x) * x == (x + n) * (n - x + 1)) { + return x; + } + } + return -1; + } }; \ No newline at end of file diff --git a/solution/2400-2499/2485.Find the Pivot Integer/Solution.go b/solution/2400-2499/2485.Find the Pivot Integer/Solution.go index 61991d5c3ff16..9d1b0a5b59d14 100644 --- a/solution/2400-2499/2485.Find the Pivot Integer/Solution.go +++ b/solution/2400-2499/2485.Find the Pivot Integer/Solution.go @@ -1,8 +1,8 @@ func pivotInteger(n int) int { - y := n * (n + 1) / 2 - x := int(math.Sqrt(float64(y))) - if x*x == y { - return x + for x := 1; x <= n; x++ { + if (1+x)*x == (x+n)*(n-x+1) { + return x + } } return -1 } \ No newline at end of file diff --git a/solution/2400-2499/2485.Find the Pivot Integer/Solution.java b/solution/2400-2499/2485.Find the Pivot Integer/Solution.java index 515a34366c479..a8ea30924c2aa 100644 --- a/solution/2400-2499/2485.Find the Pivot Integer/Solution.java +++ b/solution/2400-2499/2485.Find the Pivot Integer/Solution.java @@ -1,7 +1,10 @@ -class Solution { - public int pivotInteger(int n) { - int y = n * (n + 1) / 2; - int x = (int) Math.sqrt(y); - return x * x == y ? x : -1; - } +class Solution { + public int pivotInteger(int n) { + for (int x = 1; x <= n; ++x) { + if ((1 + x) * x == (x + n) * (n - x + 1)) { + return x; + } + } + return -1; + } } \ No newline at end of file diff --git a/solution/2400-2499/2485.Find the Pivot Integer/Solution.php b/solution/2400-2499/2485.Find the Pivot Integer/Solution.php index f5a7244d4fb28..3ff4d71c1ba5a 100644 --- a/solution/2400-2499/2485.Find the Pivot Integer/Solution.php +++ b/solution/2400-2499/2485.Find the Pivot Integer/Solution.php @@ -14,4 +14,4 @@ function pivotInteger($n) { } return -1; } -} \ No newline at end of file +} diff --git a/solution/2400-2499/2485.Find the Pivot Integer/Solution.py b/solution/2400-2499/2485.Find the Pivot Integer/Solution.py index e53f8d12b5c19..d8eeae6c9995f 100644 --- a/solution/2400-2499/2485.Find the Pivot Integer/Solution.py +++ b/solution/2400-2499/2485.Find the Pivot Integer/Solution.py @@ -1,5 +1,6 @@ -class Solution: - def pivotInteger(self, n: int) -> int: - y = n * (n + 1) // 2 - x = int(sqrt(y)) - return x if x * x == y else -1 +class Solution: + def pivotInteger(self, n: int) -> int: + for x in range(1, n + 1): + if (1 + x) * x == (x + n) * (n - x + 1): + return x + return -1 diff --git a/solution/2400-2499/2485.Find the Pivot Integer/Solution.ts b/solution/2400-2499/2485.Find the Pivot Integer/Solution.ts index 475323417d131..665a365439c2b 100644 --- a/solution/2400-2499/2485.Find the Pivot Integer/Solution.ts +++ b/solution/2400-2499/2485.Find the Pivot Integer/Solution.ts @@ -1,5 +1,8 @@ function pivotInteger(n: number): number { - const y = Math.floor((n * (n + 1)) / 2); - const x = Math.floor(Math.sqrt(y)); - return x * x === y ? x : -1; + for (let x = 1; x <= n; ++x) { + if ((1 + x) * x === (x + n) * (n - x + 1)) { + return x; + } + } + return -1; } diff --git a/solution/2400-2499/2485.Find the Pivot Integer/Solution2.cpp b/solution/2400-2499/2485.Find the Pivot Integer/Solution2.cpp new file mode 100644 index 0000000000000..7b78b521a2925 --- /dev/null +++ b/solution/2400-2499/2485.Find the Pivot Integer/Solution2.cpp @@ -0,0 +1,8 @@ +class Solution { +public: + int pivotInteger(int n) { + int y = n * (n + 1) / 2; + int x = sqrt(y); + return x * x == y ? x : -1; + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2485.Find the Pivot Integer/Solution2.go b/solution/2400-2499/2485.Find the Pivot Integer/Solution2.go new file mode 100644 index 0000000000000..61991d5c3ff16 --- /dev/null +++ b/solution/2400-2499/2485.Find the Pivot Integer/Solution2.go @@ -0,0 +1,8 @@ +func pivotInteger(n int) int { + y := n * (n + 1) / 2 + x := int(math.Sqrt(float64(y))) + if x*x == y { + return x + } + return -1 +} \ No newline at end of file diff --git a/solution/2400-2499/2485.Find the Pivot Integer/Solution2.java b/solution/2400-2499/2485.Find the Pivot Integer/Solution2.java new file mode 100644 index 0000000000000..4a32759103639 --- /dev/null +++ b/solution/2400-2499/2485.Find the Pivot Integer/Solution2.java @@ -0,0 +1,7 @@ +class Solution { + public int pivotInteger(int n) { + int y = n * (n + 1) / 2; + int x = (int) Math.sqrt(y); + return x * x == y ? x : -1; + } +} \ No newline at end of file diff --git a/solution/2400-2499/2485.Find the Pivot Integer/Solution2.py b/solution/2400-2499/2485.Find the Pivot Integer/Solution2.py new file mode 100644 index 0000000000000..4f86032efbe5b --- /dev/null +++ b/solution/2400-2499/2485.Find the Pivot Integer/Solution2.py @@ -0,0 +1,5 @@ +class Solution: + def pivotInteger(self, n: int) -> int: + y = n * (n + 1) // 2 + x = int(sqrt(y)) + return x if x * x == y else -1 diff --git a/solution/2400-2499/2485.Find the Pivot Integer/Solution2.ts b/solution/2400-2499/2485.Find the Pivot Integer/Solution2.ts new file mode 100644 index 0000000000000..475323417d131 --- /dev/null +++ b/solution/2400-2499/2485.Find the Pivot Integer/Solution2.ts @@ -0,0 +1,5 @@ +function pivotInteger(n: number): number { + const y = Math.floor((n * (n + 1)) / 2); + const x = Math.floor(Math.sqrt(y)); + return x * x === y ? x : -1; +} diff --git a/solution/2400-2499/2486.Append Characters to String to Make Subsequence/Solution.py b/solution/2400-2499/2486.Append Characters to String to Make Subsequence/Solution.py index d23af9b595e97..a96c10611b028 100644 --- a/solution/2400-2499/2486.Append Characters to String to Make Subsequence/Solution.py +++ b/solution/2400-2499/2486.Append Characters to String to Make Subsequence/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def appendCharacters(self, s: str, t: str) -> int: - i, m = 0, len(s) - for j, c in enumerate(t): - while i < m and s[i] != c: - i += 1 - if i == m: - return len(t) - j - i += 1 - return 0 +class Solution: + def appendCharacters(self, s: str, t: str) -> int: + i, m = 0, len(s) + for j, c in enumerate(t): + while i < m and s[i] != c: + i += 1 + if i == m: + return len(t) - j + i += 1 + return 0 diff --git a/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.cpp b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.cpp index cf1351b6e3eb6..c83217c597632 100644 --- a/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.cpp +++ b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.cpp @@ -1,26 +1,34 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* removeNodes(ListNode* head) { - ListNode* dummy = new ListNode(1e9, head); - ListNode* cur = head; - vector stk = {dummy}; - for (ListNode* cur = head; cur; cur = cur->next) { - while (stk.back()->val < cur->val) { - stk.pop_back(); - } - stk.back()->next = cur; - stk.push_back(cur); - } - return dummy->next; - } +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeNodes(ListNode* head) { + vector nums; + while (head) { + nums.emplace_back(head->val); + head = head->next; + } + vector stk; + for (int v : nums) { + while (!stk.empty() && stk.back() < v) { + stk.pop_back(); + } + stk.push_back(v); + } + ListNode* dummy = new ListNode(); + head = dummy; + for (int v : stk) { + head->next = new ListNode(v); + head = head->next; + } + return dummy->next; + } }; \ No newline at end of file diff --git a/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.go b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.go index 9a4bb565bc837..fcefffa532460 100644 --- a/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.go +++ b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.go @@ -6,14 +6,23 @@ * } */ func removeNodes(head *ListNode) *ListNode { - dummy := &ListNode{1 << 30, head} - stk := []*ListNode{dummy} - for cur := head; cur != nil; cur = cur.Next { - for stk[len(stk)-1].Val < cur.Val { + nums := []int{} + for head != nil { + nums = append(nums, head.Val) + head = head.Next + } + stk := []int{} + for _, v := range nums { + for len(stk) > 0 && stk[len(stk)-1] < v { stk = stk[:len(stk)-1] } - stk[len(stk)-1].Next = cur - stk = append(stk, cur) + stk = append(stk, v) + } + dummy := &ListNode{} + head = dummy + for _, v := range stk { + head.Next = &ListNode{Val: v} + head = head.Next } return dummy.Next } \ No newline at end of file diff --git a/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.java b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.java index 404408aa83cfa..a4c6164028053 100644 --- a/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.java +++ b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.java @@ -1,25 +1,33 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode removeNodes(ListNode head) { - ListNode dummy = new ListNode(1 << 30, head); - Deque stk = new ArrayDeque<>(); - stk.offerLast(dummy); - for (ListNode cur = head; cur != null; cur = cur.next) { - while (stk.peekLast().val < cur.val) { - stk.pollLast(); - } - stk.peekLast().next = cur; - stk.offerLast(cur); - } - return dummy.next; - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode removeNodes(ListNode head) { + List nums = new ArrayList<>(); + while (head != null) { + nums.add(head.val); + head = head.next; + } + Deque stk = new ArrayDeque<>(); + for (int v : nums) { + while (!stk.isEmpty() && stk.peekLast() < v) { + stk.pollLast(); + } + stk.offerLast(v); + } + ListNode dummy = new ListNode(); + head = dummy; + while (!stk.isEmpty()) { + head.next = new ListNode(stk.pollFirst()); + head = head.next; + } + return dummy.next; + } } \ No newline at end of file diff --git a/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.py b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.py index e8cbd596639a6..b11db0144e316 100644 --- a/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.py +++ b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.py @@ -1,17 +1,22 @@ -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: - dummy = ListNode(inf, head) - cur = head - stk = [dummy] - while cur: - while stk[-1].val < cur.val: - stk.pop() - stk[-1].next = cur - stk.append(cur) - cur = cur.next - return dummy.next +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: + nums = [] + while head: + nums.append(head.val) + head = head.next + stk = [] + for v in nums: + while stk and stk[-1] < v: + stk.pop() + stk.append(v) + dummy = ListNode() + head = dummy + for v in stk: + head.next = ListNode(v) + head = head.next + return dummy.next diff --git a/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.ts b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.ts index fd149b2ca61e9..04fdb565be8b5 100644 --- a/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.ts +++ b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution.ts @@ -11,14 +11,22 @@ */ function removeNodes(head: ListNode | null): ListNode | null { - const dummy = new ListNode(Infinity, head); - const stk: ListNode[] = [dummy]; - for (let cur = head; cur; cur = cur.next) { - while (stk.at(-1)!.val < cur.val) { + const nums = []; + for (; head; head = head.next) { + nums.push(head.val); + } + const stk: number[] = []; + for (const v of nums) { + while (stk.length && stk.at(-1)! < v) { stk.pop(); } - stk.at(-1)!.next = cur; - stk.push(cur); + stk.push(v); + } + const dummy = new ListNode(); + head = dummy; + for (const v of stk) { + head.next = new ListNode(v); + head = head.next; } return dummy.next; } diff --git a/solution/2400-2499/2487.Remove Nodes From Linked List/Solution2.cpp b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution2.cpp new file mode 100644 index 0000000000000..64b10afc32f43 --- /dev/null +++ b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution2.cpp @@ -0,0 +1,26 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeNodes(ListNode* head) { + ListNode* dummy = new ListNode(1e9, head); + ListNode* cur = head; + vector stk = {dummy}; + for (ListNode* cur = head; cur; cur = cur->next) { + while (stk.back()->val < cur->val) { + stk.pop_back(); + } + stk.back()->next = cur; + stk.push_back(cur); + } + return dummy->next; + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2487.Remove Nodes From Linked List/Solution2.go b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution2.go new file mode 100644 index 0000000000000..9a4bb565bc837 --- /dev/null +++ b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution2.go @@ -0,0 +1,19 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func removeNodes(head *ListNode) *ListNode { + dummy := &ListNode{1 << 30, head} + stk := []*ListNode{dummy} + for cur := head; cur != nil; cur = cur.Next { + for stk[len(stk)-1].Val < cur.Val { + stk = stk[:len(stk)-1] + } + stk[len(stk)-1].Next = cur + stk = append(stk, cur) + } + return dummy.Next +} \ No newline at end of file diff --git a/solution/2400-2499/2487.Remove Nodes From Linked List/Solution2.java b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution2.java new file mode 100644 index 0000000000000..b446a4f45f8fc --- /dev/null +++ b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution2.java @@ -0,0 +1,25 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode removeNodes(ListNode head) { + ListNode dummy = new ListNode(1 << 30, head); + Deque stk = new ArrayDeque<>(); + stk.offerLast(dummy); + for (ListNode cur = head; cur != null; cur = cur.next) { + while (stk.peekLast().val < cur.val) { + stk.pollLast(); + } + stk.peekLast().next = cur; + stk.offerLast(cur); + } + return dummy.next; + } +} \ No newline at end of file diff --git a/solution/2400-2499/2487.Remove Nodes From Linked List/Solution2.py b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution2.py new file mode 100644 index 0000000000000..084da602cfdb5 --- /dev/null +++ b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution2.py @@ -0,0 +1,17 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: + dummy = ListNode(inf, head) + cur = head + stk = [dummy] + while cur: + while stk[-1].val < cur.val: + stk.pop() + stk[-1].next = cur + stk.append(cur) + cur = cur.next + return dummy.next diff --git a/solution/2400-2499/2487.Remove Nodes From Linked List/Solution2.ts b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution2.ts new file mode 100644 index 0000000000000..fd149b2ca61e9 --- /dev/null +++ b/solution/2400-2499/2487.Remove Nodes From Linked List/Solution2.ts @@ -0,0 +1,24 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function removeNodes(head: ListNode | null): ListNode | null { + const dummy = new ListNode(Infinity, head); + const stk: ListNode[] = [dummy]; + for (let cur = head; cur; cur = cur.next) { + while (stk.at(-1)!.val < cur.val) { + stk.pop(); + } + stk.at(-1)!.next = cur; + stk.push(cur); + } + return dummy.next; +} diff --git a/solution/2400-2499/2490.Circular Sentence/Solution.cpp b/solution/2400-2499/2490.Circular Sentence/Solution.cpp index 65be8486be31a..d173b13ca3ca5 100644 --- a/solution/2400-2499/2490.Circular Sentence/Solution.cpp +++ b/solution/2400-2499/2490.Circular Sentence/Solution.cpp @@ -1,15 +1,23 @@ -class Solution { -public: - bool isCircularSentence(string s) { - int n = s.size(); - if (s[0] != s.back()) { - return false; - } - for (int i = 1; i < n; ++i) { - if (s[i] == ' ' && s[i - 1] != s[i + 1]) { - return false; - } - } - return true; - } +class Solution { +public: + bool isCircularSentence(string sentence) { + auto ss = split(sentence, ' '); + int n = ss.size(); + for (int i = 0; i < n; ++i) { + if (ss[i].back() != ss[(i + 1) % n][0]) { + return false; + } + } + return true; + } + + vector split(string& s, char delim) { + stringstream ss(s); + string item; + vector res; + while (getline(ss, item, delim)) { + res.emplace_back(item); + } + return res; + } }; \ No newline at end of file diff --git a/solution/2400-2499/2490.Circular Sentence/Solution.go b/solution/2400-2499/2490.Circular Sentence/Solution.go index bbfb7f8893370..7f7d410a67c16 100644 --- a/solution/2400-2499/2490.Circular Sentence/Solution.go +++ b/solution/2400-2499/2490.Circular Sentence/Solution.go @@ -1,10 +1,8 @@ -func isCircularSentence(s string) bool { - n := len(s) - if s[0] != s[n-1] { - return false - } - for i := 1; i < n; i++ { - if s[i] == ' ' && s[i-1] != s[i+1] { +func isCircularSentence(sentence string) bool { + ss := strings.Split(sentence, " ") + n := len(ss) + for i, s := range ss { + if s[len(s)-1] != ss[(i+1)%n][0] { return false } } diff --git a/solution/2400-2499/2490.Circular Sentence/Solution.java b/solution/2400-2499/2490.Circular Sentence/Solution.java index 313e6ee1cccb3..e0acf17b0e7a7 100644 --- a/solution/2400-2499/2490.Circular Sentence/Solution.java +++ b/solution/2400-2499/2490.Circular Sentence/Solution.java @@ -1,14 +1,12 @@ -class Solution { - public boolean isCircularSentence(String s) { - int n = s.length(); - if (s.charAt(0) != s.charAt(n - 1)) { - return false; - } - for (int i = 1; i < n; ++i) { - if (s.charAt(i) == ' ' && s.charAt(i - 1) != s.charAt(i + 1)) { - return false; - } - } - return true; - } +class Solution { + public boolean isCircularSentence(String sentence) { + var ss = sentence.split(" "); + int n = ss.length; + for (int i = 0; i < n; ++i) { + if (ss[i].charAt(ss[i].length() - 1) != ss[(i + 1) % n].charAt(0)) { + return false; + } + } + return true; + } } \ No newline at end of file diff --git a/solution/2400-2499/2490.Circular Sentence/Solution.js b/solution/2400-2499/2490.Circular Sentence/Solution.js index 9ec909f1f96e3..15941798faaa4 100644 --- a/solution/2400-2499/2490.Circular Sentence/Solution.js +++ b/solution/2400-2499/2490.Circular Sentence/Solution.js @@ -1,14 +1,12 @@ /** - * @param {string} s + * @param {string} sentence * @return {boolean} */ -var isCircularSentence = function (s) { - const n = s.length; - if (s[0] !== s[n - 1]) { - return false; - } - for (let i = 1; i < n; ++i) { - if (s[i] === ' ' && s[i - 1] !== s[i + 1]) { +var isCircularSentence = function (sentence) { + const ss = sentence.split(' '); + const n = ss.length; + for (let i = 0; i < n; ++i) { + if (ss[i][ss[i].length - 1] !== ss[(i + 1) % n][0]) { return false; } } diff --git a/solution/2400-2499/2490.Circular Sentence/Solution.py b/solution/2400-2499/2490.Circular Sentence/Solution.py index ead19573673e2..15e5a4902ddfd 100644 --- a/solution/2400-2499/2490.Circular Sentence/Solution.py +++ b/solution/2400-2499/2490.Circular Sentence/Solution.py @@ -1,5 +1,5 @@ -class Solution: - def isCircularSentence(self, s: str) -> bool: - return s[0] == s[-1] and all( - c != " " or s[i - 1] == s[i + 1] for i, c in enumerate(s) - ) +class Solution: + def isCircularSentence(self, sentence: str) -> bool: + ss = sentence.split() + n = len(ss) + return all(s[-1] == ss[(i + 1) % n][0] for i, s in enumerate(ss)) diff --git a/solution/2400-2499/2490.Circular Sentence/Solution.ts b/solution/2400-2499/2490.Circular Sentence/Solution.ts index fd7c3f19a1a62..3dc0c0b8a006e 100644 --- a/solution/2400-2499/2490.Circular Sentence/Solution.ts +++ b/solution/2400-2499/2490.Circular Sentence/Solution.ts @@ -1,10 +1,8 @@ -function isCircularSentence(s: string): boolean { - const n = s.length; - if (s[0] !== s[n - 1]) { - return false; - } - for (let i = 1; i < n; ++i) { - if (s[i] === ' ' && s[i - 1] !== s[i + 1]) { +function isCircularSentence(sentence: string): boolean { + const ss = sentence.split(' '); + const n = ss.length; + for (let i = 0; i < n; ++i) { + if (ss[i][ss[i].length - 1] !== ss[(i + 1) % n][0]) { return false; } } diff --git a/solution/2400-2499/2490.Circular Sentence/Solution2.cpp b/solution/2400-2499/2490.Circular Sentence/Solution2.cpp new file mode 100644 index 0000000000000..b69f51f23a5ad --- /dev/null +++ b/solution/2400-2499/2490.Circular Sentence/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + bool isCircularSentence(string s) { + int n = s.size(); + if (s[0] != s.back()) { + return false; + } + for (int i = 1; i < n; ++i) { + if (s[i] == ' ' && s[i - 1] != s[i + 1]) { + return false; + } + } + return true; + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2490.Circular Sentence/Solution2.go b/solution/2400-2499/2490.Circular Sentence/Solution2.go new file mode 100644 index 0000000000000..bbfb7f8893370 --- /dev/null +++ b/solution/2400-2499/2490.Circular Sentence/Solution2.go @@ -0,0 +1,12 @@ +func isCircularSentence(s string) bool { + n := len(s) + if s[0] != s[n-1] { + return false + } + for i := 1; i < n; i++ { + if s[i] == ' ' && s[i-1] != s[i+1] { + return false + } + } + return true +} \ No newline at end of file diff --git a/solution/2400-2499/2490.Circular Sentence/Solution2.java b/solution/2400-2499/2490.Circular Sentence/Solution2.java new file mode 100644 index 0000000000000..6d1a3ce473f69 --- /dev/null +++ b/solution/2400-2499/2490.Circular Sentence/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public boolean isCircularSentence(String s) { + int n = s.length(); + if (s.charAt(0) != s.charAt(n - 1)) { + return false; + } + for (int i = 1; i < n; ++i) { + if (s.charAt(i) == ' ' && s.charAt(i - 1) != s.charAt(i + 1)) { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/solution/2400-2499/2490.Circular Sentence/Solution2.js b/solution/2400-2499/2490.Circular Sentence/Solution2.js new file mode 100644 index 0000000000000..9ec909f1f96e3 --- /dev/null +++ b/solution/2400-2499/2490.Circular Sentence/Solution2.js @@ -0,0 +1,16 @@ +/** + * @param {string} s + * @return {boolean} + */ +var isCircularSentence = function (s) { + const n = s.length; + if (s[0] !== s[n - 1]) { + return false; + } + for (let i = 1; i < n; ++i) { + if (s[i] === ' ' && s[i - 1] !== s[i + 1]) { + return false; + } + } + return true; +}; diff --git a/solution/2400-2499/2490.Circular Sentence/Solution2.py b/solution/2400-2499/2490.Circular Sentence/Solution2.py new file mode 100644 index 0000000000000..5baefc9398b61 --- /dev/null +++ b/solution/2400-2499/2490.Circular Sentence/Solution2.py @@ -0,0 +1,5 @@ +class Solution: + def isCircularSentence(self, s: str) -> bool: + return s[0] == s[-1] and all( + c != " " or s[i - 1] == s[i + 1] for i, c in enumerate(s) + ) diff --git a/solution/2400-2499/2490.Circular Sentence/Solution2.rs b/solution/2400-2499/2490.Circular Sentence/Solution2.rs new file mode 100644 index 0000000000000..62475285797e5 --- /dev/null +++ b/solution/2400-2499/2490.Circular Sentence/Solution2.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn is_circular_sentence(sentence: String) -> bool { + let n = sentence.len(); + let chars: Vec = sentence.chars().collect(); + + if chars[0] != chars[n - 1] { + return false; + } + + for i in 1..n - 1 { + if chars[i] == ' ' && chars[i - 1] != chars[i + 1] { + return false; + } + } + + true + } +} diff --git a/solution/2400-2499/2490.Circular Sentence/Solution2.ts b/solution/2400-2499/2490.Circular Sentence/Solution2.ts new file mode 100644 index 0000000000000..fd7c3f19a1a62 --- /dev/null +++ b/solution/2400-2499/2490.Circular Sentence/Solution2.ts @@ -0,0 +1,12 @@ +function isCircularSentence(s: string): boolean { + const n = s.length; + if (s[0] !== s[n - 1]) { + return false; + } + for (let i = 1; i < n; ++i) { + if (s[i] === ' ' && s[i - 1] !== s[i + 1]) { + return false; + } + } + return true; +} diff --git a/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/Solution2.cpp b/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/Solution2.cpp new file mode 100644 index 0000000000000..98214cb731549 --- /dev/null +++ b/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/Solution2.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + long long dividePlayers(vector& skill) { + int s = accumulate(skill.begin(), skill.end(), 0); + int m = skill.size() / 2; + if (s % m) return -1; + int t = s / m; + int d[1010] = {0}; + long long ans = 0; + for (int& v : skill) { + if (d[t - v]) { + ans += 1ll * v * (t - v); + --d[t - v]; + --m; + } else { + ++d[v]; + } + } + return m == 0 ? ans : -1; + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/Solution2.go b/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/Solution2.go new file mode 100644 index 0000000000000..cf1b45d90e049 --- /dev/null +++ b/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/Solution2.go @@ -0,0 +1,26 @@ +func dividePlayers(skill []int) int64 { + s := 0 + for _, v := range skill { + s += v + } + m := len(skill) >> 1 + if s%m != 0 { + return -1 + } + t := s / m + d := [1010]int{} + ans := 0 + for _, v := range skill { + if d[t-v] > 0 { + ans += v * (t - v) + d[t-v]-- + m-- + } else { + d[v]++ + } + } + if m == 0 { + return int64(ans) + } + return -1 +} \ No newline at end of file diff --git a/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/Solution2.java b/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/Solution2.java new file mode 100644 index 0000000000000..f221de450ce40 --- /dev/null +++ b/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/Solution2.java @@ -0,0 +1,22 @@ +class Solution { + public long dividePlayers(int[] skill) { + int s = Arrays.stream(skill).sum(); + int m = skill.length >> 1; + if (s % m != 0) { + return -1; + } + int t = s / m; + int[] d = new int[1010]; + long ans = 0; + for (int v : skill) { + if (d[t - v] > 0) { + ans += (long) v * (t - v); + --d[t - v]; + --m; + } else { + ++d[v]; + } + } + return m == 0 ? ans : -1; + } +} \ No newline at end of file diff --git a/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/Solution2.py b/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/Solution2.py new file mode 100644 index 0000000000000..fea45e3ff8963 --- /dev/null +++ b/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def dividePlayers(self, skill: List[int]) -> int: + s = sum(skill) + m = len(skill) >> 1 + if s % m: + return -1 + t = s // m + d = defaultdict(int) + ans = 0 + for v in skill: + if d[t - v]: + ans += v * (t - v) + m -= 1 + d[t - v] -= 1 + else: + d[v] += 1 + return -1 if m else ans diff --git a/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/Solution2.cpp b/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/Solution2.cpp new file mode 100644 index 0000000000000..dfef5ae252ba1 --- /dev/null +++ b/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/Solution2.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int minScore(int n, vector>& roads) { + vector>> g(n); + bool vis[n]; + memset(vis, 0, sizeof vis); + for (auto& e : roads) { + int a = e[0] - 1, b = e[1] - 1, d = e[2]; + g[a].emplace_back(b, d); + g[b].emplace_back(a, d); + } + int ans = INT_MAX; + queue q{{0}}; + vis[0] = true; + while (!q.empty()) { + for (int k = q.size(); k; --k) { + int i = q.front(); + q.pop(); + for (auto [j, d] : g[i]) { + ans = min(ans, d); + if (!vis[j]) { + vis[j] = true; + q.push(j); + } + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/Solution2.go b/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/Solution2.go new file mode 100644 index 0000000000000..9def1d3e4db6e --- /dev/null +++ b/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/Solution2.go @@ -0,0 +1,28 @@ +func minScore(n int, roads [][]int) int { + type pair struct{ i, v int } + g := make([][]pair, n) + for _, e := range roads { + a, b, d := e[0]-1, e[1]-1, e[2] + g[a] = append(g[a], pair{b, d}) + g[b] = append(g[b], pair{a, d}) + } + vis := make([]bool, n) + ans := 1 << 30 + q := []int{0} + vis[0] = true + for len(q) > 0 { + for k := len(q); k > 0; k-- { + i := q[0] + q = q[1:] + for _, nxt := range g[i] { + j, d := nxt.i, nxt.v + ans = min(ans, d) + if !vis[j] { + vis[j] = true + q = append(q, j) + } + } + } + } + return ans +} \ No newline at end of file diff --git a/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/Solution2.java b/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/Solution2.java new file mode 100644 index 0000000000000..e2ac8e71eea9a --- /dev/null +++ b/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/Solution2.java @@ -0,0 +1,30 @@ +class Solution { + public int minScore(int n, int[][] roads) { + List[] g = new List[n]; + boolean[] vis = new boolean[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (var e : roads) { + int a = e[0] - 1, b = e[1] - 1, d = e[2]; + g[a].add(new int[] {b, d}); + g[b].add(new int[] {a, d}); + } + Deque q = new ArrayDeque<>(); + q.offer(0); + vis[0] = true; + int ans = 1 << 30; + while (!q.isEmpty()) { + for (int k = q.size(); k > 0; --k) { + int i = q.pollFirst(); + for (var nxt : g[i]) { + int j = nxt[0], d = nxt[1]; + ans = Math.min(ans, d); + if (!vis[j]) { + vis[j] = true; + q.offer(j); + } + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/Solution2.py b/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/Solution2.py new file mode 100644 index 0000000000000..1de67c607c20d --- /dev/null +++ b/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/Solution2.py @@ -0,0 +1,19 @@ +class Solution: + def minScore(self, n: int, roads: List[List[int]]) -> int: + g = defaultdict(list) + for a, b, d in roads: + g[a].append((b, d)) + g[b].append((a, d)) + vis = [False] * (n + 1) + vis[1] = True + ans = inf + q = deque([1]) + while q: + for _ in range(len(q)): + i = q.popleft() + for j, d in g[i]: + ans = min(ans, d) + if not vis[j]: + vis[j] = True + q.append(j) + return ans diff --git a/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.c b/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.c index 7025592a8f869..c91d3d9894c90 100644 --- a/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.c +++ b/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.c @@ -19,4 +19,4 @@ int maximumValue(char** strs, int strsSize) { ans = max(ans, num); } return ans; -} +} \ No newline at end of file diff --git a/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.cpp b/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.cpp index 59eae82ba1e8d..1df3c0314ba64 100644 --- a/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.cpp +++ b/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - int maximumValue(vector& strs) { - auto f = [](string& s) { - int x = 0; - for (char& c : s) { - if (!isdigit(c)) { - return (int) s.size(); - } - x = x * 10 + c - '0'; - } - return x; - }; - int ans = 0; - for (auto& s : strs) { - ans = max(ans, f(s)); - } - return ans; - } +class Solution { +public: + int maximumValue(vector& strs) { + auto f = [](string& s) { + int x = 0; + for (char& c : s) { + if (!isdigit(c)) { + return (int) s.size(); + } + x = x * 10 + c - '0'; + } + return x; + }; + int ans = 0; + for (auto& s : strs) { + ans = max(ans, f(s)); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.cs b/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.cs index c66524ddcd654..9741ced8a5837 100644 --- a/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.cs +++ b/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.cs @@ -1,16 +1,16 @@ -public class Solution { - public int MaximumValue(string[] strs) { - return strs.Max(f); - } - - private int f(string s) { - int x = 0; - foreach (var c in s) { - if (c >= 'a') { - return s.Length; - } - x = x * 10 + (c - '0'); - } - return x; - } -} \ No newline at end of file +public class Solution { + public int MaximumValue(string[] strs) { + return strs.Max(f); + } + + private int f(string s) { + int x = 0; + foreach (var c in s) { + if (c >= 'a') { + return s.Length; + } + x = x * 10 + (c - '0'); + } + return x; + } +} diff --git a/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.java b/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.java index c7b49eeb208f9..423d0a93712c4 100644 --- a/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.java +++ b/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.java @@ -1,21 +1,21 @@ -class Solution { - public int maximumValue(String[] strs) { - int ans = 0; - for (var s : strs) { - ans = Math.max(ans, f(s)); - } - return ans; - } - - private int f(String s) { - int x = 0; - for (int i = 0, n = s.length(); i < n; ++i) { - char c = s.charAt(i); - if (Character.isLetter(c)) { - return n; - } - x = x * 10 + (c - '0'); - } - return x; - } +class Solution { + public int maximumValue(String[] strs) { + int ans = 0; + for (var s : strs) { + ans = Math.max(ans, f(s)); + } + return ans; + } + + private int f(String s) { + int x = 0; + for (int i = 0, n = s.length(); i < n; ++i) { + char c = s.charAt(i); + if (Character.isLetter(c)) { + return n; + } + x = x * 10 + (c - '0'); + } + return x; + } } \ No newline at end of file diff --git a/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.py b/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.py index 4ee57fe9c8d7c..d4572a8d089e5 100644 --- a/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.py +++ b/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution.py @@ -1,6 +1,6 @@ -class Solution: - def maximumValue(self, strs: List[str]) -> int: - def f(s: str) -> int: - return int(s) if all(c.isdigit() for c in s) else len(s) - - return max(f(s) for s in strs) +class Solution: + def maximumValue(self, strs: List[str]) -> int: + def f(s: str) -> int: + return int(s) if all(c.isdigit() for c in s) else len(s) + + return max(f(s) for s in strs) diff --git a/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution2.py b/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution2.py new file mode 100644 index 0000000000000..ae300c0d5a472 --- /dev/null +++ b/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def maximumValue(self, strs: List[str]) -> int: + def f(s: str) -> int: + x = 0 + for c in s: + if c.isalpha(): + return len(s) + x = x * 10 + ord(c) - ord("0") + return x + + return max(f(s) for s in strs) diff --git a/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution2.rs b/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution2.rs new file mode 100644 index 0000000000000..f9f9d64a10cab --- /dev/null +++ b/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution2.rs @@ -0,0 +1,28 @@ +impl Solution { + pub fn maximum_value(strs: Vec) -> i32 { + let parse = |s: String| -> i32 { + let mut x = 0; + + for c in s.chars() { + if c >= 'a' && c <= 'z' { + x = s.len(); + break; + } + + x = x * 10 + (((c as u8) - b'0') as usize); + } + + x as i32 + }; + + let mut ans = 0; + for s in strs { + let v = parse(s); + if v > ans { + ans = v; + } + } + + ans + } +} diff --git a/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution3.rs b/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution3.rs new file mode 100644 index 0000000000000..6dd7804323882 --- /dev/null +++ b/solution/2400-2499/2496.Maximum Value of a String in an Array/Solution3.rs @@ -0,0 +1,20 @@ +use std::cmp::max; + +impl Solution { + pub fn maximum_value(strs: Vec) -> i32 { + let mut ans = 0; + + for s in strs { + match s.parse::() { + Ok(v) => { + ans = max(ans, v); + } + Err(_) => { + ans = max(ans, s.len() as i32); + } + } + } + + ans + } +} diff --git a/solution/2500-2599/2501.Longest Square Streak in an Array/Solution.cpp b/solution/2500-2599/2501.Longest Square Streak in an Array/Solution.cpp index b4019d704d053..619f5422d823d 100644 --- a/solution/2500-2599/2501.Longest Square Streak in an Array/Solution.cpp +++ b/solution/2500-2599/2501.Longest Square Streak in an Array/Solution.cpp @@ -1,41 +1,17 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int countGreatEnoughNodes(TreeNode* root, int k) { - int ans = 0; - function(TreeNode*)> dfs = [&](TreeNode* root) { - if (!root) { - return priority_queue(); - } - auto left = dfs(root->left); - auto right = dfs(root->right); - while (right.size()) { - left.push(right.top()); - right.pop(); - if (left.size() > k) { - left.pop(); - } - } - if (left.size() == k && left.top() < root->val) { - ++ans; - } - left.push(root->val); - if (left.size() > k) { - left.pop(); - } - return left; - }; - dfs(root); - return ans; - } +class Solution { +public: + int longestSquareStreak(vector& nums) { + unordered_set s(nums.begin(), nums.end()); + int ans = -1; + for (int& v : nums) { + int t = 0; + long long x = v; + while (s.count(x)) { + x *= x; + ++t; + } + if (t > 1) ans = max(ans, t); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2500-2599/2501.Longest Square Streak in an Array/Solution.go b/solution/2500-2599/2501.Longest Square Streak in an Array/Solution.go index bd7f270e88234..f611bb5353c46 100644 --- a/solution/2500-2599/2501.Longest Square Streak in an Array/Solution.go +++ b/solution/2500-2599/2501.Longest Square Streak in an Array/Solution.go @@ -1,46 +1,18 @@ -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func countGreatEnoughNodes(root *TreeNode, k int) (ans int) { - var dfs func(*TreeNode) hp - dfs = func(root *TreeNode) hp { - if root == nil { - return hp{} - } - l, r := dfs(root.Left), dfs(root.Right) - for _, x := range r.IntSlice { - l.push(x) - if l.Len() > k { - l.pop() - } - } - if l.Len() == k && root.Val > l.IntSlice[0] { - ans++ +func longestSquareStreak(nums []int) int { + s := map[int]bool{} + for _, v := range nums { + s[v] = true + } + ans := -1 + for _, v := range nums { + t := 0 + for s[v] { + v *= v + t++ } - l.push(root.Val) - if l.Len() > k { - l.pop() + if t > 1 && t > ans { + ans = t } - return l } - dfs(root) - return -} - -type hp struct{ sort.IntSlice } - -func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } -func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) } -func (h *hp) Pop() any { - a := h.IntSlice - v := a[len(a)-1] - h.IntSlice = a[:len(a)-1] - return v -} -func (h *hp) push(v int) { heap.Push(h, v) } -func (h *hp) pop() int { return heap.Pop(h).(int) } \ No newline at end of file + return ans +} \ No newline at end of file diff --git a/solution/2500-2599/2501.Longest Square Streak in an Array/Solution2.cpp b/solution/2500-2599/2501.Longest Square Streak in an Array/Solution2.cpp new file mode 100644 index 0000000000000..428b56ade443a --- /dev/null +++ b/solution/2500-2599/2501.Longest Square Streak in an Array/Solution2.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int longestSquareStreak(vector& nums) { + unordered_set s(nums.begin(), nums.end()); + int ans = 0; + unordered_map f; + function dfs = [&](int x) -> int { + if (!s.count(x)) return 0; + if (f.count(x)) return f[x]; + long long t = 1ll * x * x; + if (t > INT_MAX) return 1; + f[x] = 1 + dfs(x * x); + return f[x]; + }; + for (int& v : nums) ans = max(ans, dfs(v)); + return ans < 2 ? -1 : ans; + } +}; \ No newline at end of file diff --git a/solution/2500-2599/2501.Longest Square Streak in an Array/Solution2.go b/solution/2500-2599/2501.Longest Square Streak in an Array/Solution2.go new file mode 100644 index 0000000000000..627d8f43ac444 --- /dev/null +++ b/solution/2500-2599/2501.Longest Square Streak in an Array/Solution2.go @@ -0,0 +1,27 @@ +func longestSquareStreak(nums []int) (ans int) { + s := map[int]bool{} + for _, v := range nums { + s[v] = true + } + f := map[int]int{} + var dfs func(int) int + dfs = func(x int) int { + if !s[x] { + return 0 + } + if v, ok := f[x]; ok { + return v + } + f[x] = 1 + dfs(x*x) + return f[x] + } + for _, v := range nums { + if t := dfs(v); ans < t { + ans = t + } + } + if ans < 2 { + return -1 + } + return ans +} \ No newline at end of file diff --git a/solution/2500-2599/2501.Longest Square Streak in an Array/Solution2.java b/solution/2500-2599/2501.Longest Square Streak in an Array/Solution2.java new file mode 100644 index 0000000000000..428f30cd61025 --- /dev/null +++ b/solution/2500-2599/2501.Longest Square Streak in an Array/Solution2.java @@ -0,0 +1,27 @@ +class Solution { + private Map f = new HashMap<>(); + private Set s = new HashSet<>(); + + public int longestSquareStreak(int[] nums) { + for (int v : nums) { + s.add(v); + } + int ans = 0; + for (int v : nums) { + ans = Math.max(ans, dfs(v)); + } + return ans < 2 ? -1 : ans; + } + + private int dfs(int x) { + if (!s.contains(x)) { + return 0; + } + if (f.containsKey(x)) { + return f.get(x); + } + int ans = 1 + dfs(x * x); + f.put(x, ans); + return ans; + } +} \ No newline at end of file diff --git a/solution/2500-2599/2501.Longest Square Streak in an Array/Solution2.py b/solution/2500-2599/2501.Longest Square Streak in an Array/Solution2.py new file mode 100644 index 0000000000000..385f8b98c68bd --- /dev/null +++ b/solution/2500-2599/2501.Longest Square Streak in an Array/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def longestSquareStreak(self, nums: List[int]) -> int: + @cache + def dfs(x): + if x not in s: + return 0 + return 1 + dfs(x * x) + + s = set(nums) + ans = max(dfs(x) for x in nums) + return -1 if ans < 2 else ans diff --git a/solution/2500-2599/2502.Design Memory Allocator/Solution.cpp b/solution/2500-2599/2502.Design Memory Allocator/Solution.cpp index 37f87c034d5e1..eb13e16d55a8d 100644 --- a/solution/2500-2599/2502.Design Memory Allocator/Solution.cpp +++ b/solution/2500-2599/2502.Design Memory Allocator/Solution.cpp @@ -1,40 +1,41 @@ class Allocator { public: Allocator(int n) { - tm[-1] = -1; - tm[n] = n; + m = vector(n); } int allocate(int size, int mID) { - int s = -1; - for (auto& [v, c] : tm) { - if (s != -1) { - int e = v - 1; - if (e - s + 1 >= size) { - tm[s] = s + size - 1; - d[mID].emplace_back(s); - return s; - } + int cnt = 0; + for (int i = 0; i < m.size(); ++i) { + if (m[i]) { + cnt = 0; + } else if (++cnt == size) { + fill(i - size + 1, i + 1, mID); + return i - size + 1; } - s = c + 1; } return -1; } int free(int mID) { int ans = 0; - for (int& s : d[mID]) { - int e = tm[s]; - tm.erase(s); - ans += e - s + 1; + for (int i = 0; i < m.size(); ++i) { + if (m[i] == mID) { + m[i] = 0; + ++ans; + } } - d.erase(mID); return ans; } private: - map tm; - unordered_map> d; + vector m; + + void fill(int from, int to, int val) { + for (int i = from; i < to; ++i) { + m[i] = val; + } + } }; /** diff --git a/solution/2500-2599/2502.Design Memory Allocator/Solution.go b/solution/2500-2599/2502.Design Memory Allocator/Solution.go index 631739b839551..0ca6b59c2e198 100644 --- a/solution/2500-2599/2502.Design Memory Allocator/Solution.go +++ b/solution/2500-2599/2502.Design Memory Allocator/Solution.go @@ -1,43 +1,37 @@ type Allocator struct { - rbt *redblacktree.Tree - d map[int][]int + m []int } func Constructor(n int) Allocator { - rbt := redblacktree.NewWithIntComparator() - rbt.Put(-1, -1) - rbt.Put(n, n) - return Allocator{rbt, map[int][]int{}} + return Allocator{make([]int, n)} } func (this *Allocator) Allocate(size int, mID int) int { - s := -1 - it := this.rbt.Iterator() - for it.Next() { - v := it.Key().(int) - if s != -1 { - e := v - 1 - if e-s+1 >= size { - this.rbt.Put(s, s+size-1) - this.d[mID] = append(this.d[mID], s) - return s + cnt := 0 + for i, v := range this.m { + if v > 0 { + cnt = 0 + } else { + cnt++ + if cnt == size { + for j := i - size + 1; j <= i; j++ { + this.m[j] = mID + } + return i - size + 1 } } - s = it.Value().(int) + 1 } return -1 } -func (this *Allocator) Free(mID int) int { - ans := 0 - for _, s := range this.d[mID] { - if e, ok := this.rbt.Get(s); ok { - this.rbt.Remove(s) - ans += e.(int) - s + 1 +func (this *Allocator) Free(mID int) (ans int) { + for i, v := range this.m { + if v == mID { + this.m[i] = 0 + ans++ } } - this.d[mID] = []int{} - return ans + return } /** diff --git a/solution/2500-2599/2502.Design Memory Allocator/Solution.java b/solution/2500-2599/2502.Design Memory Allocator/Solution.java index 75b3c421a16b1..80093a11c9d50 100644 --- a/solution/2500-2599/2502.Design Memory Allocator/Solution.java +++ b/solution/2500-2599/2502.Design Memory Allocator/Solution.java @@ -1,36 +1,31 @@ class Allocator { - private TreeMap tm = new TreeMap<>(); - private Map> d = new HashMap<>(); + private int[] m; public Allocator(int n) { - tm.put(-1, -1); - tm.put(n, n); + m = new int[n]; } public int allocate(int size, int mID) { - int s = -1; - for (var entry : tm.entrySet()) { - int v = entry.getKey(); - if (s != -1) { - int e = v - 1; - if (e - s + 1 >= size) { - tm.put(s, s + size - 1); - d.computeIfAbsent(mID, k -> new ArrayList<>()).add(s); - return s; - } + int cnt = 0; + for (int i = 0; i < m.length; ++i) { + if (m[i] > 0) { + cnt = 0; + } else if (++cnt == size) { + Arrays.fill(m, i - size + 1, i + 1, mID); + return i - size + 1; } - s = entry.getValue() + 1; } return -1; } public int free(int mID) { int ans = 0; - for (int s : d.getOrDefault(mID, Collections.emptyList())) { - int e = tm.remove(s); - ans += e - s + 1; + for (int i = 0; i < m.length; ++i) { + if (m[i] == mID) { + m[i] = 0; + ++ans; + } } - d.remove(mID); return ans; } } diff --git a/solution/2500-2599/2502.Design Memory Allocator/Solution.py b/solution/2500-2599/2502.Design Memory Allocator/Solution.py index 22270a882204e..3a8d941cc466c 100644 --- a/solution/2500-2599/2502.Design Memory Allocator/Solution.py +++ b/solution/2500-2599/2502.Design Memory Allocator/Solution.py @@ -1,26 +1,25 @@ -from sortedcontainers import SortedList - - class Allocator: def __init__(self, n: int): - self.sl = SortedList([(-1, -1), (n, n)]) - self.d = defaultdict(list) + self.m = [0] * n def allocate(self, size: int, mID: int) -> int: - for (_, s), (e, _) in pairwise(self.sl): - s, e = s + 1, e - 1 - if e - s + 1 >= size: - self.sl.add((s, s + size - 1)) - self.d[mID].append((s, s + size - 1)) - return s + cnt = 0 + for i, v in enumerate(self.m): + if v: + cnt = 0 + else: + cnt += 1 + if cnt == size: + self.m[i - size + 1 : i + 1] = [mID] * size + return i - size + 1 return -1 def free(self, mID: int) -> int: ans = 0 - for block in self.d[mID]: - self.sl.remove(block) - ans += block[1] - block[0] + 1 - del self.d[mID] + for i, v in enumerate(self.m): + if v == mID: + self.m[i] = 0 + ans += 1 return ans diff --git a/solution/2500-2599/2502.Design Memory Allocator/Solution2.cpp b/solution/2500-2599/2502.Design Memory Allocator/Solution2.cpp new file mode 100644 index 0000000000000..37f87c034d5e1 --- /dev/null +++ b/solution/2500-2599/2502.Design Memory Allocator/Solution2.cpp @@ -0,0 +1,45 @@ +class Allocator { +public: + Allocator(int n) { + tm[-1] = -1; + tm[n] = n; + } + + int allocate(int size, int mID) { + int s = -1; + for (auto& [v, c] : tm) { + if (s != -1) { + int e = v - 1; + if (e - s + 1 >= size) { + tm[s] = s + size - 1; + d[mID].emplace_back(s); + return s; + } + } + s = c + 1; + } + return -1; + } + + int free(int mID) { + int ans = 0; + for (int& s : d[mID]) { + int e = tm[s]; + tm.erase(s); + ans += e - s + 1; + } + d.erase(mID); + return ans; + } + +private: + map tm; + unordered_map> d; +}; + +/** + * Your Allocator object will be instantiated and called as such: + * Allocator* obj = new Allocator(n); + * int param_1 = obj->allocate(size,mID); + * int param_2 = obj->free(mID); + */ \ No newline at end of file diff --git a/solution/2500-2599/2502.Design Memory Allocator/Solution2.go b/solution/2500-2599/2502.Design Memory Allocator/Solution2.go new file mode 100644 index 0000000000000..631739b839551 --- /dev/null +++ b/solution/2500-2599/2502.Design Memory Allocator/Solution2.go @@ -0,0 +1,48 @@ +type Allocator struct { + rbt *redblacktree.Tree + d map[int][]int +} + +func Constructor(n int) Allocator { + rbt := redblacktree.NewWithIntComparator() + rbt.Put(-1, -1) + rbt.Put(n, n) + return Allocator{rbt, map[int][]int{}} +} + +func (this *Allocator) Allocate(size int, mID int) int { + s := -1 + it := this.rbt.Iterator() + for it.Next() { + v := it.Key().(int) + if s != -1 { + e := v - 1 + if e-s+1 >= size { + this.rbt.Put(s, s+size-1) + this.d[mID] = append(this.d[mID], s) + return s + } + } + s = it.Value().(int) + 1 + } + return -1 +} + +func (this *Allocator) Free(mID int) int { + ans := 0 + for _, s := range this.d[mID] { + if e, ok := this.rbt.Get(s); ok { + this.rbt.Remove(s) + ans += e.(int) - s + 1 + } + } + this.d[mID] = []int{} + return ans +} + +/** + * Your Allocator object will be instantiated and called as such: + * obj := Constructor(n); + * param_1 := obj.Allocate(size,mID); + * param_2 := obj.Free(mID); + */ \ No newline at end of file diff --git a/solution/2500-2599/2502.Design Memory Allocator/Solution2.java b/solution/2500-2599/2502.Design Memory Allocator/Solution2.java new file mode 100644 index 0000000000000..75b3c421a16b1 --- /dev/null +++ b/solution/2500-2599/2502.Design Memory Allocator/Solution2.java @@ -0,0 +1,43 @@ +class Allocator { + private TreeMap tm = new TreeMap<>(); + private Map> d = new HashMap<>(); + + public Allocator(int n) { + tm.put(-1, -1); + tm.put(n, n); + } + + public int allocate(int size, int mID) { + int s = -1; + for (var entry : tm.entrySet()) { + int v = entry.getKey(); + if (s != -1) { + int e = v - 1; + if (e - s + 1 >= size) { + tm.put(s, s + size - 1); + d.computeIfAbsent(mID, k -> new ArrayList<>()).add(s); + return s; + } + } + s = entry.getValue() + 1; + } + return -1; + } + + public int free(int mID) { + int ans = 0; + for (int s : d.getOrDefault(mID, Collections.emptyList())) { + int e = tm.remove(s); + ans += e - s + 1; + } + d.remove(mID); + return ans; + } +} + +/** + * Your Allocator object will be instantiated and called as such: + * Allocator obj = new Allocator(n); + * int param_1 = obj.allocate(size,mID); + * int param_2 = obj.free(mID); + */ \ No newline at end of file diff --git a/solution/2500-2599/2502.Design Memory Allocator/Solution2.py b/solution/2500-2599/2502.Design Memory Allocator/Solution2.py new file mode 100644 index 0000000000000..22270a882204e --- /dev/null +++ b/solution/2500-2599/2502.Design Memory Allocator/Solution2.py @@ -0,0 +1,30 @@ +from sortedcontainers import SortedList + + +class Allocator: + def __init__(self, n: int): + self.sl = SortedList([(-1, -1), (n, n)]) + self.d = defaultdict(list) + + def allocate(self, size: int, mID: int) -> int: + for (_, s), (e, _) in pairwise(self.sl): + s, e = s + 1, e - 1 + if e - s + 1 >= size: + self.sl.add((s, s + size - 1)) + self.d[mID].append((s, s + size - 1)) + return s + return -1 + + def free(self, mID: int) -> int: + ans = 0 + for block in self.d[mID]: + self.sl.remove(block) + ans += block[1] - block[0] + 1 + del self.d[mID] + return ans + + +# Your Allocator object will be instantiated and called as such: +# obj = Allocator(n) +# param_1 = obj.allocate(size,mID) +# param_2 = obj.free(mID) diff --git a/solution/2500-2599/2503.Maximum Number of Points From Grid Queries/Solution2.py b/solution/2500-2599/2503.Maximum Number of Points From Grid Queries/Solution2.py new file mode 100644 index 0000000000000..bdc55851df917 --- /dev/null +++ b/solution/2500-2599/2503.Maximum Number of Points From Grid Queries/Solution2.py @@ -0,0 +1,32 @@ +class Solution: + def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]: + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + def union(a, b): + pa, pb = find(a), find(b) + if pa == pb: + return + p[pa] = pb + size[pb] += size[pa] + + m, n = len(grid), len(grid[0]) + arr = sorted((grid[i][j], i, j) for i in range(m) for j in range(n)) + k = len(queries) + ans = [0] * k + p = list(range(m * n)) + size = [1] * len(p) + j = 0 + for i, v in sorted(enumerate(queries), key=lambda x: x[1]): + while j < len(arr) and arr[j][0] < v: + _, a, b = arr[j] + for x, y in pairwise((-1, 0, 1, 0, -1)): + c, d = a + x, b + y + if 0 <= c < m and 0 <= d < n and grid[c][d] < v: + union(a * n + b, c * n + d) + j += 1 + if grid[0][0] < v: + ans[i] = size[find(0)] + return ans diff --git a/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/Solution2.rs b/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/Solution2.rs new file mode 100644 index 0000000000000..e45c3d8d4a370 --- /dev/null +++ b/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/Solution2.rs @@ -0,0 +1,29 @@ +impl Solution { + pub fn capture_forts(forts: Vec) -> i32 { + let mut ans = 0; + let mut i = 0; + + while + let Some((idx, &value)) = forts + .iter() + .enumerate() + .skip(i) + .find(|&(_, &x)| x != 0) + { + if + let Some((jdx, _)) = forts + .iter() + .enumerate() + .skip(idx + 1) + .find(|&(_, &x)| x != 0) + { + if value + forts[jdx] == 0 { + ans = ans.max(jdx - idx - 1); + } + } + i = idx + 1; + } + + ans as i32 + } +} diff --git a/solution/2500-2599/2512.Reward Top K Students/Solution.java b/solution/2500-2599/2512.Reward Top K Students/Solution.java index e75191ead3e5f..1f20bd0cece13 100644 --- a/solution/2500-2599/2512.Reward Top K Students/Solution.java +++ b/solution/2500-2599/2512.Reward Top K Students/Solution.java @@ -1,33 +1,33 @@ -class Solution { - public List topStudents(String[] positive_feedback, String[] negative_feedback, - String[] report, int[] student_id, int k) { - Set ps = new HashSet<>(); - Set ns = new HashSet<>(); - for (var s : positive_feedback) { - ps.add(s); - } - for (var s : negative_feedback) { - ns.add(s); - } - int n = report.length; - int[][] arr = new int[n][0]; - for (int i = 0; i < n; ++i) { - int sid = student_id[i]; - int t = 0; - for (var s : report[i].split(" ")) { - if (ps.contains(s)) { - t += 3; - } else if (ns.contains(s)) { - t -= 1; - } - } - arr[i] = new int[] {t, sid}; - } - Arrays.sort(arr, (a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]); - List ans = new ArrayList<>(); - for (int i = 0; i < k; ++i) { - ans.add(arr[i][1]); - } - return ans; - } +class Solution { + public List topStudents(String[] positive_feedback, String[] negative_feedback, + String[] report, int[] student_id, int k) { + Set ps = new HashSet<>(); + Set ns = new HashSet<>(); + for (var s : positive_feedback) { + ps.add(s); + } + for (var s : negative_feedback) { + ns.add(s); + } + int n = report.length; + int[][] arr = new int[n][0]; + for (int i = 0; i < n; ++i) { + int sid = student_id[i]; + int t = 0; + for (var s : report[i].split(" ")) { + if (ps.contains(s)) { + t += 3; + } else if (ns.contains(s)) { + t -= 1; + } + } + arr[i] = new int[] {t, sid}; + } + Arrays.sort(arr, (a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]); + List ans = new ArrayList<>(); + for (int i = 0; i < k; ++i) { + ans.add(arr[i][1]); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2500-2599/2514.Count Anagrams/Solution2.py b/solution/2500-2599/2514.Count Anagrams/Solution2.py new file mode 100644 index 0000000000000..60448951478f0 --- /dev/null +++ b/solution/2500-2599/2514.Count Anagrams/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def countAnagrams(self, s: str) -> int: + mod = 10**9 + 7 + ans = mul = 1 + for w in s.split(): + cnt = Counter() + for i, c in enumerate(w, 1): + cnt[c] += 1 + mul = mul * cnt[c] % mod + ans = ans * i % mod + return ans * pow(mul, -1, mod) % mod diff --git a/solution/2500-2599/2515.Shortest Distance to Target String in a Circular Array/Solution.c b/solution/2500-2599/2515.Shortest Distance to Target String in a Circular Array/Solution.c index 847e58784598b..e85d1928de6a6 100644 --- a/solution/2500-2599/2515.Shortest Distance to Target String in a Circular Array/Solution.c +++ b/solution/2500-2599/2515.Shortest Distance to Target String in a Circular Array/Solution.c @@ -5,4 +5,4 @@ int closetTarget(char** words, int wordsSize, char* target, int startIndex) { } } return -1; -} +} \ No newline at end of file diff --git a/solution/2500-2599/2515.Shortest Distance to Target String in a Circular Array/Solution2.rs b/solution/2500-2599/2515.Shortest Distance to Target String in a Circular Array/Solution2.rs new file mode 100644 index 0000000000000..c4af43593039e --- /dev/null +++ b/solution/2500-2599/2515.Shortest Distance to Target String in a Circular Array/Solution2.rs @@ -0,0 +1,20 @@ +use std::cmp::min; + +impl Solution { + pub fn closet_target(words: Vec, target: String, start_index: i32) -> i32 { + let mut ans = words.len(); + + for (i, w) in words.iter().enumerate() { + if *w == target { + let t = ((i as i32) - start_index).abs(); + ans = min(ans, min(t as usize, words.len() - (t as usize))); + } + } + + if ans == words.len() { + return -1; + } + + ans as i32 + } +} diff --git a/solution/2500-2599/2517.Maximum Tastiness of Candy Basket/Solution.cs b/solution/2500-2599/2517.Maximum Tastiness of Candy Basket/Solution.cs index cc93ecef77dd2..ad270865bc016 100644 --- a/solution/2500-2599/2517.Maximum Tastiness of Candy Basket/Solution.cs +++ b/solution/2500-2599/2517.Maximum Tastiness of Candy Basket/Solution.cs @@ -23,4 +23,4 @@ private bool check(int[] price, int x, int k) { } return cnt >= k; } -} \ No newline at end of file +} diff --git a/solution/2500-2599/2520.Count the Digits That Divide a Number/Solution.c b/solution/2500-2599/2520.Count the Digits That Divide a Number/Solution.c index 89f52b18e28a1..a75bd6cdba9c9 100644 --- a/solution/2500-2599/2520.Count the Digits That Divide a Number/Solution.c +++ b/solution/2500-2599/2520.Count the Digits That Divide a Number/Solution.c @@ -8,4 +8,4 @@ int countDigits(int num) { cur /= 10; } return ans; -} +} \ No newline at end of file diff --git a/solution/2500-2599/2520.Count the Digits That Divide a Number/Solution2.rs b/solution/2500-2599/2520.Count the Digits That Divide a Number/Solution2.rs new file mode 100644 index 0000000000000..9283826149bd4 --- /dev/null +++ b/solution/2500-2599/2520.Count the Digits That Divide a Number/Solution2.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn count_digits(num: i32) -> i32 { + num + .to_string() + .chars() + .filter(|&c| c != '0') + .filter(|&c| num % (c.to_digit(10).unwrap() as i32) == 0) + .count() as i32 + } +} diff --git a/solution/2500-2599/2520.Count the Digits That Divide a Number/Solution2.ts b/solution/2500-2599/2520.Count the Digits That Divide a Number/Solution2.ts new file mode 100644 index 0000000000000..e82445b639d15 --- /dev/null +++ b/solution/2500-2599/2520.Count the Digits That Divide a Number/Solution2.ts @@ -0,0 +1,9 @@ +function countDigits(num: number): number { + let ans = 0; + for (const s of num.toString()) { + if (num % Number(s) === 0) { + ans++; + } + } + return ans; +} diff --git a/solution/2500-2599/2524.Maximum Frequency Score of a Subarray/Solution.cpp b/solution/2500-2599/2524.Maximum Frequency Score of a Subarray/Solution.cpp index bb758608a78bb..853ea3acc3f23 100644 --- a/solution/2500-2599/2524.Maximum Frequency Score of a Subarray/Solution.cpp +++ b/solution/2500-2599/2524.Maximum Frequency Score of a Subarray/Solution.cpp @@ -1,38 +1,38 @@ -class Solution { -public: - int maxFrequencyScore(vector& nums, int k) { - using ll = long long; - const int mod = 1e9 + 7; - auto qpow = [&](ll a, ll n) { - ll ans = 1; - for (; n; n >>= 1) { - if (n & 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return ans; - }; - unordered_map cnt; - for (int i = 0; i < k; ++i) { - cnt[nums[i]]++; - } - ll cur = 0; - for (auto& [k, v] : cnt) { - cur = (cur + qpow(k, v)) % mod; - } - ll ans = cur; - for (int i = k; i < nums.size(); ++i) { - int a = nums[i - k], b = nums[i]; - if (a != b) { - cur += cnt[b] ? (b - 1) * qpow(b, cnt[b]) % mod : b; - cur -= cnt[a] > 1 ? (a - 1) * qpow(a, cnt[a] - 1) % mod : a; - cur = (cur + mod) % mod; - ans = max(ans, cur); - cnt[b]++; - cnt[a]--; - } - } - return ans; - } +class Solution { +public: + int maxFrequencyScore(vector& nums, int k) { + using ll = long long; + const int mod = 1e9 + 7; + auto qpow = [&](ll a, ll n) { + ll ans = 1; + for (; n; n >>= 1) { + if (n & 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return ans; + }; + unordered_map cnt; + for (int i = 0; i < k; ++i) { + cnt[nums[i]]++; + } + ll cur = 0; + for (auto& [k, v] : cnt) { + cur = (cur + qpow(k, v)) % mod; + } + ll ans = cur; + for (int i = k; i < nums.size(); ++i) { + int a = nums[i - k], b = nums[i]; + if (a != b) { + cur += cnt[b] ? (b - 1) * qpow(b, cnt[b]) % mod : b; + cur -= cnt[a] > 1 ? (a - 1) * qpow(a, cnt[a] - 1) % mod : a; + cur = (cur + mod) % mod; + ans = max(ans, cur); + cnt[b]++; + cnt[a]--; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2500-2599/2524.Maximum Frequency Score of a Subarray/Solution.java b/solution/2500-2599/2524.Maximum Frequency Score of a Subarray/Solution.java index 43c71f2e86343..fb94ef9355c97 100644 --- a/solution/2500-2599/2524.Maximum Frequency Score of a Subarray/Solution.java +++ b/solution/2500-2599/2524.Maximum Frequency Score of a Subarray/Solution.java @@ -1,47 +1,47 @@ -class Solution { - private final int mod = (int) 1e9 + 7; - - public int maxFrequencyScore(int[] nums, int k) { - Map cnt = new HashMap<>(); - for (int i = 0; i < k; ++i) { - cnt.merge(nums[i], 1, Integer::sum); - } - long cur = 0; - for (var e : cnt.entrySet()) { - cur = (cur + qpow(e.getKey(), e.getValue())) % mod; - } - long ans = cur; - for (int i = k; i < nums.length; ++i) { - int a = nums[i - k]; - int b = nums[i]; - if (a != b) { - if (cnt.getOrDefault(b, 0) > 0) { - cur += (b - 1) * qpow(b, cnt.get(b)) % mod; - } else { - cur += b; - } - if (cnt.getOrDefault(a, 0) > 1) { - cur -= (a - 1) * qpow(a, cnt.get(a) - 1) % mod; - } else { - cur -= a; - } - cur = (cur + mod) % mod; - cnt.put(b, cnt.getOrDefault(b, 0) + 1); - cnt.put(a, cnt.getOrDefault(a, 0) - 1); - ans = Math.max(ans, cur); - } - } - return (int) ans; - } - - private long qpow(long a, long n) { - long ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return ans; - } +class Solution { + private final int mod = (int) 1e9 + 7; + + public int maxFrequencyScore(int[] nums, int k) { + Map cnt = new HashMap<>(); + for (int i = 0; i < k; ++i) { + cnt.merge(nums[i], 1, Integer::sum); + } + long cur = 0; + for (var e : cnt.entrySet()) { + cur = (cur + qpow(e.getKey(), e.getValue())) % mod; + } + long ans = cur; + for (int i = k; i < nums.length; ++i) { + int a = nums[i - k]; + int b = nums[i]; + if (a != b) { + if (cnt.getOrDefault(b, 0) > 0) { + cur += (b - 1) * qpow(b, cnt.get(b)) % mod; + } else { + cur += b; + } + if (cnt.getOrDefault(a, 0) > 1) { + cur -= (a - 1) * qpow(a, cnt.get(a) - 1) % mod; + } else { + cur -= a; + } + cur = (cur + mod) % mod; + cnt.put(b, cnt.getOrDefault(b, 0) + 1); + cnt.put(a, cnt.getOrDefault(a, 0) - 1); + ans = Math.max(ans, cur); + } + } + return (int) ans; + } + + private long qpow(long a, long n) { + long ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.cpp b/solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.cpp new file mode 100644 index 0000000000000..086dbf7ff6dfa --- /dev/null +++ b/solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + string categorizeBox(int length, int width, int height, int mass) { + long v = (long) length * width * height; + bool bulky = length >= 1e4 || width >= 1e4 || height >= 1e4 || v >= 1e9; + bool heavy = mass >= 100; + + if (bulky && heavy) { + return "Both"; + } + if (bulky) { + return "Bulky"; + } + if (heavy) { + return "Heavy"; + } + + return "Neither"; + } +}; \ No newline at end of file diff --git a/solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.go b/solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.go new file mode 100644 index 0000000000000..9f699ccbab80d --- /dev/null +++ b/solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.go @@ -0,0 +1,15 @@ +func categorizeBox(length int, width int, height int, mass int) string { + v := length * width * height + bulky := length >= 1e4 || width >= 1e4 || height >= 1e4 || v >= 1e9 + heavy := mass >= 100 + if bulky && heavy { + return "Both" + } + if bulky { + return "Bulky" + } + if heavy { + return "Heavy" + } + return "Neither" +} \ No newline at end of file diff --git a/solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.java b/solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.java new file mode 100644 index 0000000000000..a0597b4e03004 --- /dev/null +++ b/solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.java @@ -0,0 +1,19 @@ +class Solution { + public String categorizeBox(int length, int width, int height, int mass) { + long v = (long) length * width * height; + boolean bulky = length >= 1e4 || width >= 1e4 || height >= 1e4 || v >= 1e9; + boolean heavy = mass >= 100; + + if (bulky && heavy) { + return "Both"; + } + if (bulky) { + return "Bulky"; + } + if (heavy) { + return "Heavy"; + } + + return "Neither"; + } +} \ No newline at end of file diff --git a/solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.py b/solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.py new file mode 100644 index 0000000000000..7d32bc8b7d6cc --- /dev/null +++ b/solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.py @@ -0,0 +1,14 @@ +class Solution: + def categorizeBox(self, length: int, width: int, height: int, mass: int) -> str: + v = length * width * height + bulky = any(x >= 10000 for x in (length, width, height)) or v >= 10**9 + heavy = mass >= 100 + + if bulky and heavy: + return "Both" + if bulky: + return "Bulky" + if heavy: + return "Heavy" + + return "Neither" diff --git a/solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.rs b/solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.rs new file mode 100644 index 0000000000000..c8e16b8876123 --- /dev/null +++ b/solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn categorize_box(length: i32, width: i32, height: i32, mass: i32) -> String { + let v = length * width * height; + let bulky = + length >= 10000 || + width >= 10000 || + height >= 10000 || + (length as i64) * (width as i64) * (height as i64) >= 1000000000; + + let heavy = mass >= 100; + + if bulky && heavy { + return "Both".to_string(); + } + if bulky { + return "Bulky".to_string(); + } + if heavy { + return "Heavy".to_string(); + } + + "Neither".to_string() + } +} diff --git a/solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.ts b/solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.ts new file mode 100644 index 0000000000000..0cd9871bcfaa2 --- /dev/null +++ b/solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.ts @@ -0,0 +1,15 @@ +function categorizeBox(length: number, width: number, height: number, mass: number): string { + const v = length * width * height; + const bulky = length >= 1e4 || width >= 1e4 || height >= 1e4 || v >= 1e9; + const heavy = mass >= 100; + if (bulky && heavy) { + return 'Both'; + } + if (bulky) { + return 'Bulky'; + } + if (heavy) { + return 'Heavy'; + } + return 'Neither'; +} diff --git a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.c b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.c index 3f9daf90fb834..8262cf30c55c4 100644 --- a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.c +++ b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.c @@ -1,21 +1,13 @@ #define max(a, b) (((a) > (b)) ? (a) : (b)) -int search(int* nums, int numsSize, int target) { - int left = 0; - int right = numsSize; - while (left < right) { - int mid = (left + right) >> 1; - if (nums[mid] < target) { - left = mid + 1; - } else { - right = mid; +int maximumCount(int* nums, int numsSize) { + int count[2] = {0}; + for (int i = 0; i < numsSize; i++) { + if (nums[i] < 0) { + count[0]++; + } else if (nums[i] > 0) { + count[1]++; } } - return left; -} - -int maximumCount(int* nums, int numsSize) { - int i = search(nums, numsSize, 0); - int j = search(nums, numsSize, 1); - return max(i, numsSize - j); -} + return max(count[0], count[1]); +} \ No newline at end of file diff --git a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.cpp b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.cpp index 0725754a7ed46..ca924f9995e67 100644 --- a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.cpp +++ b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.cpp @@ -1,8 +1,15 @@ class Solution { public: int maximumCount(vector& nums) { - int a = nums.end() - lower_bound(nums.begin(), nums.end(), 1); - int b = lower_bound(nums.begin(), nums.end(), 0) - nums.begin(); + int a = 0, b = 0; + for (int& v : nums) { + if (v > 0) { + ++a; + } + if (v < 0) { + ++b; + } + } return max(a, b); } }; \ No newline at end of file diff --git a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.go b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.go index 5606180f7e6a6..bb4508a3da925 100644 --- a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.go +++ b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.go @@ -1,5 +1,12 @@ func maximumCount(nums []int) int { - a := len(nums) - sort.SearchInts(nums, 1) - b := sort.SearchInts(nums, 0) + a, b := 0, 0 + for _, v := range nums { + if v > 0 { + a++ + } + if v < 0 { + b++ + } + } return max(a, b) } \ No newline at end of file diff --git a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.java b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.java index 8eae0f526f906..492ca1b07a803 100644 --- a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.java +++ b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.java @@ -1,20 +1,14 @@ class Solution { public int maximumCount(int[] nums) { - int a = nums.length - search(nums, 1); - int b = search(nums, 0); - return Math.max(a, b); - } - - private int search(int[] nums, int x) { - int left = 0, right = nums.length; - while (left < right) { - int mid = (left + right) >> 1; - if (nums[mid] >= x) { - right = mid; - } else { - left = mid + 1; + int a = 0, b = 0; + for (int v : nums) { + if (v > 0) { + ++a; + } + if (v < 0) { + ++b; } } - return left; + return Math.max(a, b); } } \ No newline at end of file diff --git a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.py b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.py index bc659537afcc8..9a4fb379b8092 100644 --- a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.py +++ b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.py @@ -1,5 +1,5 @@ class Solution: def maximumCount(self, nums: List[int]) -> int: - a = len(nums) - bisect_left(nums, 1) - b = bisect_left(nums, 0) + a = sum(v > 0 for v in nums) + b = sum(v < 0 for v in nums) return max(a, b) diff --git a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.rs b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.rs index 75c5f9ed944fc..d8fc9365fcd4d 100644 --- a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.rs +++ b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.rs @@ -1,22 +1,13 @@ impl Solution { - fn search(nums: &Vec, target: i32) -> usize { - let mut left = 0; - let mut right = nums.len(); - while left < right { - let mid = (left + right) >> 1; - if nums[mid] < target { - left = mid + 1; - } else { - right = mid; + pub fn maximum_count(nums: Vec) -> i32 { + let mut count = [0, 0]; + for &num in nums.iter() { + if num < 0 { + count[0] += 1; + } else if num > 0 { + count[1] += 1; } } - left - } - - pub fn maximum_count(nums: Vec) -> i32 { - let n = nums.len(); - let i = Self::search(&nums, 0); - let j = Self::search(&nums, 1); - i.max(n - j) as i32 + *count.iter().max().unwrap() } } diff --git a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.ts b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.ts index aae118f62b519..b89b8204abf3c 100644 --- a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.ts +++ b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.ts @@ -1,19 +1,11 @@ function maximumCount(nums: number[]): number { - const search = (target: number) => { - let left = 0; - let right = n; - while (left < right) { - const mid = (left + right) >>> 1; - if (nums[mid] < target) { - left = mid + 1; - } else { - right = mid; - } + const count = [0, 0]; + for (const num of nums) { + if (num < 0) { + count[0]++; + } else if (num > 0) { + count[1]++; } - return left; - }; - const n = nums.length; - const i = search(0); - const j = search(1); - return Math.max(i, n - j); + } + return Math.max(...count); } diff --git a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.c b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.c new file mode 100644 index 0000000000000..9c4877a6a99e2 --- /dev/null +++ b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.c @@ -0,0 +1,21 @@ +#define max(a, b) (((a) > (b)) ? (a) : (b)) + +int search(int* nums, int numsSize, int target) { + int left = 0; + int right = numsSize; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] < target) { + left = mid + 1; + } else { + right = mid; + } + } + return left; +} + +int maximumCount(int* nums, int numsSize) { + int i = search(nums, numsSize, 0); + int j = search(nums, numsSize, 1); + return max(i, numsSize - j); +} \ No newline at end of file diff --git a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.cpp b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.cpp new file mode 100644 index 0000000000000..0725754a7ed46 --- /dev/null +++ b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.cpp @@ -0,0 +1,8 @@ +class Solution { +public: + int maximumCount(vector& nums) { + int a = nums.end() - lower_bound(nums.begin(), nums.end(), 1); + int b = lower_bound(nums.begin(), nums.end(), 0) - nums.begin(); + return max(a, b); + } +}; \ No newline at end of file diff --git a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.go b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.go new file mode 100644 index 0000000000000..5606180f7e6a6 --- /dev/null +++ b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.go @@ -0,0 +1,5 @@ +func maximumCount(nums []int) int { + a := len(nums) - sort.SearchInts(nums, 1) + b := sort.SearchInts(nums, 0) + return max(a, b) +} \ No newline at end of file diff --git a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.java b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.java new file mode 100644 index 0000000000000..8eae0f526f906 --- /dev/null +++ b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.java @@ -0,0 +1,20 @@ +class Solution { + public int maximumCount(int[] nums) { + int a = nums.length - search(nums, 1); + int b = search(nums, 0); + return Math.max(a, b); + } + + private int search(int[] nums, int x) { + int left = 0, right = nums.length; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} \ No newline at end of file diff --git a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.py b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.py new file mode 100644 index 0000000000000..bc659537afcc8 --- /dev/null +++ b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.py @@ -0,0 +1,5 @@ +class Solution: + def maximumCount(self, nums: List[int]) -> int: + a = len(nums) - bisect_left(nums, 1) + b = bisect_left(nums, 0) + return max(a, b) diff --git a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.rs b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.rs new file mode 100644 index 0000000000000..75c5f9ed944fc --- /dev/null +++ b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.rs @@ -0,0 +1,22 @@ +impl Solution { + fn search(nums: &Vec, target: i32) -> usize { + let mut left = 0; + let mut right = nums.len(); + while left < right { + let mid = (left + right) >> 1; + if nums[mid] < target { + left = mid + 1; + } else { + right = mid; + } + } + left + } + + pub fn maximum_count(nums: Vec) -> i32 { + let n = nums.len(); + let i = Self::search(&nums, 0); + let j = Self::search(&nums, 1); + i.max(n - j) as i32 + } +} diff --git a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.ts b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.ts new file mode 100644 index 0000000000000..aae118f62b519 --- /dev/null +++ b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution2.ts @@ -0,0 +1,19 @@ +function maximumCount(nums: number[]): number { + const search = (target: number) => { + let left = 0; + let right = n; + while (left < right) { + const mid = (left + right) >>> 1; + if (nums[mid] < target) { + left = mid + 1; + } else { + right = mid; + } + } + return left; + }; + const n = nums.length; + const i = search(0); + const j = search(1); + return Math.max(i, n - j); +} diff --git a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution3.rs b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution3.rs new file mode 100644 index 0000000000000..61945cb483e7d --- /dev/null +++ b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution3.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn maximum_count(nums: Vec) -> i32 { + let mut a = 0; + let mut b = 0; + + for n in nums { + if n > 0 { + a += 1; + } else if n < 0 { + b += 1; + } + } + + std::cmp::max(a, b) + } +} diff --git a/solution/2500-2599/2530.Maximal Score After Applying K Operations/Solution.go b/solution/2500-2599/2530.Maximal Score After Applying K Operations/Solution.go index 43b47d58ddc66..e06fdda4d23a7 100644 --- a/solution/2500-2599/2530.Maximal Score After Applying K Operations/Solution.go +++ b/solution/2500-2599/2530.Maximal Score After Applying K Operations/Solution.go @@ -1,10 +1,10 @@ func maxKelements(nums []int, k int) (ans int64) { - h := hp{nums} - heap.Init(&h) + h := &hp{nums} + heap.Init(h) for ; k > 0; k-- { - ans += int64(h.IntSlice[0]) - h.IntSlice[0] = (h.IntSlice[0] + 2) / 3 - heap.Fix(&h, 0) + v := h.pop() + ans += int64(v) + h.push((v + 2) / 3) } return } @@ -12,5 +12,12 @@ func maxKelements(nums []int, k int) (ans int64) { type hp struct{ sort.IntSlice } func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } -func (hp) Push(any) {} -func (hp) Pop() (_ any) { return } \ No newline at end of file +func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) } +func (h *hp) Pop() any { + a := h.IntSlice + v := a[len(a)-1] + h.IntSlice = a[:len(a)-1] + return v +} +func (h *hp) push(v int) { heap.Push(h, v) } +func (h *hp) pop() int { return heap.Pop(h).(int) } \ No newline at end of file diff --git a/solution/2500-2599/2530.Maximal Score After Applying K Operations/Solution2.cpp b/solution/2500-2599/2530.Maximal Score After Applying K Operations/Solution2.cpp new file mode 100644 index 0000000000000..9f71cefbcfdee --- /dev/null +++ b/solution/2500-2599/2530.Maximal Score After Applying K Operations/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + long long maxKelements(vector& nums, int k) { + make_heap(nums.begin(), nums.end()); + long long ans = 0; + while (k--) { + int v = nums[0]; + ans += v; + pop_heap(nums.begin(), nums.end()); + nums.back() = (v + 2) / 3; + push_heap(nums.begin(), nums.end()); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2500-2599/2530.Maximal Score After Applying K Operations/Solution2.go b/solution/2500-2599/2530.Maximal Score After Applying K Operations/Solution2.go new file mode 100644 index 0000000000000..43b47d58ddc66 --- /dev/null +++ b/solution/2500-2599/2530.Maximal Score After Applying K Operations/Solution2.go @@ -0,0 +1,16 @@ +func maxKelements(nums []int, k int) (ans int64) { + h := hp{nums} + heap.Init(&h) + for ; k > 0; k-- { + ans += int64(h.IntSlice[0]) + h.IntSlice[0] = (h.IntSlice[0] + 2) / 3 + heap.Fix(&h, 0) + } + return +} + +type hp struct{ sort.IntSlice } + +func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } +func (hp) Push(any) {} +func (hp) Pop() (_ any) { return } \ No newline at end of file diff --git a/solution/2500-2599/2530.Maximal Score After Applying K Operations/Solution2.py b/solution/2500-2599/2530.Maximal Score After Applying K Operations/Solution2.py new file mode 100644 index 0000000000000..919bec63516f4 --- /dev/null +++ b/solution/2500-2599/2530.Maximal Score After Applying K Operations/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def maxKelements(self, nums: List[int], k: int) -> int: + for i, v in enumerate(nums): + nums[i] = -v + heapify(nums) + ans = 0 + for _ in range(k): + ans -= heapreplace(nums, -ceil(-nums[0] / 3)) + return ans diff --git a/solution/2500-2599/2535.Difference Between Element Sum and Digit Sum of an Array/Solution.c b/solution/2500-2599/2535.Difference Between Element Sum and Digit Sum of an Array/Solution.c index c5aecc51aec5a..9048644a6884e 100644 --- a/solution/2500-2599/2535.Difference Between Element Sum and Digit Sum of an Array/Solution.c +++ b/solution/2500-2599/2535.Difference Between Element Sum and Digit Sum of an Array/Solution.c @@ -8,4 +8,4 @@ int differenceOfSum(int* nums, int numsSize) { } } return ans; -} +} \ No newline at end of file diff --git a/solution/2500-2599/2535.Difference Between Element Sum and Digit Sum of an Array/Solution2.rs b/solution/2500-2599/2535.Difference Between Element Sum and Digit Sum of an Array/Solution2.rs new file mode 100644 index 0000000000000..622f661a54fe3 --- /dev/null +++ b/solution/2500-2599/2535.Difference Between Element Sum and Digit Sum of an Array/Solution2.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn difference_of_sum(nums: Vec) -> i32 { + let a: i32 = nums.iter().sum(); + let b: i32 = nums + .iter() + .map(|&n| + n + .to_string() + .chars() + .map(|c| c.to_digit(10).unwrap() as i32) + .sum::() + ) + .sum(); + (a - b).abs() + } +} diff --git a/solution/2500-2599/2537.Count the Number of Good Subarrays/Solution.cpp b/solution/2500-2599/2537.Count the Number of Good Subarrays/Solution.cpp index 4396f8df46af6..7083ca87fec59 100644 --- a/solution/2500-2599/2537.Count the Number of Good Subarrays/Solution.cpp +++ b/solution/2500-2599/2537.Count the Number of Good Subarrays/Solution.cpp @@ -16,4 +16,4 @@ class Solution { } return ans; } -}; +}; \ No newline at end of file diff --git a/solution/2500-2599/2538.Difference Between Maximum and Minimum Price Sum/Solution.cpp b/solution/2500-2599/2538.Difference Between Maximum and Minimum Price Sum/Solution.cpp index 2bce7586509d9..647ee2d129779 100644 --- a/solution/2500-2599/2538.Difference Between Maximum and Minimum Price Sum/Solution.cpp +++ b/solution/2500-2599/2538.Difference Between Maximum and Minimum Price Sum/Solution.cpp @@ -25,4 +25,4 @@ class Solution { dfs(0, -1); return ans; } -}; +}; \ No newline at end of file diff --git a/solution/2500-2599/2539.Count the Number of Good Subsequences/Solution.cpp b/solution/2500-2599/2539.Count the Number of Good Subsequences/Solution.cpp new file mode 100644 index 0000000000000..2f58bd17aa7c5 --- /dev/null +++ b/solution/2500-2599/2539.Count the Number of Good Subsequences/Solution.cpp @@ -0,0 +1,52 @@ +int N = 10001; +int MOD = 1e9 + 7; +long f[10001]; +long g[10001]; + +long qmi(long a, long k, long p) { + long res = 1; + while (k != 0) { + if ((k & 1) == 1) { + res = res * a % p; + } + k >>= 1; + a = a * a % p; + } + return res; +} + +int init = []() { + f[0] = 1; + g[0] = 1; + for (int i = 1; i < N; ++i) { + f[i] = f[i - 1] * i % MOD; + g[i] = qmi(f[i], MOD - 2, MOD); + } + return 0; +}(); + +int comb(int n, int k) { + return (f[n] * g[k] % MOD) * g[n - k] % MOD; +} + +class Solution { +public: + int countGoodSubsequences(string s) { + int cnt[26]{}; + int mx = 1; + for (char& c : s) { + mx = max(mx, ++cnt[c - 'a']); + } + long ans = 0; + for (int i = 1; i <= mx; ++i) { + long x = 1; + for (int j = 0; j < 26; ++j) { + if (cnt[j] >= i) { + x = (x * (comb(cnt[j], i) + 1)) % MOD; + } + } + ans = (ans + x - 1) % MOD; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2500-2599/2540.Minimum Common Value/Solution.c b/solution/2500-2599/2540.Minimum Common Value/Solution.c index 9d16b19ad42ae..1c725b104c739 100644 --- a/solution/2500-2599/2540.Minimum Common Value/Solution.c +++ b/solution/2500-2599/2540.Minimum Common Value/Solution.c @@ -12,4 +12,4 @@ int getCommon(int* nums1, int nums1Size, int* nums2, int nums2Size) { } } return -1; -} +} \ No newline at end of file diff --git a/solution/2500-2599/2540.Minimum Common Value/Solution2.rs b/solution/2500-2599/2540.Minimum Common Value/Solution2.rs new file mode 100644 index 0000000000000..660d92e9762bb --- /dev/null +++ b/solution/2500-2599/2540.Minimum Common Value/Solution2.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn get_common(nums1: Vec, nums2: Vec) -> i32 { + let mut iter1 = nums1.iter(); + let mut iter2 = nums2.iter(); + let mut num1 = iter1.next(); + let mut num2 = iter2.next(); + + while let (Some(n1), Some(n2)) = (num1, num2) { + if n1 == n2 { + return *n1; + } else if n1 < n2 { + num1 = iter1.next(); + } else { + num2 = iter2.next(); + } + } + + -1 + } +} diff --git a/solution/2500-2599/2541.Minimum Operations to Make Array Equal II/Solution.c b/solution/2500-2599/2541.Minimum Operations to Make Array Equal II/Solution.c index df60a31b11d8c..cb844a755368d 100644 --- a/solution/2500-2599/2541.Minimum Operations to Make Array Equal II/Solution.c +++ b/solution/2500-2599/2541.Minimum Operations to Make Array Equal II/Solution.c @@ -21,4 +21,4 @@ long long minOperations(int* nums1, int nums1Size, int* nums2, int nums2Size, in return -1; } return sum2 / (k * 2); -} +} \ No newline at end of file diff --git a/solution/2500-2599/2544.Alternating Digit Sum/Solution.c b/solution/2500-2599/2544.Alternating Digit Sum/Solution.c index f960cdfd8cb5c..ef2e9145560bb 100644 --- a/solution/2500-2599/2544.Alternating Digit Sum/Solution.c +++ b/solution/2500-2599/2544.Alternating Digit Sum/Solution.c @@ -7,4 +7,4 @@ int alternateDigitSum(int n) { n /= 10; } return ans * -sign; -} +} \ No newline at end of file diff --git a/solution/2500-2599/2544.Alternating Digit Sum/Solution.py b/solution/2500-2599/2544.Alternating Digit Sum/Solution.py index 5214d72010f84..82b6f6852b089 100644 --- a/solution/2500-2599/2544.Alternating Digit Sum/Solution.py +++ b/solution/2500-2599/2544.Alternating Digit Sum/Solution.py @@ -1,3 +1,3 @@ -class Solution: - def alternateDigitSum(self, n: int) -> int: - return sum((-1) ** i * int(x) for i, x in enumerate(str(n))) +class Solution: + def alternateDigitSum(self, n: int) -> int: + return sum((-1) ** i * int(x) for i, x in enumerate(str(n))) diff --git a/solution/2500-2599/2544.Alternating Digit Sum/Solution2.py b/solution/2500-2599/2544.Alternating Digit Sum/Solution2.py new file mode 100644 index 0000000000000..a1b03fa87f36b --- /dev/null +++ b/solution/2500-2599/2544.Alternating Digit Sum/Solution2.py @@ -0,0 +1,8 @@ +class Solution: + def alternateDigitSum(self, n: int) -> int: + ans, sign = 0, 1 + for c in str(n): + x = int(c) + ans += sign * x + sign *= -1 + return ans diff --git a/solution/2500-2599/2544.Alternating Digit Sum/Solution2.rs b/solution/2500-2599/2544.Alternating Digit Sum/Solution2.rs new file mode 100644 index 0000000000000..905b51056789f --- /dev/null +++ b/solution/2500-2599/2544.Alternating Digit Sum/Solution2.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn alternate_digit_sum(n: i32) -> i32 { + let mut ans = 0; + let mut sign = 1; + + for c in format!("{}", n).chars() { + let x = c.to_digit(10).unwrap() as i32; + ans += x * sign; + sign *= -1; + } + + ans + } +} diff --git a/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/Solution.c b/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/Solution.c index 64b9d3710a147..5fc29e268c0eb 100644 --- a/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/Solution.c +++ b/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/Solution.c @@ -13,4 +13,4 @@ bool makeStringsEqual(char* s, char* target) { } } return !(count & 1); -} +} \ No newline at end of file diff --git a/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/Solution.cpp b/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/Solution.cpp index f1208c5645611..d15d5e2c38653 100644 --- a/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/Solution.cpp +++ b/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/Solution.cpp @@ -1,18 +1,18 @@ -class Solution { -public: - int monkeyMove(int n) { - const int mod = 1e9 + 7; - using ll = long long; - auto qpow = [&](ll a, int n) { - ll ans = 1; - for (; n; n >>= 1) { - if (n & 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return ans; - }; - return (qpow(2, n) - 2 + mod) % mod; - } +class Solution { +public: + int monkeyMove(int n) { + const int mod = 1e9 + 7; + using ll = long long; + auto qpow = [&](ll a, int n) { + ll ans = 1; + for (; n; n >>= 1) { + if (n & 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return ans; + }; + return (qpow(2, n) - 2 + mod) % mod; + } }; \ No newline at end of file diff --git a/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/Solution.java b/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/Solution.java index 54eb03771b345..bcf4ab1fd5bda 100644 --- a/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/Solution.java +++ b/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public int monkeyMove(int n) { - final int mod = (int) 1e9 + 7; - return (qpow(2, n, mod) - 2 + mod) % mod; - } - - private int qpow(long a, int n, int mod) { - long ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return (int) ans; - } +class Solution { + public int monkeyMove(int n) { + final int mod = (int) 1e9 + 7; + return (qpow(2, n, mod) - 2 + mod) % mod; + } + + private int qpow(long a, int n, int mod) { + long ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return (int) ans; + } } \ No newline at end of file diff --git a/solution/2500-2599/2553.Separate the Digits in an Array/Solution.c b/solution/2500-2599/2553.Separate the Digits in an Array/Solution.c index 63016669a2d02..36faf9b24dfaf 100644 --- a/solution/2500-2599/2553.Separate the Digits in an Array/Solution.c +++ b/solution/2500-2599/2553.Separate the Digits in an Array/Solution.c @@ -20,4 +20,4 @@ int* separateDigits(int* nums, int numsSize, int* returnSize) { } *returnSize = n; return ans; -} +} \ No newline at end of file diff --git a/solution/2500-2599/2553.Separate the Digits in an Array/Solution2.rs b/solution/2500-2599/2553.Separate the Digits in an Array/Solution2.rs new file mode 100644 index 0000000000000..98bb06490489a --- /dev/null +++ b/solution/2500-2599/2553.Separate the Digits in an Array/Solution2.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn separate_digits(nums: Vec) -> Vec { + let mut ans = vec![]; + + for n in nums { + let mut t = vec![]; + let mut x = n; + + while x != 0 { + t.push(x % 10); + x /= 10; + } + + for i in (0..t.len()).rev() { + ans.push(t[i]); + } + } + + ans + } +} diff --git a/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/Solution2.cpp b/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/Solution2.cpp new file mode 100644 index 0000000000000..3f6ce58ddc314 --- /dev/null +++ b/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/Solution2.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int maxCount(vector& banned, int n, int maxSum) { + banned.push_back(0); + banned.push_back(n + 1); + sort(banned.begin(), banned.end()); + banned.erase(unique(banned.begin(), banned.end()), banned.end()); + banned.erase(remove_if(banned.begin(), banned.end(), [&](int x) { return x > n + 1; }), banned.end()); + int ans = 0; + for (int k = 1; k < banned.size(); ++k) { + int i = banned[k - 1], j = banned[k]; + int left = 0, right = j - i - 1; + while (left < right) { + int mid = left + ((right - left + 1) / 2); + if ((i + 1 + i + mid) * 1LL * mid / 2 <= maxSum) { + left = mid; + } else { + right = mid - 1; + } + } + ans += left; + maxSum -= (i + 1 + i + left) * 1LL * left / 2; + if (maxSum <= 0) { + break; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/Solution2.go b/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/Solution2.go new file mode 100644 index 0000000000000..53fae4b61c58e --- /dev/null +++ b/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/Solution2.go @@ -0,0 +1,29 @@ +func maxCount(banned []int, n int, maxSum int) (ans int) { + banned = append(banned, []int{0, n + 1}...) + sort.Ints(banned) + ban := []int{} + for i, x := range banned { + if (i > 0 && x == banned[i-1]) || x > n+1 { + continue + } + ban = append(ban, x) + } + for k := 1; k < len(ban); k++ { + i, j := ban[k-1], ban[k] + left, right := 0, j-i-1 + for left < right { + mid := (left + right + 1) >> 1 + if (i+1+i+mid)*mid/2 <= maxSum { + left = mid + } else { + right = mid - 1 + } + } + ans += left + maxSum -= (i + 1 + i + left) * left / 2 + if maxSum <= 0 { + break + } + } + return +} \ No newline at end of file diff --git a/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/Solution2.java b/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/Solution2.java new file mode 100644 index 0000000000000..95bd781c6fe91 --- /dev/null +++ b/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/Solution2.java @@ -0,0 +1,33 @@ +class Solution { + public int maxCount(int[] banned, int n, int maxSum) { + Set black = new HashSet<>(); + black.add(0); + black.add(n + 1); + for (int x : banned) { + if (x < n + 2) { + black.add(x); + } + } + List ban = new ArrayList<>(black); + Collections.sort(ban); + int ans = 0; + for (int k = 1; k < ban.size(); ++k) { + int i = ban.get(k - 1), j = ban.get(k); + int left = 0, right = j - i - 1; + while (left < right) { + int mid = (left + right + 1) >>> 1; + if ((i + 1 + i + mid) * 1L * mid / 2 <= maxSum) { + left = mid; + } else { + right = mid - 1; + } + } + ans += left; + maxSum -= (i + 1 + i + left) * 1L * left / 2; + if (maxSum <= 0) { + break; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/Solution2.py b/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/Solution2.py new file mode 100644 index 0000000000000..c3f1740c8f202 --- /dev/null +++ b/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/Solution2.py @@ -0,0 +1,18 @@ +class Solution: + def maxCount(self, banned: List[int], n: int, maxSum: int) -> int: + banned.extend([0, n + 1]) + ban = sorted(x for x in set(banned) if x < n + 2) + ans = 0 + for i, j in pairwise(ban): + left, right = 0, j - i - 1 + while left < right: + mid = (left + right + 1) >> 1 + if (i + 1 + i + mid) * mid // 2 <= maxSum: + left = mid + else: + right = mid - 1 + ans += left + maxSum -= (i + 1 + i + left) * left // 2 + if maxSum <= 0: + break + return ans diff --git a/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.cpp b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.cpp index 08d9da05538e3..fe3b7ea0c4e6b 100644 --- a/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.cpp +++ b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.cpp @@ -2,17 +2,18 @@ class Solution { public: vector vowelStrings(vector& words, vector>& queries) { unordered_set vowels = {'a', 'e', 'i', 'o', 'u'}; - int n = words.size(); - int s[n + 1]; - s[0] = 0; - for (int i = 0; i < n; ++i) { + vector nums; + for (int i = 0; i < words.size(); ++i) { char a = words[i][0], b = words[i].back(); - s[i + 1] = s[i] + (vowels.count(a) && vowels.count(b)); + if (vowels.count(a) && vowels.count(b)) { + nums.push_back(i); + } } vector ans; for (auto& q : queries) { int l = q[0], r = q[1]; - ans.push_back(s[r + 1] - s[l]); + int cnt = upper_bound(nums.begin(), nums.end(), r) - lower_bound(nums.begin(), nums.end(), l); + ans.push_back(cnt); } return ans; } diff --git a/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.go b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.go index 4f86f29e376fa..3117c76906028 100644 --- a/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.go +++ b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.go @@ -1,18 +1,15 @@ func vowelStrings(words []string, queries [][]int) []int { vowels := map[byte]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true} - n := len(words) - s := make([]int, n+1) + nums := []int{} for i, w := range words { - x := 0 if vowels[w[0]] && vowels[w[len(w)-1]] { - x = 1 + nums = append(nums, i) } - s[i+1] = s[i] + x } ans := make([]int, len(queries)) for i, q := range queries { l, r := q[0], q[1] - ans[i] = s[r+1] - s[l] + ans[i] = sort.SearchInts(nums, r+1) - sort.SearchInts(nums, l) } return ans } \ No newline at end of file diff --git a/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.java b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.java index 254fd217e8486..36027268138e0 100644 --- a/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.java +++ b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.java @@ -1,18 +1,33 @@ class Solution { + private List nums = new ArrayList<>(); + public int[] vowelStrings(String[] words, int[][] queries) { Set vowels = Set.of('a', 'e', 'i', 'o', 'u'); - int n = words.length; - int[] s = new int[n + 1]; - for (int i = 0; i < n; ++i) { + for (int i = 0; i < words.length; ++i) { char a = words[i].charAt(0), b = words[i].charAt(words[i].length() - 1); - s[i + 1] = s[i] + (vowels.contains(a) && vowels.contains(b) ? 1 : 0); + if (vowels.contains(a) && vowels.contains(b)) { + nums.add(i); + } } int m = queries.length; int[] ans = new int[m]; for (int i = 0; i < m; ++i) { int l = queries[i][0], r = queries[i][1]; - ans[i] = s[r + 1] - s[l]; + ans[i] = search(r + 1) - search(l); } return ans; } + + private int search(int x) { + int l = 0, r = nums.size(); + while (l < r) { + int mid = (l + r) >> 1; + if (nums.get(mid) >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } } \ No newline at end of file diff --git a/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.py b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.py index ed3e27ad7a79a..f3d9a16c224a1 100644 --- a/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.py +++ b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.py @@ -1,9 +1,5 @@ class Solution: def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]: vowels = set("aeiou") - s = list( - accumulate( - (int(w[0] in vowels and w[-1] in vowels) for w in words), initial=0 - ) - ) - return [s[r + 1] - s[l] for l, r in queries] + nums = [i for i, w in enumerate(words) if w[0] in vowels and w[-1] in vowels] + return [bisect_right(nums, r) - bisect_left(nums, l) for l, r in queries] diff --git a/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.ts b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.ts index 9d5941c4a921c..be1bcb30a809d 100644 --- a/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.ts +++ b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution.ts @@ -1,14 +1,23 @@ function vowelStrings(words: string[], queries: number[][]): number[] { const vowels = new Set(['a', 'e', 'i', 'o', 'u']); - const n = words.length; - const s: number[] = new Array(n + 1).fill(0); - for (let i = 0; i < n; ++i) { + const nums: number[] = []; + for (let i = 0; i < words.length; ++i) { if (vowels.has(words[i][0]) && vowels.has(words[i][words[i].length - 1])) { - s[i + 1] = s[i] + 1; - } else { - s[i + 1] = s[i]; + nums.push(i); } } - - return queries.map(([l, r]) => s[r + 1] - s[l]); + const search = (x: number): number => { + let l = 0, + r = nums.length; + while (l < r) { + const mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + return queries.map(([l, r]) => search(r + 1) - search(l)); } diff --git a/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution2.cpp b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution2.cpp new file mode 100644 index 0000000000000..08d9da05538e3 --- /dev/null +++ b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + vector vowelStrings(vector& words, vector>& queries) { + unordered_set vowels = {'a', 'e', 'i', 'o', 'u'}; + int n = words.size(); + int s[n + 1]; + s[0] = 0; + for (int i = 0; i < n; ++i) { + char a = words[i][0], b = words[i].back(); + s[i + 1] = s[i] + (vowels.count(a) && vowels.count(b)); + } + vector ans; + for (auto& q : queries) { + int l = q[0], r = q[1]; + ans.push_back(s[r + 1] - s[l]); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution2.go b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution2.go new file mode 100644 index 0000000000000..4f86f29e376fa --- /dev/null +++ b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution2.go @@ -0,0 +1,18 @@ +func vowelStrings(words []string, queries [][]int) []int { + vowels := map[byte]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true} + n := len(words) + s := make([]int, n+1) + for i, w := range words { + x := 0 + if vowels[w[0]] && vowels[w[len(w)-1]] { + x = 1 + } + s[i+1] = s[i] + x + } + ans := make([]int, len(queries)) + for i, q := range queries { + l, r := q[0], q[1] + ans[i] = s[r+1] - s[l] + } + return ans +} \ No newline at end of file diff --git a/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution2.java b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution2.java new file mode 100644 index 0000000000000..254fd217e8486 --- /dev/null +++ b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution2.java @@ -0,0 +1,18 @@ +class Solution { + public int[] vowelStrings(String[] words, int[][] queries) { + Set vowels = Set.of('a', 'e', 'i', 'o', 'u'); + int n = words.length; + int[] s = new int[n + 1]; + for (int i = 0; i < n; ++i) { + char a = words[i].charAt(0), b = words[i].charAt(words[i].length() - 1); + s[i + 1] = s[i] + (vowels.contains(a) && vowels.contains(b) ? 1 : 0); + } + int m = queries.length; + int[] ans = new int[m]; + for (int i = 0; i < m; ++i) { + int l = queries[i][0], r = queries[i][1]; + ans[i] = s[r + 1] - s[l]; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution2.py b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution2.py new file mode 100644 index 0000000000000..ed3e27ad7a79a --- /dev/null +++ b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]: + vowels = set("aeiou") + s = list( + accumulate( + (int(w[0] in vowels and w[-1] in vowels) for w in words), initial=0 + ) + ) + return [s[r + 1] - s[l] for l, r in queries] diff --git a/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution2.ts b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution2.ts new file mode 100644 index 0000000000000..6f3f88314a224 --- /dev/null +++ b/solution/2500-2599/2559.Count Vowel Strings in Ranges/Solution2.ts @@ -0,0 +1,13 @@ +function vowelStrings(words: string[], queries: number[][]): number[] { + const vowels = new Set(['a', 'e', 'i', 'o', 'u']); + const n = words.length; + const s: number[] = new Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + if (vowels.has(words[i][0]) && vowels.has(words[i][words[i].length - 1])) { + s[i + 1] = s[i] + 1; + } else { + s[i + 1] = s[i]; + } + } + return queries.map(([l, r]) => s[r + 1] - s[l]); +} diff --git a/solution/2500-2599/2562.Find the Array Concatenation Value/Solution.c b/solution/2500-2599/2562.Find the Array Concatenation Value/Solution.c index 441f38e0b61c8..8b3f9046f9370 100644 --- a/solution/2500-2599/2562.Find the Array Concatenation Value/Solution.c +++ b/solution/2500-2599/2562.Find the Array Concatenation Value/Solution.c @@ -20,4 +20,4 @@ long long findTheArrayConcVal(int* nums, int numsSize) { ans += nums[i]; } return ans; -} +} \ No newline at end of file diff --git a/solution/2500-2599/2562.Find the Array Concatenation Value/Solution2.rs b/solution/2500-2599/2562.Find the Array Concatenation Value/Solution2.rs new file mode 100644 index 0000000000000..ddb06074900ca --- /dev/null +++ b/solution/2500-2599/2562.Find the Array Concatenation Value/Solution2.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn find_the_array_conc_val(nums: Vec) -> i64 { + let mut ans = 0; + let mut n = nums.len(); + + for i in 0..n / 2 { + ans += format!("{}{}", nums[i], nums[n - i - 1]) + .parse::() + .unwrap(); + } + + if n % 2 != 0 { + ans += nums[n / 2] as i64; + } + + ans + } +} diff --git a/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/Solution.c b/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/Solution.c index 999eb3bba1799..dad17e1f0c729 100644 --- a/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/Solution.c +++ b/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/Solution.c @@ -33,4 +33,4 @@ int minMaxDifference(int num) { } free(nums); return max - min; -} +} \ No newline at end of file diff --git a/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/Solution2.rs b/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/Solution2.rs new file mode 100644 index 0000000000000..768d5997a6925 --- /dev/null +++ b/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/Solution2.rs @@ -0,0 +1,30 @@ +impl Solution { + pub fn min_max_difference(num: i32) -> i32 { + let mut s = num.to_string().into_bytes(); + let first = s[0]; + for i in 0..s.len() { + if s[i] == first { + s[i] = b'0'; + } + } + let mi = String::from_utf8_lossy(&s).parse::().unwrap(); + + let mut t = num.to_string().into_bytes(); + for i in 0..t.len() { + if t[i] != b'9' { + let second = t[i]; + + for j in 0..t.len() { + if t[j] == second { + t[j] = b'9'; + } + } + + let mx = String::from_utf8_lossy(&t).parse::().unwrap(); + return mx - mi; + } + } + + num - mi + } +} diff --git a/solution/2500-2599/2567.Minimum Score by Changing Two Elements/Solution.c b/solution/2500-2599/2567.Minimum Score by Changing Two Elements/Solution.c index 5d605d67b9800..1e40afca892ec 100644 --- a/solution/2500-2599/2567.Minimum Score by Changing Two Elements/Solution.c +++ b/solution/2500-2599/2567.Minimum Score by Changing Two Elements/Solution.c @@ -7,4 +7,4 @@ int cmp(const void* a, const void* b) { int minimizeSum(int* nums, int numsSize) { qsort(nums, numsSize, sizeof(int), cmp); return min(nums[numsSize - 1] - nums[2], min(nums[numsSize - 2] - nums[1], nums[numsSize - 3] - nums[0])); -} +} \ No newline at end of file diff --git a/solution/2500-2599/2574.Left and Right Sum Differences/Solution.c b/solution/2500-2599/2574.Left and Right Sum Differences/Solution.c index f2068a7f47601..2df8f4be681ff 100644 --- a/solution/2500-2599/2574.Left and Right Sum Differences/Solution.c +++ b/solution/2500-2599/2574.Left and Right Sum Differences/Solution.c @@ -15,4 +15,4 @@ int* leftRigthDifference(int* nums, int numsSize, int* returnSize) { } *returnSize = numsSize; return ans; -} +} \ No newline at end of file diff --git a/solution/2500-2599/2574.Left and Right Sum Differences/Solution2.rs b/solution/2500-2599/2574.Left and Right Sum Differences/Solution2.rs new file mode 100644 index 0000000000000..4d900ff9a04dd --- /dev/null +++ b/solution/2500-2599/2574.Left and Right Sum Differences/Solution2.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn left_right_difference(nums: Vec) -> Vec { + let mut ans = vec![]; + + for i in 0..nums.len() { + let mut left = 0; + for j in 0..i { + left += nums[j]; + } + + let mut right = 0; + for k in i + 1..nums.len() { + right += nums[k]; + } + + ans.push((left - right).abs()); + } + + ans + } +} diff --git a/solution/2500-2599/2574.Left and Right Sum Differences/Solution2.ts b/solution/2500-2599/2574.Left and Right Sum Differences/Solution2.ts new file mode 100644 index 0000000000000..a9d7a8865f49a --- /dev/null +++ b/solution/2500-2599/2574.Left and Right Sum Differences/Solution2.ts @@ -0,0 +1,10 @@ +function leftRigthDifference(nums: number[]): number[] { + let left = 0; + let right = nums.reduce((r, v) => r + v); + return nums.map(v => { + right -= v; + const res = Math.abs(left - right); + left += v; + return res; + }); +} diff --git a/solution/2500-2599/2574.Left and Right Sum Differences/Solution3.rs b/solution/2500-2599/2574.Left and Right Sum Differences/Solution3.rs new file mode 100644 index 0000000000000..3b26f98186c19 --- /dev/null +++ b/solution/2500-2599/2574.Left and Right Sum Differences/Solution3.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn left_right_difference(nums: Vec) -> Vec { + let mut left = 0; + let mut right: i32 = nums.iter().sum(); + let mut ans = vec![]; + + for &x in &nums { + right -= x; + ans.push((left - right).abs()); + left += x; + } + + ans + } +} diff --git a/solution/2500-2599/2575.Find the Divisibility Array of a String/Solution.c b/solution/2500-2599/2575.Find the Divisibility Array of a String/Solution.c index b33340325be00..88ad3e1fe4d73 100644 --- a/solution/2500-2599/2575.Find the Divisibility Array of a String/Solution.c +++ b/solution/2500-2599/2575.Find the Divisibility Array of a String/Solution.c @@ -11,4 +11,4 @@ int* divisibilityArray(char* word, int m, int* returnSize) { } *returnSize = n; return ans; -} +} \ No newline at end of file diff --git a/solution/2500-2599/2578.Split With Minimum Sum/Solution.rs b/solution/2500-2599/2578.Split With Minimum Sum/Solution.rs index 05ded3c50570d..38da74c9c5b03 100644 --- a/solution/2500-2599/2578.Split With Minimum Sum/Solution.rs +++ b/solution/2500-2599/2578.Split With Minimum Sum/Solution.rs @@ -1,11 +1,23 @@ impl Solution { - pub fn split_num(num: i32) -> i32 { - let mut s = num.to_string().into_bytes(); - s.sort_unstable(); + pub fn split_num(mut num: i32) -> i32 { + let mut cnt = vec![0; 10]; + let mut n = 0; + + while num != 0 { + cnt[(num as usize) % 10] += 1; + num /= 10; + n += 1; + } let mut ans = vec![0; 2]; - for (i, c) in s.iter().enumerate() { - ans[i & 1] = ans[i & 1] * 10 + ((c - b'0') as i32); + let mut j = 0; + for i in 0..n { + while cnt[j] == 0 { + j += 1; + } + cnt[j] -= 1; + + ans[i & 1] = ans[i & 1] * 10 + (j as i32); } ans[0] + ans[1] diff --git a/solution/2500-2599/2578.Split With Minimum Sum/Solution2.cpp b/solution/2500-2599/2578.Split With Minimum Sum/Solution2.cpp new file mode 100644 index 0000000000000..6d1be81f843b0 --- /dev/null +++ b/solution/2500-2599/2578.Split With Minimum Sum/Solution2.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int splitNum(int num) { + string s = to_string(num); + sort(s.begin(), s.end()); + int ans[2]{}; + for (int i = 0; i < s.size(); ++i) { + ans[i & 1] = ans[i & 1] * 10 + s[i] - '0'; + } + return ans[0] + ans[1]; + } +}; \ No newline at end of file diff --git a/solution/2500-2599/2578.Split With Minimum Sum/Solution2.go b/solution/2500-2599/2578.Split With Minimum Sum/Solution2.go new file mode 100644 index 0000000000000..28ca9195c5528 --- /dev/null +++ b/solution/2500-2599/2578.Split With Minimum Sum/Solution2.go @@ -0,0 +1,9 @@ +func splitNum(num int) int { + s := []byte(strconv.Itoa(num)) + sort.Slice(s, func(i, j int) bool { return s[i] < s[j] }) + ans := [2]int{} + for i, c := range s { + ans[i&1] = ans[i&1]*10 + int(c-'0') + } + return ans[0] + ans[1] +} \ No newline at end of file diff --git a/solution/2500-2599/2578.Split With Minimum Sum/Solution2.java b/solution/2500-2599/2578.Split With Minimum Sum/Solution2.java new file mode 100644 index 0000000000000..59be565db19dc --- /dev/null +++ b/solution/2500-2599/2578.Split With Minimum Sum/Solution2.java @@ -0,0 +1,11 @@ +class Solution { + public int splitNum(int num) { + char[] s = (num + "").toCharArray(); + Arrays.sort(s); + int[] ans = new int[2]; + for (int i = 0; i < s.length; ++i) { + ans[i & 1] = ans[i & 1] * 10 + s[i] - '0'; + } + return ans[0] + ans[1]; + } +} \ No newline at end of file diff --git a/solution/2500-2599/2578.Split With Minimum Sum/Solution2.py b/solution/2500-2599/2578.Split With Minimum Sum/Solution2.py new file mode 100644 index 0000000000000..a4e5bf9621dab --- /dev/null +++ b/solution/2500-2599/2578.Split With Minimum Sum/Solution2.py @@ -0,0 +1,4 @@ +class Solution: + def splitNum(self, num: int) -> int: + s = sorted(str(num)) + return int(''.join(s[::2])) + int(''.join(s[1::2])) diff --git a/solution/2500-2599/2578.Split With Minimum Sum/Solution2.rs b/solution/2500-2599/2578.Split With Minimum Sum/Solution2.rs new file mode 100644 index 0000000000000..05ded3c50570d --- /dev/null +++ b/solution/2500-2599/2578.Split With Minimum Sum/Solution2.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn split_num(num: i32) -> i32 { + let mut s = num.to_string().into_bytes(); + s.sort_unstable(); + + let mut ans = vec![0; 2]; + for (i, c) in s.iter().enumerate() { + ans[i & 1] = ans[i & 1] * 10 + ((c - b'0') as i32); + } + + ans[0] + ans[1] + } +} diff --git a/solution/2500-2599/2578.Split With Minimum Sum/Solution2.ts b/solution/2500-2599/2578.Split With Minimum Sum/Solution2.ts new file mode 100644 index 0000000000000..378008b725a69 --- /dev/null +++ b/solution/2500-2599/2578.Split With Minimum Sum/Solution2.ts @@ -0,0 +1,9 @@ +function splitNum(num: number): number { + const s: string[] = String(num).split(''); + s.sort(); + const ans: number[] = Array(2).fill(0); + for (let i = 0; i < s.length; ++i) { + ans[i & 1] = ans[i & 1] * 10 + Number(s[i]); + } + return ans[0] + ans[1]; +} diff --git a/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution.cpp b/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution.cpp index ee32b2d974ece..2e87162537e3b 100644 --- a/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution.cpp +++ b/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - int countWays(vector>& ranges) { - sort(ranges.begin(), ranges.end()); - int cnt = 0, mx = -1; - for (auto& e : ranges) { - cnt += e[0] > mx; - mx = max(mx, e[1]); - } - using ll = long long; - auto qpow = [&](ll a, int n, int mod) { - ll ans = 1; - for (; n; n >>= 1) { - if (n & 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return ans; - }; - return qpow(2, cnt, 1e9 + 7); - } +class Solution { +public: + int countWays(vector>& ranges) { + sort(ranges.begin(), ranges.end()); + int cnt = 0, mx = -1; + for (auto& e : ranges) { + cnt += e[0] > mx; + mx = max(mx, e[1]); + } + using ll = long long; + auto qpow = [&](ll a, int n, int mod) { + ll ans = 1; + for (; n; n >>= 1) { + if (n & 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return ans; + }; + return qpow(2, cnt, 1e9 + 7); + } }; \ No newline at end of file diff --git a/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution.java b/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution.java index 9ee8a50921283..b6b7d2b29d838 100644 --- a/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution.java +++ b/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution.java @@ -1,24 +1,24 @@ -class Solution { - public int countWays(int[][] ranges) { - Arrays.sort(ranges, (a, b) -> a[0] - b[0]); - int cnt = 0, mx = -1; - for (int[] e : ranges) { - if (e[0] > mx) { - ++cnt; - } - mx = Math.max(mx, e[1]); - } - return qpow(2, cnt, (int) 1e9 + 7); - } - - private int qpow(long a, int n, int mod) { - long ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return (int) ans; - } +class Solution { + public int countWays(int[][] ranges) { + Arrays.sort(ranges, (a, b) -> a[0] - b[0]); + int cnt = 0, mx = -1; + for (int[] e : ranges) { + if (e[0] > mx) { + ++cnt; + } + mx = Math.max(mx, e[1]); + } + return qpow(2, cnt, (int) 1e9 + 7); + } + + private int qpow(long a, int n, int mod) { + long ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return (int) ans; + } } \ No newline at end of file diff --git a/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution2.cpp b/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution2.cpp new file mode 100644 index 0000000000000..ea304375ce07f --- /dev/null +++ b/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution2.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int countWays(vector>& ranges) { + sort(ranges.begin(), ranges.end()); + int ans = 1, mx = -1; + const int mod = 1e9 + 7; + for (auto& e : ranges) { + if (e[0] > mx) { + ans = ans * 2 % mod; + } + mx = max(mx, e[1]); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution2.go b/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution2.go new file mode 100644 index 0000000000000..c68838396fcb4 --- /dev/null +++ b/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution2.go @@ -0,0 +1,14 @@ +func countWays(ranges [][]int) int { + sort.Slice(ranges, func(i, j int) bool { return ranges[i][0] < ranges[j][0] }) + ans, mx := 1, -1 + const mod = 1e9 + 7 + for _, e := range ranges { + if e[0] > mx { + ans = ans * 2 % mod + } + if mx < e[1] { + mx = e[1] + } + } + return ans +} \ No newline at end of file diff --git a/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution2.java b/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution2.java new file mode 100644 index 0000000000000..e00f0f431c025 --- /dev/null +++ b/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public int countWays(int[][] ranges) { + Arrays.sort(ranges, (a, b) -> a[0] - b[0]); + int mx = -1; + int ans = 1; + final int mod = (int) 1e9 + 7; + for (int[] e : ranges) { + if (e[0] > mx) { + ans = ans * 2 % mod; + } + mx = Math.max(mx, e[1]); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution2.py b/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution2.py new file mode 100644 index 0000000000000..2febd05b5eeab --- /dev/null +++ b/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def countWays(self, ranges: List[List[int]]) -> int: + ranges.sort() + mx = -1 + mod = 10**9 + 7 + ans = 1 + for start, end in ranges: + if start > mx: + ans = ans * 2 % mod + mx = max(mx, end) + return ans diff --git a/solution/2500-2599/2582.Pass the Pillow/Solution.cpp b/solution/2500-2599/2582.Pass the Pillow/Solution.cpp index f614ab1ad67d8..7440e2c241e1c 100644 --- a/solution/2500-2599/2582.Pass the Pillow/Solution.cpp +++ b/solution/2500-2599/2582.Pass the Pillow/Solution.cpp @@ -1,8 +1,13 @@ class Solution { public: int passThePillow(int n, int time) { - int k = time / (n - 1); - int mod = time % (n - 1); - return k & 1 ? n - mod : mod + 1; + int ans = 1, k = 1; + while (time--) { + ans += k; + if (ans == 1 || ans == n) { + k *= -1; + } + } + return ans; } }; \ No newline at end of file diff --git a/solution/2500-2599/2582.Pass the Pillow/Solution.go b/solution/2500-2599/2582.Pass the Pillow/Solution.go index 085fd638dded4..a53172993903d 100644 --- a/solution/2500-2599/2582.Pass the Pillow/Solution.go +++ b/solution/2500-2599/2582.Pass the Pillow/Solution.go @@ -1,7 +1,10 @@ func passThePillow(n int, time int) int { - k, mod := time/(n-1), time%(n-1) - if k&1 == 1 { - return n - mod + ans, k := 1, 1 + for ; time > 0; time-- { + ans += k + if ans == 1 || ans == n { + k *= -1 + } } - return mod + 1 + return ans } \ No newline at end of file diff --git a/solution/2500-2599/2582.Pass the Pillow/Solution.java b/solution/2500-2599/2582.Pass the Pillow/Solution.java index 4378941d504bb..b2818c58dd452 100644 --- a/solution/2500-2599/2582.Pass the Pillow/Solution.java +++ b/solution/2500-2599/2582.Pass the Pillow/Solution.java @@ -1,7 +1,12 @@ class Solution { public int passThePillow(int n, int time) { - int k = time / (n - 1); - int mod = time % (n - 1); - return (k & 1) == 1 ? n - mod : mod + 1; + int ans = 1, k = 1; + while (time-- > 0) { + ans += k; + if (ans == 1 || ans == n) { + k *= -1; + } + } + return ans; } } \ No newline at end of file diff --git a/solution/2500-2599/2582.Pass the Pillow/Solution.py b/solution/2500-2599/2582.Pass the Pillow/Solution.py index ce2c3a243a64e..9c3996bd0d1cd 100644 --- a/solution/2500-2599/2582.Pass the Pillow/Solution.py +++ b/solution/2500-2599/2582.Pass the Pillow/Solution.py @@ -1,4 +1,8 @@ class Solution: def passThePillow(self, n: int, time: int) -> int: - k, mod = divmod(time, n - 1) - return n - mod if k & 1 else mod + 1 + ans = k = 1 + for _ in range(time): + ans += k + if ans == 1 or ans == n: + k *= -1 + return ans diff --git a/solution/2500-2599/2582.Pass the Pillow/Solution.rs b/solution/2500-2599/2582.Pass the Pillow/Solution.rs index 1f72f9bcdcbd4..12795923bb587 100644 --- a/solution/2500-2599/2582.Pass the Pillow/Solution.rs +++ b/solution/2500-2599/2582.Pass the Pillow/Solution.rs @@ -1,12 +1,16 @@ impl Solution { pub fn pass_the_pillow(n: i32, time: i32) -> i32 { - let mut k = time / (n - 1); - let mut _mod = time % (n - 1); + let mut ans = 1; + let mut k = 1; - if (k & 1) == 1 { - return n - _mod; + for i in 1..=time { + ans += k; + + if ans == 1 || ans == n { + k *= -1; + } } - _mod + 1 + ans } } diff --git a/solution/2500-2599/2582.Pass the Pillow/Solution.ts b/solution/2500-2599/2582.Pass the Pillow/Solution.ts index 4af6cb1ba16ff..97dd57b151d59 100644 --- a/solution/2500-2599/2582.Pass the Pillow/Solution.ts +++ b/solution/2500-2599/2582.Pass the Pillow/Solution.ts @@ -1,5 +1,11 @@ function passThePillow(n: number, time: number): number { - const k = time / (n - 1); - const mod = time % (n - 1); - return (k & 1) == 1 ? n - mod : mod + 1; + let ans = 1, + k = 1; + while (time-- > 0) { + ans += k; + if (ans === 1 || ans === n) { + k *= -1; + } + } + return ans; } diff --git a/solution/2500-2599/2582.Pass the Pillow/Solution2.cpp b/solution/2500-2599/2582.Pass the Pillow/Solution2.cpp new file mode 100644 index 0000000000000..f614ab1ad67d8 --- /dev/null +++ b/solution/2500-2599/2582.Pass the Pillow/Solution2.cpp @@ -0,0 +1,8 @@ +class Solution { +public: + int passThePillow(int n, int time) { + int k = time / (n - 1); + int mod = time % (n - 1); + return k & 1 ? n - mod : mod + 1; + } +}; \ No newline at end of file diff --git a/solution/2500-2599/2582.Pass the Pillow/Solution2.go b/solution/2500-2599/2582.Pass the Pillow/Solution2.go new file mode 100644 index 0000000000000..085fd638dded4 --- /dev/null +++ b/solution/2500-2599/2582.Pass the Pillow/Solution2.go @@ -0,0 +1,7 @@ +func passThePillow(n int, time int) int { + k, mod := time/(n-1), time%(n-1) + if k&1 == 1 { + return n - mod + } + return mod + 1 +} \ No newline at end of file diff --git a/solution/2500-2599/2582.Pass the Pillow/Solution2.java b/solution/2500-2599/2582.Pass the Pillow/Solution2.java new file mode 100644 index 0000000000000..4378941d504bb --- /dev/null +++ b/solution/2500-2599/2582.Pass the Pillow/Solution2.java @@ -0,0 +1,7 @@ +class Solution { + public int passThePillow(int n, int time) { + int k = time / (n - 1); + int mod = time % (n - 1); + return (k & 1) == 1 ? n - mod : mod + 1; + } +} \ No newline at end of file diff --git a/solution/2500-2599/2582.Pass the Pillow/Solution2.py b/solution/2500-2599/2582.Pass the Pillow/Solution2.py new file mode 100644 index 0000000000000..ce2c3a243a64e --- /dev/null +++ b/solution/2500-2599/2582.Pass the Pillow/Solution2.py @@ -0,0 +1,4 @@ +class Solution: + def passThePillow(self, n: int, time: int) -> int: + k, mod = divmod(time, n - 1) + return n - mod if k & 1 else mod + 1 diff --git a/solution/2500-2599/2582.Pass the Pillow/Solution2.rs b/solution/2500-2599/2582.Pass the Pillow/Solution2.rs new file mode 100644 index 0000000000000..1f72f9bcdcbd4 --- /dev/null +++ b/solution/2500-2599/2582.Pass the Pillow/Solution2.rs @@ -0,0 +1,12 @@ +impl Solution { + pub fn pass_the_pillow(n: i32, time: i32) -> i32 { + let mut k = time / (n - 1); + let mut _mod = time % (n - 1); + + if (k & 1) == 1 { + return n - _mod; + } + + _mod + 1 + } +} diff --git a/solution/2500-2599/2582.Pass the Pillow/Solution2.ts b/solution/2500-2599/2582.Pass the Pillow/Solution2.ts new file mode 100644 index 0000000000000..4af6cb1ba16ff --- /dev/null +++ b/solution/2500-2599/2582.Pass the Pillow/Solution2.ts @@ -0,0 +1,5 @@ +function passThePillow(n: number, time: number): number { + const k = time / (n - 1); + const mod = time % (n - 1); + return (k & 1) == 1 ? n - mod : mod + 1; +} diff --git a/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/Solution2.cpp b/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/Solution2.cpp new file mode 100644 index 0000000000000..4bbc8040ab0f3 --- /dev/null +++ b/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/Solution2.cpp @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + long long kthLargestLevelSum(TreeNode* root, int k) { + vector arr; + function dfs = [&](TreeNode* root, int d) { + if (!root) { + return; + } + if (arr.size() <= d) { + arr.push_back(0); + } + arr[d] += root->val; + dfs(root->left, d + 1); + dfs(root->right, d + 1); + }; + dfs(root, 0); + if (arr.size() < k) { + return -1; + } + sort(arr.rbegin(), arr.rend()); + return arr[k - 1]; + } +}; \ No newline at end of file diff --git a/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/Solution2.go b/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/Solution2.go new file mode 100644 index 0000000000000..159afa99a59c7 --- /dev/null +++ b/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/Solution2.go @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func kthLargestLevelSum(root *TreeNode, k int) int64 { + arr := []int{} + var dfs func(*TreeNode, int) + dfs = func(root *TreeNode, d int) { + if root == nil { + return + } + if len(arr) <= d { + arr = append(arr, 0) + } + arr[d] += root.Val + dfs(root.Left, d+1) + dfs(root.Right, d+1) + } + + dfs(root, 0) + if n := len(arr); n >= k { + sort.Ints(arr) + return int64(arr[n-k]) + } + return -1 +} \ No newline at end of file diff --git a/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/Solution2.java b/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/Solution2.java new file mode 100644 index 0000000000000..84cc935c336e3 --- /dev/null +++ b/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/Solution2.java @@ -0,0 +1,39 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private List arr = new ArrayList<>(); + + public long kthLargestLevelSum(TreeNode root, int k) { + dfs(root, 0); + if (arr.size() < k) { + return -1; + } + Collections.sort(arr, Collections.reverseOrder()); + return arr.get(k - 1); + } + + private void dfs(TreeNode root, int d) { + if (root == null) { + return; + } + if (arr.size() <= d) { + arr.add(0L); + } + arr.set(d, arr.get(d) + root.val); + dfs(root.left, d + 1); + dfs(root.right, d + 1); + } +} \ No newline at end of file diff --git a/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/Solution2.py b/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/Solution2.py new file mode 100644 index 0000000000000..e42ccc61937c0 --- /dev/null +++ b/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/Solution2.py @@ -0,0 +1,20 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def kthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int: + def dfs(root, d): + if root is None: + return + if len(arr) <= d: + arr.append(0) + arr[d] += root.val + dfs(root.left, d + 1) + dfs(root.right, d + 1) + + arr = [] + dfs(root, 0) + return -1 if len(arr) < k else nlargest(k, arr)[-1] diff --git a/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/Solution2.ts b/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/Solution2.ts new file mode 100644 index 0000000000000..4d44fd0ed77f6 --- /dev/null +++ b/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/Solution2.ts @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function kthLargestLevelSum(root: TreeNode | null, k: number): number { + const dfs = (root: TreeNode, d: number) => { + if (!root) { + return; + } + if (arr.length <= d) { + arr.push(0); + } + arr[d] += root.val; + dfs(root.left, d + 1); + dfs(root.right, d + 1); + }; + const arr: number[] = []; + dfs(root, 0); + if (arr.length < k) { + return -1; + } + arr.sort((a, b) => b - a); + return arr[k - 1]; +} diff --git a/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution2.cpp b/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution2.cpp new file mode 100644 index 0000000000000..cee8f0182d2f9 --- /dev/null +++ b/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution2.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + long long findScore(vector& nums) { + int n = nums.size(); + vector idx(n); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { + return nums[i] < nums[j] || (nums[i] == nums[j] && i < j); + }); + long long ans = 0; + vector vis(n + 2); + for (int i : idx) { + if (!vis[i + 1]) { + ans += nums[i]; + vis[i] = vis[i + 2] = true; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution2.go b/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution2.go new file mode 100644 index 0000000000000..81caa4bd964af --- /dev/null +++ b/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution2.go @@ -0,0 +1,19 @@ +func findScore(nums []int) (ans int64) { + n := len(nums) + idx := make([]int, n) + for i := range idx { + idx[i] = i + } + sort.Slice(idx, func(i, j int) bool { + i, j = idx[i], idx[j] + return nums[i] < nums[j] || (nums[i] == nums[j] && i < j) + }) + vis := make([]bool, n+2) + for _, i := range idx { + if !vis[i+1] { + ans += int64(nums[i]) + vis[i], vis[i+2] = true, true + } + } + return +} \ No newline at end of file diff --git a/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution2.java b/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution2.java new file mode 100644 index 0000000000000..960c61cb37d47 --- /dev/null +++ b/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution2.java @@ -0,0 +1,20 @@ +class Solution { + public long findScore(int[] nums) { + int n = nums.length; + boolean[] vis = new boolean[n + 2]; + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; ++i) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> nums[i] - nums[j]); + long ans = 0; + for (int i : idx) { + if (!vis[i + 1]) { + ans += nums[i]; + vis[i] = true; + vis[i + 2] = true; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution2.py b/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution2.py new file mode 100644 index 0000000000000..26995e933695a --- /dev/null +++ b/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution2.py @@ -0,0 +1,11 @@ +class Solution: + def findScore(self, nums: List[int]) -> int: + n = len(nums) + vis = [False] * (n + 2) + idx = sorted(range(n), key=lambda i: (nums[i], i)) + ans = 0 + for i in idx: + if not vis[i + 1]: + ans += nums[i] + vis[i] = vis[i + 2] = True + return ans diff --git a/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution2.ts b/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution2.ts new file mode 100644 index 0000000000000..11b6830161e97 --- /dev/null +++ b/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution2.ts @@ -0,0 +1,18 @@ +function findScore(nums: number[]): number { + const n = nums.length; + const idx: number[] = new Array(n); + for (let i = 0; i < n; ++i) { + idx[i] = i; + } + idx.sort((i, j) => (nums[i] == nums[j] ? i - j : nums[i] - nums[j])); + const vis: boolean[] = new Array(n + 2).fill(false); + let ans = 0; + for (const i of idx) { + if (!vis[i + 1]) { + ans += nums[i]; + vis[i] = true; + vis[i + 2] = true; + } + } + return ans; +} diff --git a/solution/2500-2599/2594.Minimum Time to Repair Cars/Solution.py b/solution/2500-2599/2594.Minimum Time to Repair Cars/Solution.py index 805f9eac4ac7c..572c39a47a538 100644 --- a/solution/2500-2599/2594.Minimum Time to Repair Cars/Solution.py +++ b/solution/2500-2599/2594.Minimum Time to Repair Cars/Solution.py @@ -1,6 +1,6 @@ -class Solution: - def repairCars(self, ranks: List[int], cars: int) -> int: - def check(t: int) -> bool: - return sum(int(sqrt(t // r)) for r in ranks) >= cars - - return bisect_left(range(ranks[0] * cars * cars), True, key=check) +class Solution: + def repairCars(self, ranks: List[int], cars: int) -> int: + def check(t: int) -> bool: + return sum(int(sqrt(t // r)) for r in ranks) >= cars + + return bisect_left(range(ranks[0] * cars * cars), True, key=check) diff --git a/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.cpp b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.cpp index 99e9a81c43f92..c69b22fe67729 100644 --- a/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.cpp +++ b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.cpp @@ -1,9 +1,10 @@ -class Solution { -public: - vector evenOddBit(int n) { - int mask = 0x5555; - int even = __builtin_popcount(n & mask); - int odd = __builtin_popcount(n & ~mask); - return {even, odd}; - } +class Solution { +public: + vector evenOddBit(int n) { + vector ans(2); + for (int i = 0; n > 0; n >>= 1, i ^= 1) { + ans[i] += n & 1; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.go b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.go index 3a74ff14f44ba..8d2ee41f3d99d 100644 --- a/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.go +++ b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.go @@ -1,6 +1,7 @@ func evenOddBit(n int) []int { - mask := 0x5555 - even := bits.OnesCount32(uint32(n & mask)) - odd := bits.OnesCount32(uint32(n & ^mask)) - return []int{even, odd} + ans := make([]int, 2) + for i := 0; n != 0; n, i = n>>1, i^1 { + ans[i] += n & 1 + } + return ans } \ No newline at end of file diff --git a/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.java b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.java index dc55fd9692b5a..04f443c5138bb 100644 --- a/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.java +++ b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.java @@ -1,8 +1,9 @@ -class Solution { - public int[] evenOddBit(int n) { - int mask = 0x5555; - int even = Integer.bitCount(n & mask); - int odd = Integer.bitCount(n & ~mask); - return new int[] {even, odd}; - } +class Solution { + public int[] evenOddBit(int n) { + int[] ans = new int[2]; + for (int i = 0; n > 0; n >>= 1, i ^= 1) { + ans[i] += n & 1; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.py b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.py index 39528ec3e4d8c..cc30bcdbd7e58 100644 --- a/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.py +++ b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.py @@ -1,6 +1,9 @@ -class Solution: - def evenOddBit(self, n: int) -> List[int]: - mask = 0x5555 - even = (n & mask).bit_count() - odd = (n & ~mask).bit_count() - return [even, odd] +class Solution: + def evenOddBit(self, n: int) -> List[int]: + ans = [0, 0] + i = 0 + while n: + ans[i] += n & 1 + i ^= 1 + n >>= 1 + return ans diff --git a/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.rs b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.rs index afb114de66a98..0c19d1c9ce05e 100644 --- a/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.rs +++ b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution.rs @@ -1,8 +1,15 @@ impl Solution { - pub fn even_odd_bit(n: i32) -> Vec { - let mask: i32 = 0x5555; - let even = (n & mask).count_ones() as i32; - let odd = (n & !mask).count_ones() as i32; - vec![even, odd] + pub fn even_odd_bit(mut n: i32) -> Vec { + let mut ans = vec![0; 2]; + + let mut i = 0; + while n != 0 { + ans[i] += n & 1; + + n >>= 1; + i ^= 1; + } + + ans } } diff --git a/solution/2500-2599/2595.Number of Even and Odd Bits/Solution2.cpp b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution2.cpp new file mode 100644 index 0000000000000..a76b67346a4a2 --- /dev/null +++ b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution2.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + vector evenOddBit(int n) { + int mask = 0x5555; + int even = __builtin_popcount(n & mask); + int odd = __builtin_popcount(n & ~mask); + return {even, odd}; + } +}; \ No newline at end of file diff --git a/solution/2500-2599/2595.Number of Even and Odd Bits/Solution2.go b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution2.go new file mode 100644 index 0000000000000..3a74ff14f44ba --- /dev/null +++ b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution2.go @@ -0,0 +1,6 @@ +func evenOddBit(n int) []int { + mask := 0x5555 + even := bits.OnesCount32(uint32(n & mask)) + odd := bits.OnesCount32(uint32(n & ^mask)) + return []int{even, odd} +} \ No newline at end of file diff --git a/solution/2500-2599/2595.Number of Even and Odd Bits/Solution2.java b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution2.java new file mode 100644 index 0000000000000..694b31bfb8d65 --- /dev/null +++ b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution2.java @@ -0,0 +1,8 @@ +class Solution { + public int[] evenOddBit(int n) { + int mask = 0x5555; + int even = Integer.bitCount(n & mask); + int odd = Integer.bitCount(n & ~mask); + return new int[] {even, odd}; + } +} \ No newline at end of file diff --git a/solution/2500-2599/2595.Number of Even and Odd Bits/Solution2.py b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution2.py new file mode 100644 index 0000000000000..af3e0a69d67d8 --- /dev/null +++ b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution2.py @@ -0,0 +1,6 @@ +class Solution: + def evenOddBit(self, n: int) -> List[int]: + mask = 0x5555 + even = (n & mask).bit_count() + odd = (n & ~mask).bit_count() + return [even, odd] diff --git a/solution/2500-2599/2595.Number of Even and Odd Bits/Solution2.rs b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution2.rs new file mode 100644 index 0000000000000..afb114de66a98 --- /dev/null +++ b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution2.rs @@ -0,0 +1,8 @@ +impl Solution { + pub fn even_odd_bit(n: i32) -> Vec { + let mask: i32 = 0x5555; + let even = (n & mask).count_ones() as i32; + let odd = (n & !mask).count_ones() as i32; + vec![even, odd] + } +} diff --git a/solution/2500-2599/2595.Number of Even and Odd Bits/Solution2.ts b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution2.ts new file mode 100644 index 0000000000000..9f726b5fcb2fb --- /dev/null +++ b/solution/2500-2599/2595.Number of Even and Odd Bits/Solution2.ts @@ -0,0 +1,15 @@ +function evenOddBit(n: number): number[] { + const mask = 0x5555; + const even = bitCount(n & mask); + const odd = bitCount(n & ~mask); + return [even, odd]; +} + +function bitCount(i: number): number { + i = i - ((i >>> 1) & 0x55555555); + i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); + i = (i + (i >>> 4)) & 0x0f0f0f0f; + i = i + (i >>> 8); + i = i + (i >>> 16); + return i & 0x3f; +} diff --git a/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.cpp b/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.cpp index 67bb6be23464d..d06396be47541 100644 --- a/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.cpp +++ b/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.cpp @@ -1,12 +1,12 @@ -class Solution { -public: - int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { - if (numOnes >= k) { - return k; - } - if (numZeros >= k - numOnes) { - return numOnes; - } - return numOnes - (k - numOnes - numZeros); - } +class Solution { +public: + int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { + if (numOnes >= k) { + return k; + } + if (numZeros >= k - numOnes) { + return numOnes; + } + return numOnes - (k - numOnes - numZeros); + } }; \ No newline at end of file diff --git a/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.cs b/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.cs index ce191e7a3db0d..a4238057a321d 100644 --- a/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.cs +++ b/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.cs @@ -1,11 +1,11 @@ -public class Solution { - public int KItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { - if (numOnes >= k) { - return k; - } - if (numZeros >= k - numOnes) { - return numOnes; - } - return numOnes - (k - numOnes - numZeros); - } -} \ No newline at end of file +public class Solution { + public int KItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { + if (numOnes >= k) { + return k; + } + if (numZeros >= k - numOnes) { + return numOnes; + } + return numOnes - (k - numOnes - numZeros); + } +} diff --git a/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.java b/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.java index 144ab3f8fac0a..20f032fd38965 100644 --- a/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.java +++ b/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.java @@ -1,11 +1,11 @@ -class Solution { - public int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { - if (numOnes >= k) { - return k; - } - if (numZeros >= k - numOnes) { - return numOnes; - } - return numOnes - (k - numOnes - numZeros); - } +class Solution { + public int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { + if (numOnes >= k) { + return k; + } + if (numZeros >= k - numOnes) { + return numOnes; + } + return numOnes - (k - numOnes - numZeros); + } } \ No newline at end of file diff --git a/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.py b/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.py index ab06be0eff776..1f8014b968dfa 100644 --- a/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.py +++ b/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def kItemsWithMaximumSum( - self, numOnes: int, numZeros: int, numNegOnes: int, k: int - ) -> int: - if numOnes >= k: - return k - if numZeros >= k - numOnes: - return numOnes - return numOnes - (k - numOnes - numZeros) +class Solution: + def kItemsWithMaximumSum( + self, numOnes: int, numZeros: int, numNegOnes: int, k: int + ) -> int: + if numOnes >= k: + return k + if numZeros >= k - numOnes: + return numOnes + return numOnes - (k - numOnes - numZeros) diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.cpp b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.cpp index b5bcf71e0cd3b..0e5298d8239b3 100644 --- a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.cpp +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.cpp @@ -1,19 +1,16 @@ class Solution { public: int minNumber(vector& nums1, vector& nums2) { - int mask1 = 0, mask2 = 0; - for (int x : nums1) { - mask1 |= 1 << x; + int ans = 100; + for (int a : nums1) { + for (int b : nums2) { + if (a == b) { + ans = min(ans, a); + } else { + ans = min({ans, a * 10 + b, b * 10 + a}); + } + } } - for (int x : nums2) { - mask2 |= 1 << x; - } - int mask = mask1 & mask2; - if (mask) { - return __builtin_ctz(mask); - } - int a = __builtin_ctz(mask1); - int b = __builtin_ctz(mask2); - return min(a * 10 + b, b * 10 + a); + return ans; } }; \ No newline at end of file diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.go b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.go index f1a4a02631784..f0d349d35ebf6 100644 --- a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.go +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.go @@ -1,14 +1,13 @@ func minNumber(nums1 []int, nums2 []int) int { - var mask1, mask2 uint - for _, x := range nums1 { - mask1 |= 1 << x + ans := 100 + for _, a := range nums1 { + for _, b := range nums2 { + if a == b { + ans = min(ans, a) + } else { + ans = min(ans, min(a*10+b, b*10+a)) + } + } } - for _, x := range nums2 { - mask2 |= 1 << x - } - if mask := mask1 & mask2; mask != 0 { - return bits.TrailingZeros(mask) - } - a, b := bits.TrailingZeros(mask1), bits.TrailingZeros(mask2) - return min(a*10+b, b*10+a) + return ans } \ No newline at end of file diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.java b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.java index 002d72ba65520..3fb58eeeeaa61 100644 --- a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.java +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.java @@ -1,18 +1,15 @@ class Solution { public int minNumber(int[] nums1, int[] nums2) { - int mask1 = 0, mask2 = 0; - for (int x : nums1) { - mask1 |= 1 << x; + int ans = 100; + for (int a : nums1) { + for (int b : nums2) { + if (a == b) { + ans = Math.min(ans, a); + } else { + ans = Math.min(ans, Math.min(a * 10 + b, b * 10 + a)); + } + } } - for (int x : nums2) { - mask2 |= 1 << x; - } - int mask = mask1 & mask2; - if (mask != 0) { - return Integer.numberOfTrailingZeros(mask); - } - int a = Integer.numberOfTrailingZeros(mask1); - int b = Integer.numberOfTrailingZeros(mask2); - return Math.min(a * 10 + b, b * 10 + a); + return ans; } } \ No newline at end of file diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.py b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.py index 1c7e6038a0f7e..46585c47d6975 100644 --- a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.py +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.py @@ -1,13 +1,10 @@ class Solution: def minNumber(self, nums1: List[int], nums2: List[int]) -> int: - mask1 = mask2 = 0 - for x in nums1: - mask1 |= 1 << x - for x in nums2: - mask2 |= 1 << x - mask = mask1 & mask2 - if mask: - return (mask & -mask).bit_length() - 1 - a = (mask1 & -mask1).bit_length() - 1 - b = (mask2 & -mask2).bit_length() - 1 - return min(a * 10 + b, b * 10 + a) + ans = 100 + for a in nums1: + for b in nums2: + if a == b: + ans = min(ans, a) + else: + ans = min(ans, 10 * a + b, 10 * b + a) + return ans diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.rs b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.rs index df721423252e4..61696eb732540 100644 --- a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.rs +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.rs @@ -1,34 +1,17 @@ -use std::collections::HashMap; - impl Solution { pub fn min_number(nums1: Vec, nums2: Vec) -> i32 { - let mut h1: HashMap = HashMap::new(); - - for &n in &nums1 { - h1.insert(n, true); - } - - let mut h2: HashMap = HashMap::new(); - for &n in &nums2 { - h2.insert(n, true); - } - - let mut a = 0; - let mut b = 0; - for i in 1..10 { - if h1.contains_key(&i) && h2.contains_key(&i) { - return i; - } - - if a == 0 && h1.contains_key(&i) { - a = i; - } + let mut ans = 100; - if b == 0 && h2.contains_key(&i) { - b = i; + for &a in &nums1 { + for &b in &nums2 { + if a == b { + ans = std::cmp::min(ans, a); + } else { + ans = std::cmp::min(ans, std::cmp::min(a * 10 + b, b * 10 + a)); + } } } - std::cmp::min(a * 10 + b, b * 10 + a) + ans } } diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.ts b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.ts index 4694d1b93a6da..37494c84c2308 100644 --- a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.ts +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.ts @@ -1,46 +1,13 @@ function minNumber(nums1: number[], nums2: number[]): number { - let mask1: number = 0; - let mask2: number = 0; - for (const x of nums1) { - mask1 |= 1 << x; - } - for (const x of nums2) { - mask2 |= 1 << x; - } - const mask = mask1 & mask2; - if (mask !== 0) { - return numberOfTrailingZeros(mask); - } - const a = numberOfTrailingZeros(mask1); - const b = numberOfTrailingZeros(mask2); - return Math.min(a * 10 + b, b * 10 + a); -} - -function numberOfTrailingZeros(i: number): number { - let y = 0; - if (i === 0) { - return 32; - } - let n = 31; - y = i << 16; - if (y != 0) { - n = n - 16; - i = y; - } - y = i << 8; - if (y != 0) { - n = n - 8; - i = y; - } - y = i << 4; - if (y != 0) { - n = n - 4; - i = y; - } - y = i << 2; - if (y != 0) { - n = n - 2; - i = y; - } - return n - ((i << 1) >>> 31); + let ans = 100; + for (const a of nums1) { + for (const b of nums2) { + if (a === b) { + ans = Math.min(ans, a); + } else { + ans = Math.min(ans, a * 10 + b, b * 10 + a); + } + } + } + return ans; } diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution2.cpp b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution2.cpp new file mode 100644 index 0000000000000..a5f20188cc8bc --- /dev/null +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution2.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int minNumber(vector& nums1, vector& nums2) { + bitset<10> s1; + bitset<10> s2; + for (int x : nums1) { + s1[x] = 1; + } + for (int x : nums2) { + s2[x] = 1; + } + int a = 0, b = 0; + for (int i = 1; i < 10; ++i) { + if (s1[i] && s2[i]) { + return i; + } + if (!a && s1[i]) { + a = i; + } + if (!b && s2[i]) { + b = i; + } + } + return min(a * 10 + b, b * 10 + a); + } +}; \ No newline at end of file diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution2.go b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution2.go new file mode 100644 index 0000000000000..a472acbf0ee6d --- /dev/null +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution2.go @@ -0,0 +1,23 @@ +func minNumber(nums1 []int, nums2 []int) int { + s1 := [10]bool{} + s2 := [10]bool{} + for _, x := range nums1 { + s1[x] = true + } + for _, x := range nums2 { + s2[x] = true + } + a, b := 0, 0 + for i := 1; i < 10; i++ { + if s1[i] && s2[i] { + return i + } + if a == 0 && s1[i] { + a = i + } + if b == 0 && s2[i] { + b = i + } + } + return min(a*10+b, b*10+a) +} \ No newline at end of file diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution2.java b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution2.java new file mode 100644 index 0000000000000..6974b3c93f004 --- /dev/null +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution2.java @@ -0,0 +1,25 @@ +class Solution { + public int minNumber(int[] nums1, int[] nums2) { + boolean[] s1 = new boolean[10]; + boolean[] s2 = new boolean[10]; + for (int x : nums1) { + s1[x] = true; + } + for (int x : nums2) { + s2[x] = true; + } + int a = 0, b = 0; + for (int i = 1; i < 10; ++i) { + if (s1[i] && s2[i]) { + return i; + } + if (a == 0 && s1[i]) { + a = i; + } + if (b == 0 && s2[i]) { + b = i; + } + } + return Math.min(a * 10 + b, b * 10 + a); + } +} \ No newline at end of file diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution2.py b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution2.py new file mode 100644 index 0000000000000..7405ee93a4b14 --- /dev/null +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def minNumber(self, nums1: List[int], nums2: List[int]) -> int: + s = set(nums1) & set(nums2) + if s: + return min(s) + a, b = min(nums1), min(nums2) + return min(a * 10 + b, b * 10 + a) diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution2.rs b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution2.rs new file mode 100644 index 0000000000000..df721423252e4 --- /dev/null +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution2.rs @@ -0,0 +1,34 @@ +use std::collections::HashMap; + +impl Solution { + pub fn min_number(nums1: Vec, nums2: Vec) -> i32 { + let mut h1: HashMap = HashMap::new(); + + for &n in &nums1 { + h1.insert(n, true); + } + + let mut h2: HashMap = HashMap::new(); + for &n in &nums2 { + h2.insert(n, true); + } + + let mut a = 0; + let mut b = 0; + for i in 1..10 { + if h1.contains_key(&i) && h2.contains_key(&i) { + return i; + } + + if a == 0 && h1.contains_key(&i) { + a = i; + } + + if b == 0 && h2.contains_key(&i) { + b = i; + } + } + + std::cmp::min(a * 10 + b, b * 10 + a) + } +} diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution2.ts b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution2.ts new file mode 100644 index 0000000000000..1dd7333d3293b --- /dev/null +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution2.ts @@ -0,0 +1,24 @@ +function minNumber(nums1: number[], nums2: number[]): number { + const s1: boolean[] = new Array(10).fill(false); + const s2: boolean[] = new Array(10).fill(false); + for (const x of nums1) { + s1[x] = true; + } + for (const x of nums2) { + s2[x] = true; + } + let a = 0; + let b = 0; + for (let i = 1; i < 10; ++i) { + if (s1[i] && s2[i]) { + return i; + } + if (a === 0 && s1[i]) { + a = i; + } + if (b === 0 && s2[i]) { + b = i; + } + } + return Math.min(a * 10 + b, b * 10 + a); +} diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution3.cpp b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution3.cpp new file mode 100644 index 0000000000000..b5bcf71e0cd3b --- /dev/null +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution3.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int minNumber(vector& nums1, vector& nums2) { + int mask1 = 0, mask2 = 0; + for (int x : nums1) { + mask1 |= 1 << x; + } + for (int x : nums2) { + mask2 |= 1 << x; + } + int mask = mask1 & mask2; + if (mask) { + return __builtin_ctz(mask); + } + int a = __builtin_ctz(mask1); + int b = __builtin_ctz(mask2); + return min(a * 10 + b, b * 10 + a); + } +}; \ No newline at end of file diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution3.go b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution3.go new file mode 100644 index 0000000000000..f1a4a02631784 --- /dev/null +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution3.go @@ -0,0 +1,14 @@ +func minNumber(nums1 []int, nums2 []int) int { + var mask1, mask2 uint + for _, x := range nums1 { + mask1 |= 1 << x + } + for _, x := range nums2 { + mask2 |= 1 << x + } + if mask := mask1 & mask2; mask != 0 { + return bits.TrailingZeros(mask) + } + a, b := bits.TrailingZeros(mask1), bits.TrailingZeros(mask2) + return min(a*10+b, b*10+a) +} \ No newline at end of file diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution3.java b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution3.java new file mode 100644 index 0000000000000..002d72ba65520 --- /dev/null +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution3.java @@ -0,0 +1,18 @@ +class Solution { + public int minNumber(int[] nums1, int[] nums2) { + int mask1 = 0, mask2 = 0; + for (int x : nums1) { + mask1 |= 1 << x; + } + for (int x : nums2) { + mask2 |= 1 << x; + } + int mask = mask1 & mask2; + if (mask != 0) { + return Integer.numberOfTrailingZeros(mask); + } + int a = Integer.numberOfTrailingZeros(mask1); + int b = Integer.numberOfTrailingZeros(mask2); + return Math.min(a * 10 + b, b * 10 + a); + } +} \ No newline at end of file diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution3.py b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution3.py new file mode 100644 index 0000000000000..1c7e6038a0f7e --- /dev/null +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution3.py @@ -0,0 +1,13 @@ +class Solution: + def minNumber(self, nums1: List[int], nums2: List[int]) -> int: + mask1 = mask2 = 0 + for x in nums1: + mask1 |= 1 << x + for x in nums2: + mask2 |= 1 << x + mask = mask1 & mask2 + if mask: + return (mask & -mask).bit_length() - 1 + a = (mask1 & -mask1).bit_length() - 1 + b = (mask2 & -mask2).bit_length() - 1 + return min(a * 10 + b, b * 10 + a) diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution3.ts b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution3.ts new file mode 100644 index 0000000000000..4694d1b93a6da --- /dev/null +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution3.ts @@ -0,0 +1,46 @@ +function minNumber(nums1: number[], nums2: number[]): number { + let mask1: number = 0; + let mask2: number = 0; + for (const x of nums1) { + mask1 |= 1 << x; + } + for (const x of nums2) { + mask2 |= 1 << x; + } + const mask = mask1 & mask2; + if (mask !== 0) { + return numberOfTrailingZeros(mask); + } + const a = numberOfTrailingZeros(mask1); + const b = numberOfTrailingZeros(mask2); + return Math.min(a * 10 + b, b * 10 + a); +} + +function numberOfTrailingZeros(i: number): number { + let y = 0; + if (i === 0) { + return 32; + } + let n = 31; + y = i << 16; + if (y != 0) { + n = n - 16; + i = y; + } + y = i << 8; + if (y != 0) { + n = n - 8; + i = y; + } + y = i << 4; + if (y != 0) { + n = n - 4; + i = y; + } + y = i << 2; + if (y != 0) { + n = n - 2; + i = y; + } + return n - ((i << 1) >>> 31); +} diff --git a/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.cpp b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.cpp index 2d92dfef6c591..4d17ea6a89cb4 100644 --- a/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.cpp +++ b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.cpp @@ -7,11 +7,12 @@ class Solution { for (int i = 0; i < m; ++i) { d[chars[i] - 'a'] = vals[i]; } - int ans = 0, f = 0; + int ans = 0, tot = 0, mi = 0; for (char& c : s) { int v = d[c - 'a']; - f = max(f, 0) + v; - ans = max(ans, f); + tot += v; + ans = max(ans, tot - mi); + mi = min(mi, tot); } return ans; } diff --git a/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.go b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.go index 764da969a92c2..04492d389ff11 100644 --- a/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.go +++ b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.go @@ -6,11 +6,12 @@ func maximumCostSubstring(s string, chars string, vals []int) (ans int) { for i, c := range chars { d[c-'a'] = vals[i] } - f := 0 + tot, mi := 0, 0 for _, c := range s { v := d[c-'a'] - f = max(f, 0) + v - ans = max(ans, f) + tot += v + ans = max(ans, tot-mi) + mi = min(mi, tot) } return } \ No newline at end of file diff --git a/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.java b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.java index fc3aab51eedb4..b88a6b1fce19e 100644 --- a/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.java +++ b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.java @@ -8,12 +8,13 @@ public int maximumCostSubstring(String s, String chars, int[] vals) { for (int i = 0; i < m; ++i) { d[chars.charAt(i) - 'a'] = vals[i]; } - int ans = 0, f = 0; + int ans = 0, tot = 0, mi = 0; int n = s.length(); for (int i = 0; i < n; ++i) { int v = d[s.charAt(i) - 'a']; - f = Math.max(f, 0) + v; - ans = Math.max(ans, f); + tot += v; + ans = Math.max(ans, tot - mi); + mi = Math.min(mi, tot); } return ans; } diff --git a/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.py b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.py index e3bf230590448..44b19bcf7b72d 100644 --- a/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.py +++ b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.py @@ -1,9 +1,10 @@ class Solution: def maximumCostSubstring(self, s: str, chars: str, vals: List[int]) -> int: d = {c: v for c, v in zip(chars, vals)} - ans = f = 0 + ans = tot = mi = 0 for c in s: v = d.get(c, ord(c) - ord('a') + 1) - f = max(f, 0) + v - ans = max(ans, f) + tot += v + ans = max(ans, tot - mi) + mi = min(mi, tot) return ans diff --git a/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution2.cpp b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution2.cpp new file mode 100644 index 0000000000000..2d92dfef6c591 --- /dev/null +++ b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution2.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int maximumCostSubstring(string s, string chars, vector& vals) { + vector d(26); + iota(d.begin(), d.end(), 1); + int m = chars.size(); + for (int i = 0; i < m; ++i) { + d[chars[i] - 'a'] = vals[i]; + } + int ans = 0, f = 0; + for (char& c : s) { + int v = d[c - 'a']; + f = max(f, 0) + v; + ans = max(ans, f); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution2.go b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution2.go new file mode 100644 index 0000000000000..764da969a92c2 --- /dev/null +++ b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution2.go @@ -0,0 +1,16 @@ +func maximumCostSubstring(s string, chars string, vals []int) (ans int) { + d := [26]int{} + for i := range d { + d[i] = i + 1 + } + for i, c := range chars { + d[c-'a'] = vals[i] + } + f := 0 + for _, c := range s { + v := d[c-'a'] + f = max(f, 0) + v + ans = max(ans, f) + } + return +} \ No newline at end of file diff --git a/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution2.java b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution2.java new file mode 100644 index 0000000000000..fc3aab51eedb4 --- /dev/null +++ b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution2.java @@ -0,0 +1,20 @@ +class Solution { + public int maximumCostSubstring(String s, String chars, int[] vals) { + int[] d = new int[26]; + for (int i = 0; i < d.length; ++i) { + d[i] = i + 1; + } + int m = chars.length(); + for (int i = 0; i < m; ++i) { + d[chars.charAt(i) - 'a'] = vals[i]; + } + int ans = 0, f = 0; + int n = s.length(); + for (int i = 0; i < n; ++i) { + int v = d[s.charAt(i) - 'a']; + f = Math.max(f, 0) + v; + ans = Math.max(ans, f); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution2.py b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution2.py new file mode 100644 index 0000000000000..e3bf230590448 --- /dev/null +++ b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution2.py @@ -0,0 +1,9 @@ +class Solution: + def maximumCostSubstring(self, s: str, chars: str, vals: List[int]) -> int: + d = {c: v for c, v in zip(chars, vals)} + ans = f = 0 + for c in s: + v = d.get(c, ord(c) - ord('a') + 1) + f = max(f, 0) + v + ans = max(ans, f) + return ans diff --git a/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution2.ts b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution2.ts new file mode 100644 index 0000000000000..23e9d69707dee --- /dev/null +++ b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution2.ts @@ -0,0 +1,13 @@ +function maximumCostSubstring(s: string, chars: string, vals: number[]): number { + const d: number[] = Array.from({ length: 26 }, (_, i) => i + 1); + for (let i = 0; i < chars.length; ++i) { + d[chars.charCodeAt(i) - 97] = vals[i]; + } + let ans = 0; + let f = 0; + for (const c of s) { + f = Math.max(f, 0) + d[c.charCodeAt(0) - 97]; + ans = Math.max(ans, f); + } + return ans; +} diff --git a/solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.ts b/solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.ts index 23e9d69707dee..58888330b1584 100644 --- a/solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.ts +++ b/solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.ts @@ -1,13 +1,24 @@ -function maximumCostSubstring(s: string, chars: string, vals: number[]): number { - const d: number[] = Array.from({ length: 26 }, (_, i) => i + 1); - for (let i = 0; i < chars.length; ++i) { - d[chars.charCodeAt(i) - 97] = vals[i]; - } +function makeSubKSumEqual(arr: number[], k: number): number { + const n = arr.length; + const g = gcd(n, k); let ans = 0; - let f = 0; - for (const c of s) { - f = Math.max(f, 0) + d[c.charCodeAt(0) - 97]; - ans = Math.max(ans, f); + for (let i = 0; i < g; ++i) { + const t: number[] = []; + for (let j = i; j < n; j += g) { + t.push(arr[j]); + } + t.sort((a, b) => a - b); + const mid = t[t.length >> 1]; + for (const x of t) { + ans += Math.abs(x - mid); + } } return ans; } + +function gcd(a: number, b: number): number { + if (b === 0) { + return a; + } + return gcd(b, a % b); +} diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.cpp b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.cpp index c787615fd3559..4efc5e8da5971 100644 --- a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.cpp +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.cpp @@ -8,32 +8,28 @@ class Solution { g[v].push_back(u); } const int inf = 1 << 30; - auto bfs = [&](int u) -> int { + auto bfs = [&](int u, int v) -> int { int dist[n]; - memset(dist, -1, sizeof(dist)); + fill(dist, dist + n, inf); dist[u] = 0; - queue> q; - q.emplace(u, -1); - int ans = inf; + queue q{{u}}; while (!q.empty()) { - auto p = q.front(); - u = p.first; - int fa = p.second; + int i = q.front(); q.pop(); - for (int v : g[u]) { - if (dist[v] < 0) { - dist[v] = dist[u] + 1; - q.emplace(v, u); - } else if (v != fa) { - ans = min(ans, dist[u] + dist[v] + 1); + for (int j : g[i]) { + if ((i == u && j == v) || (i == v && j == u) || dist[j] != inf) { + continue; } + dist[j] = dist[i] + 1; + q.push(j); } } - return ans; + return dist[v] + 1; }; int ans = inf; - for (int i = 0; i < n; ++i) { - ans = min(ans, bfs(i)); + for (auto& e : edges) { + int u = e[0], v = e[1]; + ans = min(ans, bfs(u, v)); } return ans < inf ? ans : -1; } diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.go b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.go index 48cf7ff782d86..dd494859fdedb 100644 --- a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.go +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.go @@ -6,33 +6,30 @@ func findShortestCycle(n int, edges [][]int) int { g[v] = append(g[v], u) } const inf = 1 << 30 - bfs := func(u int) int { + bfs := func(u, v int) int { dist := make([]int, n) for i := range dist { - dist[i] = -1 + dist[i] = inf } dist[u] = 0 - q := [][2]int{{u, -1}} - ans := inf + q := []int{u} for len(q) > 0 { - p := q[0] - u = p[0] - fa := p[1] + i := q[0] q = q[1:] - for _, v := range g[u] { - if dist[v] < 0 { - dist[v] = dist[u] + 1 - q = append(q, [2]int{v, u}) - } else if v != fa { - ans = min(ans, dist[u]+dist[v]+1) + for _, j := range g[i] { + if (i == u && j == v) || (i == v && j == u) || dist[j] != inf { + continue } + dist[j] = dist[i] + 1 + q = append(q, j) } } - return ans + return dist[v] + 1 } ans := inf - for i := 0; i < n; i++ { - ans = min(ans, bfs(i)) + for _, e := range edges { + u, v := e[0], e[1] + ans = min(ans, bfs(u, v)) } if ans < inf { return ans diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.java b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.java index 7918b31b02a54..07997ce445eb5 100644 --- a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.java +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.java @@ -11,32 +11,29 @@ public int findShortestCycle(int n, int[][] edges) { g[v].add(u); } int ans = inf; - for (int i = 0; i < n; ++i) { - ans = Math.min(ans, bfs(i)); + for (var e : edges) { + int u = e[0], v = e[1]; + ans = Math.min(ans, bfs(u, v)); } return ans < inf ? ans : -1; } - private int bfs(int u) { + private int bfs(int u, int v) { int[] dist = new int[g.length]; - Arrays.fill(dist, -1); + Arrays.fill(dist, inf); dist[u] = 0; - Deque q = new ArrayDeque<>(); - q.offer(new int[] {u, -1}); - int ans = inf; + Deque q = new ArrayDeque<>(); + q.offer(u); while (!q.isEmpty()) { - var p = q.poll(); - u = p[0]; - int fa = p[1]; - for (int v : g[u]) { - if (dist[v] < 0) { - dist[v] = dist[u] + 1; - q.offer(new int[] {v, u}); - } else if (v != fa) { - ans = Math.min(ans, dist[u] + dist[v] + 1); + int i = q.poll(); + for (int j : g[i]) { + if ((i == u && j == v) || (i == v && j == u) || dist[j] != inf) { + continue; } + dist[j] = dist[i] + 1; + q.offer(j); } } - return ans; + return dist[v] + 1; } } \ No newline at end of file diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.py b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.py index 64922ddb9de34..0c377cbd09f1a 100644 --- a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.py +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.py @@ -1,23 +1,20 @@ class Solution: def findShortestCycle(self, n: int, edges: List[List[int]]) -> int: - def bfs(u: int) -> int: - dist = [-1] * n + def bfs(u: int, v: int) -> int: + dist = [inf] * n dist[u] = 0 - q = deque([(u, -1)]) - ans = inf + q = deque([u]) while q: - u, fa = q.popleft() - for v in g[u]: - if dist[v] < 0: - dist[v] = dist[u] + 1 - q.append((v, u)) - elif v != fa: - ans = min(ans, dist[u] + dist[v] + 1) - return ans + i = q.popleft() + for j in g[i]: + if (i, j) != (u, v) and (j, i) != (u, v) and dist[j] == inf: + dist[j] = dist[i] + 1 + q.append(j) + return dist[v] + 1 - g = defaultdict(list) + g = defaultdict(set) for u, v in edges: - g[u].append(v) - g[v].append(u) - ans = min(bfs(i) for i in range(n)) + g[u].add(v) + g[v].add(u) + ans = min(bfs(u, v) for u, v in edges) return ans if ans < inf else -1 diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.ts b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.ts index 0f89c33c0934f..caf783a6488b1 100644 --- a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.ts +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.ts @@ -6,28 +6,24 @@ function findShortestCycle(n: number, edges: number[][]): number { } const inf = 1 << 30; let ans = inf; - const bfs = (u: number) => { - const dist: number[] = new Array(n).fill(-1); + const bfs = (u: number, v: number) => { + const dist: number[] = new Array(n).fill(inf); dist[u] = 0; - const q: number[][] = [[u, -1]]; - let ans = inf; + const q: number[] = [u]; while (q.length) { - const p = q.shift()!; - u = p[0]; - const fa = p[1]; - for (const v of g[u]) { - if (dist[v] < 0) { - dist[v] = dist[u] + 1; - q.push([v, u]); - } else if (v !== fa) { - ans = Math.min(ans, dist[u] + dist[v] + 1); + const i = q.shift()!; + for (const j of g[i]) { + if ((i == u && j == v) || (i == v && j == u) || dist[j] != inf) { + continue; } + dist[j] = dist[i] + 1; + q.push(j); } } - return ans; + return 1 + dist[v]; }; - for (let i = 0; i < n; ++i) { - ans = Math.min(ans, bfs(i)); + for (const [u, v] of edges) { + ans = Math.min(ans, bfs(u, v)); } return ans < inf ? ans : -1; } diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution2.cpp b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution2.cpp new file mode 100644 index 0000000000000..c787615fd3559 --- /dev/null +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution2.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + int findShortestCycle(int n, vector>& edges) { + vector> g(n); + for (auto& e : edges) { + int u = e[0], v = e[1]; + g[u].push_back(v); + g[v].push_back(u); + } + const int inf = 1 << 30; + auto bfs = [&](int u) -> int { + int dist[n]; + memset(dist, -1, sizeof(dist)); + dist[u] = 0; + queue> q; + q.emplace(u, -1); + int ans = inf; + while (!q.empty()) { + auto p = q.front(); + u = p.first; + int fa = p.second; + q.pop(); + for (int v : g[u]) { + if (dist[v] < 0) { + dist[v] = dist[u] + 1; + q.emplace(v, u); + } else if (v != fa) { + ans = min(ans, dist[u] + dist[v] + 1); + } + } + } + return ans; + }; + int ans = inf; + for (int i = 0; i < n; ++i) { + ans = min(ans, bfs(i)); + } + return ans < inf ? ans : -1; + } +}; \ No newline at end of file diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution2.go b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution2.go new file mode 100644 index 0000000000000..48cf7ff782d86 --- /dev/null +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution2.go @@ -0,0 +1,41 @@ +func findShortestCycle(n int, edges [][]int) int { + g := make([][]int, n) + for _, e := range edges { + u, v := e[0], e[1] + g[u] = append(g[u], v) + g[v] = append(g[v], u) + } + const inf = 1 << 30 + bfs := func(u int) int { + dist := make([]int, n) + for i := range dist { + dist[i] = -1 + } + dist[u] = 0 + q := [][2]int{{u, -1}} + ans := inf + for len(q) > 0 { + p := q[0] + u = p[0] + fa := p[1] + q = q[1:] + for _, v := range g[u] { + if dist[v] < 0 { + dist[v] = dist[u] + 1 + q = append(q, [2]int{v, u}) + } else if v != fa { + ans = min(ans, dist[u]+dist[v]+1) + } + } + } + return ans + } + ans := inf + for i := 0; i < n; i++ { + ans = min(ans, bfs(i)) + } + if ans < inf { + return ans + } + return -1 +} \ No newline at end of file diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution2.java b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution2.java new file mode 100644 index 0000000000000..7918b31b02a54 --- /dev/null +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution2.java @@ -0,0 +1,42 @@ +class Solution { + private List[] g; + private final int inf = 1 << 30; + + public int findShortestCycle(int n, int[][] edges) { + g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (var e : edges) { + int u = e[0], v = e[1]; + g[u].add(v); + g[v].add(u); + } + int ans = inf; + for (int i = 0; i < n; ++i) { + ans = Math.min(ans, bfs(i)); + } + return ans < inf ? ans : -1; + } + + private int bfs(int u) { + int[] dist = new int[g.length]; + Arrays.fill(dist, -1); + dist[u] = 0; + Deque q = new ArrayDeque<>(); + q.offer(new int[] {u, -1}); + int ans = inf; + while (!q.isEmpty()) { + var p = q.poll(); + u = p[0]; + int fa = p[1]; + for (int v : g[u]) { + if (dist[v] < 0) { + dist[v] = dist[u] + 1; + q.offer(new int[] {v, u}); + } else if (v != fa) { + ans = Math.min(ans, dist[u] + dist[v] + 1); + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution2.py b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution2.py new file mode 100644 index 0000000000000..64922ddb9de34 --- /dev/null +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution2.py @@ -0,0 +1,23 @@ +class Solution: + def findShortestCycle(self, n: int, edges: List[List[int]]) -> int: + def bfs(u: int) -> int: + dist = [-1] * n + dist[u] = 0 + q = deque([(u, -1)]) + ans = inf + while q: + u, fa = q.popleft() + for v in g[u]: + if dist[v] < 0: + dist[v] = dist[u] + 1 + q.append((v, u)) + elif v != fa: + ans = min(ans, dist[u] + dist[v] + 1) + return ans + + g = defaultdict(list) + for u, v in edges: + g[u].append(v) + g[v].append(u) + ans = min(bfs(i) for i in range(n)) + return ans if ans < inf else -1 diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution2.ts b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution2.ts new file mode 100644 index 0000000000000..0f89c33c0934f --- /dev/null +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution2.ts @@ -0,0 +1,33 @@ +function findShortestCycle(n: number, edges: number[][]): number { + const g: number[][] = new Array(n).fill(0).map(() => []); + for (const [u, v] of edges) { + g[u].push(v); + g[v].push(u); + } + const inf = 1 << 30; + let ans = inf; + const bfs = (u: number) => { + const dist: number[] = new Array(n).fill(-1); + dist[u] = 0; + const q: number[][] = [[u, -1]]; + let ans = inf; + while (q.length) { + const p = q.shift()!; + u = p[0]; + const fa = p[1]; + for (const v of g[u]) { + if (dist[v] < 0) { + dist[v] = dist[u] + 1; + q.push([v, u]); + } else if (v !== fa) { + ans = Math.min(ans, dist[u] + dist[v] + 1); + } + } + } + return ans; + }; + for (let i = 0; i < n; ++i) { + ans = Math.min(ans, bfs(i)); + } + return ans < inf ? ans : -1; +} diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.cpp b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.cpp index a12d1cff4b094..ba0182b36f851 100644 --- a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.cpp +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.cpp @@ -1,17 +1,24 @@ class Solution { public: int findTheLongestBalancedSubstring(string s) { - int zero = 0, one = 0; + int n = s.size(); int ans = 0; - for (char& c : s) { - if (c == '0') { - if (one > 0) { - zero = 0; - one = 0; + auto check = [&](int i, int j) -> bool { + int cnt = 0; + for (int k = i; k <= j; ++k) { + if (s[k] == '1') { + ++cnt; + } else if (cnt) { + return false; + } + } + return cnt * 2 == j - i + 1; + }; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + if (check(i, j)) { + ans = max(ans, j - i + 1); } - ++zero; - } else { - ans = max(ans, 2 * min(zero, ++one)); } } return ans; diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.go b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.go index b9dac835e9516..86d3623292f4f 100644 --- a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.go +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.go @@ -1,14 +1,21 @@ func findTheLongestBalancedSubstring(s string) (ans int) { - zero, one := 0, 0 - for _, c := range s { - if c == '0' { - if one > 0 { - zero, one = 0, 0 + n := len(s) + check := func(i, j int) bool { + cnt := 0 + for k := i; k <= j; k++ { + if s[k] == '1' { + cnt++ + } else if cnt > 0 { + return false + } + } + return cnt*2 == j-i+1 + } + for i := 0; i < n; i++ { + for j := i + 1; j < n; j++ { + if check(i, j) { + ans = max(ans, j-i+1) } - zero++ - } else { - one++ - ans = max(ans, 2*min(zero, one)) } } return diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.java b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.java index 1277ba5f3514d..9d24836c2205d 100644 --- a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.java +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.java @@ -1,18 +1,26 @@ class Solution { public int findTheLongestBalancedSubstring(String s) { - int zero = 0, one = 0; - int ans = 0, n = s.length(); + int n = s.length(); + int ans = 0; for (int i = 0; i < n; ++i) { - if (s.charAt(i) == '0') { - if (one > 0) { - zero = 0; - one = 0; + for (int j = i + 1; j < n; ++j) { + if (check(s, i, j)) { + ans = Math.max(ans, j - i + 1); } - ++zero; - } else { - ans = Math.max(ans, 2 * Math.min(zero, ++one)); } } return ans; } + + private boolean check(String s, int i, int j) { + int cnt = 0; + for (int k = i; k <= j; ++k) { + if (s.charAt(k) == '1') { + ++cnt; + } else if (cnt > 0) { + return false; + } + } + return cnt * 2 == j - i + 1; + } } \ No newline at end of file diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.py b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.py index 7c1d367e1859d..7b084c8db74ae 100644 --- a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.py +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.py @@ -1,12 +1,18 @@ class Solution: def findTheLongestBalancedSubstring(self, s: str) -> int: - ans = zero = one = 0 - for c in s: - if c == '0': - if one: - zero = one = 0 - zero += 1 - else: - one += 1 - ans = max(ans, 2 * min(one, zero)) + def check(i, j): + cnt = 0 + for k in range(i, j + 1): + if s[k] == '1': + cnt += 1 + elif cnt: + return False + return cnt * 2 == (j - i + 1) + + n = len(s) + ans = 0 + for i in range(n): + for j in range(i + 1, n): + if check(i, j): + ans = max(ans, j - i + 1) return ans diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.rs b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.rs index a71bb46372784..ca74536aa974c 100644 --- a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.rs +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.rs @@ -1,22 +1,34 @@ impl Solution { pub fn find_the_longest_balanced_substring(s: String) -> i32 { - let mut zero = 0; - let mut one = 0; + let check = |i: usize, j: usize| -> bool { + let mut cnt = 0; + + for k in i..=j { + if s.as_bytes()[k] == b'1' { + cnt += 1; + } else if cnt > 0 { + return false; + } + } + + cnt * 2 == j - i + 1 + }; + let mut ans = 0; + let n = s.len(); + for i in 0..n - 1 { + for j in (i + 1..n).rev() { + if j - i + 1 < ans { + break; + } - for &c in s.as_bytes().iter() { - if c == b'0' { - if one > 0 { - zero = 0; - one = 0; + if check(i, j) { + ans = std::cmp::max(ans, j - i + 1); + break; } - zero += 1; - } else { - one += 1; - ans = std::cmp::max(ans, std::cmp::min(zero, one) * 2); } } - ans + ans as i32 } } diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.ts b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.ts index c10af75d357ca..e2ccc431c31c7 100644 --- a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.ts +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.ts @@ -1,16 +1,22 @@ function findTheLongestBalancedSubstring(s: string): number { - let zero = 0; - let one = 0; + const n = s.length; let ans = 0; - for (const c of s) { - if (c === '0') { - if (one > 0) { - zero = 0; - one = 0; + const check = (i: number, j: number): boolean => { + let cnt = 0; + for (let k = i; k <= j; ++k) { + if (s[k] === '1') { + ++cnt; + } else if (cnt > 0) { + return false; + } + } + return cnt * 2 === j - i + 1; + }; + for (let i = 0; i < n; ++i) { + for (let j = i + 1; j < n; j += 2) { + if (check(i, j)) { + ans = Math.max(ans, j - i + 1); } - ++zero; - } else { - ans = Math.max(ans, 2 * Math.min(zero, ++one)); } } return ans; diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution2.cpp b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution2.cpp new file mode 100644 index 0000000000000..a12d1cff4b094 --- /dev/null +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int findTheLongestBalancedSubstring(string s) { + int zero = 0, one = 0; + int ans = 0; + for (char& c : s) { + if (c == '0') { + if (one > 0) { + zero = 0; + one = 0; + } + ++zero; + } else { + ans = max(ans, 2 * min(zero, ++one)); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution2.go b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution2.go new file mode 100644 index 0000000000000..b9dac835e9516 --- /dev/null +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution2.go @@ -0,0 +1,15 @@ +func findTheLongestBalancedSubstring(s string) (ans int) { + zero, one := 0, 0 + for _, c := range s { + if c == '0' { + if one > 0 { + zero, one = 0, 0 + } + zero++ + } else { + one++ + ans = max(ans, 2*min(zero, one)) + } + } + return +} \ No newline at end of file diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution2.java b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution2.java new file mode 100644 index 0000000000000..1277ba5f3514d --- /dev/null +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution2.java @@ -0,0 +1,18 @@ +class Solution { + public int findTheLongestBalancedSubstring(String s) { + int zero = 0, one = 0; + int ans = 0, n = s.length(); + for (int i = 0; i < n; ++i) { + if (s.charAt(i) == '0') { + if (one > 0) { + zero = 0; + one = 0; + } + ++zero; + } else { + ans = Math.max(ans, 2 * Math.min(zero, ++one)); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution2.py b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution2.py new file mode 100644 index 0000000000000..7c1d367e1859d --- /dev/null +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def findTheLongestBalancedSubstring(self, s: str) -> int: + ans = zero = one = 0 + for c in s: + if c == '0': + if one: + zero = one = 0 + zero += 1 + else: + one += 1 + ans = max(ans, 2 * min(one, zero)) + return ans diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution2.rs b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution2.rs new file mode 100644 index 0000000000000..a71bb46372784 --- /dev/null +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution2.rs @@ -0,0 +1,22 @@ +impl Solution { + pub fn find_the_longest_balanced_substring(s: String) -> i32 { + let mut zero = 0; + let mut one = 0; + let mut ans = 0; + + for &c in s.as_bytes().iter() { + if c == b'0' { + if one > 0 { + zero = 0; + one = 0; + } + zero += 1; + } else { + one += 1; + ans = std::cmp::max(ans, std::cmp::min(zero, one) * 2); + } + } + + ans + } +} diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution2.ts b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution2.ts new file mode 100644 index 0000000000000..c10af75d357ca --- /dev/null +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution2.ts @@ -0,0 +1,17 @@ +function findTheLongestBalancedSubstring(s: string): number { + let zero = 0; + let one = 0; + let ans = 0; + for (const c of s) { + if (c === '0') { + if (one > 0) { + zero = 0; + one = 0; + } + ++zero; + } else { + ans = Math.max(ans, 2 * Math.min(zero, ++one)); + } + } + return ans; +} diff --git a/solution/2600-2699/2611.Mice and Cheese/Solution2.cpp b/solution/2600-2699/2611.Mice and Cheese/Solution2.cpp new file mode 100644 index 0000000000000..7746e502f6218 --- /dev/null +++ b/solution/2600-2699/2611.Mice and Cheese/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int miceAndCheese(vector& reward1, vector& reward2, int k) { + int n = reward1.size(); + int ans = 0; + for (int i = 0; i < n; ++i) { + ans += reward2[i]; + reward1[i] -= reward2[i]; + } + sort(reward1.rbegin(), reward1.rend()); + ans += accumulate(reward1.begin(), reward1.begin() + k, 0); + return ans; + } +}; \ No newline at end of file diff --git a/solution/2600-2699/2611.Mice and Cheese/Solution2.go b/solution/2600-2699/2611.Mice and Cheese/Solution2.go new file mode 100644 index 0000000000000..58ed110a8cc8e --- /dev/null +++ b/solution/2600-2699/2611.Mice and Cheese/Solution2.go @@ -0,0 +1,12 @@ +func miceAndCheese(reward1 []int, reward2 []int, k int) (ans int) { + for i, x := range reward2 { + ans += x + reward1[i] -= x + } + sort.Ints(reward1) + n := len(reward1) + for i := 0; i < k; i++ { + ans += reward1[n-i-1] + } + return +} \ No newline at end of file diff --git a/solution/2600-2699/2611.Mice and Cheese/Solution2.java b/solution/2600-2699/2611.Mice and Cheese/Solution2.java new file mode 100644 index 0000000000000..a36a82044eafa --- /dev/null +++ b/solution/2600-2699/2611.Mice and Cheese/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public int miceAndCheese(int[] reward1, int[] reward2, int k) { + int ans = 0; + int n = reward1.length; + for (int i = 0; i < n; ++i) { + ans += reward2[i]; + reward1[i] -= reward2[i]; + } + Arrays.sort(reward1); + for (int i = 0; i < k; ++i) { + ans += reward1[n - i - 1]; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2600-2699/2611.Mice and Cheese/Solution2.py b/solution/2600-2699/2611.Mice and Cheese/Solution2.py new file mode 100644 index 0000000000000..073d551d7cc61 --- /dev/null +++ b/solution/2600-2699/2611.Mice and Cheese/Solution2.py @@ -0,0 +1,6 @@ +class Solution: + def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int: + for i, x in enumerate(reward2): + reward1[i] -= x + reward1.sort(reverse=True) + return sum(reward2) + sum(reward1[:k]) diff --git a/solution/2600-2699/2611.Mice and Cheese/Solution2.ts b/solution/2600-2699/2611.Mice and Cheese/Solution2.ts new file mode 100644 index 0000000000000..a91a35fa6dd4c --- /dev/null +++ b/solution/2600-2699/2611.Mice and Cheese/Solution2.ts @@ -0,0 +1,13 @@ +function miceAndCheese(reward1: number[], reward2: number[], k: number): number { + const n = reward1.length; + let ans = 0; + for (let i = 0; i < n; ++i) { + ans += reward2[i]; + reward1[i] -= reward2[i]; + } + reward1.sort((a, b) => b - a); + for (let i = 0; i < k; ++i) { + ans += reward1[i]; + } + return ans; +} diff --git a/solution/2600-2699/2612.Minimum Reverse Operations/Solution2.ts b/solution/2600-2699/2612.Minimum Reverse Operations/Solution2.ts new file mode 100644 index 0000000000000..aa507ef254aab --- /dev/null +++ b/solution/2600-2699/2612.Minimum Reverse Operations/Solution2.ts @@ -0,0 +1,648 @@ +function minReverseOperations(n: number, p: number, banned: number[], k: number): number[] { + const ans = new Array(n).fill(-1); + const ts = new Array(2).fill(0).map(() => new TreapMultiSet()); + for (let i = 0; i < n; ++i) { + ts[i % 2].add(i); + } + ans[p] = 0; + ts[p % 2].delete(p); + for (const i of banned) { + ts[i % 2].delete(i); + } + ts[0].add(n); + ts[1].add(n); + let q = [p]; + while (q.length) { + const t: number[] = []; + for (const i of q) { + const mi = Math.max(i - k + 1, k - i - 1); + const mx = Math.min(i + k - 1, n * 2 - k - i - 1); + const s = ts[mi % 2]; + for (let j = s.ceil(mi)!; j <= mx; j = s.ceil(j)!) { + t.push(j); + ans[j] = ans[i] + 1; + s.delete(j); + } + } + q = t; + } + return ans; +} + +type CompareFunction = ( + a: T, + b: T, +) => R extends 'number' ? number : boolean; + +interface ITreapMultiSet extends Iterable { + add: (...value: T[]) => this; + has: (value: T) => boolean; + delete: (value: T) => void; + + bisectLeft: (value: T) => number; + bisectRight: (value: T) => number; + + indexOf: (value: T) => number; + lastIndexOf: (value: T) => number; + + at: (index: number) => T | undefined; + first: () => T | undefined; + last: () => T | undefined; + + lower: (value: T) => T | undefined; + higher: (value: T) => T | undefined; + floor: (value: T) => T | undefined; + ceil: (value: T) => T | undefined; + + shift: () => T | undefined; + pop: (index?: number) => T | undefined; + + count: (value: T) => number; + + keys: () => IterableIterator; + values: () => IterableIterator; + rvalues: () => IterableIterator; + entries: () => IterableIterator<[number, T]>; + + readonly size: number; +} + +class TreapNode { + value: T; + count: number; + size: number; + priority: number; + left: TreapNode | null; + right: TreapNode | null; + + constructor(value: T) { + this.value = value; + this.count = 1; + this.size = 1; + this.priority = Math.random(); + this.left = null; + this.right = null; + } + + static getSize(node: TreapNode | null): number { + return node?.size ?? 0; + } + + static getFac(node: TreapNode | null): number { + return node?.priority ?? 0; + } + + pushUp(): void { + let tmp = this.count; + tmp += TreapNode.getSize(this.left); + tmp += TreapNode.getSize(this.right); + this.size = tmp; + } + + rotateRight(): TreapNode { + // eslint-disable-next-line @typescript-eslint/no-this-alias + let node: TreapNode = this; + const left = node.left; + node.left = left?.right ?? null; + left && (left.right = node); + left && (node = left); + node.right?.pushUp(); + node.pushUp(); + return node; + } + + rotateLeft(): TreapNode { + // eslint-disable-next-line @typescript-eslint/no-this-alias + let node: TreapNode = this; + const right = node.right; + node.right = right?.left ?? null; + right && (right.left = node); + right && (node = right); + node.left?.pushUp(); + node.pushUp(); + return node; + } +} + +class TreapMultiSet implements ITreapMultiSet { + private readonly root: TreapNode; + private readonly compareFn: CompareFunction; + private readonly leftBound: T; + private readonly rightBound: T; + + constructor(compareFn?: CompareFunction); + constructor(compareFn: CompareFunction, leftBound: T, rightBound: T); + constructor( + compareFn: CompareFunction = (a: any, b: any) => a - b, + leftBound: any = -Infinity, + rightBound: any = Infinity, + ) { + this.root = new TreapNode(rightBound); + this.root.priority = Infinity; + this.root.left = new TreapNode(leftBound); + this.root.left.priority = -Infinity; + this.root.pushUp(); + + this.leftBound = leftBound; + this.rightBound = rightBound; + this.compareFn = compareFn; + } + + get size(): number { + return this.root.size - 2; + } + + get height(): number { + const getHeight = (node: TreapNode | null): number => { + if (node == null) return 0; + return 1 + Math.max(getHeight(node.left), getHeight(node.right)); + }; + + return getHeight(this.root); + } + + /** + * + * @complexity `O(logn)` + * @description Returns true if value is a member. + */ + has(value: T): boolean { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): boolean => { + if (node == null) return false; + if (compare(node.value, value) === 0) return true; + if (compare(node.value, value) < 0) return dfs(node.right, value); + return dfs(node.left, value); + }; + + return dfs(this.root, value); + } + + /** + * + * @complexity `O(logn)` + * @description Add value to sorted set. + */ + add(...values: T[]): this { + const compare = this.compareFn; + const dfs = ( + node: TreapNode | null, + value: T, + parent: TreapNode, + direction: 'left' | 'right', + ): void => { + if (node == null) return; + if (compare(node.value, value) === 0) { + node.count++; + node.pushUp(); + } else if (compare(node.value, value) > 0) { + if (node.left) { + dfs(node.left, value, node, 'left'); + } else { + node.left = new TreapNode(value); + node.pushUp(); + } + + if (TreapNode.getFac(node.left) > node.priority) { + parent[direction] = node.rotateRight(); + } + } else if (compare(node.value, value) < 0) { + if (node.right) { + dfs(node.right, value, node, 'right'); + } else { + node.right = new TreapNode(value); + node.pushUp(); + } + + if (TreapNode.getFac(node.right) > node.priority) { + parent[direction] = node.rotateLeft(); + } + } + parent.pushUp(); + }; + + values.forEach(value => dfs(this.root.left, value, this.root, 'left')); + return this; + } + + /** + * + * @complexity `O(logn)` + * @description Remove value from sorted set if it is a member. + * If value is not a member, do nothing. + */ + delete(value: T): void { + const compare = this.compareFn; + const dfs = ( + node: TreapNode | null, + value: T, + parent: TreapNode, + direction: 'left' | 'right', + ): void => { + if (node == null) return; + + if (compare(node.value, value) === 0) { + if (node.count > 1) { + node.count--; + node?.pushUp(); + } else if (node.left == null && node.right == null) { + parent[direction] = null; + } else { + // 旋到根节点 + if ( + node.right == null || + TreapNode.getFac(node.left) > TreapNode.getFac(node.right) + ) { + parent[direction] = node.rotateRight(); + dfs(parent[direction]?.right ?? null, value, parent[direction]!, 'right'); + } else { + parent[direction] = node.rotateLeft(); + dfs(parent[direction]?.left ?? null, value, parent[direction]!, 'left'); + } + } + } else if (compare(node.value, value) > 0) { + dfs(node.left, value, node, 'left'); + } else if (compare(node.value, value) < 0) { + dfs(node.right, value, node, 'right'); + } + + parent?.pushUp(); + }; + + dfs(this.root.left, value, this.root, 'left'); + } + + /** + * + * @complexity `O(logn)` + * @description Returns an index to insert value in the sorted set. + * If the value is already present, the insertion point will be before (to the left of) any existing values. + */ + bisectLeft(value: T): number { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + + if (compare(node.value, value) === 0) { + return TreapNode.getSize(node.left); + } else if (compare(node.value, value) > 0) { + return dfs(node.left, value); + } else if (compare(node.value, value) < 0) { + return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count; + } + + return 0; + }; + + return dfs(this.root, value) - 1; + } + + /** + * + * @complexity `O(logn)` + * @description Returns an index to insert value in the sorted set. + * If the value is already present, the insertion point will be before (to the right of) any existing values. + */ + bisectRight(value: T): number { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + + if (compare(node.value, value) === 0) { + return TreapNode.getSize(node.left) + node.count; + } else if (compare(node.value, value) > 0) { + return dfs(node.left, value); + } else if (compare(node.value, value) < 0) { + return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count; + } + + return 0; + }; + return dfs(this.root, value) - 1; + } + + /** + * + * @complexity `O(logn)` + * @description Returns the index of the first occurrence of a value in the set, or -1 if it is not present. + */ + indexOf(value: T): number { + const compare = this.compareFn; + let isExist = false; + + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + + if (compare(node.value, value) === 0) { + isExist = true; + return TreapNode.getSize(node.left); + } else if (compare(node.value, value) > 0) { + return dfs(node.left, value); + } else if (compare(node.value, value) < 0) { + return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count; + } + + return 0; + }; + const res = dfs(this.root, value) - 1; + return isExist ? res : -1; + } + + /** + * + * @complexity `O(logn)` + * @description Returns the index of the last occurrence of a value in the set, or -1 if it is not present. + */ + lastIndexOf(value: T): number { + const compare = this.compareFn; + let isExist = false; + + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + + if (compare(node.value, value) === 0) { + isExist = true; + return TreapNode.getSize(node.left) + node.count - 1; + } else if (compare(node.value, value) > 0) { + return dfs(node.left, value); + } else if (compare(node.value, value) < 0) { + return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count; + } + + return 0; + }; + + const res = dfs(this.root, value) - 1; + return isExist ? res : -1; + } + + /** + * + * @complexity `O(logn)` + * @description Returns the item located at the specified index. + * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): T | undefined { + if (index < 0) index += this.size; + if (index < 0 || index >= this.size) return undefined; + + const dfs = (node: TreapNode | null, rank: number): T | undefined => { + if (node == null) return undefined; + + if (TreapNode.getSize(node.left) >= rank) { + return dfs(node.left, rank); + } else if (TreapNode.getSize(node.left) + node.count >= rank) { + return node.value; + } else { + return dfs(node.right, rank - TreapNode.getSize(node.left) - node.count); + } + }; + + const res = dfs(this.root, index + 2); + return ([this.leftBound, this.rightBound] as any[]).includes(res) ? undefined : res; + } + + /** + * + * @complexity `O(logn)` + * @description Find and return the element less than `val`, return `undefined` if no such element found. + */ + lower(value: T): T | undefined { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): T | undefined => { + if (node == null) return undefined; + if (compare(node.value, value) >= 0) return dfs(node.left, value); + + const tmp = dfs(node.right, value); + if (tmp == null || compare(node.value, tmp) > 0) { + return node.value; + } else { + return tmp; + } + }; + + const res = dfs(this.root, value) as any; + return res === this.leftBound ? undefined : res; + } + + /** + * + * @complexity `O(logn)` + * @description Find and return the element greater than `val`, return `undefined` if no such element found. + */ + higher(value: T): T | undefined { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): T | undefined => { + if (node == null) return undefined; + if (compare(node.value, value) <= 0) return dfs(node.right, value); + + const tmp = dfs(node.left, value); + + if (tmp == null || compare(node.value, tmp) < 0) { + return node.value; + } else { + return tmp; + } + }; + + const res = dfs(this.root, value) as any; + return res === this.rightBound ? undefined : res; + } + + /** + * + * @complexity `O(logn)` + * @description Find and return the element less than or equal to `val`, return `undefined` if no such element found. + */ + floor(value: T): T | undefined { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): T | undefined => { + if (node == null) return undefined; + if (compare(node.value, value) === 0) return node.value; + if (compare(node.value, value) >= 0) return dfs(node.left, value); + + const tmp = dfs(node.right, value); + if (tmp == null || compare(node.value, tmp) > 0) { + return node.value; + } else { + return tmp; + } + }; + + const res = dfs(this.root, value) as any; + return res === this.leftBound ? undefined : res; + } + + /** + * + * @complexity `O(logn)` + * @description Find and return the element greater than or equal to `val`, return `undefined` if no such element found. + */ + ceil(value: T): T | undefined { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): T | undefined => { + if (node == null) return undefined; + if (compare(node.value, value) === 0) return node.value; + if (compare(node.value, value) <= 0) return dfs(node.right, value); + + const tmp = dfs(node.left, value); + + if (tmp == null || compare(node.value, tmp) < 0) { + return node.value; + } else { + return tmp; + } + }; + + const res = dfs(this.root, value) as any; + return res === this.rightBound ? undefined : res; + } + + /** + * @complexity `O(logn)` + * @description + * Returns the last element from set. + * If the set is empty, undefined is returned. + */ + first(): T | undefined { + const iter = this.inOrder(); + iter.next(); + const res = iter.next().value; + return res === this.rightBound ? undefined : res; + } + + /** + * @complexity `O(logn)` + * @description + * Returns the last element from set. + * If the set is empty, undefined is returned . + */ + last(): T | undefined { + const iter = this.reverseInOrder(); + iter.next(); + const res = iter.next().value; + return res === this.leftBound ? undefined : res; + } + + /** + * @complexity `O(logn)` + * @description + * Removes the first element from an set and returns it. + * If the set is empty, undefined is returned and the set is not modified. + */ + shift(): T | undefined { + const first = this.first(); + if (first === undefined) return undefined; + this.delete(first); + return first; + } + + /** + * @complexity `O(logn)` + * @description + * Removes the last element from an set and returns it. + * If the set is empty, undefined is returned and the set is not modified. + */ + pop(index?: number): T | undefined { + if (index == null) { + const last = this.last(); + if (last === undefined) return undefined; + this.delete(last); + return last; + } + + const toDelete = this.at(index); + if (toDelete == null) return; + this.delete(toDelete); + return toDelete; + } + + /** + * + * @complexity `O(logn)` + * @description + * Returns number of occurrences of value in the sorted set. + */ + count(value: T): number { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + if (compare(node.value, value) === 0) return node.count; + if (compare(node.value, value) < 0) return dfs(node.right, value); + return dfs(node.left, value); + }; + + return dfs(this.root, value); + } + + *[Symbol.iterator](): Generator { + yield* this.values(); + } + + /** + * @description + * Returns an iterable of keys in the set. + */ + *keys(): Generator { + yield* this.values(); + } + + /** + * @description + * Returns an iterable of values in the set. + */ + *values(): Generator { + const iter = this.inOrder(); + iter.next(); + const steps = this.size; + for (let _ = 0; _ < steps; _++) { + yield iter.next().value; + } + } + + /** + * @description + * Returns a generator for reversed order traversing the set. + */ + *rvalues(): Generator { + const iter = this.reverseInOrder(); + iter.next(); + const steps = this.size; + for (let _ = 0; _ < steps; _++) { + yield iter.next().value; + } + } + + /** + * @description + * Returns an iterable of key, value pairs for every entry in the set. + */ + *entries(): IterableIterator<[number, T]> { + const iter = this.inOrder(); + iter.next(); + const steps = this.size; + for (let i = 0; i < steps; i++) { + yield [i, iter.next().value]; + } + } + + private *inOrder(root: TreapNode | null = this.root): Generator { + if (root == null) return; + yield* this.inOrder(root.left); + const count = root.count; + for (let _ = 0; _ < count; _++) { + yield root.value; + } + yield* this.inOrder(root.right); + } + + private *reverseInOrder(root: TreapNode | null = this.root): Generator { + if (root == null) return; + yield* this.reverseInOrder(root.right); + const count = root.count; + for (let _ = 0; _ < count; _++) { + yield root.value; + } + yield* this.reverseInOrder(root.left); + } +} diff --git a/solution/2600-2699/2639.Find the Width of Columns of a Grid/Solution2.py b/solution/2600-2699/2639.Find the Width of Columns of a Grid/Solution2.py new file mode 100644 index 0000000000000..c8b6b486c2720 --- /dev/null +++ b/solution/2600-2699/2639.Find the Width of Columns of a Grid/Solution2.py @@ -0,0 +1,3 @@ +class Solution: + def findColumnWidth(self, grid: List[List[int]]) -> List[int]: + return [max(len(str(x)) for x in col) for col in zip(*grid)] diff --git a/solution/2600-2699/2641.Cousins in Binary Tree II/Solution2.cpp b/solution/2600-2699/2641.Cousins in Binary Tree II/Solution2.cpp new file mode 100644 index 0000000000000..f1cf0973093d3 --- /dev/null +++ b/solution/2600-2699/2641.Cousins in Binary Tree II/Solution2.cpp @@ -0,0 +1,44 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* replaceValueInTree(TreeNode* root) { + root->val = 0; + vector q; + q.emplace_back(root); + while (!q.empty()) { + vector p = q; + q.clear(); + int s = 0; + for (TreeNode* node : p) { + if (node->left) { + q.emplace_back(node->left); + s += node->left->val; + } + if (node->right) { + q.emplace_back(node->right); + s += node->right->val; + } + } + for (TreeNode* node : p) { + int t = (node->left ? node->left->val : 0) + (node->right ? node->right->val : 0); + if (node->left) { + node->left->val = s - t; + } + if (node->right) { + node->right->val = s - t; + } + } + } + return root; + } +}; \ No newline at end of file diff --git a/solution/2600-2699/2641.Cousins in Binary Tree II/Solution2.go b/solution/2600-2699/2641.Cousins in Binary Tree II/Solution2.go new file mode 100644 index 0000000000000..7a56ebbd1ac99 --- /dev/null +++ b/solution/2600-2699/2641.Cousins in Binary Tree II/Solution2.go @@ -0,0 +1,43 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func replaceValueInTree(root *TreeNode) *TreeNode { + root.Val = 0 + q := []*TreeNode{root} + for len(q) > 0 { + p := q + q = []*TreeNode{} + s := 0 + for _, node := range p { + if node.Left != nil { + q = append(q, node.Left) + s += node.Left.Val + } + if node.Right != nil { + q = append(q, node.Right) + s += node.Right.Val + } + } + for _, node := range p { + t := 0 + if node.Left != nil { + t += node.Left.Val + } + if node.Right != nil { + t += node.Right.Val + } + if node.Left != nil { + node.Left.Val = s - t + } + if node.Right != nil { + node.Right.Val = s - t + } + } + } + return root +} \ No newline at end of file diff --git a/solution/2600-2699/2641.Cousins in Binary Tree II/Solution2.java b/solution/2600-2699/2641.Cousins in Binary Tree II/Solution2.java new file mode 100644 index 0000000000000..242624e55f2c4 --- /dev/null +++ b/solution/2600-2699/2641.Cousins in Binary Tree II/Solution2.java @@ -0,0 +1,47 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode replaceValueInTree(TreeNode root) { + root.val = 0; + List q = List.of(root); + while (!q.isEmpty()) { + List p = q; + q = new ArrayList<>(); + int s = 0; + for (TreeNode node : p) { + if (node.left != null) { + q.add(node.left); + s += node.left.val; + } + if (node.right != null) { + q.add(node.right); + s += node.right.val; + } + } + for (TreeNode node : p) { + int t = (node.left == null ? 0 : node.left.val) + + (node.right == null ? 0 : node.right.val); + if (node.left != null) { + node.left.val = s - t; + } + if (node.right != null) { + node.right.val = s - t; + } + } + } + return root; + } +} \ No newline at end of file diff --git a/solution/2600-2699/2641.Cousins in Binary Tree II/Solution2.py b/solution/2600-2699/2641.Cousins in Binary Tree II/Solution2.py new file mode 100644 index 0000000000000..85e5299bb2ed1 --- /dev/null +++ b/solution/2600-2699/2641.Cousins in Binary Tree II/Solution2.py @@ -0,0 +1,30 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def replaceValueInTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + root.val = 0 + q = [root] + while q: + s = 0 + p = q + q = [] + for node in p: + if node.left: + q.append(node.left) + s += node.left.val + if node.right: + q.append(node.right) + s += node.right.val + for node in p: + t = (node.left.val if node.left else 0) + ( + node.right.val if node.right else 0 + ) + if node.left: + node.left.val = s - t + if node.right: + node.right.val = s - t + return root diff --git a/solution/2600-2699/2641.Cousins in Binary Tree II/Solution2.ts b/solution/2600-2699/2641.Cousins in Binary Tree II/Solution2.ts new file mode 100644 index 0000000000000..0fd5e6331d997 --- /dev/null +++ b/solution/2600-2699/2641.Cousins in Binary Tree II/Solution2.ts @@ -0,0 +1,43 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function replaceValueInTree(root: TreeNode | null): TreeNode | null { + root.val = 0; + let q: TreeNode[] = [root]; + while (q.length) { + const p: TreeNode[] = q; + q = []; + let s: number = 0; + for (const { left, right } of p) { + if (left) { + q.push(left); + s += left.val; + } + if (right) { + q.push(right); + s += right.val; + } + } + for (const { left, right } of p) { + const t: number = (left?.val ?? 0) + (right?.val ?? 0); + if (left) { + left.val = s - t; + } + if (right) { + right.val = s - t; + } + } + } + return root; +} diff --git a/solution/2600-2699/2642.Design Graph With Shortest Path Calculator/Solution.cs b/solution/2600-2699/2642.Design Graph With Shortest Path Calculator/Solution.cs index 99eb67b744470..e01288a645172 100644 --- a/solution/2600-2699/2642.Design Graph With Shortest Path Calculator/Solution.cs +++ b/solution/2600-2699/2642.Design Graph With Shortest Path Calculator/Solution.cs @@ -19,11 +19,11 @@ public Graph(int n, int[][] edges) { g[e[0]][e[1]] = e[2]; } } - + public void AddEdge(int[] edge) { g[edge[0]][edge[1]] = edge[2]; } - + public int ShortestPath(int node1, int node2) { int[] dist = new int[n]; bool[] vis = new bool[n]; diff --git a/solution/2600-2699/2644.Find the Maximum Divisibility Score/Solution.java b/solution/2600-2699/2644.Find the Maximum Divisibility Score/Solution.java index 86e7de49ad05f..3622d4e0fe03d 100644 --- a/solution/2600-2699/2644.Find the Maximum Divisibility Score/Solution.java +++ b/solution/2600-2699/2644.Find the Maximum Divisibility Score/Solution.java @@ -18,4 +18,4 @@ public int maxDivScore(int[] nums, int[] divisors) { } return ans; } -} +} \ No newline at end of file diff --git a/solution/2600-2699/2645.Minimum Additions to Make Valid String/Solution.cpp b/solution/2600-2699/2645.Minimum Additions to Make Valid String/Solution.cpp index 1a277e9f031bb..1984299611c85 100644 --- a/solution/2600-2699/2645.Minimum Additions to Make Valid String/Solution.cpp +++ b/solution/2600-2699/2645.Minimum Additions to Make Valid String/Solution.cpp @@ -15,4 +15,4 @@ class Solution { } return ans; } -}; +}; \ No newline at end of file diff --git a/solution/2600-2699/2645.Minimum Additions to Make Valid String/Solution.java b/solution/2600-2699/2645.Minimum Additions to Make Valid String/Solution.java index 4a8e32677bc9f..b029bb2e6c9f8 100644 --- a/solution/2600-2699/2645.Minimum Additions to Make Valid String/Solution.java +++ b/solution/2600-2699/2645.Minimum Additions to Make Valid String/Solution.java @@ -14,4 +14,4 @@ public int addMinimum(String word) { } return ans; } -} +} \ No newline at end of file diff --git a/solution/2600-2699/2652.Sum Multiples/Solution2.cpp b/solution/2600-2699/2652.Sum Multiples/Solution2.cpp new file mode 100644 index 0000000000000..8f1c53546c326 --- /dev/null +++ b/solution/2600-2699/2652.Sum Multiples/Solution2.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + int sumOfMultiples(int n) { + auto f = [&](int x) { + int m = n / x; + return (x + m * x) * m / 2; + }; + return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7); + } +}; \ No newline at end of file diff --git a/solution/2600-2699/2652.Sum Multiples/Solution2.go b/solution/2600-2699/2652.Sum Multiples/Solution2.go new file mode 100644 index 0000000000000..ac43419a643ae --- /dev/null +++ b/solution/2600-2699/2652.Sum Multiples/Solution2.go @@ -0,0 +1,7 @@ +func sumOfMultiples(n int) int { + f := func(x int) int { + m := n / x + return (x + m*x) * m / 2 + } + return f(3) + f(5) + f(7) - f(3*5) - f(3*7) - f(5*7) + f(3*5*7) +} \ No newline at end of file diff --git a/solution/2600-2699/2652.Sum Multiples/Solution2.java b/solution/2600-2699/2652.Sum Multiples/Solution2.java new file mode 100644 index 0000000000000..e43e673cf2a0f --- /dev/null +++ b/solution/2600-2699/2652.Sum Multiples/Solution2.java @@ -0,0 +1,13 @@ +class Solution { + private int n; + + public int sumOfMultiples(int n) { + this.n = n; + return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7); + } + + private int f(int x) { + int m = n / x; + return (x + m * x) * m / 2; + } +} \ No newline at end of file diff --git a/solution/2600-2699/2652.Sum Multiples/Solution2.py b/solution/2600-2699/2652.Sum Multiples/Solution2.py new file mode 100644 index 0000000000000..95fb970857902 --- /dev/null +++ b/solution/2600-2699/2652.Sum Multiples/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def sumOfMultiples(self, n: int) -> int: + def f(x: int) -> int: + m = n // x + return (x + m * x) * m // 2 + + return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7) diff --git a/solution/2600-2699/2652.Sum Multiples/Solution2.rs b/solution/2600-2699/2652.Sum Multiples/Solution2.rs new file mode 100644 index 0000000000000..a98ac33349f2c --- /dev/null +++ b/solution/2600-2699/2652.Sum Multiples/Solution2.rs @@ -0,0 +1,5 @@ +impl Solution { + pub fn sum_of_multiples(n: i32) -> i32 { + (1..=n).filter(|&x| (x % 3 == 0 || x % 5 == 0 || x % 7 == 0)).sum() + } +} diff --git a/solution/2600-2699/2652.Sum Multiples/Solution2.ts b/solution/2600-2699/2652.Sum Multiples/Solution2.ts new file mode 100644 index 0000000000000..5d9ae879d5933 --- /dev/null +++ b/solution/2600-2699/2652.Sum Multiples/Solution2.ts @@ -0,0 +1,7 @@ +function sumOfMultiples(n: number): number { + const f = (x: number): number => { + const m = Math.floor(n / x); + return ((x + m * x) * m) >> 1; + }; + return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7); +} diff --git a/solution/2600-2699/2652.Sum Multiples/Solution3.rs b/solution/2600-2699/2652.Sum Multiples/Solution3.rs new file mode 100644 index 0000000000000..f1d512040e79b --- /dev/null +++ b/solution/2600-2699/2652.Sum Multiples/Solution3.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn sum_of_multiples(n: i32) -> i32 { + fn f(x: i32, n: i32) -> i32 { + let m = n / x; + ((x + m * x) * m) / 2 + } + + f(3, n) + f(5, n) + f(7, n) - f(3 * 5, n) - f(3 * 7, n) - f(5 * 7, n) + f(3 * 5 * 7, n) + } +} diff --git a/solution/2600-2699/2653.Sliding Subarray Beauty/Solution2.py b/solution/2600-2699/2653.Sliding Subarray Beauty/Solution2.py new file mode 100644 index 0000000000000..e49aec3e83b9f --- /dev/null +++ b/solution/2600-2699/2653.Sliding Subarray Beauty/Solution2.py @@ -0,0 +1,19 @@ +class Solution: + def getSubarrayBeauty(self, nums: List[int], k: int, x: int) -> List[int]: + def f(x: int) -> int: + s = 0 + for i in range(50): + s += cnt[i] + if s >= x: + return i - 50 + return 0 + + cnt = [0] * 101 + for v in nums[:k]: + cnt[v + 50] += 1 + ans = [f(x)] + for i in range(k, len(nums)): + cnt[nums[i] + 50] += 1 + cnt[nums[i - k] + 50] -= 1 + ans.append(f(x)) + return ans diff --git a/solution/2600-2699/2656.Maximum Sum With Exactly K Elements/Solution2.rs b/solution/2600-2699/2656.Maximum Sum With Exactly K Elements/Solution2.rs new file mode 100644 index 0000000000000..783246f35a8cf --- /dev/null +++ b/solution/2600-2699/2656.Maximum Sum With Exactly K Elements/Solution2.rs @@ -0,0 +1,7 @@ +impl Solution { + pub fn maximize_sum(nums: Vec, k: i32) -> i32 { + let mx = *nums.iter().max().unwrap_or(&0); + + ((0 + k - 1) * k) / 2 + k * mx + } +} diff --git a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.cpp b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.cpp index 20edbdd260cbc..5f8385ad9dc64 100644 --- a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.cpp +++ b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.cpp @@ -1,17 +1,16 @@ -class Solution { -public: - vector findThePrefixCommonArray(vector& A, vector& B) { - int n = A.size(); - vector ans; - vector vis(n + 1, 1); - int s = 0; - for (int i = 0; i < n; ++i) { - vis[A[i]] ^= 1; - s += vis[A[i]]; - vis[B[i]] ^= 1; - s += vis[B[i]]; - ans.push_back(s); - } - return ans; - } +class Solution { +public: + vector findThePrefixCommonArray(vector& A, vector& B) { + int n = A.size(); + vector ans(n); + vector cnt1(n + 1), cnt2(n + 1); + for (int i = 0; i < n; ++i) { + ++cnt1[A[i]]; + ++cnt2[B[i]]; + for (int j = 1; j <= n; ++j) { + ans[i] += min(cnt1[j], cnt2[j]); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.go b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.go index 255d1c1ecc287..5544f00f57aaf 100644 --- a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.go +++ b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.go @@ -1,16 +1,15 @@ -func findThePrefixCommonArray(A []int, B []int) (ans []int) { - vis := make([]int, len(A)+1) - for i := range vis { - vis[i] = 1 - } - s := 0 +func findThePrefixCommonArray(A []int, B []int) []int { + n := len(A) + cnt1 := make([]int, n+1) + cnt2 := make([]int, n+1) + ans := make([]int, n) for i, a := range A { b := B[i] - vis[a] ^= 1 - s += vis[a] - vis[b] ^= 1 - s += vis[b] - ans = append(ans, s) + cnt1[a]++ + cnt2[b]++ + for j := 1; j <= n; j++ { + ans[i] += min(cnt1[j], cnt2[j]) + } } - return + return ans } \ No newline at end of file diff --git a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.java b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.java index 8bcfc980a427a..c60fe315c0a57 100644 --- a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.java +++ b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.java @@ -1,17 +1,16 @@ -class Solution { - public int[] findThePrefixCommonArray(int[] A, int[] B) { - int n = A.length; - int[] ans = new int[n]; - int[] vis = new int[n + 1]; - Arrays.fill(vis, 1); - int s = 0; - for (int i = 0; i < n; ++i) { - vis[A[i]] ^= 1; - s += vis[A[i]]; - vis[B[i]] ^= 1; - s += vis[B[i]]; - ans[i] = s; - } - return ans; - } +class Solution { + public int[] findThePrefixCommonArray(int[] A, int[] B) { + int n = A.length; + int[] ans = new int[n]; + int[] cnt1 = new int[n + 1]; + int[] cnt2 = new int[n + 1]; + for (int i = 0; i < n; ++i) { + ++cnt1[A[i]]; + ++cnt2[B[i]]; + for (int j = 1; j <= n; ++j) { + ans[i] += Math.min(cnt1[j], cnt2[j]); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.py b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.py index 1c2a57f984d33..e9de69108a5b9 100644 --- a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.py +++ b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.py @@ -1,12 +1,11 @@ -class Solution: - def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]: - ans = [] - vis = [1] * (len(A) + 1) - s = 0 - for a, b in zip(A, B): - vis[a] ^= 1 - s += vis[a] - vis[b] ^= 1 - s += vis[b] - ans.append(s) - return ans +class Solution: + def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]: + ans = [] + cnt1 = Counter() + cnt2 = Counter() + for a, b in zip(A, B): + cnt1[a] += 1 + cnt2[b] += 1 + t = sum(min(v, cnt2[x]) for x, v in cnt1.items()) + ans.append(t) + return ans diff --git a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.ts b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.ts index 7dc8c3472790a..bdd978fdc63bd 100644 --- a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.ts +++ b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution.ts @@ -1,15 +1,14 @@ function findThePrefixCommonArray(A: number[], B: number[]): number[] { const n = A.length; - const vis: number[] = Array(n + 1).fill(1); - const ans: number[] = []; - let s = 0; + const cnt1: number[] = Array(n + 1).fill(0); + const cnt2: number[] = Array(n + 1).fill(0); + const ans: number[] = Array(n).fill(0); for (let i = 0; i < n; ++i) { - const [a, b] = [A[i], B[i]]; - vis[a] ^= 1; - s += vis[a]; - vis[b] ^= 1; - s += vis[b]; - ans.push(s); + ++cnt1[A[i]]; + ++cnt2[B[i]]; + for (let j = 1; j <= n; ++j) { + ans[i] += Math.min(cnt1[j], cnt2[j]); + } } return ans; } diff --git a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution2.cpp b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution2.cpp new file mode 100644 index 0000000000000..a90e43cd3b03d --- /dev/null +++ b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector findThePrefixCommonArray(vector& A, vector& B) { + int n = A.size(); + vector ans; + vector vis(n + 1, 1); + int s = 0; + for (int i = 0; i < n; ++i) { + vis[A[i]] ^= 1; + s += vis[A[i]]; + vis[B[i]] ^= 1; + s += vis[B[i]]; + ans.push_back(s); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution2.go b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution2.go new file mode 100644 index 0000000000000..255d1c1ecc287 --- /dev/null +++ b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution2.go @@ -0,0 +1,16 @@ +func findThePrefixCommonArray(A []int, B []int) (ans []int) { + vis := make([]int, len(A)+1) + for i := range vis { + vis[i] = 1 + } + s := 0 + for i, a := range A { + b := B[i] + vis[a] ^= 1 + s += vis[a] + vis[b] ^= 1 + s += vis[b] + ans = append(ans, s) + } + return +} \ No newline at end of file diff --git a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution2.java b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution2.java new file mode 100644 index 0000000000000..2e435a2368bd3 --- /dev/null +++ b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution2.java @@ -0,0 +1,17 @@ +class Solution { + public int[] findThePrefixCommonArray(int[] A, int[] B) { + int n = A.length; + int[] ans = new int[n]; + int[] vis = new int[n + 1]; + Arrays.fill(vis, 1); + int s = 0; + for (int i = 0; i < n; ++i) { + vis[A[i]] ^= 1; + s += vis[A[i]]; + vis[B[i]] ^= 1; + s += vis[B[i]]; + ans[i] = s; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution2.py b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution2.py new file mode 100644 index 0000000000000..eda514ae76550 --- /dev/null +++ b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution2.py @@ -0,0 +1,12 @@ +class Solution: + def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]: + ans = [] + vis = [1] * (len(A) + 1) + s = 0 + for a, b in zip(A, B): + vis[a] ^= 1 + s += vis[a] + vis[b] ^= 1 + s += vis[b] + ans.append(s) + return ans diff --git a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution2.ts b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution2.ts new file mode 100644 index 0000000000000..7dc8c3472790a --- /dev/null +++ b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution2.ts @@ -0,0 +1,15 @@ +function findThePrefixCommonArray(A: number[], B: number[]): number[] { + const n = A.length; + const vis: number[] = Array(n + 1).fill(1); + const ans: number[] = []; + let s = 0; + for (let i = 0; i < n; ++i) { + const [a, b] = [A[i], B[i]]; + vis[a] ^= 1; + s += vis[a]; + vis[b] ^= 1; + s += vis[b]; + ans.push(s); + } + return ans; +} diff --git a/solution/2600-2699/2659.Make Array Empty/Solution2.py b/solution/2600-2699/2659.Make Array Empty/Solution2.py new file mode 100644 index 0000000000000..5dab36892111d --- /dev/null +++ b/solution/2600-2699/2659.Make Array Empty/Solution2.py @@ -0,0 +1,31 @@ +class BinaryIndexedTree: + def __init__(self, n): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x, delta): + while x <= self.n: + self.c[x] += delta + x += x & -x + + def query(self, x): + s = 0 + while x: + s += self.c[x] + x -= x & -x + return s + + +class Solution: + def countOperationsToEmptyArray(self, nums: List[int]) -> int: + pos = {x: i for i, x in enumerate(nums)} + nums.sort() + ans = pos[nums[0]] + 1 + n = len(nums) + tree = BinaryIndexedTree(n) + for k, (a, b) in enumerate(pairwise(nums)): + i, j = pos[a], pos[b] + d = j - i - tree.query(j + 1) + tree.query(i + 1) + ans += d + (n - k) * int(i > j) + tree.update(i + 1, 1) + return ans diff --git a/solution/2600-2699/2660.Determine the Winner of a Bowling Game/Solution.cpp b/solution/2600-2699/2660.Determine the Winner of a Bowling Game/Solution.cpp index 04e8e01c806d7..f68fc84b243ad 100644 --- a/solution/2600-2699/2660.Determine the Winner of a Bowling Game/Solution.cpp +++ b/solution/2600-2699/2660.Determine the Winner of a Bowling Game/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - int isWinner(vector& player1, vector& player2) { - auto f = [](vector& arr) { - int s = 0; - for (int i = 0, n = arr.size(); i < n; ++i) { - int k = (i && arr[i - 1] == 10) || (i > 1 && arr[i - 2] == 10) ? 2 : 1; - s += k * arr[i]; - } - return s; - }; - int a = f(player1), b = f(player2); - return a > b ? 1 : (b > a ? 2 : 0); - } +class Solution { +public: + int isWinner(vector& player1, vector& player2) { + auto f = [](vector& arr) { + int s = 0; + for (int i = 0, n = arr.size(); i < n; ++i) { + int k = (i && arr[i - 1] == 10) || (i > 1 && arr[i - 2] == 10) ? 2 : 1; + s += k * arr[i]; + } + return s; + }; + int a = f(player1), b = f(player2); + return a > b ? 1 : (b > a ? 2 : 0); + } }; \ No newline at end of file diff --git a/solution/2600-2699/2660.Determine the Winner of a Bowling Game/Solution.py b/solution/2600-2699/2660.Determine the Winner of a Bowling Game/Solution.py index ab6b3394f821b..3da56bcf58a71 100644 --- a/solution/2600-2699/2660.Determine the Winner of a Bowling Game/Solution.py +++ b/solution/2600-2699/2660.Determine the Winner of a Bowling Game/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def isWinner(self, player1: List[int], player2: List[int]) -> int: - def f(arr: List[int]) -> int: - s = 0 - for i, x in enumerate(arr): - k = 2 if (i and arr[i - 1] == 10) or (i > 1 and arr[i - 2] == 10) else 1 - s += k * x - return s - - a, b = f(player1), f(player2) - return 1 if a > b else (2 if b > a else 0) +class Solution: + def isWinner(self, player1: List[int], player2: List[int]) -> int: + def f(arr: List[int]) -> int: + s = 0 + for i, x in enumerate(arr): + k = 2 if (i and arr[i - 1] == 10) or (i > 1 and arr[i - 2] == 10) else 1 + s += k * x + return s + + a, b = f(player1), f(player2) + return 1 if a > b else (2 if b > a else 0) diff --git a/solution/2600-2699/2670.Find the Distinct Difference Array/Solution.py b/solution/2600-2699/2670.Find the Distinct Difference Array/Solution.py index 5150fa9779e89..9b33b1da3c288 100644 --- a/solution/2600-2699/2670.Find the Distinct Difference Array/Solution.py +++ b/solution/2600-2699/2670.Find the Distinct Difference Array/Solution.py @@ -1,15 +1,9 @@ class Solution: def distinctDifferenceArray(self, nums: List[int]) -> List[int]: n = len(nums) - suf = [0] * (n + 1) - s = set() - for i in range(n - 1, -1, -1): - s.add(nums[i]) - suf[i] = len(s) - - s.clear() ans = [0] * n - for i, x in enumerate(nums): - s.add(x) - ans[i] = len(s) - suf[i + 1] + for i in range(n): + a = len(set(nums[: i + 1])) + b = len(set(nums[i + 1 :])) + ans[i] = a - b return ans diff --git a/solution/2600-2699/2670.Find the Distinct Difference Array/Solution.rs b/solution/2600-2699/2670.Find the Distinct Difference Array/Solution.rs index 78ccbb62109b2..43551e558951a 100644 --- a/solution/2600-2699/2670.Find the Distinct Difference Array/Solution.rs +++ b/solution/2600-2699/2670.Find the Distinct Difference Array/Solution.rs @@ -2,20 +2,24 @@ use std::collections::HashSet; impl Solution { pub fn distinct_difference_array(nums: Vec) -> Vec { - let n = nums.len(); - let mut s = vec![0; n + 1]; - let mut set = HashSet::new(); + let mut ans: Vec = Vec::new(); - for i in (0..n).rev() { - set.insert(nums[i]); - s[i] = set.len(); - } + for i in 0..nums.len() { + let mut j = 0; + let mut hash1 = HashSet::new(); + while j <= i { + hash1.insert(nums[j]); + j += 1; + } + + let mut k = i + 1; + let mut hash2 = HashSet::new(); + while k < nums.len() { + hash2.insert(nums[k]); + k += 1; + } - let mut ans = Vec::new(); - set.clear(); - for i in 0..n { - set.insert(nums[i]); - ans.push((set.len() - s[i + 1]) as i32); + ans.push((hash1.len() - hash2.len()) as i32); } ans diff --git a/solution/2600-2699/2670.Find the Distinct Difference Array/Solution2.py b/solution/2600-2699/2670.Find the Distinct Difference Array/Solution2.py new file mode 100644 index 0000000000000..5150fa9779e89 --- /dev/null +++ b/solution/2600-2699/2670.Find the Distinct Difference Array/Solution2.py @@ -0,0 +1,15 @@ +class Solution: + def distinctDifferenceArray(self, nums: List[int]) -> List[int]: + n = len(nums) + suf = [0] * (n + 1) + s = set() + for i in range(n - 1, -1, -1): + s.add(nums[i]) + suf[i] = len(s) + + s.clear() + ans = [0] * n + for i, x in enumerate(nums): + s.add(x) + ans[i] = len(s) - suf[i + 1] + return ans diff --git a/solution/2600-2699/2670.Find the Distinct Difference Array/Solution2.rs b/solution/2600-2699/2670.Find the Distinct Difference Array/Solution2.rs new file mode 100644 index 0000000000000..78ccbb62109b2 --- /dev/null +++ b/solution/2600-2699/2670.Find the Distinct Difference Array/Solution2.rs @@ -0,0 +1,23 @@ +use std::collections::HashSet; + +impl Solution { + pub fn distinct_difference_array(nums: Vec) -> Vec { + let n = nums.len(); + let mut s = vec![0; n + 1]; + let mut set = HashSet::new(); + + for i in (0..n).rev() { + set.insert(nums[i]); + s[i] = set.len(); + } + + let mut ans = Vec::new(); + set.clear(); + for i in 0..n { + set.insert(nums[i]); + ans.push((set.len() - s[i + 1]) as i32); + } + + ans + } +} diff --git a/solution/2600-2699/2678.Number of Senior Citizens/Solution2.rs b/solution/2600-2699/2678.Number of Senior Citizens/Solution2.rs new file mode 100644 index 0000000000000..867e6ab362591 --- /dev/null +++ b/solution/2600-2699/2678.Number of Senior Citizens/Solution2.rs @@ -0,0 +1,9 @@ +impl Solution { + pub fn count_seniors(details: Vec) -> i32 { + details + .iter() + .filter_map(|s| s[11..13].parse::().ok()) + .filter(|&age| age > 60) + .count() as i32 + } +} diff --git a/solution/2600-2699/2678.Number of Senior Citizens/Solution2.ts b/solution/2600-2699/2678.Number of Senior Citizens/Solution2.ts new file mode 100644 index 0000000000000..1c269b1903ca6 --- /dev/null +++ b/solution/2600-2699/2678.Number of Senior Citizens/Solution2.ts @@ -0,0 +1,3 @@ +function countSeniors(details: string[]): number { + return details.filter(v => parseInt(v.slice(11, 13)) > 60).length; +} diff --git a/solution/2600-2699/2679.Sum in a Matrix/Solution.py b/solution/2600-2699/2679.Sum in a Matrix/Solution.py index e0c742de5eae0..1755c238050e6 100644 --- a/solution/2600-2699/2679.Sum in a Matrix/Solution.py +++ b/solution/2600-2699/2679.Sum in a Matrix/Solution.py @@ -1,5 +1,5 @@ -class Solution: - def matrixSum(self, nums: List[List[int]]) -> int: - for row in nums: - row.sort() - return sum(map(max, zip(*nums))) +class Solution: + def matrixSum(self, nums: List[List[int]]) -> int: + for row in nums: + row.sort() + return sum(map(max, zip(*nums))) diff --git a/solution/2600-2699/2679.Sum in a Matrix/Solution.rs b/solution/2600-2699/2679.Sum in a Matrix/Solution.rs index 93212861342c3..4f3f48bdbc350 100644 --- a/solution/2600-2699/2679.Sum in a Matrix/Solution.rs +++ b/solution/2600-2699/2679.Sum in a Matrix/Solution.rs @@ -1,19 +1,20 @@ impl Solution { pub fn matrix_sum(nums: Vec>) -> i32 { - let mut nums = nums.clone(); + let mut nums = nums; for row in nums.iter_mut() { row.sort(); } + let transposed: Vec> = (0..nums[0].len()) + .map(|i| { + nums.iter() + .map(|row| row[i]) + .collect() + }) + .collect(); - let mut ans = 0; - for j in 0..nums[0].len() { - let mut mx = 0; - for row in &nums { - mx = mx.max(row[j]); - } - ans += mx; - } - - ans + transposed + .iter() + .map(|row| row.iter().max().unwrap()) + .sum() } } diff --git a/solution/2600-2699/2679.Sum in a Matrix/Solution2.rs b/solution/2600-2699/2679.Sum in a Matrix/Solution2.rs new file mode 100644 index 0000000000000..93212861342c3 --- /dev/null +++ b/solution/2600-2699/2679.Sum in a Matrix/Solution2.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn matrix_sum(nums: Vec>) -> i32 { + let mut nums = nums.clone(); + for row in nums.iter_mut() { + row.sort(); + } + + let mut ans = 0; + for j in 0..nums[0].len() { + let mut mx = 0; + for row in &nums { + mx = mx.max(row[j]); + } + ans += mx; + } + + ans + } +} diff --git a/solution/2600-2699/2682.Find the Losers of the Circular Game/Solution.cpp b/solution/2600-2699/2682.Find the Losers of the Circular Game/Solution.cpp index aeb1c2649629e..f4f94aa367cbb 100644 --- a/solution/2600-2699/2682.Find the Losers of the Circular Game/Solution.cpp +++ b/solution/2600-2699/2682.Find the Losers of the Circular Game/Solution.cpp @@ -1,18 +1,18 @@ -class Solution { -public: - vector circularGameLosers(int n, int k) { - bool vis[n]; - memset(vis, false, sizeof(vis)); - for (int i = 0, p = 1; !vis[i]; ++p) { - vis[i] = true; - i = (i + p * k) % n; - } - vector ans; - for (int i = 0; i < n; ++i) { - if (!vis[i]) { - ans.push_back(i + 1); - } - } - return ans; - } +class Solution { +public: + vector circularGameLosers(int n, int k) { + bool vis[n]; + memset(vis, false, sizeof(vis)); + for (int i = 0, p = 1; !vis[i]; ++p) { + vis[i] = true; + i = (i + p * k) % n; + } + vector ans; + for (int i = 0; i < n; ++i) { + if (!vis[i]) { + ans.push_back(i + 1); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2600-2699/2683.Neighboring Bitwise XOR/Solution2.ts b/solution/2600-2699/2683.Neighboring Bitwise XOR/Solution2.ts new file mode 100644 index 0000000000000..0211597d5403f --- /dev/null +++ b/solution/2600-2699/2683.Neighboring Bitwise XOR/Solution2.ts @@ -0,0 +1,3 @@ +function doesValidArrayExist(derived: number[]): boolean { + return derived.reduce((acc, x) => acc ^ x, 0) === 0; +} diff --git a/solution/2600-2699/2697.Lexicographically Smallest Palindrome/Solution.cpp b/solution/2600-2699/2697.Lexicographically Smallest Palindrome/Solution.cpp index 6d18d9f4c7795..641fc0192a0bf 100644 --- a/solution/2600-2699/2697.Lexicographically Smallest Palindrome/Solution.cpp +++ b/solution/2600-2699/2697.Lexicographically Smallest Palindrome/Solution.cpp @@ -1,9 +1,9 @@ -class Solution { -public: - string makeSmallestPalindrome(string s) { - for (int i = 0, j = s.size() - 1; i < j; ++i, --j) { - s[i] = s[j] = min(s[i], s[j]); - } - return s; - } +class Solution { +public: + string makeSmallestPalindrome(string s) { + for (int i = 0, j = s.size() - 1; i < j; ++i, --j) { + s[i] = s[j] = min(s[i], s[j]); + } + return s; + } }; \ No newline at end of file diff --git a/solution/2600-2699/2697.Lexicographically Smallest Palindrome/Solution.java b/solution/2600-2699/2697.Lexicographically Smallest Palindrome/Solution.java index 0896d09f92443..c1b4d8db53ed9 100644 --- a/solution/2600-2699/2697.Lexicographically Smallest Palindrome/Solution.java +++ b/solution/2600-2699/2697.Lexicographically Smallest Palindrome/Solution.java @@ -1,9 +1,9 @@ -class Solution { - public String makeSmallestPalindrome(String s) { - char[] cs = s.toCharArray(); - for (int i = 0, j = cs.length - 1; i < j; ++i, --j) { - cs[i] = cs[j] = (char) Math.min(cs[i], cs[j]); - } - return new String(cs); - } +class Solution { + public String makeSmallestPalindrome(String s) { + char[] cs = s.toCharArray(); + for (int i = 0, j = cs.length - 1; i < j; ++i, --j) { + cs[i] = cs[j] = (char) Math.min(cs[i], cs[j]); + } + return new String(cs); + } } \ No newline at end of file diff --git a/solution/2600-2699/2697.Lexicographically Smallest Palindrome/Solution.py b/solution/2600-2699/2697.Lexicographically Smallest Palindrome/Solution.py index b374713ad852b..f8ad591d828cc 100644 --- a/solution/2600-2699/2697.Lexicographically Smallest Palindrome/Solution.py +++ b/solution/2600-2699/2697.Lexicographically Smallest Palindrome/Solution.py @@ -1,8 +1,8 @@ -class Solution: - def makeSmallestPalindrome(self, s: str) -> str: - cs = list(s) - i, j = 0, len(s) - 1 - while i < j: - cs[i] = cs[j] = min(cs[i], cs[j]) - i, j = i + 1, j - 1 - return "".join(cs) +class Solution: + def makeSmallestPalindrome(self, s: str) -> str: + cs = list(s) + i, j = 0, len(s) - 1 + while i < j: + cs[i] = cs[j] = min(cs[i], cs[j]) + i, j = i + 1, j - 1 + return "".join(cs) diff --git a/solution/2700-2799/2706.Buy Two Chocolates/Solution.cpp b/solution/2700-2799/2706.Buy Two Chocolates/Solution.cpp index eebaee32b7537..c472e8d54cfae 100644 --- a/solution/2700-2799/2706.Buy Two Chocolates/Solution.cpp +++ b/solution/2700-2799/2706.Buy Two Chocolates/Solution.cpp @@ -1,16 +1,8 @@ -class Solution { -public: - int buyChoco(vector& prices, int money) { - int a = 1000, b = 1000; - for (int x : prices) { - if (x < a) { - b = a; - a = x; - } else if (x < b) { - b = x; - } - } - int cost = a + b; - return money < cost ? money : money - cost; - } +class Solution { +public: + int buyChoco(vector& prices, int money) { + sort(prices.begin(), prices.end()); + int cost = prices[0] + prices[1]; + return money < cost ? money : money - cost; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2706.Buy Two Chocolates/Solution.go b/solution/2700-2799/2706.Buy Two Chocolates/Solution.go index 0b807ce6798dd..41461a376798d 100644 --- a/solution/2700-2799/2706.Buy Two Chocolates/Solution.go +++ b/solution/2700-2799/2706.Buy Two Chocolates/Solution.go @@ -1,13 +1,6 @@ func buyChoco(prices []int, money int) int { - a, b := 1001, 1001 - for _, x := range prices { - if x < a { - a, b = x, a - } else if x < b { - b = x - } - } - cost := a + b + sort.Ints(prices) + cost := prices[0] + prices[1] if money < cost { return money } diff --git a/solution/2700-2799/2706.Buy Two Chocolates/Solution.java b/solution/2700-2799/2706.Buy Two Chocolates/Solution.java index 06633d4f5a307..b42e08b86cd33 100644 --- a/solution/2700-2799/2706.Buy Two Chocolates/Solution.java +++ b/solution/2700-2799/2706.Buy Two Chocolates/Solution.java @@ -1,15 +1,7 @@ -class Solution { - public int buyChoco(int[] prices, int money) { - int a = 1000, b = 1000; - for (int x : prices) { - if (x < a) { - b = a; - a = x; - } else if (x < b) { - b = x; - } - } - int cost = a + b; - return money < cost ? money : money - cost; - } +class Solution { + public int buyChoco(int[] prices, int money) { + Arrays.sort(prices); + int cost = prices[0] + prices[1]; + return money < cost ? money : money - cost; + } } \ No newline at end of file diff --git a/solution/2700-2799/2706.Buy Two Chocolates/Solution.py b/solution/2700-2799/2706.Buy Two Chocolates/Solution.py index bb9080b851412..6556df9e073ee 100644 --- a/solution/2700-2799/2706.Buy Two Chocolates/Solution.py +++ b/solution/2700-2799/2706.Buy Two Chocolates/Solution.py @@ -1,10 +1,5 @@ -class Solution: - def buyChoco(self, prices: List[int], money: int) -> int: - a = b = inf - for x in prices: - if x < a: - a, b = x, a - elif x < b: - b = x - cost = a + b - return money if money < cost else money - cost +class Solution: + def buyChoco(self, prices: List[int], money: int) -> int: + prices.sort() + cost = prices[0] + prices[1] + return money if money < cost else money - cost diff --git a/solution/2700-2799/2706.Buy Two Chocolates/Solution.rs b/solution/2700-2799/2706.Buy Two Chocolates/Solution.rs index 533e759ec6a85..2cc21082a5b29 100644 --- a/solution/2700-2799/2706.Buy Two Chocolates/Solution.rs +++ b/solution/2700-2799/2706.Buy Two Chocolates/Solution.rs @@ -1,20 +1,10 @@ impl Solution { - pub fn buy_choco(prices: Vec, money: i32) -> i32 { - let mut a = 1000; - let mut b = 1000; - for &x in prices.iter() { - if x < a { - b = a; - a = x; - } else if x < b { - b = x; - } - } - let cost = a + b; - if money < cost { - money - } else { - money - cost + pub fn buy_choco(mut prices: Vec, money: i32) -> i32 { + prices.sort(); + let cost = prices[0] + prices[1]; + if cost > money { + return money; } + money - cost } } diff --git a/solution/2700-2799/2706.Buy Two Chocolates/Solution.ts b/solution/2700-2799/2706.Buy Two Chocolates/Solution.ts index f211795361bbd..306d13a823b9f 100644 --- a/solution/2700-2799/2706.Buy Two Chocolates/Solution.ts +++ b/solution/2700-2799/2706.Buy Two Chocolates/Solution.ts @@ -1,13 +1,5 @@ function buyChoco(prices: number[], money: number): number { - let [a, b] = [1000, 1000]; - for (const x of prices) { - if (x < a) { - b = a; - a = x; - } else if (x < b) { - b = x; - } - } - const cost = a + b; + prices.sort((a, b) => a - b); + const cost = prices[0] + prices[1]; return money < cost ? money : money - cost; } diff --git a/solution/2700-2799/2706.Buy Two Chocolates/Solution2.cpp b/solution/2700-2799/2706.Buy Two Chocolates/Solution2.cpp new file mode 100644 index 0000000000000..c7b309449fecf --- /dev/null +++ b/solution/2700-2799/2706.Buy Two Chocolates/Solution2.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int buyChoco(vector& prices, int money) { + int a = 1000, b = 1000; + for (int x : prices) { + if (x < a) { + b = a; + a = x; + } else if (x < b) { + b = x; + } + } + int cost = a + b; + return money < cost ? money : money - cost; + } +}; \ No newline at end of file diff --git a/solution/2700-2799/2706.Buy Two Chocolates/Solution2.go b/solution/2700-2799/2706.Buy Two Chocolates/Solution2.go new file mode 100644 index 0000000000000..0b807ce6798dd --- /dev/null +++ b/solution/2700-2799/2706.Buy Two Chocolates/Solution2.go @@ -0,0 +1,15 @@ +func buyChoco(prices []int, money int) int { + a, b := 1001, 1001 + for _, x := range prices { + if x < a { + a, b = x, a + } else if x < b { + b = x + } + } + cost := a + b + if money < cost { + return money + } + return money - cost +} \ No newline at end of file diff --git a/solution/2700-2799/2706.Buy Two Chocolates/Solution2.java b/solution/2700-2799/2706.Buy Two Chocolates/Solution2.java new file mode 100644 index 0000000000000..7eff13c78a9e3 --- /dev/null +++ b/solution/2700-2799/2706.Buy Two Chocolates/Solution2.java @@ -0,0 +1,15 @@ +class Solution { + public int buyChoco(int[] prices, int money) { + int a = 1000, b = 1000; + for (int x : prices) { + if (x < a) { + b = a; + a = x; + } else if (x < b) { + b = x; + } + } + int cost = a + b; + return money < cost ? money : money - cost; + } +} \ No newline at end of file diff --git a/solution/2700-2799/2706.Buy Two Chocolates/Solution2.py b/solution/2700-2799/2706.Buy Two Chocolates/Solution2.py new file mode 100644 index 0000000000000..2db79a5da7bf8 --- /dev/null +++ b/solution/2700-2799/2706.Buy Two Chocolates/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def buyChoco(self, prices: List[int], money: int) -> int: + a = b = inf + for x in prices: + if x < a: + a, b = x, a + elif x < b: + b = x + cost = a + b + return money if money < cost else money - cost diff --git a/solution/2700-2799/2706.Buy Two Chocolates/Solution2.rs b/solution/2700-2799/2706.Buy Two Chocolates/Solution2.rs new file mode 100644 index 0000000000000..533e759ec6a85 --- /dev/null +++ b/solution/2700-2799/2706.Buy Two Chocolates/Solution2.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn buy_choco(prices: Vec, money: i32) -> i32 { + let mut a = 1000; + let mut b = 1000; + for &x in prices.iter() { + if x < a { + b = a; + a = x; + } else if x < b { + b = x; + } + } + let cost = a + b; + if money < cost { + money + } else { + money - cost + } + } +} diff --git a/solution/2700-2799/2706.Buy Two Chocolates/Solution2.ts b/solution/2700-2799/2706.Buy Two Chocolates/Solution2.ts new file mode 100644 index 0000000000000..f211795361bbd --- /dev/null +++ b/solution/2700-2799/2706.Buy Two Chocolates/Solution2.ts @@ -0,0 +1,13 @@ +function buyChoco(prices: number[], money: number): number { + let [a, b] = [1000, 1000]; + for (const x of prices) { + if (x < a) { + b = a; + a = x; + } else if (x < b) { + b = x; + } + } + const cost = a + b; + return money < cost ? money : money - cost; +} diff --git a/solution/2700-2799/2707.Extra Characters in a String/Solution2.cpp b/solution/2700-2799/2707.Extra Characters in a String/Solution2.cpp new file mode 100644 index 0000000000000..898b421bb5660 --- /dev/null +++ b/solution/2700-2799/2707.Extra Characters in a String/Solution2.cpp @@ -0,0 +1,44 @@ +class Node { +public: + Node* children[26]; + bool isEnd = false; + Node() { + fill(children, children + 26, nullptr); + } +}; + +class Solution { +public: + int minExtraChar(string s, vector& dictionary) { + Node* root = new Node(); + for (const string& w : dictionary) { + Node* node = root; + for (int k = w.length() - 1; k >= 0; --k) { + int i = w[k] - 'a'; + if (node->children[i] == nullptr) { + node->children[i] = new Node(); + } + node = node->children[i]; + } + node->isEnd = true; + } + + int n = s.size(); + int f[n + 1]; + f[0] = 0; + for (int i = 1; i <= n; ++i) { + f[i] = f[i - 1] + 1; + Node* node = root; + for (int j = i - 1; ~j; --j) { + node = node->children[s[j] - 'a']; + if (node == nullptr) { + break; + } + if (node->isEnd && f[j] < f[i]) { + f[i] = f[j]; + } + } + } + return f[n]; + } +}; \ No newline at end of file diff --git a/solution/2700-2799/2707.Extra Characters in a String/Solution2.go b/solution/2700-2799/2707.Extra Characters in a String/Solution2.go new file mode 100644 index 0000000000000..96d1215e16035 --- /dev/null +++ b/solution/2700-2799/2707.Extra Characters in a String/Solution2.go @@ -0,0 +1,36 @@ +type Node struct { + children [26]*Node + isEnd bool +} + +func minExtraChar(s string, dictionary []string) int { + root := &Node{} + for _, w := range dictionary { + node := root + for k := len(w) - 1; k >= 0; k-- { + i := int(w[k] - 'a') + if node.children[i] == nil { + node.children[i] = &Node{} + } + node = node.children[i] + } + node.isEnd = true + } + + n := len(s) + f := make([]int, n+1) + for i := 1; i <= n; i++ { + f[i] = f[i-1] + 1 + node := root + for j := i - 1; j >= 0; j-- { + node = node.children[int(s[j]-'a')] + if node == nil { + break + } + if node.isEnd && f[j] < f[i] { + f[i] = f[j] + } + } + } + return f[n] +} \ No newline at end of file diff --git a/solution/2700-2799/2707.Extra Characters in a String/Solution2.java b/solution/2700-2799/2707.Extra Characters in a String/Solution2.java new file mode 100644 index 0000000000000..6de3aa359ced5 --- /dev/null +++ b/solution/2700-2799/2707.Extra Characters in a String/Solution2.java @@ -0,0 +1,37 @@ +class Node { + Node[] children = new Node[26]; + boolean isEnd; +} + +class Solution { + public int minExtraChar(String s, String[] dictionary) { + Node root = new Node(); + for (String w : dictionary) { + Node node = root; + for (int k = w.length() - 1; k >= 0; --k) { + int i = w.charAt(k) - 'a'; + if (node.children[i] == null) { + node.children[i] = new Node(); + } + node = node.children[i]; + } + node.isEnd = true; + } + int n = s.length(); + int[] f = new int[n + 1]; + for (int i = 1; i <= n; ++i) { + f[i] = f[i - 1] + 1; + Node node = root; + for (int j = i - 1; j >= 0; --j) { + node = node.children[s.charAt(j) - 'a']; + if (node == null) { + break; + } + if (node.isEnd && f[j] < f[i]) { + f[i] = f[j]; + } + } + } + return f[n]; + } +} \ No newline at end of file diff --git a/solution/2700-2799/2707.Extra Characters in a String/Solution2.py b/solution/2700-2799/2707.Extra Characters in a String/Solution2.py new file mode 100644 index 0000000000000..8e4b6c24b8306 --- /dev/null +++ b/solution/2700-2799/2707.Extra Characters in a String/Solution2.py @@ -0,0 +1,32 @@ +class Node: + __slots__ = ['children', 'is_end'] + + def __init__(self): + self.children: List[Node | None] = [None] * 26 + self.is_end = False + + +class Solution: + def minExtraChar(self, s: str, dictionary: List[str]) -> int: + root = Node() + for w in dictionary: + node = root + for c in w[::-1]: + i = ord(c) - ord('a') + if node.children[i] is None: + node.children[i] = Node() + node = node.children[i] + node.is_end = True + + n = len(s) + f = [0] * (n + 1) + for i in range(1, n + 1): + f[i] = f[i - 1] + 1 + node = root + for j in range(i - 1, -1, -1): + node = node.children[ord(s[j]) - ord('a')] + if node is None: + break + if node.is_end and f[j] < f[i]: + f[i] = f[j] + return f[n] diff --git a/solution/2700-2799/2707.Extra Characters in a String/Solution2.ts b/solution/2700-2799/2707.Extra Characters in a String/Solution2.ts new file mode 100644 index 0000000000000..502c363eabfc1 --- /dev/null +++ b/solution/2700-2799/2707.Extra Characters in a String/Solution2.ts @@ -0,0 +1,37 @@ +class Node { + children: (Node | null)[] = Array(26).fill(null); + isEnd: boolean = false; +} + +function minExtraChar(s: string, dictionary: string[]): number { + const root = new Node(); + for (const w of dictionary) { + let node = root; + for (let k = w.length - 1; ~k; --k) { + const i = w.charCodeAt(k) - 'a'.charCodeAt(0); + if (node.children[i] === null) { + node.children[i] = new Node(); + } + node = node.children[i] as Node; + } + node.isEnd = true; + } + + const n = s.length; + const f: number[] = Array(n + 1).fill(0); + for (let i = 1; i <= n; ++i) { + f[i] = f[i - 1] + 1; + let node = root; + for (let j = i - 1; ~j; --j) { + node = (node.children[s.charCodeAt(j) - 'a'.charCodeAt(0)] as Node) || null; + if (node === null) { + break; + } + if (node.isEnd && f[j] < f[i]) { + f[i] = f[j]; + } + } + } + + return f[n]; +} diff --git a/solution/2700-2799/2710.Remove Trailing Zeros From a String/Solution2.rs b/solution/2700-2799/2710.Remove Trailing Zeros From a String/Solution2.rs new file mode 100644 index 0000000000000..c76736f9dff4d --- /dev/null +++ b/solution/2700-2799/2710.Remove Trailing Zeros From a String/Solution2.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn remove_trailing_zeros(num: String) -> String { + num.chars() + .rev() + .skip_while(|&c| c == '0') + .collect::() + .chars() + .rev() + .collect::() + } +} diff --git a/solution/2700-2799/2716.Minimize String Length/Solution.rs b/solution/2700-2799/2716.Minimize String Length/Solution.rs index 642a8a0079ebb..afcc3dc816b51 100644 --- a/solution/2700-2799/2716.Minimize String Length/Solution.rs +++ b/solution/2700-2799/2716.Minimize String Length/Solution.rs @@ -1,13 +1,13 @@ -use std::collections::HashSet; +use std::collections::HashMap; impl Solution { pub fn minimized_string_length(s: String) -> i32 { - let mut set = HashSet::new(); + let mut hash = HashMap::new(); for c in s.chars() { - set.insert(c); + hash.insert(c, true); } - set.len() as i32 + hash.len() as i32 } } diff --git a/solution/2700-2799/2716.Minimize String Length/Solution2.rs b/solution/2700-2799/2716.Minimize String Length/Solution2.rs new file mode 100644 index 0000000000000..642a8a0079ebb --- /dev/null +++ b/solution/2700-2799/2716.Minimize String Length/Solution2.rs @@ -0,0 +1,13 @@ +use std::collections::HashSet; + +impl Solution { + pub fn minimized_string_length(s: String) -> i32 { + let mut set = HashSet::new(); + + for c in s.chars() { + set.insert(c); + } + + set.len() as i32 + } +} diff --git a/solution/2700-2799/2717.Semi-Ordered Permutation/Solution.rs b/solution/2700-2799/2717.Semi-Ordered Permutation/Solution.rs index 2518893fa692a..c3cc4915d6a81 100644 --- a/solution/2700-2799/2717.Semi-Ordered Permutation/Solution.rs +++ b/solution/2700-2799/2717.Semi-Ordered Permutation/Solution.rs @@ -1,18 +1,17 @@ impl Solution { pub fn semi_ordered_permutation(nums: Vec) -> i32 { - let n = nums.len(); - let i = nums - .iter() - .enumerate() - .find(|&(_, &v)| v == 1) - .map(|(i, _)| i) - .unwrap(); - let j = nums - .iter() - .enumerate() - .find(|&(_, &v)| v == (n as i32)) - .map(|(i, _)| i) - .unwrap(); + let mut i = 0; + let mut j = 0; + let mut n = nums.len(); + + for idx in 0..n { + if nums[idx] == 1 { + i = idx; + } + if nums[idx] == (n as i32) { + j = idx; + } + } let mut ans = i - 1 + n - j; if i > j { diff --git a/solution/2700-2799/2717.Semi-Ordered Permutation/Solution2.rs b/solution/2700-2799/2717.Semi-Ordered Permutation/Solution2.rs new file mode 100644 index 0000000000000..2518893fa692a --- /dev/null +++ b/solution/2700-2799/2717.Semi-Ordered Permutation/Solution2.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn semi_ordered_permutation(nums: Vec) -> i32 { + let n = nums.len(); + let i = nums + .iter() + .enumerate() + .find(|&(_, &v)| v == 1) + .map(|(i, _)| i) + .unwrap(); + let j = nums + .iter() + .enumerate() + .find(|&(_, &v)| v == (n as i32)) + .map(|(i, _)| i) + .unwrap(); + + let mut ans = i - 1 + n - j; + if i > j { + ans = i - 1 + n - j - 1; + } + + ans as i32 + } +} diff --git a/solution/2700-2799/2723.Add Two Promises/Solution.js b/solution/2700-2799/2723.Add Two Promises/Solution.js new file mode 100644 index 0000000000000..00f1ab7ecd9fa --- /dev/null +++ b/solution/2700-2799/2723.Add Two Promises/Solution.js @@ -0,0 +1,3 @@ +var addTwoPromises = async function (promise1, promise2) { + return (await promise1) + (await promise2); +}; diff --git a/solution/2700-2799/2727.Is Object Empty/Solution2.ts b/solution/2700-2799/2727.Is Object Empty/Solution2.ts new file mode 100644 index 0000000000000..a972a6659066c --- /dev/null +++ b/solution/2700-2799/2727.Is Object Empty/Solution2.ts @@ -0,0 +1,3 @@ +function isEmpty(obj: Record | any[]): boolean { + return Object.keys(obj).length === 0; +} diff --git a/solution/2700-2799/2729.Check if The Number is Fascinating/Solution.rs b/solution/2700-2799/2729.Check if The Number is Fascinating/Solution.rs new file mode 100644 index 0000000000000..6520146ebcb20 --- /dev/null +++ b/solution/2700-2799/2729.Check if The Number is Fascinating/Solution.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn is_fascinating(n: i32) -> bool { + let s = format!("{}{}{}", n, n * 2, n * 3); + + let mut cnt = vec![0; 10]; + for c in s.chars() { + let t = (c as usize) - ('0' as usize); + cnt[t] += 1; + if cnt[t] > 1 { + return false; + } + } + + cnt[0] == 0 && s.len() == 9 + } +} diff --git a/solution/2700-2799/2729.Check if The Number is Fascinating/Solution2.rs b/solution/2700-2799/2729.Check if The Number is Fascinating/Solution2.rs new file mode 100644 index 0000000000000..4bff83d3084ef --- /dev/null +++ b/solution/2700-2799/2729.Check if The Number is Fascinating/Solution2.rs @@ -0,0 +1,36 @@ +use std::collections::HashMap; + +impl Solution { + pub fn is_fascinating(mut n: i32) -> bool { + let mut i = n * 2; + let mut j = n * 3; + + let mut hash = HashMap::new(); + + while n != 0 { + let cnt = hash.entry(n % 10).or_insert(0); + *cnt += 1; + n /= 10; + } + + while i != 0 { + let cnt = hash.entry(i % 10).or_insert(0); + *cnt += 1; + i /= 10; + } + + while j != 0 { + let cnt = hash.entry(j % 10).or_insert(0); + *cnt += 1; + j /= 10; + } + + for k in 1..=9 { + if !hash.contains_key(&k) || hash[&k] > 1 { + return false; + } + } + + !hash.contains_key(&0) + } +} diff --git a/solution/2700-2799/2731.Movement of Robots/Solution.cpp b/solution/2700-2799/2731.Movement of Robots/Solution.cpp index dc05a44d0cc92..619bb5055a1bc 100644 --- a/solution/2700-2799/2731.Movement of Robots/Solution.cpp +++ b/solution/2700-2799/2731.Movement of Robots/Solution.cpp @@ -1,19 +1,19 @@ -class Solution { -public: - int sumDistance(vector& nums, string s, int d) { - int n = nums.size(); - vector arr(n); - for (int i = 0; i < n; ++i) { - arr[i] = 1LL * nums[i] + (s[i] == 'L' ? -d : d); - } - sort(arr.begin(), arr.end()); - long long ans = 0; - long long sum = 0; - const int mod = 1e9 + 7; - for (int i = 0; i < n; ++i) { - ans = (ans + i * arr[i] - sum) % mod; - sum += arr[i]; - } - return ans; - } +class Solution { +public: + int sumDistance(vector& nums, string s, int d) { + int n = nums.size(); + vector arr(n); + for (int i = 0; i < n; ++i) { + arr[i] = 1LL * nums[i] + (s[i] == 'L' ? -d : d); + } + sort(arr.begin(), arr.end()); + long long ans = 0; + long long sum = 0; + const int mod = 1e9 + 7; + for (int i = 0; i < n; ++i) { + ans = (ans + i * arr[i] - sum) % mod; + sum += arr[i]; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2731.Movement of Robots/Solution.java b/solution/2700-2799/2731.Movement of Robots/Solution.java index b2071c2066a39..75e52862000cd 100644 --- a/solution/2700-2799/2731.Movement of Robots/Solution.java +++ b/solution/2700-2799/2731.Movement of Robots/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public int sumDistance(int[] nums, String s, int d) { - int n = nums.length; - long[] arr = new long[n]; - for (int i = 0; i < n; ++i) { - arr[i] = (long) nums[i] + (s.charAt(i) == 'L' ? -d : d); - } - Arrays.sort(arr); - long ans = 0, sum = 0; - final int mod = (int) 1e9 + 7; - for (int i = 0; i < n; ++i) { - ans = (ans + i * arr[i] - sum) % mod; - sum += arr[i]; - } - return (int) ans; - } +class Solution { + public int sumDistance(int[] nums, String s, int d) { + int n = nums.length; + long[] arr = new long[n]; + for (int i = 0; i < n; ++i) { + arr[i] = (long) nums[i] + (s.charAt(i) == 'L' ? -d : d); + } + Arrays.sort(arr); + long ans = 0, sum = 0; + final int mod = (int) 1e9 + 7; + for (int i = 0; i < n; ++i) { + ans = (ans + i * arr[i] - sum) % mod; + sum += arr[i]; + } + return (int) ans; + } } \ No newline at end of file diff --git a/solution/2700-2799/2731.Movement of Robots/Solution.py b/solution/2700-2799/2731.Movement of Robots/Solution.py index 1ffa8f49a323f..5d2363921ee89 100644 --- a/solution/2700-2799/2731.Movement of Robots/Solution.py +++ b/solution/2700-2799/2731.Movement of Robots/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def sumDistance(self, nums: List[int], s: str, d: int) -> int: - mod = 10**9 + 7 - for i, c in enumerate(s): - nums[i] += d if c == "R" else -d - nums.sort() - ans = s = 0 - for i, x in enumerate(nums): - ans += i * x - s - s += x - return ans % mod +class Solution: + def sumDistance(self, nums: List[int], s: str, d: int) -> int: + mod = 10**9 + 7 + for i, c in enumerate(s): + nums[i] += d if c == "R" else -d + nums.sort() + ans = s = 0 + for i, x in enumerate(nums): + ans += i * x - s + s += x + return ans % mod diff --git a/solution/2700-2799/2733.Neither Minimum nor Maximum/Solution.py b/solution/2700-2799/2733.Neither Minimum nor Maximum/Solution.py index a55c72804bb32..fc1dee8848f3b 100644 --- a/solution/2700-2799/2733.Neither Minimum nor Maximum/Solution.py +++ b/solution/2700-2799/2733.Neither Minimum nor Maximum/Solution.py @@ -1,7 +1,3 @@ class Solution: def findNonMinOrMax(self, nums: List[int]) -> int: - mi, mx = min(nums), max(nums) - for x in nums: - if x != mi and x != mx: - return x - return -1 + return -1 if len(nums) < 3 else sorted(nums)[1] diff --git a/solution/2700-2799/2733.Neither Minimum nor Maximum/Solution2.py b/solution/2700-2799/2733.Neither Minimum nor Maximum/Solution2.py new file mode 100644 index 0000000000000..a55c72804bb32 --- /dev/null +++ b/solution/2700-2799/2733.Neither Minimum nor Maximum/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def findNonMinOrMax(self, nums: List[int]) -> int: + mi, mx = min(nums), max(nums) + for x in nums: + if x != mi and x != mx: + return x + return -1 diff --git a/solution/2700-2799/2735.Collecting Chocolates/Solution.cpp b/solution/2700-2799/2735.Collecting Chocolates/Solution.cpp index 196f50602e492..e82db8596a122 100644 --- a/solution/2700-2799/2735.Collecting Chocolates/Solution.cpp +++ b/solution/2700-2799/2735.Collecting Chocolates/Solution.cpp @@ -1,22 +1,22 @@ -class Solution { -public: - long long minCost(vector& nums, int x) { - int n = nums.size(); - int f[n][n]; - for (int i = 0; i < n; ++i) { - f[i][0] = nums[i]; - for (int j = 1; j < n; ++j) { - f[i][j] = min(f[i][j - 1], nums[(i - j + n) % n]); - } - } - long long ans = 1LL << 60; - for (int j = 0; j < n; ++j) { - long long cost = 1LL * x * j; - for (int i = 0; i < n; ++i) { - cost += f[i][j]; - } - ans = min(ans, cost); - } - return ans; - } +class Solution { +public: + long long minCost(vector& nums, int x) { + int n = nums.size(); + int f[n][n]; + for (int i = 0; i < n; ++i) { + f[i][0] = nums[i]; + for (int j = 1; j < n; ++j) { + f[i][j] = min(f[i][j - 1], nums[(i - j + n) % n]); + } + } + long long ans = 1LL << 60; + for (int j = 0; j < n; ++j) { + long long cost = 1LL * x * j; + for (int i = 0; i < n; ++i) { + cost += f[i][j]; + } + ans = min(ans, cost); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2735.Collecting Chocolates/Solution.java b/solution/2700-2799/2735.Collecting Chocolates/Solution.java index 6e4afa4a1c552..64e1eac2480fe 100644 --- a/solution/2700-2799/2735.Collecting Chocolates/Solution.java +++ b/solution/2700-2799/2735.Collecting Chocolates/Solution.java @@ -1,21 +1,21 @@ -class Solution { - public long minCost(int[] nums, int x) { - int n = nums.length; - int[][] f = new int[n][n]; - for (int i = 0; i < n; ++i) { - f[i][0] = nums[i]; - for (int j = 1; j < n; ++j) { - f[i][j] = Math.min(f[i][j - 1], nums[(i - j + n) % n]); - } - } - long ans = 1L << 60; - for (int j = 0; j < n; ++j) { - long cost = 1L * x * j; - for (int i = 0; i < n; ++i) { - cost += f[i][j]; - } - ans = Math.min(ans, cost); - } - return ans; - } +class Solution { + public long minCost(int[] nums, int x) { + int n = nums.length; + int[][] f = new int[n][n]; + for (int i = 0; i < n; ++i) { + f[i][0] = nums[i]; + for (int j = 1; j < n; ++j) { + f[i][j] = Math.min(f[i][j - 1], nums[(i - j + n) % n]); + } + } + long ans = 1L << 60; + for (int j = 0; j < n; ++j) { + long cost = 1L * x * j; + for (int i = 0; i < n; ++i) { + cost += f[i][j]; + } + ans = Math.min(ans, cost); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2700-2799/2735.Collecting Chocolates/Solution.py b/solution/2700-2799/2735.Collecting Chocolates/Solution.py index c5b0c2ebf778b..478a8787da19a 100644 --- a/solution/2700-2799/2735.Collecting Chocolates/Solution.py +++ b/solution/2700-2799/2735.Collecting Chocolates/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def minCost(self, nums: List[int], x: int) -> int: - n = len(nums) - f = [[0] * n for _ in range(n)] - for i, v in enumerate(nums): - f[i][0] = v - for j in range(1, n): - f[i][j] = min(f[i][j - 1], nums[(i - j) % n]) - return min(sum(f[i][j] for i in range(n)) + x * j for j in range(n)) +class Solution: + def minCost(self, nums: List[int], x: int) -> int: + n = len(nums) + f = [[0] * n for _ in range(n)] + for i, v in enumerate(nums): + f[i][0] = v + for j in range(1, n): + f[i][j] = min(f[i][j - 1], nums[(i - j) % n]) + return min(sum(f[i][j] for i in range(n)) + x * j for j in range(n)) diff --git a/solution/2700-2799/2736.Maximum Sum Queries/Solution.cpp b/solution/2700-2799/2736.Maximum Sum Queries/Solution.cpp index 7fd89e2078af9..87fce92eb0c60 100644 --- a/solution/2700-2799/2736.Maximum Sum Queries/Solution.cpp +++ b/solution/2700-2799/2736.Maximum Sum Queries/Solution.cpp @@ -1,56 +1,56 @@ -class BinaryIndexedTree { -private: - int n; - vector c; - -public: - BinaryIndexedTree(int n) { - this->n = n; - c.resize(n + 1, -1); - } - - void update(int x, int v) { - while (x <= n) { - c[x] = max(c[x], v); - x += x & -x; - } - } - - int query(int x) { - int mx = -1; - while (x > 0) { - mx = max(mx, c[x]); - x -= x & -x; - } - return mx; - } -}; - -class Solution { -public: - vector maximumSumQueries(vector& nums1, vector& nums2, vector>& queries) { - vector> nums; - int n = nums1.size(), m = queries.size(); - for (int i = 0; i < n; ++i) { - nums.emplace_back(-nums1[i], nums2[i]); - } - sort(nums.begin(), nums.end()); - sort(nums2.begin(), nums2.end()); - vector idx(m); - iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) { return queries[j][0] < queries[i][0]; }); - vector ans(m); - int j = 0; - BinaryIndexedTree tree(n); - for (int i : idx) { - int x = queries[i][0], y = queries[i][1]; - for (; j < n && -nums[j].first >= x; ++j) { - int k = nums2.end() - lower_bound(nums2.begin(), nums2.end(), nums[j].second); - tree.update(k, -nums[j].first + nums[j].second); - } - int k = nums2.end() - lower_bound(nums2.begin(), nums2.end(), y); - ans[i] = tree.query(k); - } - return ans; - } +class BinaryIndexedTree { +private: + int n; + vector c; + +public: + BinaryIndexedTree(int n) { + this->n = n; + c.resize(n + 1, -1); + } + + void update(int x, int v) { + while (x <= n) { + c[x] = max(c[x], v); + x += x & -x; + } + } + + int query(int x) { + int mx = -1; + while (x > 0) { + mx = max(mx, c[x]); + x -= x & -x; + } + return mx; + } +}; + +class Solution { +public: + vector maximumSumQueries(vector& nums1, vector& nums2, vector>& queries) { + vector> nums; + int n = nums1.size(), m = queries.size(); + for (int i = 0; i < n; ++i) { + nums.emplace_back(-nums1[i], nums2[i]); + } + sort(nums.begin(), nums.end()); + sort(nums2.begin(), nums2.end()); + vector idx(m); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { return queries[j][0] < queries[i][0]; }); + vector ans(m); + int j = 0; + BinaryIndexedTree tree(n); + for (int i : idx) { + int x = queries[i][0], y = queries[i][1]; + for (; j < n && -nums[j].first >= x; ++j) { + int k = nums2.end() - lower_bound(nums2.begin(), nums2.end(), nums[j].second); + tree.update(k, -nums[j].first + nums[j].second); + } + int k = nums2.end() - lower_bound(nums2.begin(), nums2.end(), y); + ans[i] = tree.query(k); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2736.Maximum Sum Queries/Solution.py b/solution/2700-2799/2736.Maximum Sum Queries/Solution.py index 1199f6c62fc9b..29da113e45826 100644 --- a/solution/2700-2799/2736.Maximum Sum Queries/Solution.py +++ b/solution/2700-2799/2736.Maximum Sum Queries/Solution.py @@ -1,39 +1,39 @@ -class BinaryIndexedTree: - __slots__ = ["n", "c"] - - def __init__(self, n: int): - self.n = n - self.c = [-1] * (n + 1) - - def update(self, x: int, v: int): - while x <= self.n: - self.c[x] = max(self.c[x], v) - x += x & -x - - def query(self, x: int) -> int: - mx = -1 - while x: - mx = max(mx, self.c[x]) - x -= x & -x - return mx - - -class Solution: - def maximumSumQueries( - self, nums1: List[int], nums2: List[int], queries: List[List[int]] - ) -> List[int]: - nums = sorted(zip(nums1, nums2), key=lambda x: -x[0]) - nums2.sort() - n, m = len(nums1), len(queries) - ans = [-1] * m - j = 0 - tree = BinaryIndexedTree(n) - for i in sorted(range(m), key=lambda i: -queries[i][0]): - x, y = queries[i] - while j < n and nums[j][0] >= x: - k = n - bisect_left(nums2, nums[j][1]) - tree.update(k, nums[j][0] + nums[j][1]) - j += 1 - k = n - bisect_left(nums2, y) - ans[i] = tree.query(k) - return ans +class BinaryIndexedTree: + __slots__ = ["n", "c"] + + def __init__(self, n: int): + self.n = n + self.c = [-1] * (n + 1) + + def update(self, x: int, v: int): + while x <= self.n: + self.c[x] = max(self.c[x], v) + x += x & -x + + def query(self, x: int) -> int: + mx = -1 + while x: + mx = max(mx, self.c[x]) + x -= x & -x + return mx + + +class Solution: + def maximumSumQueries( + self, nums1: List[int], nums2: List[int], queries: List[List[int]] + ) -> List[int]: + nums = sorted(zip(nums1, nums2), key=lambda x: -x[0]) + nums2.sort() + n, m = len(nums1), len(queries) + ans = [-1] * m + j = 0 + tree = BinaryIndexedTree(n) + for i in sorted(range(m), key=lambda i: -queries[i][0]): + x, y = queries[i] + while j < n and nums[j][0] >= x: + k = n - bisect_left(nums2, nums[j][1]) + tree.update(k, nums[j][0] + nums[j][1]) + j += 1 + k = n - bisect_left(nums2, y) + ans[i] = tree.query(k) + return ans diff --git a/solution/2700-2799/2736.Maximum Sum Queries/Solution2.java b/solution/2700-2799/2736.Maximum Sum Queries/Solution2.java new file mode 100644 index 0000000000000..c95f2d9b4c925 --- /dev/null +++ b/solution/2700-2799/2736.Maximum Sum Queries/Solution2.java @@ -0,0 +1,42 @@ +class Solution { + public int[] maximumSumQueries(int[] nums1, int[] nums2, int[][] q) { + int n = nums1.length, m = q.length; + int[][] a = new int[n][2]; + for (int i = 0; i < n; i++) { + a[i][0] = nums1[i]; + a[i][1] = nums2[i]; + } + int[][] b = new int[m][3]; + for (int i = 0; i < m; i++) { + b[i][0] = q[i][0]; + b[i][1] = q[i][1]; + b[i][2] = i; + } + Arrays.sort(a, (o1, o2) -> o1[0] - o2[0]); + Arrays.sort(b, (o1, o2) -> o1[0] - o2[0]); + TreeMap map = new TreeMap<>(); + int[] res = new int[m]; + int max = -1; + for (int i = m - 1, j = n - 1; i >= 0; i--) { + int x = b[i][0], y = b[i][1], idx = b[i][2]; + while (j >= 0 && a[j][0] >= x) { + if (max < a[j][1]) { + max = a[j][1]; + Integer key = map.floorKey(a[j][1]); + while (key != null && map.get(key) <= a[j][0] + a[j][1]) { + map.remove(key); + key = map.floorKey(key); + } + map.put(max, a[j][0] + a[j][1]); + } + j--; + } + Integer key = map.ceilingKey(y); + if (key == null) + res[idx] = -1; + else + res[idx] = map.get(key); + } + return res; + } +} \ No newline at end of file diff --git a/solution/2700-2799/2739.Total Distance Traveled/Solution.cpp b/solution/2700-2799/2739.Total Distance Traveled/Solution.cpp index 74cd70f2005a3..914a758d03a95 100644 --- a/solution/2700-2799/2739.Total Distance Traveled/Solution.cpp +++ b/solution/2700-2799/2739.Total Distance Traveled/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - int distanceTraveled(int mainTank, int additionalTank) { - int ans = 0, cur = 0; - while (mainTank > 0) { - cur++; - ans += 10; - mainTank--; - if (cur % 5 == 0 && additionalTank > 0) { - additionalTank--; - mainTank++; - } - } - return ans; - } +class Solution { +public: + int distanceTraveled(int mainTank, int additionalTank) { + int ans = 0, cur = 0; + while (mainTank > 0) { + cur++; + ans += 10; + mainTank--; + if (cur % 5 == 0 && additionalTank > 0) { + additionalTank--; + mainTank++; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2739.Total Distance Traveled/Solution.java b/solution/2700-2799/2739.Total Distance Traveled/Solution.java index 788864fc322c2..b6c9401016c41 100644 --- a/solution/2700-2799/2739.Total Distance Traveled/Solution.java +++ b/solution/2700-2799/2739.Total Distance Traveled/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public int distanceTraveled(int mainTank, int additionalTank) { - int ans = 0, cur = 0; - while (mainTank > 0) { - cur++; - ans += 10; - mainTank--; - if (cur % 5 == 0 && additionalTank > 0) { - additionalTank--; - mainTank++; - } - } - return ans; - } +class Solution { + public int distanceTraveled(int mainTank, int additionalTank) { + int ans = 0, cur = 0; + while (mainTank > 0) { + cur++; + ans += 10; + mainTank--; + if (cur % 5 == 0 && additionalTank > 0) { + additionalTank--; + mainTank++; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2700-2799/2739.Total Distance Traveled/Solution.py b/solution/2700-2799/2739.Total Distance Traveled/Solution.py index fa3a845cd60da..2068588a04af9 100644 --- a/solution/2700-2799/2739.Total Distance Traveled/Solution.py +++ b/solution/2700-2799/2739.Total Distance Traveled/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def distanceTraveled(self, mainTank: int, additionalTank: int) -> int: - ans = cur = 0 - while mainTank: - cur += 1 - ans += 10 - mainTank -= 1 - if cur % 5 == 0 and additionalTank: - additionalTank -= 1 - mainTank += 1 - return ans +class Solution: + def distanceTraveled(self, mainTank: int, additionalTank: int) -> int: + ans = cur = 0 + while mainTank: + cur += 1 + ans += 10 + mainTank -= 1 + if cur % 5 == 0 and additionalTank: + additionalTank -= 1 + mainTank += 1 + return ans diff --git a/solution/2700-2799/2740.Find the Value of the Partition/Solution.cpp b/solution/2700-2799/2740.Find the Value of the Partition/Solution.cpp index ed6965afca193..fe6b30488fc54 100644 --- a/solution/2700-2799/2740.Find the Value of the Partition/Solution.cpp +++ b/solution/2700-2799/2740.Find the Value of the Partition/Solution.cpp @@ -1,11 +1,11 @@ -class Solution { -public: - int findValueOfPartition(vector& nums) { - sort(nums.begin(), nums.end()); - int ans = 1 << 30; - for (int i = 1; i < nums.size(); ++i) { - ans = min(ans, nums[i] - nums[i - 1]); - } - return ans; - } +class Solution { +public: + int findValueOfPartition(vector& nums) { + sort(nums.begin(), nums.end()); + int ans = 1 << 30; + for (int i = 1; i < nums.size(); ++i) { + ans = min(ans, nums[i] - nums[i - 1]); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2740.Find the Value of the Partition/Solution.java b/solution/2700-2799/2740.Find the Value of the Partition/Solution.java index 9602dd097f5f8..be68f9b8fca26 100644 --- a/solution/2700-2799/2740.Find the Value of the Partition/Solution.java +++ b/solution/2700-2799/2740.Find the Value of the Partition/Solution.java @@ -1,10 +1,10 @@ -class Solution { - public int findValueOfPartition(int[] nums) { - Arrays.sort(nums); - int ans = 1 << 30; - for (int i = 1; i < nums.length; ++i) { - ans = Math.min(ans, nums[i] - nums[i - 1]); - } - return ans; - } +class Solution { + public int findValueOfPartition(int[] nums) { + Arrays.sort(nums); + int ans = 1 << 30; + for (int i = 1; i < nums.length; ++i) { + ans = Math.min(ans, nums[i] - nums[i - 1]); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2700-2799/2740.Find the Value of the Partition/Solution.py b/solution/2700-2799/2740.Find the Value of the Partition/Solution.py index a3454de6de0b6..2c696355f1f7a 100644 --- a/solution/2700-2799/2740.Find the Value of the Partition/Solution.py +++ b/solution/2700-2799/2740.Find the Value of the Partition/Solution.py @@ -1,4 +1,4 @@ -class Solution: - def findValueOfPartition(self, nums: List[int]) -> int: - nums.sort() - return min(b - a for a, b in pairwise(nums)) +class Solution: + def findValueOfPartition(self, nums: List[int]) -> int: + nums.sort() + return min(b - a for a, b in pairwise(nums)) diff --git a/solution/2700-2799/2741.Special Permutations/Solution.cpp b/solution/2700-2799/2741.Special Permutations/Solution.cpp index cfa81fd95f09b..6656bc6f82b1e 100644 --- a/solution/2700-2799/2741.Special Permutations/Solution.cpp +++ b/solution/2700-2799/2741.Special Permutations/Solution.cpp @@ -1,31 +1,31 @@ -class Solution { -public: - int specialPerm(vector& nums) { - const int mod = 1e9 + 7; - int n = nums.size(); - int m = 1 << n; - int f[m][n]; - memset(f, 0, sizeof(f)); - for (int i = 1; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if ((i >> j & 1) == 1) { - int ii = i ^ (1 << j); - if (ii == 0) { - f[i][j] = 1; - continue; - } - for (int k = 0; k < n; ++k) { - if (nums[j] % nums[k] == 0 || nums[k] % nums[j] == 0) { - f[i][j] = (f[i][j] + f[ii][k]) % mod; - } - } - } - } - } - int ans = 0; - for (int x : f[m - 1]) { - ans = (ans + x) % mod; - } - return ans; - } +class Solution { +public: + int specialPerm(vector& nums) { + const int mod = 1e9 + 7; + int n = nums.size(); + int m = 1 << n; + int f[m][n]; + memset(f, 0, sizeof(f)); + for (int i = 1; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if ((i >> j & 1) == 1) { + int ii = i ^ (1 << j); + if (ii == 0) { + f[i][j] = 1; + continue; + } + for (int k = 0; k < n; ++k) { + if (nums[j] % nums[k] == 0 || nums[k] % nums[j] == 0) { + f[i][j] = (f[i][j] + f[ii][k]) % mod; + } + } + } + } + } + int ans = 0; + for (int x : f[m - 1]) { + ans = (ans + x) % mod; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2741.Special Permutations/Solution.java b/solution/2700-2799/2741.Special Permutations/Solution.java index ae3462d48ec0f..82c3ca45bc4e2 100644 --- a/solution/2700-2799/2741.Special Permutations/Solution.java +++ b/solution/2700-2799/2741.Special Permutations/Solution.java @@ -1,29 +1,29 @@ -class Solution { - public int specialPerm(int[] nums) { - final int mod = (int) 1e9 + 7; - int n = nums.length; - int m = 1 << n; - int[][] f = new int[m][n]; - for (int i = 1; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if ((i >> j & 1) == 1) { - int ii = i ^ (1 << j); - if (ii == 0) { - f[i][j] = 1; - continue; - } - for (int k = 0; k < n; ++k) { - if (nums[j] % nums[k] == 0 || nums[k] % nums[j] == 0) { - f[i][j] = (f[i][j] + f[ii][k]) % mod; - } - } - } - } - } - int ans = 0; - for (int x : f[m - 1]) { - ans = (ans + x) % mod; - } - return ans; - } +class Solution { + public int specialPerm(int[] nums) { + final int mod = (int) 1e9 + 7; + int n = nums.length; + int m = 1 << n; + int[][] f = new int[m][n]; + for (int i = 1; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if ((i >> j & 1) == 1) { + int ii = i ^ (1 << j); + if (ii == 0) { + f[i][j] = 1; + continue; + } + for (int k = 0; k < n; ++k) { + if (nums[j] % nums[k] == 0 || nums[k] % nums[j] == 0) { + f[i][j] = (f[i][j] + f[ii][k]) % mod; + } + } + } + } + } + int ans = 0; + for (int x : f[m - 1]) { + ans = (ans + x) % mod; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2700-2799/2741.Special Permutations/Solution.py b/solution/2700-2799/2741.Special Permutations/Solution.py index 4f9cf815d7500..2cf18046d9efd 100644 --- a/solution/2700-2799/2741.Special Permutations/Solution.py +++ b/solution/2700-2799/2741.Special Permutations/Solution.py @@ -1,17 +1,17 @@ -class Solution: - def specialPerm(self, nums: List[int]) -> int: - mod = 10**9 + 7 - n = len(nums) - m = 1 << n - f = [[0] * n for _ in range(m)] - for i in range(1, m): - for j, x in enumerate(nums): - if i >> j & 1: - ii = i ^ (1 << j) - if ii == 0: - f[i][j] = 1 - continue - for k, y in enumerate(nums): - if x % y == 0 or y % x == 0: - f[i][j] = (f[i][j] + f[ii][k]) % mod - return sum(f[-1]) % mod +class Solution: + def specialPerm(self, nums: List[int]) -> int: + mod = 10**9 + 7 + n = len(nums) + m = 1 << n + f = [[0] * n for _ in range(m)] + for i in range(1, m): + for j, x in enumerate(nums): + if i >> j & 1: + ii = i ^ (1 << j) + if ii == 0: + f[i][j] = 1 + continue + for k, y in enumerate(nums): + if x % y == 0 or y % x == 0: + f[i][j] = (f[i][j] + f[ii][k]) % mod + return sum(f[-1]) % mod diff --git a/solution/2700-2799/2742.Painting the Walls/Solution.cpp b/solution/2700-2799/2742.Painting the Walls/Solution.cpp index 6508efe3058ce..fd87e91577ba8 100644 --- a/solution/2700-2799/2742.Painting the Walls/Solution.cpp +++ b/solution/2700-2799/2742.Painting the Walls/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - int paintWalls(vector& cost, vector& time) { - int n = cost.size(); - int f[n][n << 1 | 1]; - memset(f, -1, sizeof(f)); - function dfs = [&](int i, int j) -> int { - if (n - i <= j - n) { - return 0; - } - if (i >= n) { - return 1 << 30; - } - if (f[i][j] == -1) { - f[i][j] = min(dfs(i + 1, j + time[i]) + cost[i], dfs(i + 1, j - 1)); - } - return f[i][j]; - }; - return dfs(0, n); - } +class Solution { +public: + int paintWalls(vector& cost, vector& time) { + int n = cost.size(); + int f[n][n << 1 | 1]; + memset(f, -1, sizeof(f)); + function dfs = [&](int i, int j) -> int { + if (n - i <= j - n) { + return 0; + } + if (i >= n) { + return 1 << 30; + } + if (f[i][j] == -1) { + f[i][j] = min(dfs(i + 1, j + time[i]) + cost[i], dfs(i + 1, j - 1)); + } + return f[i][j]; + }; + return dfs(0, n); + } }; \ No newline at end of file diff --git a/solution/2700-2799/2742.Painting the Walls/Solution.java b/solution/2700-2799/2742.Painting the Walls/Solution.java index 7e564d3999bd4..be1e377154c93 100644 --- a/solution/2700-2799/2742.Painting the Walls/Solution.java +++ b/solution/2700-2799/2742.Painting the Walls/Solution.java @@ -1,27 +1,27 @@ -class Solution { - private int n; - private int[] cost; - private int[] time; - private Integer[][] f; - - public int paintWalls(int[] cost, int[] time) { - n = cost.length; - this.cost = cost; - this.time = time; - f = new Integer[n][n << 1 | 1]; - return dfs(0, n); - } - - private int dfs(int i, int j) { - if (n - i <= j - n) { - return 0; - } - if (i >= n) { - return 1 << 30; - } - if (f[i][j] == null) { - f[i][j] = Math.min(dfs(i + 1, j + time[i]) + cost[i], dfs(i + 1, j - 1)); - } - return f[i][j]; - } +class Solution { + private int n; + private int[] cost; + private int[] time; + private Integer[][] f; + + public int paintWalls(int[] cost, int[] time) { + n = cost.length; + this.cost = cost; + this.time = time; + f = new Integer[n][n << 1 | 1]; + return dfs(0, n); + } + + private int dfs(int i, int j) { + if (n - i <= j - n) { + return 0; + } + if (i >= n) { + return 1 << 30; + } + if (f[i][j] == null) { + f[i][j] = Math.min(dfs(i + 1, j + time[i]) + cost[i], dfs(i + 1, j - 1)); + } + return f[i][j]; + } } \ No newline at end of file diff --git a/solution/2700-2799/2742.Painting the Walls/Solution.py b/solution/2700-2799/2742.Painting the Walls/Solution.py index 1954459c760c6..8be363dc18889 100644 --- a/solution/2700-2799/2742.Painting the Walls/Solution.py +++ b/solution/2700-2799/2742.Painting the Walls/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def paintWalls(self, cost: List[int], time: List[int]) -> int: - @cache - def dfs(i: int, j: int) -> int: - if n - i <= j: - return 0 - if i >= n: - return inf - return min(dfs(i + 1, j + time[i]) + cost[i], dfs(i + 1, j - 1)) - - n = len(cost) - return dfs(0, 0) +class Solution: + def paintWalls(self, cost: List[int], time: List[int]) -> int: + @cache + def dfs(i: int, j: int) -> int: + if n - i <= j: + return 0 + if i >= n: + return inf + return min(dfs(i + 1, j + time[i]) + cost[i], dfs(i + 1, j - 1)) + + n = len(cost) + return dfs(0, 0) diff --git a/solution/2700-2799/2744.Find Maximum Number of String Pairs/Solution.cpp b/solution/2700-2799/2744.Find Maximum Number of String Pairs/Solution.cpp index be2dd78826b49..22cd57180835b 100644 --- a/solution/2700-2799/2744.Find Maximum Number of String Pairs/Solution.cpp +++ b/solution/2700-2799/2744.Find Maximum Number of String Pairs/Solution.cpp @@ -1,13 +1,13 @@ -class Solution { -public: - int maximumNumberOfStringPairs(vector& words) { - unordered_map cnt; - int ans = 0; - for (auto& w : words) { - ans += cnt[w]; - reverse(w.begin(), w.end()); - cnt[w]++; - } - return ans; - } +class Solution { +public: + int maximumNumberOfStringPairs(vector& words) { + unordered_map cnt; + int ans = 0; + for (auto& w : words) { + ans += cnt[w]; + reverse(w.begin(), w.end()); + cnt[w]++; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2744.Find Maximum Number of String Pairs/Solution.java b/solution/2700-2799/2744.Find Maximum Number of String Pairs/Solution.java index ce3c0e9374e81..5a60bdaca182b 100644 --- a/solution/2700-2799/2744.Find Maximum Number of String Pairs/Solution.java +++ b/solution/2700-2799/2744.Find Maximum Number of String Pairs/Solution.java @@ -1,11 +1,11 @@ -class Solution { - public int maximumNumberOfStringPairs(String[] words) { - Map cnt = new HashMap<>(words.length); - int ans = 0; - for (String w : words) { - ans += cnt.getOrDefault(w, 0); - cnt.merge(new StringBuilder(w).reverse().toString(), 1, Integer::sum); - } - return ans; - } +class Solution { + public int maximumNumberOfStringPairs(String[] words) { + Map cnt = new HashMap<>(words.length); + int ans = 0; + for (String w : words) { + ans += cnt.getOrDefault(w, 0); + cnt.merge(new StringBuilder(w).reverse().toString(), 1, Integer::sum); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2700-2799/2744.Find Maximum Number of String Pairs/Solution.py b/solution/2700-2799/2744.Find Maximum Number of String Pairs/Solution.py index f9d268ff7b08c..b51d119db0dd0 100644 --- a/solution/2700-2799/2744.Find Maximum Number of String Pairs/Solution.py +++ b/solution/2700-2799/2744.Find Maximum Number of String Pairs/Solution.py @@ -1,8 +1,8 @@ -class Solution: - def maximumNumberOfStringPairs(self, words: List[str]) -> int: - cnt = Counter() - ans = 0 - for w in words: - ans += cnt[w] - cnt[w[::-1]] += 1 - return ans +class Solution: + def maximumNumberOfStringPairs(self, words: List[str]) -> int: + cnt = Counter() + ans = 0 + for w in words: + ans += cnt[w] + cnt[w[::-1]] += 1 + return ans diff --git a/solution/2700-2799/2745.Construct the Longest New String/Solution.cpp b/solution/2700-2799/2745.Construct the Longest New String/Solution.cpp index b9ccbad4f9fd2..f2b2dedc717ee 100644 --- a/solution/2700-2799/2745.Construct the Longest New String/Solution.cpp +++ b/solution/2700-2799/2745.Construct the Longest New String/Solution.cpp @@ -1,12 +1,12 @@ -class Solution { -public: - int longestString(int x, int y, int z) { - if (x < y) { - return (x * 2 + z + 1) * 2; - } - if (x > y) { - return (y * 2 + z + 1) * 2; - } - return (x + y + z) * 2; - } +class Solution { +public: + int longestString(int x, int y, int z) { + if (x < y) { + return (x * 2 + z + 1) * 2; + } + if (x > y) { + return (y * 2 + z + 1) * 2; + } + return (x + y + z) * 2; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2745.Construct the Longest New String/Solution.java b/solution/2700-2799/2745.Construct the Longest New String/Solution.java index d22462501e0ea..6691051985eea 100644 --- a/solution/2700-2799/2745.Construct the Longest New String/Solution.java +++ b/solution/2700-2799/2745.Construct the Longest New String/Solution.java @@ -1,11 +1,11 @@ -class Solution { - public int longestString(int x, int y, int z) { - if (x < y) { - return (x * 2 + z + 1) * 2; - } - if (x > y) { - return (y * 2 + z + 1) * 2; - } - return (x + y + z) * 2; - } +class Solution { + public int longestString(int x, int y, int z) { + if (x < y) { + return (x * 2 + z + 1) * 2; + } + if (x > y) { + return (y * 2 + z + 1) * 2; + } + return (x + y + z) * 2; + } } \ No newline at end of file diff --git a/solution/2700-2799/2745.Construct the Longest New String/Solution.py b/solution/2700-2799/2745.Construct the Longest New String/Solution.py index 72a4b57c038be..705f812960eae 100644 --- a/solution/2700-2799/2745.Construct the Longest New String/Solution.py +++ b/solution/2700-2799/2745.Construct the Longest New String/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def longestString(self, x: int, y: int, z: int) -> int: - if x < y: - return (x * 2 + z + 1) * 2 - if x > y: - return (y * 2 + z + 1) * 2 - return (x + y + z) * 2 +class Solution: + def longestString(self, x: int, y: int, z: int) -> int: + if x < y: + return (x * 2 + z + 1) * 2 + if x > y: + return (y * 2 + z + 1) * 2 + return (x + y + z) * 2 diff --git a/solution/2700-2799/2746.Decremental String Concatenation/Solution.cpp b/solution/2700-2799/2746.Decremental String Concatenation/Solution.cpp index 5b8f48164c256..c2df39c6b2cac 100644 --- a/solution/2700-2799/2746.Decremental String Concatenation/Solution.cpp +++ b/solution/2700-2799/2746.Decremental String Concatenation/Solution.cpp @@ -1,22 +1,22 @@ -class Solution { -public: - int minimizeConcatenatedLength(vector& words) { - int n = words.size(); - int f[n][26][26]; - memset(f, 0, sizeof(f)); - function dfs = [&](int i, int a, int b) { - if (i >= n) { - return 0; - } - if (f[i][a][b]) { - return f[i][a][b]; - } - auto s = words[i]; - int m = s.size(); - int x = dfs(i + 1, a, s[m - 1] - 'a') - (s[0] - 'a' == b); - int y = dfs(i + 1, s[0] - 'a', b) - (s[m - 1] - 'a' == a); - return f[i][a][b] = m + min(x, y); - }; - return words[0].size() + dfs(1, words[0].front() - 'a', words[0].back() - 'a'); - } +class Solution { +public: + int minimizeConcatenatedLength(vector& words) { + int n = words.size(); + int f[n][26][26]; + memset(f, 0, sizeof(f)); + function dfs = [&](int i, int a, int b) { + if (i >= n) { + return 0; + } + if (f[i][a][b]) { + return f[i][a][b]; + } + auto s = words[i]; + int m = s.size(); + int x = dfs(i + 1, a, s[m - 1] - 'a') - (s[0] - 'a' == b); + int y = dfs(i + 1, s[0] - 'a', b) - (s[m - 1] - 'a' == a); + return f[i][a][b] = m + min(x, y); + }; + return words[0].size() + dfs(1, words[0].front() - 'a', words[0].back() - 'a'); + } }; \ No newline at end of file diff --git a/solution/2700-2799/2746.Decremental String Concatenation/Solution.java b/solution/2700-2799/2746.Decremental String Concatenation/Solution.java index 52f5a6bff6098..08888040470be 100644 --- a/solution/2700-2799/2746.Decremental String Concatenation/Solution.java +++ b/solution/2700-2799/2746.Decremental String Concatenation/Solution.java @@ -1,27 +1,27 @@ -class Solution { - private Integer[][][] f; - private String[] words; - private int n; - - public int minimizeConcatenatedLength(String[] words) { - n = words.length; - this.words = words; - f = new Integer[n][26][26]; - return words[0].length() - + dfs(1, words[0].charAt(0) - 'a', words[0].charAt(words[0].length() - 1) - 'a'); - } - - private int dfs(int i, int a, int b) { - if (i >= n) { - return 0; - } - if (f[i][a][b] != null) { - return f[i][a][b]; - } - String s = words[i]; - int m = s.length(); - int x = dfs(i + 1, a, s.charAt(m - 1) - 'a') - (s.charAt(0) - 'a' == b ? 1 : 0); - int y = dfs(i + 1, s.charAt(0) - 'a', b) - (s.charAt(m - 1) - 'a' == a ? 1 : 0); - return f[i][a][b] = m + Math.min(x, y); - } +class Solution { + private Integer[][][] f; + private String[] words; + private int n; + + public int minimizeConcatenatedLength(String[] words) { + n = words.length; + this.words = words; + f = new Integer[n][26][26]; + return words[0].length() + + dfs(1, words[0].charAt(0) - 'a', words[0].charAt(words[0].length() - 1) - 'a'); + } + + private int dfs(int i, int a, int b) { + if (i >= n) { + return 0; + } + if (f[i][a][b] != null) { + return f[i][a][b]; + } + String s = words[i]; + int m = s.length(); + int x = dfs(i + 1, a, s.charAt(m - 1) - 'a') - (s.charAt(0) - 'a' == b ? 1 : 0); + int y = dfs(i + 1, s.charAt(0) - 'a', b) - (s.charAt(m - 1) - 'a' == a ? 1 : 0); + return f[i][a][b] = m + Math.min(x, y); + } } \ No newline at end of file diff --git a/solution/2700-2799/2746.Decremental String Concatenation/Solution.py b/solution/2700-2799/2746.Decremental String Concatenation/Solution.py index 781938ad2b309..a443f62764f3f 100644 --- a/solution/2700-2799/2746.Decremental String Concatenation/Solution.py +++ b/solution/2700-2799/2746.Decremental String Concatenation/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def minimizeConcatenatedLength(self, words: List[str]) -> int: - @cache - def dfs(i: int, a: str, b: str) -> int: - if i >= len(words): - return 0 - s = words[i] - x = dfs(i + 1, a, s[-1]) - int(s[0] == b) - y = dfs(i + 1, s[0], b) - int(s[-1] == a) - return len(s) + min(x, y) - - return len(words[0]) + dfs(1, words[0][0], words[0][-1]) +class Solution: + def minimizeConcatenatedLength(self, words: List[str]) -> int: + @cache + def dfs(i: int, a: str, b: str) -> int: + if i >= len(words): + return 0 + s = words[i] + x = dfs(i + 1, a, s[-1]) - int(s[0] == b) + y = dfs(i + 1, s[0], b) - int(s[-1] == a) + return len(s) + min(x, y) + + return len(words[0]) + dfs(1, words[0][0], words[0][-1]) diff --git a/solution/2700-2799/2747.Count Zero Request Servers/Solution.cpp b/solution/2700-2799/2747.Count Zero Request Servers/Solution.cpp index a3ae297e6d836..11573a33a446b 100644 --- a/solution/2700-2799/2747.Count Zero Request Servers/Solution.cpp +++ b/solution/2700-2799/2747.Count Zero Request Servers/Solution.cpp @@ -1,31 +1,31 @@ -class Solution { -public: - vector countServers(int n, vector>& logs, int x, vector& queries) { - sort(logs.begin(), logs.end(), [](const auto& a, const auto& b) { - return a[1] < b[1]; - }); - int m = queries.size(); - vector> qs(m); - for (int i = 0; i < m; ++i) { - qs[i] = {queries[i], i}; - } - sort(qs.begin(), qs.end()); - unordered_map cnt; - vector ans(m); - int j = 0, k = 0; - for (auto& [r, i] : qs) { - int l = r - x; - while (k < logs.size() && logs[k][1] <= r) { - ++cnt[logs[k++][0]]; - } - while (j < logs.size() && logs[j][1] < l) { - if (--cnt[logs[j][0]] == 0) { - cnt.erase(logs[j][0]); - } - ++j; - } - ans[i] = n - cnt.size(); - } - return ans; - } +class Solution { +public: + vector countServers(int n, vector>& logs, int x, vector& queries) { + sort(logs.begin(), logs.end(), [](const auto& a, const auto& b) { + return a[1] < b[1]; + }); + int m = queries.size(); + vector> qs(m); + for (int i = 0; i < m; ++i) { + qs[i] = {queries[i], i}; + } + sort(qs.begin(), qs.end()); + unordered_map cnt; + vector ans(m); + int j = 0, k = 0; + for (auto& [r, i] : qs) { + int l = r - x; + while (k < logs.size() && logs[k][1] <= r) { + ++cnt[logs[k++][0]]; + } + while (j < logs.size() && logs[j][1] < l) { + if (--cnt[logs[j][0]] == 0) { + cnt.erase(logs[j][0]); + } + ++j; + } + ans[i] = n - cnt.size(); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2747.Count Zero Request Servers/Solution.java b/solution/2700-2799/2747.Count Zero Request Servers/Solution.java index ed5a7a4633035..e43555ab504ec 100644 --- a/solution/2700-2799/2747.Count Zero Request Servers/Solution.java +++ b/solution/2700-2799/2747.Count Zero Request Servers/Solution.java @@ -1,29 +1,29 @@ -class Solution { - public int[] countServers(int n, int[][] logs, int x, int[] queries) { - Arrays.sort(logs, (a, b) -> a[1] - b[1]); - int m = queries.length; - int[][] qs = new int[m][0]; - for (int i = 0; i < m; ++i) { - qs[i] = new int[] {queries[i], i}; - } - Arrays.sort(qs, (a, b) -> a[0] - b[0]); - Map cnt = new HashMap<>(); - int[] ans = new int[m]; - int j = 0, k = 0; - for (var q : qs) { - int r = q[0], i = q[1]; - int l = r - x; - while (k < logs.length && logs[k][1] <= r) { - cnt.merge(logs[k++][0], 1, Integer::sum); - } - while (j < logs.length && logs[j][1] < l) { - if (cnt.merge(logs[j][0], -1, Integer::sum) == 0) { - cnt.remove(logs[j][0]); - } - j++; - } - ans[i] = n - cnt.size(); - } - return ans; - } +class Solution { + public int[] countServers(int n, int[][] logs, int x, int[] queries) { + Arrays.sort(logs, (a, b) -> a[1] - b[1]); + int m = queries.length; + int[][] qs = new int[m][0]; + for (int i = 0; i < m; ++i) { + qs[i] = new int[] {queries[i], i}; + } + Arrays.sort(qs, (a, b) -> a[0] - b[0]); + Map cnt = new HashMap<>(); + int[] ans = new int[m]; + int j = 0, k = 0; + for (var q : qs) { + int r = q[0], i = q[1]; + int l = r - x; + while (k < logs.length && logs[k][1] <= r) { + cnt.merge(logs[k++][0], 1, Integer::sum); + } + while (j < logs.length && logs[j][1] < l) { + if (cnt.merge(logs[j][0], -1, Integer::sum) == 0) { + cnt.remove(logs[j][0]); + } + j++; + } + ans[i] = n - cnt.size(); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2700-2799/2747.Count Zero Request Servers/Solution.py b/solution/2700-2799/2747.Count Zero Request Servers/Solution.py index 035b89655fad4..4aa3b78547b87 100644 --- a/solution/2700-2799/2747.Count Zero Request Servers/Solution.py +++ b/solution/2700-2799/2747.Count Zero Request Servers/Solution.py @@ -1,20 +1,20 @@ -class Solution: - def countServers( - self, n: int, logs: List[List[int]], x: int, queries: List[int] - ) -> List[int]: - cnt = Counter() - logs.sort(key=lambda x: x[1]) - ans = [0] * len(queries) - j = k = 0 - for r, i in sorted(zip(queries, count())): - l = r - x - while k < len(logs) and logs[k][1] <= r: - cnt[logs[k][0]] += 1 - k += 1 - while j < len(logs) and logs[j][1] < l: - cnt[logs[j][0]] -= 1 - if cnt[logs[j][0]] == 0: - cnt.pop(logs[j][0]) - j += 1 - ans[i] = n - len(cnt) - return ans +class Solution: + def countServers( + self, n: int, logs: List[List[int]], x: int, queries: List[int] + ) -> List[int]: + cnt = Counter() + logs.sort(key=lambda x: x[1]) + ans = [0] * len(queries) + j = k = 0 + for r, i in sorted(zip(queries, count())): + l = r - x + while k < len(logs) and logs[k][1] <= r: + cnt[logs[k][0]] += 1 + k += 1 + while j < len(logs) and logs[j][1] < l: + cnt[logs[j][0]] -= 1 + if cnt[logs[j][0]] == 0: + cnt.pop(logs[j][0]) + j += 1 + ans[i] = n - len(cnt) + return ans diff --git a/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/Solution.cpp b/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/Solution.cpp index 514ace9fd93cb..10aae1da05f0c 100644 --- a/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/Solution.cpp +++ b/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - int makeTheIntegerZero(int num1, int num2) { - using ll = long long; - for (ll k = 1;; ++k) { - ll x = num1 - k * num2; - if (x < 0) { - break; - } - if (__builtin_popcountll(x) <= k && k <= x) { - return k; - } - } - return -1; - } +class Solution { +public: + int makeTheIntegerZero(int num1, int num2) { + using ll = long long; + for (ll k = 1;; ++k) { + ll x = num1 - k * num2; + if (x < 0) { + break; + } + if (__builtin_popcountll(x) <= k && k <= x) { + return k; + } + } + return -1; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/Solution.java b/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/Solution.java index 09461785ecc94..17c6a6db8f1fb 100644 --- a/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/Solution.java +++ b/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/Solution.java @@ -1,14 +1,14 @@ -class Solution { - public int makeTheIntegerZero(int num1, int num2) { - for (long k = 1;; ++k) { - long x = num1 - k * num2; - if (x < 0) { - break; - } - if (Long.bitCount(x) <= k && k <= x) { - return (int) k; - } - } - return -1; - } +class Solution { + public int makeTheIntegerZero(int num1, int num2) { + for (long k = 1;; ++k) { + long x = num1 - k * num2; + if (x < 0) { + break; + } + if (Long.bitCount(x) <= k && k <= x) { + return (int) k; + } + } + return -1; + } } \ No newline at end of file diff --git a/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/Solution.py b/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/Solution.py index 25a8844fa46b8..00eb77e8bd951 100644 --- a/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/Solution.py +++ b/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def makeTheIntegerZero(self, num1: int, num2: int) -> int: - for k in count(1): - x = num1 - k * num2 - if x < 0: - break - if x.bit_count() <= k <= x: - return k - return -1 +class Solution: + def makeTheIntegerZero(self, num1: int, num2: int) -> int: + for k in count(1): + x = num1 - k * num2 + if x < 0: + break + if x.bit_count() <= k <= x: + return k + return -1 diff --git a/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/Solution.cpp b/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/Solution.cpp index 274709a64448b..ed0206bf377d3 100644 --- a/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/Solution.cpp +++ b/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/Solution.cpp @@ -1,17 +1,17 @@ -class Solution { -public: - int numberOfGoodSubarraySplits(vector& nums) { - const int mod = 1e9 + 7; - int ans = 1, j = -1; - for (int i = 0; i < nums.size(); ++i) { - if (nums[i] == 0) { - continue; - } - if (j > -1) { - ans = 1LL * ans * (i - j) % mod; - } - j = i; - } - return j == -1 ? 0 : ans; - } +class Solution { +public: + int numberOfGoodSubarraySplits(vector& nums) { + const int mod = 1e9 + 7; + int ans = 1, j = -1; + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] == 0) { + continue; + } + if (j > -1) { + ans = 1LL * ans * (i - j) % mod; + } + j = i; + } + return j == -1 ? 0 : ans; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/Solution.cs b/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/Solution.cs index b616a24292772..b9d645b081536 100644 --- a/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/Solution.cs +++ b/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/Solution.cs @@ -1,17 +1,17 @@ -public class Solution { - public int NumberOfGoodSubarraySplits(int[] nums) { - long ans = 1, j = -1; - int mod = 1000000007; - int n = nums.Length; - for (int i = 0; i < n; ++i) { - if (nums[i] == 0) { - continue; - } - if (j > -1) { - ans = ans * (i - j) % mod; - } - j = i; - } - return j == -1 ? 0 : (int) ans; - } -} \ No newline at end of file +public class Solution { + public int NumberOfGoodSubarraySplits(int[] nums) { + long ans = 1, j = -1; + int mod = 1000000007; + int n = nums.Length; + for (int i = 0; i < n; ++i) { + if (nums[i] == 0) { + continue; + } + if (j > -1) { + ans = ans * (i - j) % mod; + } + j = i; + } + return j == -1 ? 0 : (int) ans; + } +} diff --git a/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/Solution.java b/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/Solution.java index eec9cc447cd2e..61ef113bb79fe 100644 --- a/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/Solution.java +++ b/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/Solution.java @@ -1,16 +1,16 @@ -class Solution { - public int numberOfGoodSubarraySplits(int[] nums) { - final int mod = (int) 1e9 + 7; - int ans = 1, j = -1; - for (int i = 0; i < nums.length; ++i) { - if (nums[i] == 0) { - continue; - } - if (j > -1) { - ans = (int) ((long) ans * (i - j) % mod); - } - j = i; - } - return j == -1 ? 0 : ans; - } +class Solution { + public int numberOfGoodSubarraySplits(int[] nums) { + final int mod = (int) 1e9 + 7; + int ans = 1, j = -1; + for (int i = 0; i < nums.length; ++i) { + if (nums[i] == 0) { + continue; + } + if (j > -1) { + ans = (int) ((long) ans * (i - j) % mod); + } + j = i; + } + return j == -1 ? 0 : ans; + } } \ No newline at end of file diff --git a/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/Solution.py b/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/Solution.py index 6b82c14889e40..e5f51144d14a9 100644 --- a/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/Solution.py +++ b/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def numberOfGoodSubarraySplits(self, nums: List[int]) -> int: - mod = 10**9 + 7 - ans, j = 1, -1 - for i, x in enumerate(nums): - if x == 0: - continue - if j > -1: - ans = ans * (i - j) % mod - j = i - return 0 if j == -1 else ans +class Solution: + def numberOfGoodSubarraySplits(self, nums: List[int]) -> int: + mod = 10**9 + 7 + ans, j = 1, -1 + for i, x in enumerate(nums): + if x == 0: + continue + if j > -1: + ans = ans * (i - j) % mod + j = i + return 0 if j == -1 else ans diff --git a/solution/2700-2799/2753.Count Houses in a Circular Street II/Solution.cpp b/solution/2700-2799/2753.Count Houses in a Circular Street II/Solution.cpp index c6fc7a4fef21d..a7f15f1040e98 100644 --- a/solution/2700-2799/2753.Count Houses in a Circular Street II/Solution.cpp +++ b/solution/2700-2799/2753.Count Houses in a Circular Street II/Solution.cpp @@ -1,27 +1,27 @@ -/** - * Definition for a street. - * class Street { - * public: - * Street(vector doors); - * void closeDoor(); - * bool isDoorOpen(); - * void moveRight(); - * }; - */ -class Solution { -public: - int houseCount(Street* street, int k) { - while (!street->isDoorOpen()) { - street->moveRight(); - } - int ans = 0; - for (int i = 1; i <= k; ++i) { - street->moveRight(); - if (street->isDoorOpen()) { - ans = i; - street->closeDoor(); - } - } - return ans; - } +/** + * Definition for a street. + * class Street { + * public: + * Street(vector doors); + * void closeDoor(); + * bool isDoorOpen(); + * void moveRight(); + * }; + */ +class Solution { +public: + int houseCount(Street* street, int k) { + while (!street->isDoorOpen()) { + street->moveRight(); + } + int ans = 0; + for (int i = 1; i <= k; ++i) { + street->moveRight(); + if (street->isDoorOpen()) { + ans = i; + street->closeDoor(); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2753.Count Houses in a Circular Street II/Solution.java b/solution/2700-2799/2753.Count Houses in a Circular Street II/Solution.java index 3bd79a1fe7440..048e4dbce6395 100644 --- a/solution/2700-2799/2753.Count Houses in a Circular Street II/Solution.java +++ b/solution/2700-2799/2753.Count Houses in a Circular Street II/Solution.java @@ -1,25 +1,25 @@ -/** - * Definition for a street. - * class Street { - * public Street(int[] doors); - * public void closeDoor(); - * public boolean isDoorOpen(); - * public void moveRight(); - * } - */ -class Solution { - public int houseCount(Street street, int k) { - while (!street.isDoorOpen()) { - street.moveRight(); - } - int ans = 0; - for (int i = 1; i <= k; ++i) { - street.moveRight(); - if (street.isDoorOpen()) { - ans = i; - street.closeDoor(); - } - } - return ans; - } +/** + * Definition for a street. + * class Street { + * public Street(int[] doors); + * public void closeDoor(); + * public boolean isDoorOpen(); + * public void moveRight(); + * } + */ +class Solution { + public int houseCount(Street street, int k) { + while (!street.isDoorOpen()) { + street.moveRight(); + } + int ans = 0; + for (int i = 1; i <= k; ++i) { + street.moveRight(); + if (street.isDoorOpen()) { + ans = i; + street.closeDoor(); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2700-2799/2753.Count Houses in a Circular Street II/Solution.py b/solution/2700-2799/2753.Count Houses in a Circular Street II/Solution.py index f2e4d7fd0a9fd..3f7c717564ac5 100644 --- a/solution/2700-2799/2753.Count Houses in a Circular Street II/Solution.py +++ b/solution/2700-2799/2753.Count Houses in a Circular Street II/Solution.py @@ -1,18 +1,18 @@ -# Definition for a street. -# class Street: -# def closeDoor(self): -# pass -# def isDoorOpen(self): -# pass -# def moveRight(self): -# pass -class Solution: - def houseCount(self, street: Optional["Street"], k: int) -> int: - while not street.isDoorOpen(): - street.moveRight() - for i in range(1, k + 1): - street.moveRight() - if street.isDoorOpen(): - ans = i - street.closeDoor() - return ans +# Definition for a street. +# class Street: +# def closeDoor(self): +# pass +# def isDoorOpen(self): +# pass +# def moveRight(self): +# pass +class Solution: + def houseCount(self, street: Optional["Street"], k: int) -> int: + while not street.isDoorOpen(): + street.moveRight() + for i in range(1, k + 1): + street.moveRight() + if street.isDoorOpen(): + ans = i + street.closeDoor() + return ans diff --git a/solution/2700-2799/2757.Generate Circular Array Values/Solution.ts b/solution/2700-2799/2757.Generate Circular Array Values/Solution.ts index f54478622dc7c..0e25b3b149f15 100644 --- a/solution/2700-2799/2757.Generate Circular Array Values/Solution.ts +++ b/solution/2700-2799/2757.Generate Circular Array Values/Solution.ts @@ -5,7 +5,6 @@ function* cycleGenerator(arr: number[], startIndex: number): Generator& nums, int threshold) { - int ans = 0; - for (int l = 0, n = nums.size(); l < n;) { - if (nums[l] % 2 == 0 && nums[l] <= threshold) { - int r = l + 1; - while (r < n && nums[r] % 2 != nums[r - 1] % 2 && nums[r] <= threshold) { - ++r; - } - ans = max(ans, r - l); - l = r; - } else { - ++l; - } - } - return ans; - } +class Solution { +public: + int longestAlternatingSubarray(vector& nums, int threshold) { + int ans = 0, n = nums.size(); + for (int l = 0; l < n; ++l) { + if (nums[l] % 2 == 0 && nums[l] <= threshold) { + int r = l + 1; + while (r < n && nums[r] % 2 != nums[r - 1] % 2 && nums[r] <= threshold) { + ++r; + } + ans = max(ans, r - l); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution.go b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution.go index dec40b0d38289..4beb047fd6457 100644 --- a/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution.go +++ b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution.go @@ -1,14 +1,12 @@ func longestAlternatingSubarray(nums []int, threshold int) (ans int) { - for l, n := 0, len(nums); l < n; { + n := len(nums) + for l := range nums { if nums[l]%2 == 0 && nums[l] <= threshold { r := l + 1 for r < n && nums[r]%2 != nums[r-1]%2 && nums[r] <= threshold { r++ } ans = max(ans, r-l) - l = r - } else { - l++ } } return diff --git a/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution.java b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution.java index 9cc720f431619..8413b2c2b1973 100644 --- a/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution.java +++ b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution.java @@ -1,18 +1,15 @@ -class Solution { - public int longestAlternatingSubarray(int[] nums, int threshold) { - int ans = 0; - for (int l = 0, n = nums.length; l < n;) { - if (nums[l] % 2 == 0 && nums[l] <= threshold) { - int r = l + 1; - while (r < n && nums[r] % 2 != nums[r - 1] % 2 && nums[r] <= threshold) { - ++r; - } - ans = Math.max(ans, r - l); - l = r; - } else { - ++l; - } - } - return ans; - } +class Solution { + public int longestAlternatingSubarray(int[] nums, int threshold) { + int ans = 0, n = nums.length; + for (int l = 0; l < n; ++l) { + if (nums[l] % 2 == 0 && nums[l] <= threshold) { + int r = l + 1; + while (r < n && nums[r] % 2 != nums[r - 1] % 2 && nums[r] <= threshold) { + ++r; + } + ans = Math.max(ans, r - l); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution.py b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution.py index f0909ae9ee8d4..844e10683290d 100644 --- a/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution.py +++ b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution.py @@ -1,13 +1,10 @@ -class Solution: - def longestAlternatingSubarray(self, nums: List[int], threshold: int) -> int: - ans, l, n = 0, 0, len(nums) - while l < n: - if nums[l] % 2 == 0 and nums[l] <= threshold: - r = l + 1 - while r < n and nums[r] % 2 != nums[r - 1] % 2 and nums[r] <= threshold: - r += 1 - ans = max(ans, r - l) - l = r - else: - l += 1 - return ans +class Solution: + def longestAlternatingSubarray(self, nums: List[int], threshold: int) -> int: + ans, n = 0, len(nums) + for l in range(n): + if nums[l] % 2 == 0 and nums[l] <= threshold: + r = l + 1 + while r < n and nums[r] % 2 != nums[r - 1] % 2 and nums[r] <= threshold: + r += 1 + ans = max(ans, r - l) + return ans diff --git a/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution.ts b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution.ts index 57b6dbf4213e8..bcc9b29e27208 100644 --- a/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution.ts +++ b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution.ts @@ -1,16 +1,13 @@ function longestAlternatingSubarray(nums: number[], threshold: number): number { const n = nums.length; let ans = 0; - for (let l = 0; l < n; ) { + for (let l = 0; l < n; ++l) { if (nums[l] % 2 === 0 && nums[l] <= threshold) { let r = l + 1; while (r < n && nums[r] % 2 !== nums[r - 1] % 2 && nums[r] <= threshold) { ++r; } ans = Math.max(ans, r - l); - l = r; - } else { - ++l; } } return ans; diff --git a/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution2.cpp b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution2.cpp new file mode 100644 index 0000000000000..3f17be01b080a --- /dev/null +++ b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution2.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int longestAlternatingSubarray(vector& nums, int threshold) { + int ans = 0; + for (int l = 0, n = nums.size(); l < n;) { + if (nums[l] % 2 == 0 && nums[l] <= threshold) { + int r = l + 1; + while (r < n && nums[r] % 2 != nums[r - 1] % 2 && nums[r] <= threshold) { + ++r; + } + ans = max(ans, r - l); + l = r; + } else { + ++l; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution2.go b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution2.go new file mode 100644 index 0000000000000..dec40b0d38289 --- /dev/null +++ b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution2.go @@ -0,0 +1,15 @@ +func longestAlternatingSubarray(nums []int, threshold int) (ans int) { + for l, n := 0, len(nums); l < n; { + if nums[l]%2 == 0 && nums[l] <= threshold { + r := l + 1 + for r < n && nums[r]%2 != nums[r-1]%2 && nums[r] <= threshold { + r++ + } + ans = max(ans, r-l) + l = r + } else { + l++ + } + } + return +} \ No newline at end of file diff --git a/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution2.java b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution2.java new file mode 100644 index 0000000000000..c56b2e3cbf576 --- /dev/null +++ b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution2.java @@ -0,0 +1,18 @@ +class Solution { + public int longestAlternatingSubarray(int[] nums, int threshold) { + int ans = 0; + for (int l = 0, n = nums.length; l < n;) { + if (nums[l] % 2 == 0 && nums[l] <= threshold) { + int r = l + 1; + while (r < n && nums[r] % 2 != nums[r - 1] % 2 && nums[r] <= threshold) { + ++r; + } + ans = Math.max(ans, r - l); + l = r; + } else { + ++l; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution2.py b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution2.py new file mode 100644 index 0000000000000..e454fa744517c --- /dev/null +++ b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def longestAlternatingSubarray(self, nums: List[int], threshold: int) -> int: + ans, l, n = 0, 0, len(nums) + while l < n: + if nums[l] % 2 == 0 and nums[l] <= threshold: + r = l + 1 + while r < n and nums[r] % 2 != nums[r - 1] % 2 and nums[r] <= threshold: + r += 1 + ans = max(ans, r - l) + l = r + else: + l += 1 + return ans diff --git a/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution2.ts b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution2.ts new file mode 100644 index 0000000000000..57b6dbf4213e8 --- /dev/null +++ b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution2.ts @@ -0,0 +1,17 @@ +function longestAlternatingSubarray(nums: number[], threshold: number): number { + const n = nums.length; + let ans = 0; + for (let l = 0; l < n; ) { + if (nums[l] % 2 === 0 && nums[l] <= threshold) { + let r = l + 1; + while (r < n && nums[r] % 2 !== nums[r - 1] % 2 && nums[r] <= threshold) { + ++r; + } + ans = Math.max(ans, r - l); + l = r; + } else { + ++l; + } + } + return ans; +} diff --git a/solution/2700-2799/2761.Prime Pairs With Target Sum/Solution.cpp b/solution/2700-2799/2761.Prime Pairs With Target Sum/Solution.cpp index 3b980fc13ce70..e6d61a2c02156 100644 --- a/solution/2700-2799/2761.Prime Pairs With Target Sum/Solution.cpp +++ b/solution/2700-2799/2761.Prime Pairs With Target Sum/Solution.cpp @@ -1,22 +1,22 @@ -class Solution { -public: - vector> findPrimePairs(int n) { - bool primes[n]; - memset(primes, true, sizeof(primes)); - for (int i = 2; i < n; ++i) { - if (primes[i]) { - for (int j = i + i; j < n; j += i) { - primes[j] = false; - } - } - } - vector> ans; - for (int x = 2; x <= n / 2; ++x) { - int y = n - x; - if (primes[x] && primes[y]) { - ans.push_back({x, y}); - } - } - return ans; - } +class Solution { +public: + vector> findPrimePairs(int n) { + bool primes[n]; + memset(primes, true, sizeof(primes)); + for (int i = 2; i < n; ++i) { + if (primes[i]) { + for (int j = i + i; j < n; j += i) { + primes[j] = false; + } + } + } + vector> ans; + for (int x = 2; x <= n / 2; ++x) { + int y = n - x; + if (primes[x] && primes[y]) { + ans.push_back({x, y}); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2761.Prime Pairs With Target Sum/Solution.java b/solution/2700-2799/2761.Prime Pairs With Target Sum/Solution.java index fe99991531bb2..32ba058fef686 100644 --- a/solution/2700-2799/2761.Prime Pairs With Target Sum/Solution.java +++ b/solution/2700-2799/2761.Prime Pairs With Target Sum/Solution.java @@ -1,21 +1,21 @@ -class Solution { - public List> findPrimePairs(int n) { - boolean[] primes = new boolean[n]; - Arrays.fill(primes, true); - for (int i = 2; i < n; ++i) { - if (primes[i]) { - for (int j = i + i; j < n; j += i) { - primes[j] = false; - } - } - } - List> ans = new ArrayList<>(); - for (int x = 2; x <= n / 2; ++x) { - int y = n - x; - if (primes[x] && primes[y]) { - ans.add(List.of(x, y)); - } - } - return ans; - } +class Solution { + public List> findPrimePairs(int n) { + boolean[] primes = new boolean[n]; + Arrays.fill(primes, true); + for (int i = 2; i < n; ++i) { + if (primes[i]) { + for (int j = i + i; j < n; j += i) { + primes[j] = false; + } + } + } + List> ans = new ArrayList<>(); + for (int x = 2; x <= n / 2; ++x) { + int y = n - x; + if (primes[x] && primes[y]) { + ans.add(List.of(x, y)); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2700-2799/2761.Prime Pairs With Target Sum/Solution.py b/solution/2700-2799/2761.Prime Pairs With Target Sum/Solution.py index 8d0cb85f73fba..7642a346cd330 100644 --- a/solution/2700-2799/2761.Prime Pairs With Target Sum/Solution.py +++ b/solution/2700-2799/2761.Prime Pairs With Target Sum/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def findPrimePairs(self, n: int) -> List[List[int]]: - primes = [True] * n - for i in range(2, n): - if primes[i]: - for j in range(i + i, n, i): - primes[j] = False - ans = [] - for x in range(2, n // 2 + 1): - y = n - x - if primes[x] and primes[y]: - ans.append([x, y]) - return ans +class Solution: + def findPrimePairs(self, n: int) -> List[List[int]]: + primes = [True] * n + for i in range(2, n): + if primes[i]: + for j in range(i + i, n, i): + primes[j] = False + ans = [] + for x in range(2, n // 2 + 1): + y = n - x + if primes[x] and primes[y]: + ans.append([x, y]) + return ans diff --git a/solution/2700-2799/2762.Continuous Subarrays/Solution.cpp b/solution/2700-2799/2762.Continuous Subarrays/Solution.cpp index cff62ad96a67a..5cde2f73dab62 100644 --- a/solution/2700-2799/2762.Continuous Subarrays/Solution.cpp +++ b/solution/2700-2799/2762.Continuous Subarrays/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - long long continuousSubarrays(vector& nums) { - long long ans = 0; - int i = 0, n = nums.size(); - multiset s; - for (int j = 0; j < n; ++j) { - s.insert(nums[j]); - while (*s.rbegin() - *s.begin() > 2) { - s.erase(s.find(nums[i++])); - } - ans += j - i + 1; - } - return ans; - } +class Solution { +public: + long long continuousSubarrays(vector& nums) { + long long ans = 0; + int i = 0, n = nums.size(); + multiset s; + for (int j = 0; j < n; ++j) { + s.insert(nums[j]); + while (*s.rbegin() - *s.begin() > 2) { + s.erase(s.find(nums[i++])); + } + ans += j - i + 1; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2762.Continuous Subarrays/Solution.java b/solution/2700-2799/2762.Continuous Subarrays/Solution.java index 497bf0887c9c4..e77e75c319cb4 100644 --- a/solution/2700-2799/2762.Continuous Subarrays/Solution.java +++ b/solution/2700-2799/2762.Continuous Subarrays/Solution.java @@ -1,19 +1,19 @@ -class Solution { - public long continuousSubarrays(int[] nums) { - long ans = 0; - int i = 0, n = nums.length; - TreeMap tm = new TreeMap<>(); - for (int j = 0; j < n; ++j) { - tm.merge(nums[j], 1, Integer::sum); - while (tm.lastEntry().getKey() - tm.firstEntry().getKey() > 2) { - tm.merge(nums[i], -1, Integer::sum); - if (tm.get(nums[i]) == 0) { - tm.remove(nums[i]); - } - ++i; - } - ans += j - i + 1; - } - return ans; - } +class Solution { + public long continuousSubarrays(int[] nums) { + long ans = 0; + int i = 0, n = nums.length; + TreeMap tm = new TreeMap<>(); + for (int j = 0; j < n; ++j) { + tm.merge(nums[j], 1, Integer::sum); + while (tm.lastEntry().getKey() - tm.firstEntry().getKey() > 2) { + tm.merge(nums[i], -1, Integer::sum); + if (tm.get(nums[i]) == 0) { + tm.remove(nums[i]); + } + ++i; + } + ans += j - i + 1; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2700-2799/2762.Continuous Subarrays/Solution.py b/solution/2700-2799/2762.Continuous Subarrays/Solution.py index a4adf14ca5301..8089ee16dd76b 100644 --- a/solution/2700-2799/2762.Continuous Subarrays/Solution.py +++ b/solution/2700-2799/2762.Continuous Subarrays/Solution.py @@ -1,14 +1,14 @@ -from sortedcontainers import SortedList - - -class Solution: - def continuousSubarrays(self, nums: List[int]) -> int: - ans = i = 0 - sl = SortedList() - for x in nums: - sl.add(x) - while sl[-1] - sl[0] > 2: - sl.remove(nums[i]) - i += 1 - ans += len(sl) - return ans +from sortedcontainers import SortedList + + +class Solution: + def continuousSubarrays(self, nums: List[int]) -> int: + ans = i = 0 + sl = SortedList() + for x in nums: + sl.add(x) + while sl[-1] - sl[0] > 2: + sl.remove(nums[i]) + i += 1 + ans += len(sl) + return ans diff --git a/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/Solution.cpp b/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/Solution.cpp index 6088ef72e6963..f501c90721f9a 100644 --- a/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/Solution.cpp +++ b/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/Solution.cpp @@ -1,26 +1,26 @@ -class Solution { -public: - int sumImbalanceNumbers(vector& nums) { - int n = nums.size(); - int ans = 0; - for (int i = 0; i < n; ++i) { - multiset s; - int cnt = 0; - for (int j = i; j < n; ++j) { - auto it = s.lower_bound(nums[j]); - if (it != s.end() && *it - nums[j] > 1) { - ++cnt; - } - if (it != s.begin() && nums[j] - *prev(it) > 1) { - ++cnt; - } - if (it != s.end() && it != s.begin() && *it - *prev(it) > 1) { - --cnt; - } - s.insert(nums[j]); - ans += cnt; - } - } - return ans; - } +class Solution { +public: + int sumImbalanceNumbers(vector& nums) { + int n = nums.size(); + int ans = 0; + for (int i = 0; i < n; ++i) { + multiset s; + int cnt = 0; + for (int j = i; j < n; ++j) { + auto it = s.lower_bound(nums[j]); + if (it != s.end() && *it - nums[j] > 1) { + ++cnt; + } + if (it != s.begin() && nums[j] - *prev(it) > 1) { + ++cnt; + } + if (it != s.end() && it != s.begin() && *it - *prev(it) > 1) { + --cnt; + } + s.insert(nums[j]); + ans += cnt; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/Solution.java b/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/Solution.java index 375c2c3ee5d58..5b4e22daf891a 100644 --- a/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/Solution.java +++ b/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/Solution.java @@ -1,26 +1,26 @@ -class Solution { - public int sumImbalanceNumbers(int[] nums) { - int n = nums.length; - int ans = 0; - for (int i = 0; i < n; ++i) { - TreeMap tm = new TreeMap<>(); - int cnt = 0; - for (int j = i; j < n; ++j) { - Integer k = tm.ceilingKey(nums[j]); - if (k != null && k - nums[j] > 1) { - ++cnt; - } - Integer h = tm.floorKey(nums[j]); - if (h != null && nums[j] - h > 1) { - ++cnt; - } - if (h != null && k != null && k - h > 1) { - --cnt; - } - tm.merge(nums[j], 1, Integer::sum); - ans += cnt; - } - } - return ans; - } +class Solution { + public int sumImbalanceNumbers(int[] nums) { + int n = nums.length; + int ans = 0; + for (int i = 0; i < n; ++i) { + TreeMap tm = new TreeMap<>(); + int cnt = 0; + for (int j = i; j < n; ++j) { + Integer k = tm.ceilingKey(nums[j]); + if (k != null && k - nums[j] > 1) { + ++cnt; + } + Integer h = tm.floorKey(nums[j]); + if (h != null && nums[j] - h > 1) { + ++cnt; + } + if (h != null && k != null && k - h > 1) { + --cnt; + } + tm.merge(nums[j], 1, Integer::sum); + ans += cnt; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/Solution.py b/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/Solution.py index 9d78469a3609d..776fdc1764d7a 100644 --- a/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/Solution.py +++ b/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/Solution.py @@ -1,22 +1,22 @@ -from sortedcontainers import SortedList - - -class Solution: - def sumImbalanceNumbers(self, nums: List[int]) -> int: - n = len(nums) - ans = 0 - for i in range(n): - sl = SortedList() - cnt = 0 - for j in range(i, n): - k = sl.bisect_left(nums[j]) - h = k - 1 - if h >= 0 and nums[j] - sl[h] > 1: - cnt += 1 - if k < len(sl) and sl[k] - nums[j] > 1: - cnt += 1 - if h >= 0 and k < len(sl) and sl[k] - sl[h] > 1: - cnt -= 1 - sl.add(nums[j]) - ans += cnt - return ans +from sortedcontainers import SortedList + + +class Solution: + def sumImbalanceNumbers(self, nums: List[int]) -> int: + n = len(nums) + ans = 0 + for i in range(n): + sl = SortedList() + cnt = 0 + for j in range(i, n): + k = sl.bisect_left(nums[j]) + h = k - 1 + if h >= 0 and nums[j] - sl[h] > 1: + cnt += 1 + if k < len(sl) and sl[k] - nums[j] > 1: + cnt += 1 + if h >= 0 and k < len(sl) and sl[k] - sl[h] > 1: + cnt -= 1 + sl.add(nums[j]) + ans += cnt + return ans diff --git a/solution/2700-2799/2768.Number of Black Blocks/Solution.cpp b/solution/2700-2799/2768.Number of Black Blocks/Solution.cpp index cb086480cb754..6a6435b6bf295 100644 --- a/solution/2700-2799/2768.Number of Black Blocks/Solution.cpp +++ b/solution/2700-2799/2768.Number of Black Blocks/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - vector countBlackBlocks(int m, int n, vector>& coordinates) { - unordered_map cnt; - int dirs[5] = {0, 0, -1, -1, 0}; - for (auto& e : coordinates) { - int x = e[0], y = e[1]; - for (int k = 0; k < 4; ++k) { - int i = x + dirs[k], j = y + dirs[k + 1]; - if (i >= 0 && i < m - 1 && j >= 0 && j < n - 1) { - ++cnt[1LL * i * n + j]; - } - } - } - vector ans(5); - ans[0] = (m - 1LL) * (n - 1); - for (auto& [_, x] : cnt) { - ++ans[x]; - --ans[0]; - } - return ans; - } +class Solution { +public: + vector countBlackBlocks(int m, int n, vector>& coordinates) { + unordered_map cnt; + int dirs[5] = {0, 0, -1, -1, 0}; + for (auto& e : coordinates) { + int x = e[0], y = e[1]; + for (int k = 0; k < 4; ++k) { + int i = x + dirs[k], j = y + dirs[k + 1]; + if (i >= 0 && i < m - 1 && j >= 0 && j < n - 1) { + ++cnt[1LL * i * n + j]; + } + } + } + vector ans(5); + ans[0] = (m - 1LL) * (n - 1); + for (auto& [_, x] : cnt) { + ++ans[x]; + --ans[0]; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2768.Number of Black Blocks/Solution.java b/solution/2700-2799/2768.Number of Black Blocks/Solution.java index f6b2dd91d20ab..02871c1ad22ac 100644 --- a/solution/2700-2799/2768.Number of Black Blocks/Solution.java +++ b/solution/2700-2799/2768.Number of Black Blocks/Solution.java @@ -1,22 +1,22 @@ -class Solution { - public long[] countBlackBlocks(int m, int n, int[][] coordinates) { - Map cnt = new HashMap<>(coordinates.length); - int[] dirs = {0, 0, -1, -1, 0}; - for (var e : coordinates) { - int x = e[0], y = e[1]; - for (int k = 0; k < 4; ++k) { - int i = x + dirs[k], j = y + dirs[k + 1]; - if (i >= 0 && i < m - 1 && j >= 0 && j < n - 1) { - cnt.merge(1L * i * n + j, 1, Integer::sum); - } - } - } - long[] ans = new long[5]; - ans[0] = (m - 1L) * (n - 1); - for (int x : cnt.values()) { - ++ans[x]; - --ans[0]; - } - return ans; - } +class Solution { + public long[] countBlackBlocks(int m, int n, int[][] coordinates) { + Map cnt = new HashMap<>(coordinates.length); + int[] dirs = {0, 0, -1, -1, 0}; + for (var e : coordinates) { + int x = e[0], y = e[1]; + for (int k = 0; k < 4; ++k) { + int i = x + dirs[k], j = y + dirs[k + 1]; + if (i >= 0 && i < m - 1 && j >= 0 && j < n - 1) { + cnt.merge(1L * i * n + j, 1, Integer::sum); + } + } + } + long[] ans = new long[5]; + ans[0] = (m - 1L) * (n - 1); + for (int x : cnt.values()) { + ++ans[x]; + --ans[0]; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2700-2799/2768.Number of Black Blocks/Solution.py b/solution/2700-2799/2768.Number of Black Blocks/Solution.py index 683f49ea30e02..f47e07302ac4d 100644 --- a/solution/2700-2799/2768.Number of Black Blocks/Solution.py +++ b/solution/2700-2799/2768.Number of Black Blocks/Solution.py @@ -1,15 +1,15 @@ -class Solution: - def countBlackBlocks( - self, m: int, n: int, coordinates: List[List[int]] - ) -> List[int]: - cnt = Counter() - for x, y in coordinates: - for a, b in pairwise((0, 0, -1, -1, 0)): - i, j = x + a, y + b - if 0 <= i < m - 1 and 0 <= j < n - 1: - cnt[(i, j)] += 1 - ans = [0] * 5 - for x in cnt.values(): - ans[x] += 1 - ans[0] = (m - 1) * (n - 1) - len(cnt.values()) - return ans +class Solution: + def countBlackBlocks( + self, m: int, n: int, coordinates: List[List[int]] + ) -> List[int]: + cnt = Counter() + for x, y in coordinates: + for a, b in pairwise((0, 0, -1, -1, 0)): + i, j = x + a, y + b + if 0 <= i < m - 1 and 0 <= j < n - 1: + cnt[(i, j)] += 1 + ans = [0] * 5 + for x in cnt.values(): + ans[x] += 1 + ans[0] = (m - 1) * (n - 1) - len(cnt.values()) + return ans diff --git a/solution/2700-2799/2774.Array Upper Bound/Solution2.ts b/solution/2700-2799/2774.Array Upper Bound/Solution2.ts new file mode 100644 index 0000000000000..c450c769cbc6e --- /dev/null +++ b/solution/2700-2799/2774.Array Upper Bound/Solution2.ts @@ -0,0 +1,13 @@ +declare global { + interface Array { + upperBound(target: number): number; + } +} + +Array.prototype.upperBound = function (target: number) { + return this.lastIndexOf(target); +}; + +// [3,4,5].upperBound(5); // 2 +// [1,4,5].upperBound(2); // -1 +// [3,4,6,6,6,6,7].upperBound(6) // 5 diff --git a/solution/2700-2799/2778.Sum of Squares of Special Elements/Solution.cpp b/solution/2700-2799/2778.Sum of Squares of Special Elements/Solution.cpp index e1ae7b1325a32..3365ff7707637 100644 --- a/solution/2700-2799/2778.Sum of Squares of Special Elements/Solution.cpp +++ b/solution/2700-2799/2778.Sum of Squares of Special Elements/Solution.cpp @@ -1,13 +1,13 @@ -class Solution { -public: - int sumOfSquares(vector& nums) { - int n = nums.size(); - int ans = 0; - for (int i = 1; i <= n; ++i) { - if (n % i == 0) { - ans += nums[i - 1] * nums[i - 1]; - } - } - return ans; - } +class Solution { +public: + int sumOfSquares(vector& nums) { + int n = nums.size(); + int ans = 0; + for (int i = 1; i <= n; ++i) { + if (n % i == 0) { + ans += nums[i - 1] * nums[i - 1]; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2778.Sum of Squares of Special Elements/Solution.java b/solution/2700-2799/2778.Sum of Squares of Special Elements/Solution.java index 7daf272c80bd2..901f76456865d 100644 --- a/solution/2700-2799/2778.Sum of Squares of Special Elements/Solution.java +++ b/solution/2700-2799/2778.Sum of Squares of Special Elements/Solution.java @@ -1,12 +1,12 @@ -class Solution { - public int sumOfSquares(int[] nums) { - int n = nums.length; - int ans = 0; - for (int i = 1; i <= n; ++i) { - if (n % i == 0) { - ans += nums[i - 1] * nums[i - 1]; - } - } - return ans; - } +class Solution { + public int sumOfSquares(int[] nums) { + int n = nums.length; + int ans = 0; + for (int i = 1; i <= n; ++i) { + if (n % i == 0) { + ans += nums[i - 1] * nums[i - 1]; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2700-2799/2778.Sum of Squares of Special Elements/Solution.py b/solution/2700-2799/2778.Sum of Squares of Special Elements/Solution.py index dc10bcaf29bb3..f38435cc30cca 100644 --- a/solution/2700-2799/2778.Sum of Squares of Special Elements/Solution.py +++ b/solution/2700-2799/2778.Sum of Squares of Special Elements/Solution.py @@ -1,4 +1,4 @@ -class Solution: - def sumOfSquares(self, nums: List[int]) -> int: - n = len(nums) - return sum(x * x for i, x in enumerate(nums, 1) if n % i == 0) +class Solution: + def sumOfSquares(self, nums: List[int]) -> int: + n = len(nums) + return sum(x * x for i, x in enumerate(nums, 1) if n % i == 0) diff --git a/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/Solution.cpp b/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/Solution.cpp index 8fef4f6cbc0f8..78743e0b68ef7 100644 --- a/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/Solution.cpp +++ b/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/Solution.cpp @@ -1,17 +1,17 @@ -class Solution { -public: - int maximumBeauty(vector& nums, int k) { - int m = *max_element(nums.begin(), nums.end()) + k * 2 + 2; - vector d(m); - for (int x : nums) { - d[x]++; - d[x + k * 2 + 1]--; - } - int ans = 0, s = 0; - for (int x : d) { - s += x; - ans = max(ans, s); - } - return ans; - } +class Solution { +public: + int maximumBeauty(vector& nums, int k) { + int m = *max_element(nums.begin(), nums.end()) + k * 2 + 2; + vector d(m); + for (int x : nums) { + d[x]++; + d[x + k * 2 + 1]--; + } + int ans = 0, s = 0; + for (int x : d) { + s += x; + ans = max(ans, s); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/Solution.java b/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/Solution.java index fc4d7dd64aa44..4018ce8e57837 100644 --- a/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/Solution.java +++ b/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/Solution.java @@ -1,16 +1,16 @@ -class Solution { - public int maximumBeauty(int[] nums, int k) { - int m = Arrays.stream(nums).max().getAsInt() + k * 2 + 2; - int[] d = new int[m]; - for (int x : nums) { - d[x]++; - d[x + k * 2 + 1]--; - } - int ans = 0, s = 0; - for (int x : d) { - s += x; - ans = Math.max(ans, s); - } - return ans; - } +class Solution { + public int maximumBeauty(int[] nums, int k) { + int m = Arrays.stream(nums).max().getAsInt() + k * 2 + 2; + int[] d = new int[m]; + for (int x : nums) { + d[x]++; + d[x + k * 2 + 1]--; + } + int ans = 0, s = 0; + for (int x : d) { + s += x; + ans = Math.max(ans, s); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/Solution.py b/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/Solution.py index f5a3c0b774275..b8fdf62a505ee 100644 --- a/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/Solution.py +++ b/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def maximumBeauty(self, nums: List[int], k: int) -> int: - m = max(nums) + k * 2 + 2 - d = [0] * m - for x in nums: - d[x] += 1 - d[x + k * 2 + 1] -= 1 - ans = s = 0 - for x in d: - s += x - ans = max(ans, s) - return ans +class Solution: + def maximumBeauty(self, nums: List[int], k: int) -> int: + m = max(nums) + k * 2 + 2 + d = [0] * m + for x in nums: + d[x] += 1 + d[x + k * 2 + 1] -= 1 + ans = s = 0 + for x in d: + s += x + ans = max(ans, s) + return ans diff --git a/solution/2700-2799/2780.Minimum Index of a Valid Split/Solution.cpp b/solution/2700-2799/2780.Minimum Index of a Valid Split/Solution.cpp index 5443b5836ba72..bf9f775854555 100644 --- a/solution/2700-2799/2780.Minimum Index of a Valid Split/Solution.cpp +++ b/solution/2700-2799/2780.Minimum Index of a Valid Split/Solution.cpp @@ -1,24 +1,24 @@ -class Solution { -public: - int minimumIndex(vector& nums) { - int x = 0, cnt = 0; - unordered_map freq; - for (int v : nums) { - ++freq[v]; - if (freq[v] > cnt) { - cnt = freq[v]; - x = v; - } - } - int cur = 0; - for (int i = 1; i <= nums.size(); ++i) { - if (nums[i - 1] == x) { - ++cur; - if (cur * 2 > i && (cnt - cur) * 2 > nums.size() - i) { - return i - 1; - } - } - } - return -1; - } +class Solution { +public: + int minimumIndex(vector& nums) { + int x = 0, cnt = 0; + unordered_map freq; + for (int v : nums) { + ++freq[v]; + if (freq[v] > cnt) { + cnt = freq[v]; + x = v; + } + } + int cur = 0; + for (int i = 1; i <= nums.size(); ++i) { + if (nums[i - 1] == x) { + ++cur; + if (cur * 2 > i && (cnt - cur) * 2 > nums.size() - i) { + return i - 1; + } + } + } + return -1; + } }; \ No newline at end of file diff --git a/solution/2700-2799/2780.Minimum Index of a Valid Split/Solution.java b/solution/2700-2799/2780.Minimum Index of a Valid Split/Solution.java index b3ffaf72f5e4c..83f875069f724 100644 --- a/solution/2700-2799/2780.Minimum Index of a Valid Split/Solution.java +++ b/solution/2700-2799/2780.Minimum Index of a Valid Split/Solution.java @@ -1,23 +1,23 @@ -class Solution { - public int minimumIndex(List nums) { - int x = 0, cnt = 0; - Map freq = new HashMap<>(); - for (int v : nums) { - int t = freq.merge(v, 1, Integer::sum); - if (cnt < t) { - cnt = t; - x = v; - } - } - int cur = 0; - for (int i = 1; i <= nums.size(); ++i) { - if (nums.get(i - 1) == x) { - ++cur; - if (cur * 2 > i && (cnt - cur) * 2 > nums.size() - i) { - return i - 1; - } - } - } - return -1; - } +class Solution { + public int minimumIndex(List nums) { + int x = 0, cnt = 0; + Map freq = new HashMap<>(); + for (int v : nums) { + int t = freq.merge(v, 1, Integer::sum); + if (cnt < t) { + cnt = t; + x = v; + } + } + int cur = 0; + for (int i = 1; i <= nums.size(); ++i) { + if (nums.get(i - 1) == x) { + ++cur; + if (cur * 2 > i && (cnt - cur) * 2 > nums.size() - i) { + return i - 1; + } + } + } + return -1; + } } \ No newline at end of file diff --git a/solution/2700-2799/2780.Minimum Index of a Valid Split/Solution.py b/solution/2700-2799/2780.Minimum Index of a Valid Split/Solution.py index f2db9f8067bef..3bb58839c554c 100644 --- a/solution/2700-2799/2780.Minimum Index of a Valid Split/Solution.py +++ b/solution/2700-2799/2780.Minimum Index of a Valid Split/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def minimumIndex(self, nums: List[int]) -> int: - x, cnt = Counter(nums).most_common(1)[0] - cur = 0 - for i, v in enumerate(nums, 1): - if v == x: - cur += 1 - if cur * 2 > i and (cnt - cur) * 2 > len(nums) - i: - return i - 1 - return -1 +class Solution: + def minimumIndex(self, nums: List[int]) -> int: + x, cnt = Counter(nums).most_common(1)[0] + cur = 0 + for i, v in enumerate(nums, 1): + if v == x: + cur += 1 + if cur * 2 > i and (cnt - cur) * 2 > len(nums) - i: + return i - 1 + return -1 diff --git a/solution/2700-2799/2790.Maximum Number of Groups With Increasing Length/Solution.py b/solution/2700-2799/2790.Maximum Number of Groups With Increasing Length/Solution.py index 165a9b7d1fdda..029b6bbb53c6e 100644 --- a/solution/2700-2799/2790.Maximum Number of Groups With Increasing Length/Solution.py +++ b/solution/2700-2799/2790.Maximum Number of Groups With Increasing Length/Solution.py @@ -1,10 +1,11 @@ class Solution: def maxIncreasingGroups(self, usageLimits: List[int]) -> int: usageLimits.sort() - k = s = 0 - for x in usageLimits: - s += x - if s > k: + k, n = 0, len(usageLimits) + for i in range(n): + if usageLimits[i] > k: k += 1 - s -= k + usageLimits[i] -= k + if i + 1 < n: + usageLimits[i + 1] += usageLimits[i] return k diff --git a/solution/2700-2799/2790.Maximum Number of Groups With Increasing Length/Solution2.py b/solution/2700-2799/2790.Maximum Number of Groups With Increasing Length/Solution2.py new file mode 100644 index 0000000000000..165a9b7d1fdda --- /dev/null +++ b/solution/2700-2799/2790.Maximum Number of Groups With Increasing Length/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def maxIncreasingGroups(self, usageLimits: List[int]) -> int: + usageLimits.sort() + k = s = 0 + for x in usageLimits: + s += x + if s > k: + k += 1 + s -= k + return k diff --git a/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.cpp b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.cpp index 7b4b44c1ecb6e..8bbae615449e7 100644 --- a/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.cpp +++ b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.cpp @@ -1,21 +1,16 @@ class Solution { public: int countCompleteSubarrays(vector& nums) { - unordered_map d; - for (int x : nums) { - d[x] = 1; - } - int cnt = d.size(); - d.clear(); + unordered_set s(nums.begin(), nums.end()); + int cnt = s.size(); int ans = 0, n = nums.size(); - for (int i = 0, j = 0; j < n; ++j) { - d[nums[j]]++; - while (d.size() == cnt) { - ans += n - j; - if (--d[nums[i]] == 0) { - d.erase(nums[i]); + for (int i = 0; i < n; ++i) { + s.clear(); + for (int j = i; j < n; ++j) { + s.insert(nums[j]); + if (s.size() == cnt) { + ++ans; } - ++i; } } return ans; diff --git a/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.go b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.go index 34512a0dceedc..0399568064225 100644 --- a/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.go +++ b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.go @@ -1,20 +1,16 @@ func countCompleteSubarrays(nums []int) (ans int) { - d := map[int]int{} + s := map[int]bool{} for _, x := range nums { - d[x] = 1 + s[x] = true } - cnt := len(d) - i, n := 0, len(nums) - d = map[int]int{} - for j, x := range nums { - d[x]++ - for len(d) == cnt { - ans += n - j - d[nums[i]]-- - if d[nums[i]] == 0 { - delete(d, nums[i]) + cnt := len(s) + for i := range nums { + s = map[int]bool{} + for _, x := range nums[i:] { + s[x] = true + if len(s) == cnt { + ans++ } - i++ } } return diff --git a/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.java b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.java index 9bfbf3ed8e285..4bca1f6ac0789 100644 --- a/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.java +++ b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.java @@ -1,20 +1,18 @@ class Solution { public int countCompleteSubarrays(int[] nums) { - Map d = new HashMap<>(); + Set s = new HashSet<>(); for (int x : nums) { - d.put(x, 1); + s.add(x); } - int cnt = d.size(); + int cnt = s.size(); int ans = 0, n = nums.length; - d.clear(); - for (int i = 0, j = 0; j < n; ++j) { - d.merge(nums[j], 1, Integer::sum); - while (d.size() == cnt) { - ans += n - j; - if (d.merge(nums[i], -1, Integer::sum) == 0) { - d.remove(nums[i]); + for (int i = 0; i < n; ++i) { + s.clear(); + for (int j = i; j < n; ++j) { + s.add(nums[j]); + if (s.size() == cnt) { + ++ans; } - ++i; } } return ans; diff --git a/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.py b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.py index ce9d3090923af..e56df78cbef39 100644 --- a/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.py +++ b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.py @@ -1,15 +1,11 @@ class Solution: def countCompleteSubarrays(self, nums: List[int]) -> int: cnt = len(set(nums)) - d = Counter() ans, n = 0, len(nums) - i = 0 - for j, x in enumerate(nums): - d[x] += 1 - while len(d) == cnt: - ans += n - j - d[nums[i]] -= 1 - if d[nums[i]] == 0: - d.pop(nums[i]) - i += 1 + for i in range(n): + s = set() + for x in nums[i:]: + s.add(x) + if len(s) == cnt: + ans += 1 return ans diff --git a/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.rs b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.rs index f10d7ee65ab8f..1b67ee82dbef3 100644 --- a/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.rs +++ b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.rs @@ -1,22 +1,18 @@ -use std::collections::HashMap; use std::collections::HashSet; impl Solution { pub fn count_complete_subarrays(nums: Vec) -> i32 { + let mut set: HashSet<&i32> = nums.iter().collect(); let n = nums.len(); - let m = nums.iter().collect::>().len(); - let mut map = HashMap::new(); + let m = set.len(); let mut ans = 0; - let mut i = 0; - for j in 0..n { - *map.entry(nums[j]).or_insert(0) += 1; - while map.len() == m { - ans += n - j; - let v = map.entry(nums[i]).or_default(); - *v -= 1; - if *v == 0 { - map.remove(&nums[i]); + for i in 0..n { + set.clear(); + for j in i..n { + set.insert(&nums[j]); + if set.len() == m { + ans += n - j; + break; } - i += 1; } } ans as i32 diff --git a/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.ts b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.ts index 51fb37374511b..83849f97d9a18 100644 --- a/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.ts +++ b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.ts @@ -1,22 +1,15 @@ function countCompleteSubarrays(nums: number[]): number { - const d: Map = new Map(); - for (const x of nums) { - d.set(x, (d.get(x) ?? 0) + 1); - } - const cnt = d.size; - d.clear(); + const s: Set = new Set(nums); + const cnt = s.size; const n = nums.length; let ans = 0; - let i = 0; - for (let j = 0; j < n; ++j) { - d.set(nums[j], (d.get(nums[j]) ?? 0) + 1); - while (d.size === cnt) { - ans += n - j; - d.set(nums[i], d.get(nums[i])! - 1); - if (d.get(nums[i]) === 0) { - d.delete(nums[i]); + for (let i = 0; i < n; ++i) { + s.clear(); + for (let j = i; j < n; ++j) { + s.add(nums[j]); + if (s.size === cnt) { + ++ans; } - ++i; } } return ans; diff --git a/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.cpp b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.cpp new file mode 100644 index 0000000000000..7b4b44c1ecb6e --- /dev/null +++ b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int countCompleteSubarrays(vector& nums) { + unordered_map d; + for (int x : nums) { + d[x] = 1; + } + int cnt = d.size(); + d.clear(); + int ans = 0, n = nums.size(); + for (int i = 0, j = 0; j < n; ++j) { + d[nums[j]]++; + while (d.size() == cnt) { + ans += n - j; + if (--d[nums[i]] == 0) { + d.erase(nums[i]); + } + ++i; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.go b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.go new file mode 100644 index 0000000000000..34512a0dceedc --- /dev/null +++ b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.go @@ -0,0 +1,21 @@ +func countCompleteSubarrays(nums []int) (ans int) { + d := map[int]int{} + for _, x := range nums { + d[x] = 1 + } + cnt := len(d) + i, n := 0, len(nums) + d = map[int]int{} + for j, x := range nums { + d[x]++ + for len(d) == cnt { + ans += n - j + d[nums[i]]-- + if d[nums[i]] == 0 { + delete(d, nums[i]) + } + i++ + } + } + return +} \ No newline at end of file diff --git a/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.java b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.java new file mode 100644 index 0000000000000..9bfbf3ed8e285 --- /dev/null +++ b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.java @@ -0,0 +1,22 @@ +class Solution { + public int countCompleteSubarrays(int[] nums) { + Map d = new HashMap<>(); + for (int x : nums) { + d.put(x, 1); + } + int cnt = d.size(); + int ans = 0, n = nums.length; + d.clear(); + for (int i = 0, j = 0; j < n; ++j) { + d.merge(nums[j], 1, Integer::sum); + while (d.size() == cnt) { + ans += n - j; + if (d.merge(nums[i], -1, Integer::sum) == 0) { + d.remove(nums[i]); + } + ++i; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.py b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.py new file mode 100644 index 0000000000000..ce9d3090923af --- /dev/null +++ b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.py @@ -0,0 +1,15 @@ +class Solution: + def countCompleteSubarrays(self, nums: List[int]) -> int: + cnt = len(set(nums)) + d = Counter() + ans, n = 0, len(nums) + i = 0 + for j, x in enumerate(nums): + d[x] += 1 + while len(d) == cnt: + ans += n - j + d[nums[i]] -= 1 + if d[nums[i]] == 0: + d.pop(nums[i]) + i += 1 + return ans diff --git a/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.rs b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.rs new file mode 100644 index 0000000000000..f10d7ee65ab8f --- /dev/null +++ b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.rs @@ -0,0 +1,24 @@ +use std::collections::HashMap; +use std::collections::HashSet; +impl Solution { + pub fn count_complete_subarrays(nums: Vec) -> i32 { + let n = nums.len(); + let m = nums.iter().collect::>().len(); + let mut map = HashMap::new(); + let mut ans = 0; + let mut i = 0; + for j in 0..n { + *map.entry(nums[j]).or_insert(0) += 1; + while map.len() == m { + ans += n - j; + let v = map.entry(nums[i]).or_default(); + *v -= 1; + if *v == 0 { + map.remove(&nums[i]); + } + i += 1; + } + } + ans as i32 + } +} diff --git a/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.ts b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.ts new file mode 100644 index 0000000000000..51fb37374511b --- /dev/null +++ b/solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.ts @@ -0,0 +1,23 @@ +function countCompleteSubarrays(nums: number[]): number { + const d: Map = new Map(); + for (const x of nums) { + d.set(x, (d.get(x) ?? 0) + 1); + } + const cnt = d.size; + d.clear(); + const n = nums.length; + let ans = 0; + let i = 0; + for (let j = 0; j < n; ++j) { + d.set(nums[j], (d.get(nums[j]) ?? 0) + 1); + while (d.size === cnt) { + ans += n - j; + d.set(nums[i], d.get(nums[i])! - 1); + if (d.get(nums[i]) === 0) { + d.delete(nums[i]); + } + ++i; + } + } + return ans; +} diff --git a/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/Solution.cpp b/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/Solution.cpp index f11b6a1d10430..fc0a39ccb49a5 100644 --- a/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/Solution.cpp +++ b/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - int minimumSeconds(vector& nums) { - unordered_map> d; - int n = nums.size(); - for (int i = 0; i < n; ++i) { - d[nums[i]].push_back(i); - } - int ans = 1 << 30; - for (auto& [_, idx] : d) { - int m = idx.size(); - int t = idx[0] + n - idx[m - 1]; - for (int i = 1; i < m; ++i) { - t = max(t, idx[i] - idx[i - 1]); - } - ans = min(ans, t / 2); - } - return ans; - } +class Solution { +public: + int minimumSeconds(vector& nums) { + unordered_map> d; + int n = nums.size(); + for (int i = 0; i < n; ++i) { + d[nums[i]].push_back(i); + } + int ans = 1 << 30; + for (auto& [_, idx] : d) { + int m = idx.size(); + int t = idx[0] + n - idx[m - 1]; + for (int i = 1; i < m; ++i) { + t = max(t, idx[i] - idx[i - 1]); + } + ans = min(ans, t / 2); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/Solution.java b/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/Solution.java index cff04898664ae..8a84f136e5f4a 100644 --- a/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/Solution.java +++ b/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/Solution.java @@ -1,19 +1,19 @@ -class Solution { - public int minimumSeconds(List nums) { - Map> d = new HashMap<>(); - int n = nums.size(); - for (int i = 0; i < n; ++i) { - d.computeIfAbsent(nums.get(i), k -> new ArrayList<>()).add(i); - } - int ans = 1 << 30; - for (List idx : d.values()) { - int m = idx.size(); - int t = idx.get(0) + n - idx.get(m - 1); - for (int i = 1; i < m; ++i) { - t = Math.max(t, idx.get(i) - idx.get(i - 1)); - } - ans = Math.min(ans, t / 2); - } - return ans; - } +class Solution { + public int minimumSeconds(List nums) { + Map> d = new HashMap<>(); + int n = nums.size(); + for (int i = 0; i < n; ++i) { + d.computeIfAbsent(nums.get(i), k -> new ArrayList<>()).add(i); + } + int ans = 1 << 30; + for (List idx : d.values()) { + int m = idx.size(); + int t = idx.get(0) + n - idx.get(m - 1); + for (int i = 1; i < m; ++i) { + t = Math.max(t, idx.get(i) - idx.get(i - 1)); + } + ans = Math.min(ans, t / 2); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/Solution.py b/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/Solution.py index 110d9cfa60218..4c2263b94a45e 100644 --- a/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/Solution.py +++ b/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def minimumSeconds(self, nums: List[int]) -> int: - d = defaultdict(list) - for i, x in enumerate(nums): - d[x].append(i) - ans = inf - n = len(nums) - for idx in d.values(): - t = idx[0] + n - idx[-1] - for i, j in pairwise(idx): - t = max(t, j - i) - ans = min(ans, t // 2) - return ans +class Solution: + def minimumSeconds(self, nums: List[int]) -> int: + d = defaultdict(list) + for i, x in enumerate(nums): + d[x].append(i) + ans = inf + n = len(nums) + for idx in d.values(): + t = idx[0] + n - idx[-1] + for i, j in pairwise(idx): + t = max(t, j - i) + ans = min(ans, t // 2) + return ans diff --git a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.cpp b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.cpp index 2dd0977ba6a72..cd03718f40c70 100644 --- a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.cpp +++ b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.cpp @@ -1,26 +1,30 @@ -class Solution { -public: - int minimumTime(vector& nums1, vector& nums2, int x) { - int n = nums1.size(); - vector> nums; - for (int i = 0; i < n; ++i) { - nums.emplace_back(nums2[i], nums1[i]); - } - sort(nums.begin(), nums.end()); - int f[n + 1]; - memset(f, 0, sizeof(f)); - for (auto [b, a] : nums) { - for (int j = n; j; --j) { - f[j] = max(f[j], f[j - 1] + a + b * j); - } - } - int s1 = accumulate(nums1.begin(), nums1.end(), 0); - int s2 = accumulate(nums2.begin(), nums2.end(), 0); - for (int j = 0; j <= n; ++j) { - if (s1 + s2 * j - f[j] <= x) { - return j; - } - } - return -1; - } +class Solution { +public: + int minimumTime(vector& nums1, vector& nums2, int x) { + int n = nums1.size(); + vector> nums; + for (int i = 0; i < n; ++i) { + nums.emplace_back(nums2[i], nums1[i]); + } + sort(nums.begin(), nums.end()); + int f[n + 1][n + 1]; + memset(f, 0, sizeof(f)); + for (int i = 1; i <= n; ++i) { + for (int j = 0; j <= n; ++j) { + f[i][j] = f[i - 1][j]; + if (j) { + auto [b, a] = nums[i - 1]; + f[i][j] = max(f[i][j], f[i - 1][j - 1] + a + b * j); + } + } + } + int s1 = accumulate(nums1.begin(), nums1.end(), 0); + int s2 = accumulate(nums2.begin(), nums2.end(), 0); + for (int j = 0; j <= n; ++j) { + if (s1 + s2 * j - f[n][j] <= x) { + return j; + } + } + return -1; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.go b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.go index 082eadd2ec107..9c8a09a21391d 100644 --- a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.go +++ b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.go @@ -1,6 +1,9 @@ func minimumTime(nums1 []int, nums2 []int, x int) int { n := len(nums1) - f := make([]int, n+1) + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, n+1) + } type pair struct{ a, b int } nums := make([]pair, n) var s1, s2 int @@ -10,14 +13,17 @@ func minimumTime(nums1 []int, nums2 []int, x int) int { nums[i] = pair{nums1[i], nums2[i]} } sort.Slice(nums, func(i, j int) bool { return nums[i].b < nums[j].b }) - for _, e := range nums { - a, b := e.a, e.b - for j := n; j > 0; j-- { - f[j] = max(f[j], f[j-1]+a+b*j) + for i := 1; i <= n; i++ { + for j := 0; j <= n; j++ { + f[i][j] = f[i-1][j] + if j > 0 { + a, b := nums[i-1].a, nums[i-1].b + f[i][j] = max(f[i][j], f[i-1][j-1]+a+b*j) + } } } for j := 0; j <= n; j++ { - if s1+s2*j-f[j] <= x { + if s1+s2*j-f[n][j] <= x { return j } } diff --git a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.java b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.java index 40b3f6adfe8b4..6cfc0e94dfefb 100644 --- a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.java +++ b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.java @@ -1,31 +1,34 @@ -class Solution { - public int minimumTime(List nums1, List nums2, int x) { - int n = nums1.size(); - int[] f = new int[n + 1]; - int[][] nums = new int[n][0]; - for (int i = 0; i < n; ++i) { - nums[i] = new int[] {nums1.get(i), nums2.get(i)}; - } - Arrays.sort(nums, Comparator.comparingInt(a -> a[1])); - for (int[] e : nums) { - int a = e[0], b = e[1]; - for (int j = n; j > 0; --j) { - f[j] = Math.max(f[j], f[j - 1] + a + b * j); - } - } - int s1 = 0, s2 = 0; - for (int v : nums1) { - s1 += v; - } - for (int v : nums2) { - s2 += v; - } - - for (int j = 0; j <= n; ++j) { - if (s1 + s2 * j - f[j] <= x) { - return j; - } - } - return -1; - } +class Solution { + public int minimumTime(List nums1, List nums2, int x) { + int n = nums1.size(); + int[][] f = new int[n + 1][n + 1]; + int[][] nums = new int[n][0]; + for (int i = 0; i < n; ++i) { + nums[i] = new int[] {nums1.get(i), nums2.get(i)}; + } + Arrays.sort(nums, Comparator.comparingInt(a -> a[1])); + for (int i = 1; i <= n; ++i) { + for (int j = 0; j <= n; ++j) { + f[i][j] = f[i - 1][j]; + if (j > 0) { + int a = nums[i - 1][0], b = nums[i - 1][1]; + f[i][j] = Math.max(f[i][j], f[i - 1][j - 1] + a + b * j); + } + } + } + int s1 = 0, s2 = 0; + for (int v : nums1) { + s1 += v; + } + for (int v : nums2) { + s2 += v; + } + + for (int j = 0; j <= n; ++j) { + if (s1 + s2 * j - f[n][j] <= x) { + return j; + } + } + return -1; + } } \ No newline at end of file diff --git a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.py b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.py index def2084bd23ae..2ebf524ac1ae3 100644 --- a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.py +++ b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.py @@ -1,13 +1,15 @@ -class Solution: - def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int: - n = len(nums1) - f = [0] * (n + 1) - for a, b in sorted(zip(nums1, nums2), key=lambda z: z[1]): - for j in range(n, 0, -1): - f[j] = max(f[j], f[j - 1] + a + b * j) - s1 = sum(nums1) - s2 = sum(nums2) - for j in range(n + 1): - if s1 + s2 * j - f[j] <= x: - return j - return -1 +class Solution: + def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int: + n = len(nums1) + f = [[0] * (n + 1) for _ in range(n + 1)] + for i, (a, b) in enumerate(sorted(zip(nums1, nums2), key=lambda z: z[1]), 1): + for j in range(n + 1): + f[i][j] = f[i - 1][j] + if j > 0: + f[i][j] = max(f[i][j], f[i - 1][j - 1] + a + b * j) + s1 = sum(nums1) + s2 = sum(nums2) + for j in range(n + 1): + if s1 + s2 * j - f[n][j] <= x: + return j + return -1 diff --git a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.ts b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.ts index 30a602d8570d3..04f2d00439615 100644 --- a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.ts +++ b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution.ts @@ -1,20 +1,26 @@ function minimumTime(nums1: number[], nums2: number[], x: number): number { const n = nums1.length; - const f: number[] = new Array(n + 1).fill(0); + const f: number[][] = Array(n + 1) + .fill(0) + .map(() => Array(n + 1).fill(0)); const nums: number[][] = []; for (let i = 0; i < n; ++i) { nums.push([nums1[i], nums2[i]]); } nums.sort((a, b) => a[1] - b[1]); - for (const [a, b] of nums) { - for (let j = n; j > 0; --j) { - f[j] = Math.max(f[j], f[j - 1] + a + b * j); + for (let i = 1; i <= n; ++i) { + for (let j = 0; j <= n; ++j) { + f[i][j] = f[i - 1][j]; + if (j > 0) { + const [a, b] = nums[i - 1]; + f[i][j] = Math.max(f[i][j], f[i - 1][j - 1] + a + b * j); + } } } const s1 = nums1.reduce((a, b) => a + b, 0); const s2 = nums2.reduce((a, b) => a + b, 0); for (let j = 0; j <= n; ++j) { - if (s1 + s2 * j - f[j] <= x) { + if (s1 + s2 * j - f[n][j] <= x) { return j; } } diff --git a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution2.cpp b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution2.cpp new file mode 100644 index 0000000000000..a64e1bbeb890e --- /dev/null +++ b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution2.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int minimumTime(vector& nums1, vector& nums2, int x) { + int n = nums1.size(); + vector> nums; + for (int i = 0; i < n; ++i) { + nums.emplace_back(nums2[i], nums1[i]); + } + sort(nums.begin(), nums.end()); + int f[n + 1]; + memset(f, 0, sizeof(f)); + for (auto [b, a] : nums) { + for (int j = n; j; --j) { + f[j] = max(f[j], f[j - 1] + a + b * j); + } + } + int s1 = accumulate(nums1.begin(), nums1.end(), 0); + int s2 = accumulate(nums2.begin(), nums2.end(), 0); + for (int j = 0; j <= n; ++j) { + if (s1 + s2 * j - f[j] <= x) { + return j; + } + } + return -1; + } +}; \ No newline at end of file diff --git a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution2.go b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution2.go new file mode 100644 index 0000000000000..082eadd2ec107 --- /dev/null +++ b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution2.go @@ -0,0 +1,25 @@ +func minimumTime(nums1 []int, nums2 []int, x int) int { + n := len(nums1) + f := make([]int, n+1) + type pair struct{ a, b int } + nums := make([]pair, n) + var s1, s2 int + for i := range nums { + s1 += nums1[i] + s2 += nums2[i] + nums[i] = pair{nums1[i], nums2[i]} + } + sort.Slice(nums, func(i, j int) bool { return nums[i].b < nums[j].b }) + for _, e := range nums { + a, b := e.a, e.b + for j := n; j > 0; j-- { + f[j] = max(f[j], f[j-1]+a+b*j) + } + } + for j := 0; j <= n; j++ { + if s1+s2*j-f[j] <= x { + return j + } + } + return -1 +} \ No newline at end of file diff --git a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution2.java b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution2.java new file mode 100644 index 0000000000000..92602fdfe0e71 --- /dev/null +++ b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution2.java @@ -0,0 +1,31 @@ +class Solution { + public int minimumTime(List nums1, List nums2, int x) { + int n = nums1.size(); + int[] f = new int[n + 1]; + int[][] nums = new int[n][0]; + for (int i = 0; i < n; ++i) { + nums[i] = new int[] {nums1.get(i), nums2.get(i)}; + } + Arrays.sort(nums, Comparator.comparingInt(a -> a[1])); + for (int[] e : nums) { + int a = e[0], b = e[1]; + for (int j = n; j > 0; --j) { + f[j] = Math.max(f[j], f[j - 1] + a + b * j); + } + } + int s1 = 0, s2 = 0; + for (int v : nums1) { + s1 += v; + } + for (int v : nums2) { + s2 += v; + } + + for (int j = 0; j <= n; ++j) { + if (s1 + s2 * j - f[j] <= x) { + return j; + } + } + return -1; + } +} \ No newline at end of file diff --git a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution2.py b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution2.py new file mode 100644 index 0000000000000..649b57f76e22a --- /dev/null +++ b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution2.py @@ -0,0 +1,13 @@ +class Solution: + def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int: + n = len(nums1) + f = [0] * (n + 1) + for a, b in sorted(zip(nums1, nums2), key=lambda z: z[1]): + for j in range(n, 0, -1): + f[j] = max(f[j], f[j - 1] + a + b * j) + s1 = sum(nums1) + s2 = sum(nums2) + for j in range(n + 1): + if s1 + s2 * j - f[j] <= x: + return j + return -1 diff --git a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution2.ts b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution2.ts new file mode 100644 index 0000000000000..30a602d8570d3 --- /dev/null +++ b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/Solution2.ts @@ -0,0 +1,22 @@ +function minimumTime(nums1: number[], nums2: number[], x: number): number { + const n = nums1.length; + const f: number[] = new Array(n + 1).fill(0); + const nums: number[][] = []; + for (let i = 0; i < n; ++i) { + nums.push([nums1[i], nums2[i]]); + } + nums.sort((a, b) => a[1] - b[1]); + for (const [a, b] of nums) { + for (let j = n; j > 0; --j) { + f[j] = Math.max(f[j], f[j - 1] + a + b * j); + } + } + const s1 = nums1.reduce((a, b) => a + b, 0); + const s2 = nums2.reduce((a, b) => a + b, 0); + for (let j = 0; j <= n; ++j) { + if (s1 + s2 * j - f[j] <= x) { + return j; + } + } + return -1; +} diff --git a/solution/2800-2899/2810.Faulty Keyboard/Solution.cpp b/solution/2800-2899/2810.Faulty Keyboard/Solution.cpp index c1b25b9af8cae..c76636bffa1e5 100644 --- a/solution/2800-2899/2810.Faulty Keyboard/Solution.cpp +++ b/solution/2800-2899/2810.Faulty Keyboard/Solution.cpp @@ -1,14 +1,14 @@ -class Solution { -public: - string finalString(string s) { - string t; - for (char c : s) { - if (c == 'i') { - reverse(t.begin(), t.end()); - } else { - t.push_back(c); - } - } - return t; - } +class Solution { +public: + string finalString(string s) { + string t; + for (char c : s) { + if (c == 'i') { + reverse(t.begin(), t.end()); + } else { + t.push_back(c); + } + } + return t; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2810.Faulty Keyboard/Solution.java b/solution/2800-2899/2810.Faulty Keyboard/Solution.java index 1f84c3f9f0c02..62f42e7230d8d 100644 --- a/solution/2800-2899/2810.Faulty Keyboard/Solution.java +++ b/solution/2800-2899/2810.Faulty Keyboard/Solution.java @@ -1,13 +1,13 @@ -class Solution { - public String finalString(String s) { - StringBuilder t = new StringBuilder(); - for (char c : s.toCharArray()) { - if (c == 'i') { - t.reverse(); - } else { - t.append(c); - } - } - return t.toString(); - } +class Solution { + public String finalString(String s) { + StringBuilder t = new StringBuilder(); + for (char c : s.toCharArray()) { + if (c == 'i') { + t.reverse(); + } else { + t.append(c); + } + } + return t.toString(); + } } \ No newline at end of file diff --git a/solution/2800-2899/2810.Faulty Keyboard/Solution.py b/solution/2800-2899/2810.Faulty Keyboard/Solution.py index 71a2143b63cda..03426fb248d85 100644 --- a/solution/2800-2899/2810.Faulty Keyboard/Solution.py +++ b/solution/2800-2899/2810.Faulty Keyboard/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def finalString(self, s: str) -> str: - t = [] - for c in s: - if c == "i": - t = t[::-1] - else: - t.append(c) - return "".join(t) +class Solution: + def finalString(self, s: str) -> str: + t = [] + for c in s: + if c == "i": + t = t[::-1] + else: + t.append(c) + return "".join(t) diff --git a/solution/2800-2899/2811.Check if it is Possible to Split Array/Solution.cpp b/solution/2800-2899/2811.Check if it is Possible to Split Array/Solution.cpp index 12cc3ce4fddf6..73a9d67ad4e8e 100644 --- a/solution/2800-2899/2811.Check if it is Possible to Split Array/Solution.cpp +++ b/solution/2800-2899/2811.Check if it is Possible to Split Array/Solution.cpp @@ -1,31 +1,31 @@ -class Solution { -public: - bool canSplitArray(vector& nums, int m) { - int n = nums.size(); - vector s(n + 1); - for (int i = 1; i <= n; ++i) { - s[i] = s[i - 1] + nums[i - 1]; - } - int f[n][n]; - memset(f, -1, sizeof f); - function dfs = [&](int i, int j) { - if (i == j) { - return true; - } - if (f[i][j] != -1) { - return f[i][j] == 1; - } - for (int k = i; k < j; ++k) { - bool a = k == i || s[k + 1] - s[i] >= m; - bool b = k == j - 1 || s[j + 1] - s[k + 1] >= m; - if (a && b && dfs(i, k) && dfs(k + 1, j)) { - f[i][j] = 1; - return true; - } - } - f[i][j] = 0; - return false; - }; - return dfs(0, n - 1); - } +class Solution { +public: + bool canSplitArray(vector& nums, int m) { + int n = nums.size(); + vector s(n + 1); + for (int i = 1; i <= n; ++i) { + s[i] = s[i - 1] + nums[i - 1]; + } + int f[n][n]; + memset(f, -1, sizeof f); + function dfs = [&](int i, int j) { + if (i == j) { + return true; + } + if (f[i][j] != -1) { + return f[i][j] == 1; + } + for (int k = i; k < j; ++k) { + bool a = k == i || s[k + 1] - s[i] >= m; + bool b = k == j - 1 || s[j + 1] - s[k + 1] >= m; + if (a && b && dfs(i, k) && dfs(k + 1, j)) { + f[i][j] = 1; + return true; + } + } + f[i][j] = 0; + return false; + }; + return dfs(0, n - 1); + } }; \ No newline at end of file diff --git a/solution/2800-2899/2811.Check if it is Possible to Split Array/Solution.java b/solution/2800-2899/2811.Check if it is Possible to Split Array/Solution.java index 6ceefc773f59d..556934624c361 100644 --- a/solution/2800-2899/2811.Check if it is Possible to Split Array/Solution.java +++ b/solution/2800-2899/2811.Check if it is Possible to Split Array/Solution.java @@ -1,33 +1,33 @@ -class Solution { - private Boolean[][] f; - private int[] s; - private int m; - - public boolean canSplitArray(List nums, int m) { - int n = nums.size(); - f = new Boolean[n][n]; - s = new int[n + 1]; - for (int i = 1; i <= n; ++i) { - s[i] = s[i - 1] + nums.get(i - 1); - } - this.m = m; - return dfs(0, n - 1); - } - - private boolean dfs(int i, int j) { - if (i == j) { - return true; - } - if (f[i][j] != null) { - return f[i][j]; - } - for (int k = i; k < j; ++k) { - boolean a = k == i || s[k + 1] - s[i] >= m; - boolean b = k == j - 1 || s[j + 1] - s[k + 1] >= m; - if (a && b && dfs(i, k) && dfs(k + 1, j)) { - return f[i][j] = true; - } - } - return f[i][j] = false; - } +class Solution { + private Boolean[][] f; + private int[] s; + private int m; + + public boolean canSplitArray(List nums, int m) { + int n = nums.size(); + f = new Boolean[n][n]; + s = new int[n + 1]; + for (int i = 1; i <= n; ++i) { + s[i] = s[i - 1] + nums.get(i - 1); + } + this.m = m; + return dfs(0, n - 1); + } + + private boolean dfs(int i, int j) { + if (i == j) { + return true; + } + if (f[i][j] != null) { + return f[i][j]; + } + for (int k = i; k < j; ++k) { + boolean a = k == i || s[k + 1] - s[i] >= m; + boolean b = k == j - 1 || s[j + 1] - s[k + 1] >= m; + if (a && b && dfs(i, k) && dfs(k + 1, j)) { + return f[i][j] = true; + } + } + return f[i][j] = false; + } } \ No newline at end of file diff --git a/solution/2800-2899/2811.Check if it is Possible to Split Array/Solution.py b/solution/2800-2899/2811.Check if it is Possible to Split Array/Solution.py index 0cc0a4f213149..bb59588e3d03b 100644 --- a/solution/2800-2899/2811.Check if it is Possible to Split Array/Solution.py +++ b/solution/2800-2899/2811.Check if it is Possible to Split Array/Solution.py @@ -1,15 +1,15 @@ -class Solution: - def canSplitArray(self, nums: List[int], m: int) -> bool: - @cache - def dfs(i: int, j: int) -> bool: - if i == j: - return True - for k in range(i, j): - a = k == i or s[k + 1] - s[i] >= m - b = k == j - 1 or s[j + 1] - s[k + 1] >= m - if a and b and dfs(i, k) and dfs(k + 1, j): - return True - return False - - s = list(accumulate(nums, initial=0)) - return dfs(0, len(nums) - 1) +class Solution: + def canSplitArray(self, nums: List[int], m: int) -> bool: + @cache + def dfs(i: int, j: int) -> bool: + if i == j: + return True + for k in range(i, j): + a = k == i or s[k + 1] - s[i] >= m + b = k == j - 1 or s[j + 1] - s[k + 1] >= m + if a and b and dfs(i, k) and dfs(k + 1, j): + return True + return False + + s = list(accumulate(nums, initial=0)) + return dfs(0, len(nums) - 1) diff --git a/solution/2800-2899/2811.Check if it is Possible to Split Array/Solution2.ts b/solution/2800-2899/2811.Check if it is Possible to Split Array/Solution2.ts new file mode 100644 index 0000000000000..18bb1483e3be1 --- /dev/null +++ b/solution/2800-2899/2811.Check if it is Possible to Split Array/Solution2.ts @@ -0,0 +1,12 @@ +function canSplitArray(nums: number[], m: number): boolean { + const n = nums.length; + if (n <= 2) { + return true; + } + for (let i = 1; i < n; i++) { + if (nums[i - 1] + nums[i] >= m) { + return true; + } + } + return false; +} diff --git a/solution/2800-2899/2812.Find the Safest Path in a Grid/Solution.cpp b/solution/2800-2899/2812.Find the Safest Path in a Grid/Solution.cpp index efd770ca3d355..1bf9094dfea3d 100644 --- a/solution/2800-2899/2812.Find the Safest Path in a Grid/Solution.cpp +++ b/solution/2800-2899/2812.Find the Safest Path in a Grid/Solution.cpp @@ -1,78 +1,78 @@ -class UnionFind { -public: - vector p; - int n; - - UnionFind(int _n) - : n(_n) - , p(_n) { - iota(p.begin(), p.end(), 0); - } - - bool unite(int a, int b) { - int pa = find(a), pb = find(b); - if (pa == pb) return false; - p[pa] = pb; - --n; - return true; - } - - int find(int x) { - if (p[x] != x) p[x] = find(p[x]); - return p[x]; - } -}; - -class Solution { -public: - int maximumSafenessFactor(vector>& grid) { - int n = grid.size(); - if (grid[0][0] || grid[n - 1][n - 1]) { - return 0; - } - queue> q; - int dist[n][n]; - memset(dist, 0x3f, sizeof(dist)); - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j]) { - dist[i][j] = 0; - q.emplace(i, j); - } - } - } - int dirs[5] = {-1, 0, 1, 0, -1}; - while (!q.empty()) { - auto [i, j] = q.front(); - q.pop(); - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < n && y >= 0 && y < n && dist[x][y] == 0x3f3f3f3f) { - dist[x][y] = dist[i][j] + 1; - q.emplace(x, y); - } - } - } - vector> t; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - t.emplace_back(dist[i][j], i, j); - } - } - sort(t.begin(), t.end()); - reverse(t.begin(), t.end()); - UnionFind uf(n * n); - for (auto [d, i, j] : t) { - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < n && y >= 0 && y < n && dist[x][y] >= d) { - uf.unite(i * n + j, x * n + y); - } - } - if (uf.find(0) == uf.find(n * n - 1)) { - return d; - } - } - return 0; - } +class UnionFind { +public: + vector p; + int n; + + UnionFind(int _n) + : n(_n) + , p(_n) { + iota(p.begin(), p.end(), 0); + } + + bool unite(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) return false; + p[pa] = pb; + --n; + return true; + } + + int find(int x) { + if (p[x] != x) p[x] = find(p[x]); + return p[x]; + } +}; + +class Solution { +public: + int maximumSafenessFactor(vector>& grid) { + int n = grid.size(); + if (grid[0][0] || grid[n - 1][n - 1]) { + return 0; + } + queue> q; + int dist[n][n]; + memset(dist, 0x3f, sizeof(dist)); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j]) { + dist[i][j] = 0; + q.emplace(i, j); + } + } + } + int dirs[5] = {-1, 0, 1, 0, -1}; + while (!q.empty()) { + auto [i, j] = q.front(); + q.pop(); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < n && y >= 0 && y < n && dist[x][y] == 0x3f3f3f3f) { + dist[x][y] = dist[i][j] + 1; + q.emplace(x, y); + } + } + } + vector> t; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + t.emplace_back(dist[i][j], i, j); + } + } + sort(t.begin(), t.end()); + reverse(t.begin(), t.end()); + UnionFind uf(n * n); + for (auto [d, i, j] : t) { + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < n && y >= 0 && y < n && dist[x][y] >= d) { + uf.unite(i * n + j, x * n + y); + } + } + if (uf.find(0) == uf.find(n * n - 1)) { + return d; + } + } + return 0; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2812.Find the Safest Path in a Grid/Solution.java b/solution/2800-2899/2812.Find the Safest Path in a Grid/Solution.java index f87da5a1e1009..dbc3648a8ca22 100644 --- a/solution/2800-2899/2812.Find the Safest Path in a Grid/Solution.java +++ b/solution/2800-2899/2812.Find the Safest Path in a Grid/Solution.java @@ -1,86 +1,86 @@ -class Solution { - public int maximumSafenessFactor(List> grid) { - int n = grid.size(); - if (grid.get(0).get(0) == 1 || grid.get(n - 1).get(n - 1) == 1) { - return 0; - } - Deque q = new ArrayDeque<>(); - int[][] dist = new int[n][n]; - final int inf = 1 << 30; - for (int[] d : dist) { - Arrays.fill(d, inf); - } - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (grid.get(i).get(j) == 1) { - dist[i][j] = 0; - q.offer(new int[] {i, j}); - } - } - } - int[] dirs = {-1, 0, 1, 0, -1}; - while (!q.isEmpty()) { - int[] p = q.poll(); - int i = p[0], j = p[1]; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < n && y >= 0 && y < n && dist[x][y] == inf) { - dist[x][y] = dist[i][j] + 1; - q.offer(new int[] {x, y}); - } - } - } - List t = new ArrayList<>(); - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - t.add(new int[] {dist[i][j], i, j}); - } - } - t.sort((a, b) -> Integer.compare(b[0], a[0])); - UnionFind uf = new UnionFind(n * n); - for (int[] p : t) { - int d = p[0], i = p[1], j = p[2]; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < n && y >= 0 && y < n && dist[x][y] >= d) { - uf.union(i * n + j, x * n + y); - } - } - if (uf.find(0) == uf.find(n * n - 1)) { - return d; - } - } - return 0; - } -} - -class UnionFind { - public int[] p; - public int n; - - public UnionFind(int n) { - p = new int[n]; - for (int i = 0; i < n; ++i) { - p[i] = i; - } - this.n = n; - } - - public boolean union(int a, int b) { - int pa = find(a); - int pb = find(b); - if (pa == pb) { - return false; - } - p[pa] = pb; - --n; - return true; - } - - public int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } +class Solution { + public int maximumSafenessFactor(List> grid) { + int n = grid.size(); + if (grid.get(0).get(0) == 1 || grid.get(n - 1).get(n - 1) == 1) { + return 0; + } + Deque q = new ArrayDeque<>(); + int[][] dist = new int[n][n]; + final int inf = 1 << 30; + for (int[] d : dist) { + Arrays.fill(d, inf); + } + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (grid.get(i).get(j) == 1) { + dist[i][j] = 0; + q.offer(new int[] {i, j}); + } + } + } + int[] dirs = {-1, 0, 1, 0, -1}; + while (!q.isEmpty()) { + int[] p = q.poll(); + int i = p[0], j = p[1]; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < n && y >= 0 && y < n && dist[x][y] == inf) { + dist[x][y] = dist[i][j] + 1; + q.offer(new int[] {x, y}); + } + } + } + List t = new ArrayList<>(); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + t.add(new int[] {dist[i][j], i, j}); + } + } + t.sort((a, b) -> Integer.compare(b[0], a[0])); + UnionFind uf = new UnionFind(n * n); + for (int[] p : t) { + int d = p[0], i = p[1], j = p[2]; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < n && y >= 0 && y < n && dist[x][y] >= d) { + uf.union(i * n + j, x * n + y); + } + } + if (uf.find(0) == uf.find(n * n - 1)) { + return d; + } + } + return 0; + } +} + +class UnionFind { + public int[] p; + public int n; + + public UnionFind(int n) { + p = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + } + this.n = n; + } + + public boolean union(int a, int b) { + int pa = find(a); + int pb = find(b); + if (pa == pb) { + return false; + } + p[pa] = pb; + --n; + return true; + } + + public int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } } \ No newline at end of file diff --git a/solution/2800-2899/2812.Find the Safest Path in a Grid/Solution.py b/solution/2800-2899/2812.Find the Safest Path in a Grid/Solution.py index 9ea753f0b2458..fcecde663f8e5 100644 --- a/solution/2800-2899/2812.Find the Safest Path in a Grid/Solution.py +++ b/solution/2800-2899/2812.Find the Safest Path in a Grid/Solution.py @@ -1,55 +1,55 @@ -class UnionFind: - def __init__(self, n): - self.p = list(range(n)) - self.size = [1] * n - - def find(self, x): - if self.p[x] != x: - self.p[x] = self.find(self.p[x]) - return self.p[x] - - def union(self, a, b): - pa, pb = self.find(a), self.find(b) - if pa == pb: - return False - if self.size[pa] > self.size[pb]: - self.p[pb] = pa - self.size[pa] += self.size[pb] - else: - self.p[pa] = pb - self.size[pb] += self.size[pa] - return True - - -class Solution: - def maximumSafenessFactor(self, grid: List[List[int]]) -> int: - n = len(grid) - if grid[0][0] or grid[n - 1][n - 1]: - return 0 - q = deque() - dist = [[inf] * n for _ in range(n)] - for i in range(n): - for j in range(n): - if grid[i][j]: - q.append((i, j)) - dist[i][j] = 0 - dirs = (-1, 0, 1, 0, -1) - while q: - i, j = q.popleft() - for a, b in pairwise(dirs): - x, y = i + a, j + b - if 0 <= x < n and 0 <= y < n and dist[x][y] == inf: - dist[x][y] = dist[i][j] + 1 - q.append((x, y)) - - q = ((dist[i][j], i, j) for i in range(n) for j in range(n)) - q = sorted(q, reverse=True) - uf = UnionFind(n * n) - for d, i, j in q: - for a, b in pairwise(dirs): - x, y = i + a, j + b - if 0 <= x < n and 0 <= y < n and dist[x][y] >= d: - uf.union(i * n + j, x * n + y) - if uf.find(0) == uf.find(n * n - 1): - return int(d) - return 0 +class UnionFind: + def __init__(self, n): + self.p = list(range(n)) + self.size = [1] * n + + def find(self, x): + if self.p[x] != x: + self.p[x] = self.find(self.p[x]) + return self.p[x] + + def union(self, a, b): + pa, pb = self.find(a), self.find(b) + if pa == pb: + return False + if self.size[pa] > self.size[pb]: + self.p[pb] = pa + self.size[pa] += self.size[pb] + else: + self.p[pa] = pb + self.size[pb] += self.size[pa] + return True + + +class Solution: + def maximumSafenessFactor(self, grid: List[List[int]]) -> int: + n = len(grid) + if grid[0][0] or grid[n - 1][n - 1]: + return 0 + q = deque() + dist = [[inf] * n for _ in range(n)] + for i in range(n): + for j in range(n): + if grid[i][j]: + q.append((i, j)) + dist[i][j] = 0 + dirs = (-1, 0, 1, 0, -1) + while q: + i, j = q.popleft() + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < n and 0 <= y < n and dist[x][y] == inf: + dist[x][y] = dist[i][j] + 1 + q.append((x, y)) + + q = ((dist[i][j], i, j) for i in range(n) for j in range(n)) + q = sorted(q, reverse=True) + uf = UnionFind(n * n) + for d, i, j in q: + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < n and 0 <= y < n and dist[x][y] >= d: + uf.union(i * n + j, x * n + y) + if uf.find(0) == uf.find(n * n - 1): + return int(d) + return 0 diff --git a/solution/2800-2899/2812.Find the Safest Path in a Grid/Solution2.ts b/solution/2800-2899/2812.Find the Safest Path in a Grid/Solution2.ts new file mode 100644 index 0000000000000..2959547f4a387 --- /dev/null +++ b/solution/2800-2899/2812.Find the Safest Path in a Grid/Solution2.ts @@ -0,0 +1,55 @@ +function maximumSafenessFactor(grid: number[][]): number { + const n = grid.length; + const g = Array.from({ length: n }, () => new Array(n).fill(-1)); + const vis = Array.from({ length: n }, () => new Array(n).fill(false)); + let q: [number, number][] = []; + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === 1) { + q.push([i, j]); + } + } + } + let level = 0; + while (q.length) { + const t: [number, number][] = []; + for (const [x, y] of q) { + if (x < 0 || y < 0 || x === n || y === n || g[x][y] !== -1) { + continue; + } + g[x][y] = level; + t.push([x + 1, y]); + t.push([x - 1, y]); + t.push([x, y + 1]); + t.push([x, y - 1]); + } + q = t; + level++; + } + const dfs = (i: number, j: number, v: number) => { + if (i < 0 || j < 0 || i === n || j === n || vis[i][j] || g[i][j] <= v) { + return false; + } + vis[i][j] = true; + return ( + (i === n - 1 && j === n - 1) || + dfs(i + 1, j, v) || + dfs(i, j + 1, v) || + dfs(i - 1, j, v) || + dfs(i, j - 1, v) + ); + }; + + let left = 0; + let right = level; + while (left < right) { + vis.forEach(v => v.fill(false)); + const mid = (left + right) >>> 1; + if (dfs(0, 0, mid)) { + left = mid + 1; + } else { + right = mid; + } + } + return right; +} diff --git a/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/Solution.cpp b/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/Solution.cpp index a63135c94bc76..f3070a085d105 100644 --- a/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/Solution.cpp +++ b/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/Solution.cpp @@ -1,33 +1,33 @@ -class Solution { -public: - long long findMaximumElegance(vector>& items, int k) { - sort(items.begin(), items.end(), [](const vector& a, const vector& b) { - return a[0] > b[0]; - }); - long long tot = 0; - unordered_set vis; - stack dup; - for (int i = 0; i < k; ++i) { - int p = items[i][0], c = items[i][1]; - tot += p; - if (vis.count(c)) { - dup.push(p); - } else { - vis.insert(c); - } - } - int n = items.size(); - long long ans = tot + 1LL * vis.size() * vis.size(); - for (int i = k; i < n; ++i) { - int p = items[i][0], c = items[i][1]; - if (vis.count(c) || dup.empty()) { - continue; - } - vis.insert(c); - tot += p - dup.top(); - dup.pop(); - ans = max(ans, tot + (long long) (1LL * vis.size() * vis.size())); - } - return ans; - } +class Solution { +public: + long long findMaximumElegance(vector>& items, int k) { + sort(items.begin(), items.end(), [](const vector& a, const vector& b) { + return a[0] > b[0]; + }); + long long tot = 0; + unordered_set vis; + stack dup; + for (int i = 0; i < k; ++i) { + int p = items[i][0], c = items[i][1]; + tot += p; + if (vis.count(c)) { + dup.push(p); + } else { + vis.insert(c); + } + } + int n = items.size(); + long long ans = tot + 1LL * vis.size() * vis.size(); + for (int i = k; i < n; ++i) { + int p = items[i][0], c = items[i][1]; + if (vis.count(c) || dup.empty()) { + continue; + } + vis.insert(c); + tot += p - dup.top(); + dup.pop(); + ans = max(ans, tot + (long long) (1LL * vis.size() * vis.size())); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/Solution.java b/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/Solution.java index a2d8c2b77d1f1..f4cebf66efc9d 100644 --- a/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/Solution.java +++ b/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/Solution.java @@ -1,27 +1,27 @@ -class Solution { - public long findMaximumElegance(int[][] items, int k) { - Arrays.sort(items, (a, b) -> b[0] - a[0]); - int n = items.length; - long tot = 0; - Set vis = new HashSet<>(); - Deque dup = new ArrayDeque<>(); - for (int i = 0; i < k; ++i) { - int p = items[i][0], c = items[i][1]; - tot += p; - if (!vis.add(c)) { - dup.push(p); - } - } - long ans = tot + (long) vis.size() * vis.size(); - for (int i = k; i < n; ++i) { - int p = items[i][0], c = items[i][1]; - if (vis.contains(c) || dup.isEmpty()) { - continue; - } - vis.add(c); - tot += p - dup.pop(); - ans = Math.max(ans, tot + (long) vis.size() * vis.size()); - } - return ans; - } +class Solution { + public long findMaximumElegance(int[][] items, int k) { + Arrays.sort(items, (a, b) -> b[0] - a[0]); + int n = items.length; + long tot = 0; + Set vis = new HashSet<>(); + Deque dup = new ArrayDeque<>(); + for (int i = 0; i < k; ++i) { + int p = items[i][0], c = items[i][1]; + tot += p; + if (!vis.add(c)) { + dup.push(p); + } + } + long ans = tot + (long) vis.size() * vis.size(); + for (int i = k; i < n; ++i) { + int p = items[i][0], c = items[i][1]; + if (vis.contains(c) || dup.isEmpty()) { + continue; + } + vis.add(c); + tot += p - dup.pop(); + ans = Math.max(ans, tot + (long) vis.size() * vis.size()); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/Solution.py b/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/Solution.py index e7bf274f689d2..d12b5148ee265 100644 --- a/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/Solution.py +++ b/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/Solution.py @@ -1,20 +1,20 @@ -class Solution: - def findMaximumElegance(self, items: List[List[int]], k: int) -> int: - items.sort(key=lambda x: -x[0]) - tot = 0 - vis = set() - dup = [] - for p, c in items[:k]: - tot += p - if c not in vis: - vis.add(c) - else: - dup.append(p) - ans = tot + len(vis) ** 2 - for p, c in items[k:]: - if c in vis or not dup: - continue - vis.add(c) - tot += p - dup.pop() - ans = max(ans, tot + len(vis) ** 2) - return ans +class Solution: + def findMaximumElegance(self, items: List[List[int]], k: int) -> int: + items.sort(key=lambda x: -x[0]) + tot = 0 + vis = set() + dup = [] + for p, c in items[:k]: + tot += p + if c not in vis: + vis.add(c) + else: + dup.append(p) + ans = tot + len(vis) ** 2 + for p, c in items[k:]: + if c in vis or not dup: + continue + vis.add(c) + tot += p - dup.pop() + ans = max(ans, tot + len(vis) ** 2) + return ans diff --git a/solution/2800-2899/2815.Max Pair Sum in an Array/Solution.cpp b/solution/2800-2899/2815.Max Pair Sum in an Array/Solution.cpp index 4ad1f853da63a..dec4332829ac7 100644 --- a/solution/2800-2899/2815.Max Pair Sum in an Array/Solution.cpp +++ b/solution/2800-2899/2815.Max Pair Sum in an Array/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - int maxSum(vector& nums) { - int ans = -1; - int n = nums.size(); - auto f = [](int x) { - int y = 0; - for (; x; x /= 10) { - y = max(y, x % 10); - } - return y; - }; - for (int i = 0; i < n; ++i) { - for (int j = i + 1; j < n; ++j) { - int v = nums[i] + nums[j]; - if (ans < v && f(nums[i]) == f(nums[j])) { - ans = v; - } - } - } - return ans; - } +class Solution { +public: + int maxSum(vector& nums) { + int ans = -1; + int n = nums.size(); + auto f = [](int x) { + int y = 0; + for (; x; x /= 10) { + y = max(y, x % 10); + } + return y; + }; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + int v = nums[i] + nums[j]; + if (ans < v && f(nums[i]) == f(nums[j])) { + ans = v; + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2815.Max Pair Sum in an Array/Solution.java b/solution/2800-2899/2815.Max Pair Sum in an Array/Solution.java index 375cd01dece65..0b3f25343f0cb 100644 --- a/solution/2800-2899/2815.Max Pair Sum in an Array/Solution.java +++ b/solution/2800-2899/2815.Max Pair Sum in an Array/Solution.java @@ -1,23 +1,23 @@ -class Solution { - public int maxSum(int[] nums) { - int ans = -1; - int n = nums.length; - for (int i = 0; i < n; ++i) { - for (int j = i + 1; j < n; ++j) { - int v = nums[i] + nums[j]; - if (ans < v && f(nums[i]) == f(nums[j])) { - ans = v; - } - } - } - return ans; - } - - private int f(int x) { - int y = 0; - for (; x > 0; x /= 10) { - y = Math.max(y, x % 10); - } - return y; - } +class Solution { + public int maxSum(int[] nums) { + int ans = -1; + int n = nums.length; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + int v = nums[i] + nums[j]; + if (ans < v && f(nums[i]) == f(nums[j])) { + ans = v; + } + } + } + return ans; + } + + private int f(int x) { + int y = 0; + for (; x > 0; x /= 10) { + y = Math.max(y, x % 10); + } + return y; + } } \ No newline at end of file diff --git a/solution/2800-2899/2815.Max Pair Sum in an Array/Solution.py b/solution/2800-2899/2815.Max Pair Sum in an Array/Solution.py index b188180e7a518..45a85ce4c6545 100644 --- a/solution/2800-2899/2815.Max Pair Sum in an Array/Solution.py +++ b/solution/2800-2899/2815.Max Pair Sum in an Array/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def maxSum(self, nums: List[int]) -> int: - ans = -1 - for i, x in enumerate(nums): - for y in nums[i + 1 :]: - v = x + y - if ans < v and max(str(x)) == max(str(y)): - ans = v - return ans +class Solution: + def maxSum(self, nums: List[int]) -> int: + ans = -1 + for i, x in enumerate(nums): + for y in nums[i + 1 :]: + v = x + y + if ans < v and max(str(x)) == max(str(y)): + ans = v + return ans diff --git a/solution/2800-2899/2816.Double a Number Represented as a Linked List/Solution.cpp b/solution/2800-2899/2816.Double a Number Represented as a Linked List/Solution.cpp index 93ab0afd0a8e4..e2da20e42797b 100644 --- a/solution/2800-2899/2816.Double a Number Represented as a Linked List/Solution.cpp +++ b/solution/2800-2899/2816.Double a Number Represented as a Linked List/Solution.cpp @@ -1,42 +1,42 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* doubleIt(ListNode* head) { - head = reverse(head); - ListNode* dummy = new ListNode(); - ListNode* cur = dummy; - int mul = 2, carry = 0; - while (head) { - int x = head->val * mul + carry; - carry = x / 10; - cur->next = new ListNode(x % 10); - cur = cur->next; - head = head->next; - } - if (carry) { - cur->next = new ListNode(carry); - } - return reverse(dummy->next); - } - - ListNode* reverse(ListNode* head) { - ListNode* dummy = new ListNode(); - ListNode* cur = head; - while (cur) { - ListNode* next = cur->next; - cur->next = dummy->next; - dummy->next = cur; - cur = next; - } - return dummy->next; - } +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* doubleIt(ListNode* head) { + head = reverse(head); + ListNode* dummy = new ListNode(); + ListNode* cur = dummy; + int mul = 2, carry = 0; + while (head) { + int x = head->val * mul + carry; + carry = x / 10; + cur->next = new ListNode(x % 10); + cur = cur->next; + head = head->next; + } + if (carry) { + cur->next = new ListNode(carry); + } + return reverse(dummy->next); + } + + ListNode* reverse(ListNode* head) { + ListNode* dummy = new ListNode(); + ListNode* cur = head; + while (cur) { + ListNode* next = cur->next; + cur->next = dummy->next; + dummy->next = cur; + cur = next; + } + return dummy->next; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2816.Double a Number Represented as a Linked List/Solution.java b/solution/2800-2899/2816.Double a Number Represented as a Linked List/Solution.java index 41421c9a21fda..9c007a01bbca7 100644 --- a/solution/2800-2899/2816.Double a Number Represented as a Linked List/Solution.java +++ b/solution/2800-2899/2816.Double a Number Represented as a Linked List/Solution.java @@ -1,41 +1,41 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode doubleIt(ListNode head) { - head = reverse(head); - ListNode dummy = new ListNode(); - ListNode cur = dummy; - int mul = 2, carry = 0; - while (head != null) { - int x = head.val * mul + carry; - carry = x / 10; - cur.next = new ListNode(x % 10); - cur = cur.next; - head = head.next; - } - if (carry > 0) { - cur.next = new ListNode(carry); - } - return reverse(dummy.next); - } - - private ListNode reverse(ListNode head) { - ListNode dummy = new ListNode(); - ListNode cur = head; - while (cur != null) { - ListNode next = cur.next; - cur.next = dummy.next; - dummy.next = cur; - cur = next; - } - return dummy.next; - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode doubleIt(ListNode head) { + head = reverse(head); + ListNode dummy = new ListNode(); + ListNode cur = dummy; + int mul = 2, carry = 0; + while (head != null) { + int x = head.val * mul + carry; + carry = x / 10; + cur.next = new ListNode(x % 10); + cur = cur.next; + head = head.next; + } + if (carry > 0) { + cur.next = new ListNode(carry); + } + return reverse(dummy.next); + } + + private ListNode reverse(ListNode head) { + ListNode dummy = new ListNode(); + ListNode cur = head; + while (cur != null) { + ListNode next = cur.next; + cur.next = dummy.next; + dummy.next = cur; + cur = next; + } + return dummy.next; + } } \ No newline at end of file diff --git a/solution/2800-2899/2816.Double a Number Represented as a Linked List/Solution.py b/solution/2800-2899/2816.Double a Number Represented as a Linked List/Solution.py index 894c94e67c494..e9c3e799572bd 100644 --- a/solution/2800-2899/2816.Double a Number Represented as a Linked List/Solution.py +++ b/solution/2800-2899/2816.Double a Number Represented as a Linked List/Solution.py @@ -1,29 +1,29 @@ -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]: - def reverse(head): - dummy = ListNode() - cur = head - while cur: - next = cur.next - cur.next = dummy.next - dummy.next = cur - cur = next - return dummy.next - - head = reverse(head) - dummy = cur = ListNode() - mul, carry = 2, 0 - while head: - x = head.val * mul + carry - carry = x // 10 - cur.next = ListNode(x % 10) - cur = cur.next - head = head.next - if carry: - cur.next = ListNode(carry) - return reverse(dummy.next) +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]: + def reverse(head): + dummy = ListNode() + cur = head + while cur: + next = cur.next + cur.next = dummy.next + dummy.next = cur + cur = next + return dummy.next + + head = reverse(head) + dummy = cur = ListNode() + mul, carry = 2, 0 + while head: + x = head.val * mul + carry + carry = x // 10 + cur.next = ListNode(x % 10) + cur = cur.next + head = head.next + if carry: + cur.next = ListNode(carry) + return reverse(dummy.next) diff --git a/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/Solution.cpp b/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/Solution.cpp index ea56a62a86e2d..d30879a541785 100644 --- a/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/Solution.cpp +++ b/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/Solution.cpp @@ -1,19 +1,19 @@ -class Solution { -public: - int minAbsoluteDifference(vector& nums, int x) { - int ans = 1 << 30; - multiset s; - for (int i = x; i < nums.size(); ++i) { - s.insert(nums[i - x]); - auto it = s.lower_bound(nums[i]); - if (it != s.end()) { - ans = min(ans, *it - nums[i]); - } - if (it != s.begin()) { - --it; - ans = min(ans, nums[i] - *it); - } - } - return ans; - } +class Solution { +public: + int minAbsoluteDifference(vector& nums, int x) { + int ans = 1 << 30; + multiset s; + for (int i = x; i < nums.size(); ++i) { + s.insert(nums[i - x]); + auto it = s.lower_bound(nums[i]); + if (it != s.end()) { + ans = min(ans, *it - nums[i]); + } + if (it != s.begin()) { + --it; + ans = min(ans, nums[i] - *it); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/Solution.java b/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/Solution.java index cb8291ebb330d..05b4232b3b1bb 100644 --- a/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/Solution.java +++ b/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/Solution.java @@ -1,18 +1,18 @@ -class Solution { - public int minAbsoluteDifference(List nums, int x) { - TreeMap tm = new TreeMap<>(); - int ans = 1 << 30; - for (int i = x; i < nums.size(); ++i) { - tm.merge(nums.get(i - x), 1, Integer::sum); - Integer key = tm.ceilingKey(nums.get(i)); - if (key != null) { - ans = Math.min(ans, key - nums.get(i)); - } - key = tm.floorKey(nums.get(i)); - if (key != null) { - ans = Math.min(ans, nums.get(i) - key); - } - } - return ans; - } +class Solution { + public int minAbsoluteDifference(List nums, int x) { + TreeMap tm = new TreeMap<>(); + int ans = 1 << 30; + for (int i = x; i < nums.size(); ++i) { + tm.merge(nums.get(i - x), 1, Integer::sum); + Integer key = tm.ceilingKey(nums.get(i)); + if (key != null) { + ans = Math.min(ans, key - nums.get(i)); + } + key = tm.floorKey(nums.get(i)); + if (key != null) { + ans = Math.min(ans, nums.get(i) - key); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/Solution.py b/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/Solution.py index 2c1697429e0e5..5b0f30f929f7d 100644 --- a/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/Solution.py +++ b/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/Solution.py @@ -1,15 +1,15 @@ -from sortedcontainers import SortedList - - -class Solution: - def minAbsoluteDifference(self, nums: List[int], x: int) -> int: - sl = SortedList() - ans = inf - for i in range(x, len(nums)): - sl.add(nums[i - x]) - j = bisect_left(sl, nums[i]) - if j < len(sl): - ans = min(ans, sl[j] - nums[i]) - if j: - ans = min(ans, nums[i] - sl[j - 1]) - return ans +from sortedcontainers import SortedList + + +class Solution: + def minAbsoluteDifference(self, nums: List[int], x: int) -> int: + sl = SortedList() + ans = inf + for i in range(x, len(nums)): + sl.add(nums[i - x]) + j = bisect_left(sl, nums[i]) + if j < len(sl): + ans = min(ans, sl[j] - nums[i]) + if j: + ans = min(ans, nums[i] - sl[j - 1]) + return ans diff --git a/solution/2800-2899/2818.Apply Operations to Maximize Score/Solution.cpp b/solution/2800-2899/2818.Apply Operations to Maximize Score/Solution.cpp index 5dd4297032ef9..ab4b65a425615 100644 --- a/solution/2800-2899/2818.Apply Operations to Maximize Score/Solution.cpp +++ b/solution/2800-2899/2818.Apply Operations to Maximize Score/Solution.cpp @@ -1,76 +1,76 @@ -class Solution { -public: - int maximumScore(vector& nums, int k) { - const int mod = 1e9 + 7; - int n = nums.size(); - vector> arr(n); - for (int i = 0; i < n; ++i) { - arr[i] = {i, primeFactors(nums[i]), nums[i]}; - } - vector left(n, -1); - vector right(n, n); - stack stk; - for (auto [i, f, _] : arr) { - while (!stk.empty() && get<1>(arr[stk.top()]) < f) { - stk.pop(); - } - if (!stk.empty()) { - left[i] = stk.top(); - } - stk.push(i); - } - stk = stack(); - for (int i = n - 1; ~i; --i) { - int f = get<1>(arr[i]); - while (!stk.empty() && get<1>(arr[stk.top()]) <= f) { - stk.pop(); - } - if (!stk.empty()) { - right[i] = stk.top(); - } - stk.push(i); - } - sort(arr.begin(), arr.end(), [](const auto& lhs, const auto& rhs) { - return get<2>(rhs) < get<2>(lhs); - }); - long long ans = 1; - auto qpow = [&](long long a, int n) { - long long ans = 1; - for (; n; n >>= 1) { - if (n & 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return ans; - }; - for (auto [i, _, x] : arr) { - int l = left[i], r = right[i]; - long long cnt = 1LL * (i - l) * (r - i); - if (cnt <= k) { - ans = ans * qpow(x, cnt) % mod; - k -= cnt; - } else { - ans = ans * qpow(x, k) % mod; - break; - } - } - return ans; - } - - int primeFactors(int n) { - int i = 2; - unordered_set ans; - while (i <= n / i) { - while (n % i == 0) { - ans.insert(i); - n /= i; - } - ++i; - } - if (n > 1) { - ans.insert(n); - } - return ans.size(); - } +class Solution { +public: + int maximumScore(vector& nums, int k) { + const int mod = 1e9 + 7; + int n = nums.size(); + vector> arr(n); + for (int i = 0; i < n; ++i) { + arr[i] = {i, primeFactors(nums[i]), nums[i]}; + } + vector left(n, -1); + vector right(n, n); + stack stk; + for (auto [i, f, _] : arr) { + while (!stk.empty() && get<1>(arr[stk.top()]) < f) { + stk.pop(); + } + if (!stk.empty()) { + left[i] = stk.top(); + } + stk.push(i); + } + stk = stack(); + for (int i = n - 1; ~i; --i) { + int f = get<1>(arr[i]); + while (!stk.empty() && get<1>(arr[stk.top()]) <= f) { + stk.pop(); + } + if (!stk.empty()) { + right[i] = stk.top(); + } + stk.push(i); + } + sort(arr.begin(), arr.end(), [](const auto& lhs, const auto& rhs) { + return get<2>(rhs) < get<2>(lhs); + }); + long long ans = 1; + auto qpow = [&](long long a, int n) { + long long ans = 1; + for (; n; n >>= 1) { + if (n & 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return ans; + }; + for (auto [i, _, x] : arr) { + int l = left[i], r = right[i]; + long long cnt = 1LL * (i - l) * (r - i); + if (cnt <= k) { + ans = ans * qpow(x, cnt) % mod; + k -= cnt; + } else { + ans = ans * qpow(x, k) % mod; + break; + } + } + return ans; + } + + int primeFactors(int n) { + int i = 2; + unordered_set ans; + while (i <= n / i) { + while (n % i == 0) { + ans.insert(i); + n /= i; + } + ++i; + } + if (n > 1) { + ans.insert(n); + } + return ans.size(); + } }; \ No newline at end of file diff --git a/solution/2800-2899/2818.Apply Operations to Maximize Score/Solution.java b/solution/2800-2899/2818.Apply Operations to Maximize Score/Solution.java index 04cf47eadcc29..456e22ad9fa65 100644 --- a/solution/2800-2899/2818.Apply Operations to Maximize Score/Solution.java +++ b/solution/2800-2899/2818.Apply Operations to Maximize Score/Solution.java @@ -1,79 +1,79 @@ -class Solution { - private final int mod = (int) 1e9 + 7; - - public int maximumScore(List nums, int k) { - int n = nums.size(); - int[][] arr = new int[n][0]; - for (int i = 0; i < n; ++i) { - arr[i] = new int[] {i, primeFactors(nums.get(i)), nums.get(i)}; - } - int[] left = new int[n]; - int[] right = new int[n]; - Arrays.fill(left, -1); - Arrays.fill(right, n); - Deque stk = new ArrayDeque<>(); - for (int[] e : arr) { - int i = e[0], f = e[1]; - while (!stk.isEmpty() && arr[stk.peek()][1] < f) { - stk.pop(); - } - if (!stk.isEmpty()) { - left[i] = stk.peek(); - } - stk.push(i); - } - stk.clear(); - for (int i = n - 1; i >= 0; --i) { - int f = arr[i][1]; - while (!stk.isEmpty() && arr[stk.peek()][1] <= f) { - stk.pop(); - } - if (!stk.isEmpty()) { - right[i] = stk.peek(); - } - stk.push(i); - } - Arrays.sort(arr, (a, b) -> b[2] - a[2]); - long ans = 1; - for (int[] e : arr) { - int i = e[0], x = e[2]; - int l = left[i], r = right[i]; - long cnt = (long) (i - l) * (r - i); - if (cnt <= k) { - ans = ans * qpow(x, cnt) % mod; - k -= cnt; - } else { - ans = ans * qpow(x, k) % mod; - break; - } - } - return (int) ans; - } - - private int primeFactors(int n) { - int i = 2; - Set ans = new HashSet<>(); - while (i <= n / i) { - while (n % i == 0) { - ans.add(i); - n /= i; - } - ++i; - } - if (n > 1) { - ans.add(n); - } - return ans.size(); - } - - private int qpow(long a, long n) { - long ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return (int) ans; - } +class Solution { + private final int mod = (int) 1e9 + 7; + + public int maximumScore(List nums, int k) { + int n = nums.size(); + int[][] arr = new int[n][0]; + for (int i = 0; i < n; ++i) { + arr[i] = new int[] {i, primeFactors(nums.get(i)), nums.get(i)}; + } + int[] left = new int[n]; + int[] right = new int[n]; + Arrays.fill(left, -1); + Arrays.fill(right, n); + Deque stk = new ArrayDeque<>(); + for (int[] e : arr) { + int i = e[0], f = e[1]; + while (!stk.isEmpty() && arr[stk.peek()][1] < f) { + stk.pop(); + } + if (!stk.isEmpty()) { + left[i] = stk.peek(); + } + stk.push(i); + } + stk.clear(); + for (int i = n - 1; i >= 0; --i) { + int f = arr[i][1]; + while (!stk.isEmpty() && arr[stk.peek()][1] <= f) { + stk.pop(); + } + if (!stk.isEmpty()) { + right[i] = stk.peek(); + } + stk.push(i); + } + Arrays.sort(arr, (a, b) -> b[2] - a[2]); + long ans = 1; + for (int[] e : arr) { + int i = e[0], x = e[2]; + int l = left[i], r = right[i]; + long cnt = (long) (i - l) * (r - i); + if (cnt <= k) { + ans = ans * qpow(x, cnt) % mod; + k -= cnt; + } else { + ans = ans * qpow(x, k) % mod; + break; + } + } + return (int) ans; + } + + private int primeFactors(int n) { + int i = 2; + Set ans = new HashSet<>(); + while (i <= n / i) { + while (n % i == 0) { + ans.add(i); + n /= i; + } + ++i; + } + if (n > 1) { + ans.add(n); + } + return ans.size(); + } + + private int qpow(long a, long n) { + long ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return (int) ans; + } } \ No newline at end of file diff --git a/solution/2800-2899/2818.Apply Operations to Maximize Score/Solution.py b/solution/2800-2899/2818.Apply Operations to Maximize Score/Solution.py index a11c7f6ca6dfe..f05a5aad427fd 100644 --- a/solution/2800-2899/2818.Apply Operations to Maximize Score/Solution.py +++ b/solution/2800-2899/2818.Apply Operations to Maximize Score/Solution.py @@ -1,49 +1,49 @@ -def primeFactors(n): - i = 2 - ans = set() - while i * i <= n: - while n % i == 0: - ans.add(i) - n //= i - i += 1 - if n > 1: - ans.add(n) - return len(ans) - - -class Solution: - def maximumScore(self, nums: List[int], k: int) -> int: - mod = 10**9 + 7 - arr = [(i, primeFactors(x), x) for i, x in enumerate(nums)] - n = len(nums) - - left = [-1] * n - right = [n] * n - stk = [] - for i, f, x in arr: - while stk and stk[-1][0] < f: - stk.pop() - if stk: - left[i] = stk[-1][1] - stk.append((f, i)) - - stk = [] - for i, f, x in arr[::-1]: - while stk and stk[-1][0] <= f: - stk.pop() - if stk: - right[i] = stk[-1][1] - stk.append((f, i)) - - arr.sort(key=lambda x: -x[2]) - ans = 1 - for i, f, x in arr: - l, r = left[i], right[i] - cnt = (i - l) * (r - i) - if cnt <= k: - ans = ans * pow(x, cnt, mod) % mod - k -= cnt - else: - ans = ans * pow(x, k, mod) % mod - break - return ans +def primeFactors(n): + i = 2 + ans = set() + while i * i <= n: + while n % i == 0: + ans.add(i) + n //= i + i += 1 + if n > 1: + ans.add(n) + return len(ans) + + +class Solution: + def maximumScore(self, nums: List[int], k: int) -> int: + mod = 10**9 + 7 + arr = [(i, primeFactors(x), x) for i, x in enumerate(nums)] + n = len(nums) + + left = [-1] * n + right = [n] * n + stk = [] + for i, f, x in arr: + while stk and stk[-1][0] < f: + stk.pop() + if stk: + left[i] = stk[-1][1] + stk.append((f, i)) + + stk = [] + for i, f, x in arr[::-1]: + while stk and stk[-1][0] <= f: + stk.pop() + if stk: + right[i] = stk[-1][1] + stk.append((f, i)) + + arr.sort(key=lambda x: -x[2]) + ans = 1 + for i, f, x in arr: + l, r = left[i], right[i] + cnt = (i - l) * (r - i) + if cnt <= k: + ans = ans * pow(x, cnt, mod) % mod + k -= cnt + else: + ans = ans * pow(x, k, mod) % mod + break + return ans diff --git a/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/Solution.cpp b/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/Solution.cpp index 7e6c457543816..a11b3919f9150 100644 --- a/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/Solution.cpp +++ b/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/Solution.cpp @@ -1,34 +1,34 @@ -class Solution { -public: - vector minimumRelativeLosses(vector& prices, vector>& queries) { - int n = prices.size(); - sort(prices.begin(), prices.end()); - long long s[n + 1]; - s[0] = 0; - for (int i = 1; i <= n; ++i) { - s[i] = s[i - 1] + prices[i - 1]; - } - auto f = [&](int k, int m) { - int l = 0, r = upper_bound(prices.begin(), prices.end(), k) - prices.begin(); - r = min(r, m); - while (l < r) { - int mid = (l + r) >> 1; - int right = m - mid; - if (prices[mid] < 2LL * k - prices[n - right]) { - l = mid + 1; - } else { - r = mid; - } - } - return l; - }; - vector ans; - for (auto& q : queries) { - int k = q[0], m = q[1]; - int l = f(k, m); - int r = m - l; - ans.push_back(s[l] + 2LL * k * r - (s[n] - s[n - r])); - } - return ans; - } +class Solution { +public: + vector minimumRelativeLosses(vector& prices, vector>& queries) { + int n = prices.size(); + sort(prices.begin(), prices.end()); + long long s[n + 1]; + s[0] = 0; + for (int i = 1; i <= n; ++i) { + s[i] = s[i - 1] + prices[i - 1]; + } + auto f = [&](int k, int m) { + int l = 0, r = upper_bound(prices.begin(), prices.end(), k) - prices.begin(); + r = min(r, m); + while (l < r) { + int mid = (l + r) >> 1; + int right = m - mid; + if (prices[mid] < 2LL * k - prices[n - right]) { + l = mid + 1; + } else { + r = mid; + } + } + return l; + }; + vector ans; + for (auto& q : queries) { + int k = q[0], m = q[1]; + int l = f(k, m); + int r = m - l; + ans.push_back(s[l] + 2LL * k * r - (s[n] - s[n - r])); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/Solution.java b/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/Solution.java index 5f0499959a254..101504bc22246 100644 --- a/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/Solution.java +++ b/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/Solution.java @@ -1,41 +1,41 @@ -class Solution { - private int n; - private int[] prices; - - public long[] minimumRelativeLosses(int[] prices, int[][] queries) { - n = prices.length; - Arrays.sort(prices); - this.prices = prices; - long[] s = new long[n + 1]; - for (int i = 0; i < n; ++i) { - s[i + 1] = s[i] + prices[i]; - } - int q = queries.length; - long[] ans = new long[q]; - for (int i = 0; i < q; ++i) { - int k = queries[i][0], m = queries[i][1]; - int l = f(k, m); - int r = m - l; - ans[i] = s[l] + 2L * k * r - (s[n] - s[n - r]); - } - return ans; - } - - private int f(int k, int m) { - int l = 0, r = Arrays.binarySearch(prices, k); - if (r < 0) { - r = -(r + 1); - } - r = Math.min(m, r); - while (l < r) { - int mid = (l + r) >> 1; - int right = m - mid; - if (prices[mid] < 2L * k - prices[n - right]) { - l = mid + 1; - } else { - r = mid; - } - } - return l; - } +class Solution { + private int n; + private int[] prices; + + public long[] minimumRelativeLosses(int[] prices, int[][] queries) { + n = prices.length; + Arrays.sort(prices); + this.prices = prices; + long[] s = new long[n + 1]; + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + prices[i]; + } + int q = queries.length; + long[] ans = new long[q]; + for (int i = 0; i < q; ++i) { + int k = queries[i][0], m = queries[i][1]; + int l = f(k, m); + int r = m - l; + ans[i] = s[l] + 2L * k * r - (s[n] - s[n - r]); + } + return ans; + } + + private int f(int k, int m) { + int l = 0, r = Arrays.binarySearch(prices, k); + if (r < 0) { + r = -(r + 1); + } + r = Math.min(m, r); + while (l < r) { + int mid = (l + r) >> 1; + int right = m - mid; + if (prices[mid] < 2L * k - prices[n - right]) { + l = mid + 1; + } else { + r = mid; + } + } + return l; + } } \ No newline at end of file diff --git a/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/Solution.py b/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/Solution.py index 9cc30b5b2f80a..4713d2db87de7 100644 --- a/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/Solution.py +++ b/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/Solution.py @@ -1,25 +1,25 @@ -class Solution: - def minimumRelativeLosses( - self, prices: List[int], queries: List[List[int]] - ) -> List[int]: - def f(k: int, m: int) -> int: - l, r = 0, min(m, bisect_right(prices, k)) - while l < r: - mid = (l + r) >> 1 - right = m - mid - if prices[mid] < 2 * k - prices[n - right]: - l = mid + 1 - else: - r = mid - return l - - prices.sort() - s = list(accumulate(prices, initial=0)) - ans = [] - n = len(prices) - for k, m in queries: - l = f(k, m) - r = m - l - loss = s[l] + 2 * k * r - (s[n] - s[n - r]) - ans.append(loss) - return ans +class Solution: + def minimumRelativeLosses( + self, prices: List[int], queries: List[List[int]] + ) -> List[int]: + def f(k: int, m: int) -> int: + l, r = 0, min(m, bisect_right(prices, k)) + while l < r: + mid = (l + r) >> 1 + right = m - mid + if prices[mid] < 2 * k - prices[n - right]: + l = mid + 1 + else: + r = mid + return l + + prices.sort() + s = list(accumulate(prices, initial=0)) + ans = [] + n = len(prices) + for k, m in queries: + l = f(k, m) + r = m - l + loss = s[l] + 2 * k * r - (s[n] - s[n - r]) + ans.append(loss) + return ans diff --git a/solution/2800-2899/2826.Sorting Three Groups/Solution.py b/solution/2800-2899/2826.Sorting Three Groups/Solution.py index 254580d561ea0..de3c3d426220f 100644 --- a/solution/2800-2899/2826.Sorting Three Groups/Solution.py +++ b/solution/2800-2899/2826.Sorting Three Groups/Solution.py @@ -1,19 +1,19 @@ class Solution: def minimumOperations(self, nums: List[int]) -> int: - f = [0] * 3 + f = g = h = 0 for x in nums: - g = [0] * 3 + ff = gg = hh = 0 if x == 1: - g[0] = f[0] - g[1] = min(f[:2]) + 1 - g[2] = min(f) + 1 + ff = f + gg = min(f, g) + 1 + hh = min(f, g, h) + 1 elif x == 2: - g[0] = f[0] + 1 - g[1] = min(f[:2]) - g[2] = min(f) + 1 + ff = f + 1 + gg = min(f, g) + hh = min(f, g, h) + 1 else: - g[0] = f[0] + 1 - g[1] = min(f[:2]) + 1 - g[2] = min(f) - f = g - return min(f) + ff = f + 1 + gg = min(f, g) + 1 + hh = min(f, g, h) + f, g, h = ff, gg, hh + return min(f, g, h) diff --git a/solution/2800-2899/2826.Sorting Three Groups/Solution2.py b/solution/2800-2899/2826.Sorting Three Groups/Solution2.py new file mode 100644 index 0000000000000..254580d561ea0 --- /dev/null +++ b/solution/2800-2899/2826.Sorting Three Groups/Solution2.py @@ -0,0 +1,19 @@ +class Solution: + def minimumOperations(self, nums: List[int]) -> int: + f = [0] * 3 + for x in nums: + g = [0] * 3 + if x == 1: + g[0] = f[0] + g[1] = min(f[:2]) + 1 + g[2] = min(f) + 1 + elif x == 2: + g[0] = f[0] + 1 + g[1] = min(f[:2]) + g[2] = min(f) + 1 + else: + g[0] = f[0] + 1 + g[1] = min(f[:2]) + 1 + g[2] = min(f) + f = g + return min(f) diff --git a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.cpp b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.cpp index 404f4a47ff27f..3033aedafd519 100644 --- a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.cpp +++ b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.cpp @@ -1,14 +1,10 @@ -class Solution { -public: - bool isAcronym(vector& words, string s) { - if (words.size() != s.size()) { - return false; - } - for (int i = 0; i < s.size(); ++i) { - if (words[i][0] != s[i]) { - return false; - } - } - return true; - } +class Solution { +public: + bool isAcronym(vector& words, string s) { + string t; + for (auto& w : words) { + t += w[0]; + } + return t == s; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.go b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.go index 0b489df8faff1..d988e77097bec 100644 --- a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.go +++ b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.go @@ -1,11 +1,7 @@ func isAcronym(words []string, s string) bool { - if len(words) != len(s) { - return false + t := []byte{} + for _, w := range words { + t = append(t, w[0]) } - for i := range s { - if words[i][0] != s[i] { - return false - } - } - return true + return string(t) == s } \ No newline at end of file diff --git a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.java b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.java index 2407554f77a39..65705fdccc821 100644 --- a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.java +++ b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.java @@ -1,13 +1,9 @@ -class Solution { - public boolean isAcronym(List words, String s) { - if (words.size() != s.length()) { - return false; - } - for (int i = 0; i < s.length(); ++i) { - if (words.get(i).charAt(0) != s.charAt(i)) { - return false; - } - } - return true; - } +class Solution { + public boolean isAcronym(List words, String s) { + StringBuilder t = new StringBuilder(); + for (var w : words) { + t.append(w.charAt(0)); + } + return t.toString().equals(s); + } } \ No newline at end of file diff --git a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.py b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.py index 0285f88e866b6..63d5531abf744 100644 --- a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.py +++ b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.py @@ -1,3 +1,3 @@ -class Solution: - def isAcronym(self, words: List[str], s: str) -> bool: - return len(words) == len(s) and all(w[0] == c for w, c in zip(words, s)) +class Solution: + def isAcronym(self, words: List[str], s: str) -> bool: + return "".join(w[0] for w in words) == s diff --git a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.rs b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.rs index e81d4986a82f3..3e1c7d53caac3 100644 --- a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.rs +++ b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.rs @@ -1,13 +1,8 @@ impl Solution { pub fn is_acronym(words: Vec, s: String) -> bool { - if words.len() != s.len() { - return false; - } - for (i, word) in words.iter().enumerate() { - if word.chars().next().unwrap_or_default() != s.chars().nth(i).unwrap_or_default() { - return false; - } - } - true + words + .iter() + .map(|w| w.chars().next().unwrap_or_default()) + .collect::() == s } } diff --git a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.ts b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.ts index 6517403796161..a1ef3f8a24b8d 100644 --- a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.ts +++ b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution.ts @@ -1,11 +1,3 @@ function isAcronym(words: string[], s: string): boolean { - if (words.length !== s.length) { - return false; - } - for (let i = 0; i < words.length; i++) { - if (words[i][0] !== s[i]) { - return false; - } - } - return true; + return words.map(w => w[0]).join('') === s; } diff --git a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution2.cpp b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution2.cpp new file mode 100644 index 0000000000000..80d632fe7a296 --- /dev/null +++ b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + bool isAcronym(vector& words, string s) { + if (words.size() != s.size()) { + return false; + } + for (int i = 0; i < s.size(); ++i) { + if (words[i][0] != s[i]) { + return false; + } + } + return true; + } +}; \ No newline at end of file diff --git a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution2.go b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution2.go new file mode 100644 index 0000000000000..0b489df8faff1 --- /dev/null +++ b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution2.go @@ -0,0 +1,11 @@ +func isAcronym(words []string, s string) bool { + if len(words) != len(s) { + return false + } + for i := range s { + if words[i][0] != s[i] { + return false + } + } + return true +} \ No newline at end of file diff --git a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution2.java b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution2.java new file mode 100644 index 0000000000000..f20de79f2c448 --- /dev/null +++ b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution2.java @@ -0,0 +1,13 @@ +class Solution { + public boolean isAcronym(List words, String s) { + if (words.size() != s.length()) { + return false; + } + for (int i = 0; i < s.length(); ++i) { + if (words.get(i).charAt(0) != s.charAt(i)) { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution2.py b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution2.py new file mode 100644 index 0000000000000..a8985ea1165f2 --- /dev/null +++ b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution2.py @@ -0,0 +1,3 @@ +class Solution: + def isAcronym(self, words: List[str], s: str) -> bool: + return len(words) == len(s) and all(w[0] == c for w, c in zip(words, s)) diff --git a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution2.rs b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution2.rs new file mode 100644 index 0000000000000..72283b89f3392 --- /dev/null +++ b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution2.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn is_acronym(words: Vec, s: String) -> bool { + if words.len() != s.len() { + return false; + } + for (i, w) in words.iter().enumerate() { + if w.chars().next().unwrap_or_default() != s.chars().nth(i).unwrap_or_default() { + return false; + } + } + true + } +} diff --git a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution2.ts b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution2.ts new file mode 100644 index 0000000000000..6517403796161 --- /dev/null +++ b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/Solution2.ts @@ -0,0 +1,11 @@ +function isAcronym(words: string[], s: string): boolean { + if (words.length !== s.length) { + return false; + } + for (let i = 0; i < words.length; i++) { + if (words[i][0] !== s[i]) { + return false; + } + } + return true; +} diff --git a/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/Solution.cpp b/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/Solution.cpp index b9602dd6233f1..3451c86c770f7 100644 --- a/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/Solution.cpp +++ b/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/Solution.cpp @@ -1,19 +1,19 @@ -class Solution { -public: - int minimumSum(int n, int k) { - int s = 0, i = 1; - bool vis[k + n * n + 1]; - memset(vis, false, sizeof(vis)); - while (n--) { - while (vis[i]) { - ++i; - } - vis[i] = true; - if (k >= i) { - vis[k - i] = true; - } - s += i; - } - return s; - } +class Solution { +public: + int minimumSum(int n, int k) { + int s = 0, i = 1; + bool vis[k + n * n + 1]; + memset(vis, false, sizeof(vis)); + while (n--) { + while (vis[i]) { + ++i; + } + vis[i] = true; + if (k >= i) { + vis[k - i] = true; + } + s += i; + } + return s; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/Solution.java b/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/Solution.java index 73a2284dad786..b1d79af8836e9 100644 --- a/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/Solution.java +++ b/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public int minimumSum(int n, int k) { - int s = 0, i = 1; - boolean[] vis = new boolean[k + n * n + 1]; - while (n-- > 0) { - while (vis[i]) { - ++i; - } - vis[i] = true; - if (k >= i) { - vis[k - i] = true; - } - s += i; - } - return s; - } +class Solution { + public int minimumSum(int n, int k) { + int s = 0, i = 1; + boolean[] vis = new boolean[k + n * n + 1]; + while (n-- > 0) { + while (vis[i]) { + ++i; + } + vis[i] = true; + if (k >= i) { + vis[k - i] = true; + } + s += i; + } + return s; + } } \ No newline at end of file diff --git a/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/Solution.py b/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/Solution.py index 4594f3166f2fa..a6632ca525725 100644 --- a/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/Solution.py +++ b/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def minimumSum(self, n: int, k: int) -> int: - s, i = 0, 1 - vis = set() - for _ in range(n): - while i in vis: - i += 1 - vis.add(i) - vis.add(k - i) - s += i - return s +class Solution: + def minimumSum(self, n: int, k: int) -> int: + s, i = 0, 1 + vis = set() + for _ in range(n): + while i in vis: + i += 1 + vis.add(i) + vis.add(k - i) + s += i + return s diff --git a/solution/2800-2899/2830.Maximize the Profit as the Salesman/Solution.cpp b/solution/2800-2899/2830.Maximize the Profit as the Salesman/Solution.cpp index 56432462a47b4..c28c595c02336 100644 --- a/solution/2800-2899/2830.Maximize the Profit as the Salesman/Solution.cpp +++ b/solution/2800-2899/2830.Maximize the Profit as the Salesman/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - int maximizeTheProfit(int n, vector>& offers) { - sort(offers.begin(), offers.end(), [](const vector& a, const vector& b) { - return a[1] < b[1]; - }); - n = offers.size(); - vector f(n + 1); - vector g; - for (auto& o : offers) { - g.push_back(o[1]); - } - for (int i = 1; i <= n; ++i) { - auto o = offers[i - 1]; - int j = lower_bound(g.begin(), g.end(), o[0]) - g.begin(); - f[i] = max(f[i - 1], f[j] + o[2]); - } - return f[n]; - } +class Solution { +public: + int maximizeTheProfit(int n, vector>& offers) { + sort(offers.begin(), offers.end(), [](const vector& a, const vector& b) { + return a[1] < b[1]; + }); + n = offers.size(); + vector f(n + 1); + vector g; + for (auto& o : offers) { + g.push_back(o[1]); + } + for (int i = 1; i <= n; ++i) { + auto o = offers[i - 1]; + int j = lower_bound(g.begin(), g.end(), o[0]) - g.begin(); + f[i] = max(f[i - 1], f[j] + o[2]); + } + return f[n]; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2830.Maximize the Profit as the Salesman/Solution.java b/solution/2800-2899/2830.Maximize the Profit as the Salesman/Solution.java index 5826122dce9ea..587b1b1b5be2b 100644 --- a/solution/2800-2899/2830.Maximize the Profit as the Salesman/Solution.java +++ b/solution/2800-2899/2830.Maximize the Profit as the Salesman/Solution.java @@ -1,30 +1,30 @@ -class Solution { - public int maximizeTheProfit(int n, List> offers) { - offers.sort((a, b) -> a.get(1) - b.get(1)); - n = offers.size(); - int[] f = new int[n + 1]; - int[] g = new int[n]; - for (int i = 0; i < n; ++i) { - g[i] = offers.get(i).get(1); - } - for (int i = 1; i <= n; ++i) { - var o = offers.get(i - 1); - int j = search(g, o.get(0)); - f[i] = Math.max(f[i - 1], f[j] + o.get(2)); - } - return f[n]; - } - - private int search(int[] nums, int x) { - int l = 0, r = nums.length; - while (l < r) { - int mid = (l + r) >> 1; - if (nums[mid] >= x) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } +class Solution { + public int maximizeTheProfit(int n, List> offers) { + offers.sort((a, b) -> a.get(1) - b.get(1)); + n = offers.size(); + int[] f = new int[n + 1]; + int[] g = new int[n]; + for (int i = 0; i < n; ++i) { + g[i] = offers.get(i).get(1); + } + for (int i = 1; i <= n; ++i) { + var o = offers.get(i - 1); + int j = search(g, o.get(0)); + f[i] = Math.max(f[i - 1], f[j] + o.get(2)); + } + return f[n]; + } + + private int search(int[] nums, int x) { + int l = 0, r = nums.length; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } } \ No newline at end of file diff --git a/solution/2800-2899/2830.Maximize the Profit as the Salesman/Solution.py b/solution/2800-2899/2830.Maximize the Profit as the Salesman/Solution.py index 6f7eeb04aaa58..52c35b4b62eab 100644 --- a/solution/2800-2899/2830.Maximize the Profit as the Salesman/Solution.py +++ b/solution/2800-2899/2830.Maximize the Profit as the Salesman/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def maximizeTheProfit(self, n: int, offers: List[List[int]]) -> int: - offers.sort(key=lambda x: x[1]) - f = [0] * (len(offers) + 1) - g = [x[1] for x in offers] - for i, (s, _, v) in enumerate(offers, 1): - j = bisect_left(g, s) - f[i] = max(f[i - 1], f[j] + v) - return f[-1] +class Solution: + def maximizeTheProfit(self, n: int, offers: List[List[int]]) -> int: + offers.sort(key=lambda x: x[1]) + f = [0] * (len(offers) + 1) + g = [x[1] for x in offers] + for i, (s, _, v) in enumerate(offers, 1): + j = bisect_left(g, s) + f[i] = max(f[i - 1], f[j] + v) + return f[-1] diff --git a/solution/2800-2899/2833.Furthest Point From Origin/Solution.cpp b/solution/2800-2899/2833.Furthest Point From Origin/Solution.cpp index 282045d49f997..26623378779d9 100644 --- a/solution/2800-2899/2833.Furthest Point From Origin/Solution.cpp +++ b/solution/2800-2899/2833.Furthest Point From Origin/Solution.cpp @@ -1,9 +1,9 @@ -class Solution { -public: - int furthestDistanceFromOrigin(string moves) { - auto cnt = [&](char c) { - return count(moves.begin(), moves.end(), c); - }; - return abs(cnt('L') - cnt('R')) + cnt('_'); - } +class Solution { +public: + int furthestDistanceFromOrigin(string moves) { + auto cnt = [&](char c) { + return count(moves.begin(), moves.end(), c); + }; + return abs(cnt('L') - cnt('R')) + cnt('_'); + } }; \ No newline at end of file diff --git a/solution/2800-2899/2833.Furthest Point From Origin/Solution.java b/solution/2800-2899/2833.Furthest Point From Origin/Solution.java index 014448bdd881f..86e8ec7f27682 100644 --- a/solution/2800-2899/2833.Furthest Point From Origin/Solution.java +++ b/solution/2800-2899/2833.Furthest Point From Origin/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public int furthestDistanceFromOrigin(String moves) { - return Math.abs(count(moves, 'L') - count(moves, 'R')) + count(moves, '_'); - } - - private int count(String s, char c) { - int cnt = 0; - for (int i = 0; i < s.length(); ++i) { - if (s.charAt(i) == c) { - ++cnt; - } - } - return cnt; - } +class Solution { + public int furthestDistanceFromOrigin(String moves) { + return Math.abs(count(moves, 'L') - count(moves, 'R')) + count(moves, '_'); + } + + private int count(String s, char c) { + int cnt = 0; + for (int i = 0; i < s.length(); ++i) { + if (s.charAt(i) == c) { + ++cnt; + } + } + return cnt; + } } \ No newline at end of file diff --git a/solution/2800-2899/2833.Furthest Point From Origin/Solution.py b/solution/2800-2899/2833.Furthest Point From Origin/Solution.py index 4503942f97692..b0ad85909c88c 100644 --- a/solution/2800-2899/2833.Furthest Point From Origin/Solution.py +++ b/solution/2800-2899/2833.Furthest Point From Origin/Solution.py @@ -1,3 +1,3 @@ -class Solution: - def furthestDistanceFromOrigin(self, moves: str) -> int: - return abs(moves.count("L") - moves.count("R")) + moves.count("_") +class Solution: + def furthestDistanceFromOrigin(self, moves: str) -> int: + return abs(moves.count("L") - moves.count("R")) + moves.count("_") diff --git a/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/Solution.cpp b/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/Solution.cpp index 1ddef8ee2dc26..711e1ce6de611 100644 --- a/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/Solution.cpp +++ b/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/Solution.cpp @@ -1,18 +1,18 @@ -class Solution { -public: - long long minimumPossibleSum(int n, int target) { - bool vis[n + target]; - memset(vis, false, sizeof(vis)); - long long ans = 0; - for (int i = 1; n; ++i, --n) { - while (vis[i]) { - ++i; - } - ans += i; - if (target >= i) { - vis[target - i] = true; - } - } - return ans; - } +class Solution { +public: + long long minimumPossibleSum(int n, int target) { + bool vis[n + target]; + memset(vis, false, sizeof(vis)); + long long ans = 0; + for (int i = 1; n; ++i, --n) { + while (vis[i]) { + ++i; + } + ans += i; + if (target >= i) { + vis[target - i] = true; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/Solution.java b/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/Solution.java index 50a9abedb6aee..08af8b612e7a6 100644 --- a/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/Solution.java +++ b/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/Solution.java @@ -1,16 +1,16 @@ -class Solution { - public long minimumPossibleSum(int n, int target) { - boolean[] vis = new boolean[n + target]; - long ans = 0; - for (int i = 1; n > 0; --n, ++i) { - while (vis[i]) { - ++i; - } - ans += i; - if (target >= i) { - vis[target - i] = true; - } - } - return ans; - } +class Solution { + public long minimumPossibleSum(int n, int target) { + boolean[] vis = new boolean[n + target]; + long ans = 0; + for (int i = 1; n > 0; --n, ++i) { + while (vis[i]) { + ++i; + } + ans += i; + if (target >= i) { + vis[target - i] = true; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/Solution.py b/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/Solution.py index 57d250f71165e..16b056df7570b 100644 --- a/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/Solution.py +++ b/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def minimumPossibleSum(self, n: int, target: int) -> int: - vis = set() - ans = 0 - i = 1 - for _ in range(n): - while i in vis: - i += 1 - ans += i - vis.add(target - i) - i += 1 - return ans +class Solution: + def minimumPossibleSum(self, n: int, target: int) -> int: + vis = set() + ans = 0 + i = 1 + for _ in range(n): + while i in vis: + i += 1 + ans += i + vis.add(target - i) + i += 1 + return ans diff --git a/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/Solution.cpp b/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/Solution.cpp index 5f8fafc21dffd..55aada030ef30 100644 --- a/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/Solution.cpp +++ b/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/Solution.cpp @@ -1,41 +1,41 @@ -class Solution { -public: - int minOperations(vector& nums, int target) { - long long s = 0; - int cnt[32]{}; - for (int x : nums) { - s += x; - for (int i = 0; i < 32; ++i) { - if (x >> i & 1) { - ++cnt[i]; - } - } - } - if (s < target) { - return -1; - } - int i = 0, j = 0; - int ans = 0; - while (1) { - while (i < 32 && (target >> i & 1) == 0) { - ++i; - } - if (i == 32) { - return ans; - } - while (j < i) { - cnt[j + 1] += cnt[j] / 2; - cnt[j] %= 2; - ++j; - } - while (cnt[j] == 0) { - cnt[j] = 1; - ++j; - } - ans += j - i; - --cnt[j]; - j = i; - ++i; - } - } +class Solution { +public: + int minOperations(vector& nums, int target) { + long long s = 0; + int cnt[32]{}; + for (int x : nums) { + s += x; + for (int i = 0; i < 32; ++i) { + if (x >> i & 1) { + ++cnt[i]; + } + } + } + if (s < target) { + return -1; + } + int i = 0, j = 0; + int ans = 0; + while (1) { + while (i < 32 && (target >> i & 1) == 0) { + ++i; + } + if (i == 32) { + return ans; + } + while (j < i) { + cnt[j + 1] += cnt[j] / 2; + cnt[j] %= 2; + ++j; + } + while (cnt[j] == 0) { + cnt[j] = 1; + ++j; + } + ans += j - i; + --cnt[j]; + j = i; + ++i; + } + } }; \ No newline at end of file diff --git a/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/Solution.java b/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/Solution.java index 82e5ac9acd15b..819ed74668bf5 100644 --- a/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/Solution.java +++ b/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/Solution.java @@ -1,40 +1,40 @@ -class Solution { - public int minOperations(List nums, int target) { - long s = 0; - int[] cnt = new int[32]; - for (int x : nums) { - s += x; - for (int i = 0; i < 32; ++i) { - if ((x >> i & 1) == 1) { - ++cnt[i]; - } - } - } - if (s < target) { - return -1; - } - int i = 0, j = 0; - int ans = 0; - while (true) { - while (i < 32 && (target >> i & 1) == 0) { - ++i; - } - if (i == 32) { - return ans; - } - while (j < i) { - cnt[j + 1] += cnt[j] / 2; - cnt[j] %= 2; - ++j; - } - while (cnt[j] == 0) { - cnt[j] = 1; - ++j; - } - ans += j - i; - --cnt[j]; - j = i; - ++i; - } - } +class Solution { + public int minOperations(List nums, int target) { + long s = 0; + int[] cnt = new int[32]; + for (int x : nums) { + s += x; + for (int i = 0; i < 32; ++i) { + if ((x >> i & 1) == 1) { + ++cnt[i]; + } + } + } + if (s < target) { + return -1; + } + int i = 0, j = 0; + int ans = 0; + while (true) { + while (i < 32 && (target >> i & 1) == 0) { + ++i; + } + if (i == 32) { + return ans; + } + while (j < i) { + cnt[j + 1] += cnt[j] / 2; + cnt[j] %= 2; + ++j; + } + while (cnt[j] == 0) { + cnt[j] = 1; + ++j; + } + ans += j - i; + --cnt[j]; + j = i; + ++i; + } + } } \ No newline at end of file diff --git a/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/Solution.py b/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/Solution.py index bbd4329b5308b..c22aa29517bba 100644 --- a/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/Solution.py +++ b/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/Solution.py @@ -1,29 +1,29 @@ -class Solution: - def minOperations(self, nums: List[int], target: int) -> int: - s = sum(nums) - if s < target: - return -1 - cnt = [0] * 32 - for x in nums: - for i in range(32): - if x >> i & 1: - cnt[i] += 1 - i = j = 0 - ans = 0 - while 1: - while i < 32 and (target >> i & 1) == 0: - i += 1 - if i == 32: - break - while j < i: - cnt[j + 1] += cnt[j] // 2 - cnt[j] %= 2 - j += 1 - while cnt[j] == 0: - cnt[j] = 1 - j += 1 - ans += j - i - cnt[j] -= 1 - j = i - i += 1 - return ans +class Solution: + def minOperations(self, nums: List[int], target: int) -> int: + s = sum(nums) + if s < target: + return -1 + cnt = [0] * 32 + for x in nums: + for i in range(32): + if x >> i & 1: + cnt[i] += 1 + i = j = 0 + ans = 0 + while 1: + while i < 32 and (target >> i & 1) == 0: + i += 1 + if i == 32: + break + while j < i: + cnt[j + 1] += cnt[j] // 2 + cnt[j] %= 2 + j += 1 + while cnt[j] == 0: + cnt[j] = 1 + j += 1 + ans += j - i + cnt[j] -= 1 + j = i + i += 1 + return ans diff --git a/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/Solution.cpp b/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/Solution.cpp index 8d6f52cce552f..72f57a2978fbc 100644 --- a/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/Solution.cpp +++ b/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/Solution.cpp @@ -1,31 +1,31 @@ -class Solution { -public: - long long getMaxFunctionValue(vector& receiver, long long k) { - int n = receiver.size(), m = 64 - __builtin_clzll(k); - int f[n][m]; - long long g[n][m]; - for (int i = 0; i < n; ++i) { - f[i][0] = receiver[i]; - g[i][0] = i; - } - for (int j = 1; j < m; ++j) { - for (int i = 0; i < n; ++i) { - f[i][j] = f[f[i][j - 1]][j - 1]; - g[i][j] = g[i][j - 1] + g[f[i][j - 1]][j - 1]; - } - } - long long ans = 0; - for (int i = 0; i < n; ++i) { - int p = i; - long long t = 0; - for (int j = 0; j < m; ++j) { - if (k >> j & 1) { - t += g[p][j]; - p = f[p][j]; - } - } - ans = max(ans, p + t); - } - return ans; - } +class Solution { +public: + long long getMaxFunctionValue(vector& receiver, long long k) { + int n = receiver.size(), m = 64 - __builtin_clzll(k); + int f[n][m]; + long long g[n][m]; + for (int i = 0; i < n; ++i) { + f[i][0] = receiver[i]; + g[i][0] = i; + } + for (int j = 1; j < m; ++j) { + for (int i = 0; i < n; ++i) { + f[i][j] = f[f[i][j - 1]][j - 1]; + g[i][j] = g[i][j - 1] + g[f[i][j - 1]][j - 1]; + } + } + long long ans = 0; + for (int i = 0; i < n; ++i) { + int p = i; + long long t = 0; + for (int j = 0; j < m; ++j) { + if (k >> j & 1) { + t += g[p][j]; + p = f[p][j]; + } + } + ans = max(ans, p + t); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/Solution.java b/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/Solution.java index ba9dd4474dd6e..6c9baed88fc3d 100644 --- a/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/Solution.java +++ b/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/Solution.java @@ -1,30 +1,30 @@ -class Solution { - public long getMaxFunctionValue(List receiver, long k) { - int n = receiver.size(), m = 64 - Long.numberOfLeadingZeros(k); - int[][] f = new int[n][m]; - long[][] g = new long[n][m]; - for (int i = 0; i < n; ++i) { - f[i][0] = receiver.get(i); - g[i][0] = i; - } - for (int j = 1; j < m; ++j) { - for (int i = 0; i < n; ++i) { - f[i][j] = f[f[i][j - 1]][j - 1]; - g[i][j] = g[i][j - 1] + g[f[i][j - 1]][j - 1]; - } - } - long ans = 0; - for (int i = 0; i < n; ++i) { - int p = i; - long t = 0; - for (int j = 0; j < m; ++j) { - if ((k >> j & 1) == 1) { - t += g[p][j]; - p = f[p][j]; - } - } - ans = Math.max(ans, p + t); - } - return ans; - } +class Solution { + public long getMaxFunctionValue(List receiver, long k) { + int n = receiver.size(), m = 64 - Long.numberOfLeadingZeros(k); + int[][] f = new int[n][m]; + long[][] g = new long[n][m]; + for (int i = 0; i < n; ++i) { + f[i][0] = receiver.get(i); + g[i][0] = i; + } + for (int j = 1; j < m; ++j) { + for (int i = 0; i < n; ++i) { + f[i][j] = f[f[i][j - 1]][j - 1]; + g[i][j] = g[i][j - 1] + g[f[i][j - 1]][j - 1]; + } + } + long ans = 0; + for (int i = 0; i < n; ++i) { + int p = i; + long t = 0; + for (int j = 0; j < m; ++j) { + if ((k >> j & 1) == 1) { + t += g[p][j]; + p = f[p][j]; + } + } + ans = Math.max(ans, p + t); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/Solution.py b/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/Solution.py index 051c948278011..361cc9a6d7964 100644 --- a/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/Solution.py +++ b/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/Solution.py @@ -1,21 +1,21 @@ -class Solution: - def getMaxFunctionValue(self, receiver: List[int], k: int) -> int: - n, m = len(receiver), k.bit_length() - f = [[0] * m for _ in range(n)] - g = [[0] * m for _ in range(n)] - for i, x in enumerate(receiver): - f[i][0] = x - g[i][0] = i - for j in range(1, m): - for i in range(n): - f[i][j] = f[f[i][j - 1]][j - 1] - g[i][j] = g[i][j - 1] + g[f[i][j - 1]][j - 1] - ans = 0 - for i in range(n): - p, t = i, 0 - for j in range(m): - if k >> j & 1: - t += g[p][j] - p = f[p][j] - ans = max(ans, t + p) - return ans +class Solution: + def getMaxFunctionValue(self, receiver: List[int], k: int) -> int: + n, m = len(receiver), k.bit_length() + f = [[0] * m for _ in range(n)] + g = [[0] * m for _ in range(n)] + for i, x in enumerate(receiver): + f[i][0] = x + g[i][0] = i + for j in range(1, m): + for i in range(n): + f[i][j] = f[f[i][j - 1]][j - 1] + g[i][j] = g[i][j - 1] + g[f[i][j - 1]][j - 1] + ans = 0 + for i in range(n): + p, t = i, 0 + for j in range(m): + if k >> j & 1: + t += g[p][j] + p = f[p][j] + ans = max(ans, t + p) + return ans diff --git a/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/Solution.cpp b/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/Solution.cpp index 1f8ce9bbd6cdf..5a7504499d9ee 100644 --- a/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/Solution.cpp +++ b/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - bool canBeEqual(string s1, string s2) { - vector> cnt(2, vector(26, 0)); - for (int i = 0; i < s1.size(); ++i) { - ++cnt[i & 1][s1[i] - 'a']; - --cnt[i & 1][s2[i] - 'a']; - } - for (int i = 0; i < 26; ++i) { - if (cnt[0][i] || cnt[1][i]) { - return false; - } - } - return true; - } +class Solution { +public: + bool canBeEqual(string s1, string s2) { + vector> cnt(2, vector(26, 0)); + for (int i = 0; i < s1.size(); ++i) { + ++cnt[i & 1][s1[i] - 'a']; + --cnt[i & 1][s2[i] - 'a']; + } + for (int i = 0; i < 26; ++i) { + if (cnt[0][i] || cnt[1][i]) { + return false; + } + } + return true; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/Solution.java b/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/Solution.java index 779c5d4b21584..00c4b38b69a56 100644 --- a/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/Solution.java +++ b/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public boolean canBeEqual(String s1, String s2) { - int[][] cnt = new int[2][26]; - for (int i = 0; i < s1.length(); ++i) { - ++cnt[i & 1][s1.charAt(i) - 'a']; - --cnt[i & 1][s2.charAt(i) - 'a']; - } - for (int i = 0; i < 26; ++i) { - if (cnt[0][i] != 0 || cnt[1][i] != 0) { - return false; - } - } - return true; - } +class Solution { + public boolean canBeEqual(String s1, String s2) { + int[][] cnt = new int[2][26]; + for (int i = 0; i < s1.length(); ++i) { + ++cnt[i & 1][s1.charAt(i) - 'a']; + --cnt[i & 1][s2.charAt(i) - 'a']; + } + for (int i = 0; i < 26; ++i) { + if (cnt[0][i] != 0 || cnt[1][i] != 0) { + return false; + } + } + return true; + } } \ No newline at end of file diff --git a/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/Solution.py b/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/Solution.py index 33cebe1fdeba5..14ca7936a11cb 100644 --- a/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/Solution.py +++ b/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/Solution.py @@ -1,5 +1,5 @@ -class Solution: - def canBeEqual(self, s1: str, s2: str) -> bool: - return sorted(s1[::2]) == sorted(s2[::2]) and sorted(s1[1::2]) == sorted( - s2[1::2] - ) +class Solution: + def canBeEqual(self, s1: str, s2: str) -> bool: + return sorted(s1[::2]) == sorted(s2[::2]) and sorted(s1[1::2]) == sorted( + s2[1::2] + ) diff --git a/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/Solution.cpp b/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/Solution.cpp index 97fa822f61c72..9ba7258fa627d 100644 --- a/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/Solution.cpp +++ b/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - bool checkStrings(string s1, string s2) { - vector> cnt(2, vector(26, 0)); - for (int i = 0; i < s1.size(); ++i) { - ++cnt[i & 1][s1[i] - 'a']; - --cnt[i & 1][s2[i] - 'a']; - } - for (int i = 0; i < 26; ++i) { - if (cnt[0][i] || cnt[1][i]) { - return false; - } - } - return true; - } +class Solution { +public: + bool checkStrings(string s1, string s2) { + vector> cnt(2, vector(26, 0)); + for (int i = 0; i < s1.size(); ++i) { + ++cnt[i & 1][s1[i] - 'a']; + --cnt[i & 1][s2[i] - 'a']; + } + for (int i = 0; i < 26; ++i) { + if (cnt[0][i] || cnt[1][i]) { + return false; + } + } + return true; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/Solution.java b/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/Solution.java index 0c06bbd118ae7..ea93a2dbeb194 100644 --- a/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/Solution.java +++ b/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public boolean checkStrings(String s1, String s2) { - int[][] cnt = new int[2][26]; - for (int i = 0; i < s1.length(); ++i) { - ++cnt[i & 1][s1.charAt(i) - 'a']; - --cnt[i & 1][s2.charAt(i) - 'a']; - } - for (int i = 0; i < 26; ++i) { - if (cnt[0][i] != 0 || cnt[1][i] != 0) { - return false; - } - } - return true; - } +class Solution { + public boolean checkStrings(String s1, String s2) { + int[][] cnt = new int[2][26]; + for (int i = 0; i < s1.length(); ++i) { + ++cnt[i & 1][s1.charAt(i) - 'a']; + --cnt[i & 1][s2.charAt(i) - 'a']; + } + for (int i = 0; i < 26; ++i) { + if (cnt[0][i] != 0 || cnt[1][i] != 0) { + return false; + } + } + return true; + } } \ No newline at end of file diff --git a/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/Solution.py b/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/Solution.py index a563f92f47d81..35018a0ecff52 100644 --- a/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/Solution.py +++ b/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/Solution.py @@ -1,5 +1,5 @@ -class Solution: - def checkStrings(self, s1: str, s2: str) -> bool: - return sorted(s1[::2]) == sorted(s2[::2]) and sorted(s1[1::2]) == sorted( - s2[1::2] - ) +class Solution: + def checkStrings(self, s1: str, s2: str) -> bool: + return sorted(s1[::2]) == sorted(s2[::2]) and sorted(s1[1::2]) == sorted( + s2[1::2] + ) diff --git a/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/Solution.cpp b/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/Solution.cpp index 93196e49fd33f..84a59a6c93f95 100644 --- a/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/Solution.cpp +++ b/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/Solution.cpp @@ -1,24 +1,24 @@ -class Solution { -public: - long long maxSum(vector& nums, int m, int k) { - unordered_map cnt; - long long s = 0; - int n = nums.size(); - for (int i = 0; i < k; ++i) { - cnt[nums[i]]++; - s += nums[i]; - } - long long ans = cnt.size() >= m ? s : 0; - for (int i = k; i < n; ++i) { - cnt[nums[i]]++; - if (--cnt[nums[i - k]] == 0) { - cnt.erase(nums[i - k]); - } - s += nums[i] - nums[i - k]; - if (cnt.size() >= m) { - ans = max(ans, s); - } - } - return ans; - } +class Solution { +public: + long long maxSum(vector& nums, int m, int k) { + unordered_map cnt; + long long s = 0; + int n = nums.size(); + for (int i = 0; i < k; ++i) { + cnt[nums[i]]++; + s += nums[i]; + } + long long ans = cnt.size() >= m ? s : 0; + for (int i = k; i < n; ++i) { + cnt[nums[i]]++; + if (--cnt[nums[i - k]] == 0) { + cnt.erase(nums[i - k]); + } + s += nums[i] - nums[i - k]; + if (cnt.size() >= m) { + ans = max(ans, s); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/Solution.java b/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/Solution.java index cd1999a2bb738..f2464efd2aa54 100644 --- a/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/Solution.java +++ b/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/Solution.java @@ -1,26 +1,26 @@ -class Solution { - public long maxSum(List nums, int m, int k) { - Map cnt = new HashMap<>(); - int n = nums.size(); - long s = 0; - for (int i = 0; i < k; ++i) { - cnt.merge(nums.get(i), 1, Integer::sum); - s += nums.get(i); - } - long ans = 0; - if (cnt.size() >= m) { - ans = s; - } - for (int i = k; i < n; ++i) { - cnt.merge(nums.get(i), 1, Integer::sum); - if (cnt.merge(nums.get(i - k), -1, Integer::sum) == 0) { - cnt.remove(nums.get(i - k)); - } - s += nums.get(i) - nums.get(i - k); - if (cnt.size() >= m) { - ans = Math.max(ans, s); - } - } - return ans; - } +class Solution { + public long maxSum(List nums, int m, int k) { + Map cnt = new HashMap<>(); + int n = nums.size(); + long s = 0; + for (int i = 0; i < k; ++i) { + cnt.merge(nums.get(i), 1, Integer::sum); + s += nums.get(i); + } + long ans = 0; + if (cnt.size() >= m) { + ans = s; + } + for (int i = k; i < n; ++i) { + cnt.merge(nums.get(i), 1, Integer::sum); + if (cnt.merge(nums.get(i - k), -1, Integer::sum) == 0) { + cnt.remove(nums.get(i - k)); + } + s += nums.get(i) - nums.get(i - k); + if (cnt.size() >= m) { + ans = Math.max(ans, s); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/Solution.py b/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/Solution.py index 77126ad51a705..c45a872a9ecaf 100644 --- a/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/Solution.py +++ b/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/Solution.py @@ -1,16 +1,16 @@ -class Solution: - def maxSum(self, nums: List[int], m: int, k: int) -> int: - cnt = Counter(nums[:k]) - s = sum(nums[:k]) - ans = 0 - if len(cnt) >= m: - ans = s - for i in range(k, len(nums)): - cnt[nums[i]] += 1 - cnt[nums[i - k]] -= 1 - s += nums[i] - nums[i - k] - if cnt[nums[i - k]] == 0: - cnt.pop(nums[i - k]) - if len(cnt) >= m: - ans = max(ans, s) - return ans +class Solution: + def maxSum(self, nums: List[int], m: int, k: int) -> int: + cnt = Counter(nums[:k]) + s = sum(nums[:k]) + ans = 0 + if len(cnt) >= m: + ans = s + for i in range(k, len(nums)): + cnt[nums[i]] += 1 + cnt[nums[i - k]] -= 1 + s += nums[i] - nums[i - k] + if cnt[nums[i - k]] == 0: + cnt.pop(nums[i - k]) + if len(cnt) >= m: + ans = max(ans, s) + return ans diff --git a/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/Solution.cpp b/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/Solution.cpp index cff8e3d5d83aa..29ccec7c1dba6 100644 --- a/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/Solution.cpp +++ b/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/Solution.cpp @@ -1,56 +1,56 @@ -class Solution { -public: - int countKSubsequencesWithMaxBeauty(string s, int k) { - int f[26]{}; - int cnt = 0; - for (char& c : s) { - if (++f[c - 'a'] == 1) { - ++cnt; - } - } - if (cnt < k) { - return 0; - } - vector vs(cnt); - for (int i = 0, j = 0; i < 26; ++i) { - if (f[i]) { - vs[j++] = f[i]; - } - } - sort(vs.rbegin(), vs.rend()); - const int mod = 1e9 + 7; - long long ans = 1; - int val = vs[k - 1]; - int x = 0; - for (int v : vs) { - x += v == val; - } - for (int v : vs) { - if (v == val) { - break; - } - --k; - ans = ans * v % mod; - } - int c[x + 1][x + 1]; - memset(c, 0, sizeof(c)); - for (int i = 0; i <= x; ++i) { - c[i][0] = 1; - for (int j = 1; j <= i; ++j) { - c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % mod; - } - } - auto qpow = [&](long long a, int n) { - long long ans = 1; - for (; n; n >>= 1) { - if (n & 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return ans; - }; - ans = (ans * c[x][k] % mod) * qpow(val, k) % mod; - return ans; - } +class Solution { +public: + int countKSubsequencesWithMaxBeauty(string s, int k) { + int f[26]{}; + int cnt = 0; + for (char& c : s) { + if (++f[c - 'a'] == 1) { + ++cnt; + } + } + if (cnt < k) { + return 0; + } + vector vs(cnt); + for (int i = 0, j = 0; i < 26; ++i) { + if (f[i]) { + vs[j++] = f[i]; + } + } + sort(vs.rbegin(), vs.rend()); + const int mod = 1e9 + 7; + long long ans = 1; + int val = vs[k - 1]; + int x = 0; + for (int v : vs) { + x += v == val; + } + for (int v : vs) { + if (v == val) { + break; + } + --k; + ans = ans * v % mod; + } + int c[x + 1][x + 1]; + memset(c, 0, sizeof(c)); + for (int i = 0; i <= x; ++i) { + c[i][0] = 1; + for (int j = 1; j <= i; ++j) { + c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % mod; + } + } + auto qpow = [&](long long a, int n) { + long long ans = 1; + for (; n; n >>= 1) { + if (n & 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return ans; + }; + ans = (ans * c[x][k] % mod) * qpow(val, k) % mod; + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/Solution.java b/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/Solution.java index 6799d5a5926e8..ccd3e841bb7be 100644 --- a/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/Solution.java +++ b/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/Solution.java @@ -1,59 +1,59 @@ -class Solution { - private final int mod = (int) 1e9 + 7; - - public int countKSubsequencesWithMaxBeauty(String s, int k) { - int[] f = new int[26]; - int n = s.length(); - int cnt = 0; - for (int i = 0; i < n; ++i) { - if (++f[s.charAt(i) - 'a'] == 1) { - ++cnt; - } - } - if (cnt < k) { - return 0; - } - Integer[] vs = new Integer[cnt]; - for (int i = 0, j = 0; i < 26; ++i) { - if (f[i] > 0) { - vs[j++] = f[i]; - } - } - Arrays.sort(vs, (a, b) -> b - a); - long ans = 1; - int val = vs[k - 1]; - int x = 0; - for (int v : vs) { - if (v == val) { - ++x; - } - } - for (int v : vs) { - if (v == val) { - break; - } - --k; - ans = ans * v % mod; - } - int[][] c = new int[x + 1][x + 1]; - for (int i = 0; i <= x; ++i) { - c[i][0] = 1; - for (int j = 1; j <= i; ++j) { - c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % mod; - } - } - ans = ((ans * c[x][k]) % mod) * qpow(val, k) % mod; - return (int) ans; - } - - private long qpow(long a, int n) { - long ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return ans; - } +class Solution { + private final int mod = (int) 1e9 + 7; + + public int countKSubsequencesWithMaxBeauty(String s, int k) { + int[] f = new int[26]; + int n = s.length(); + int cnt = 0; + for (int i = 0; i < n; ++i) { + if (++f[s.charAt(i) - 'a'] == 1) { + ++cnt; + } + } + if (cnt < k) { + return 0; + } + Integer[] vs = new Integer[cnt]; + for (int i = 0, j = 0; i < 26; ++i) { + if (f[i] > 0) { + vs[j++] = f[i]; + } + } + Arrays.sort(vs, (a, b) -> b - a); + long ans = 1; + int val = vs[k - 1]; + int x = 0; + for (int v : vs) { + if (v == val) { + ++x; + } + } + for (int v : vs) { + if (v == val) { + break; + } + --k; + ans = ans * v % mod; + } + int[][] c = new int[x + 1][x + 1]; + for (int i = 0; i <= x; ++i) { + c[i][0] = 1; + for (int j = 1; j <= i; ++j) { + c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % mod; + } + } + ans = ((ans * c[x][k]) % mod) * qpow(val, k) % mod; + return (int) ans; + } + + private long qpow(long a, int n) { + long ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/Solution.py b/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/Solution.py index 00d1e87032c35..950fae6306202 100644 --- a/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/Solution.py +++ b/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/Solution.py @@ -1,17 +1,17 @@ -class Solution: - def countKSubsequencesWithMaxBeauty(self, s: str, k: int) -> int: - f = Counter(s) - if len(f) < k: - return 0 - mod = 10**9 + 7 - vs = sorted(f.values(), reverse=True) - val = vs[k - 1] - x = vs.count(val) - ans = 1 - for v in vs: - if v == val: - break - k -= 1 - ans = ans * v % mod - ans = ans * comb(x, k) * pow(val, k, mod) % mod - return ans +class Solution: + def countKSubsequencesWithMaxBeauty(self, s: str, k: int) -> int: + f = Counter(s) + if len(f) < k: + return 0 + mod = 10**9 + 7 + vs = sorted(f.values(), reverse=True) + val = vs[k - 1] + x = vs.count(val) + ans = 1 + for v in vs: + if v == val: + break + k -= 1 + ans = ans * v % mod + ans = ans * comb(x, k) * pow(val, k, mod) % mod + return ans diff --git a/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/Solution.cpp b/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/Solution.cpp index 5aa801d2b50fe..6ee555617f8e0 100644 --- a/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/Solution.cpp +++ b/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/Solution.cpp @@ -1,67 +1,67 @@ -class Solution { -public: - vector minOperationsQueries(int n, vector>& edges, vector>& queries) { - int m = 32 - __builtin_clz(n); - vector> g[n]; - int f[n][m]; - int p[n]; - int cnt[n][26]; - int depth[n]; - memset(f, 0, sizeof(f)); - memset(cnt, 0, sizeof(cnt)); - memset(depth, 0, sizeof(depth)); - memset(p, 0, sizeof(p)); - for (auto& e : edges) { - int u = e[0], v = e[1], w = e[2] - 1; - g[u].emplace_back(v, w); - g[v].emplace_back(u, w); - } - queue q; - q.push(0); - while (!q.empty()) { - int i = q.front(); - q.pop(); - f[i][0] = p[i]; - for (int j = 1; j < m; ++j) { - f[i][j] = f[f[i][j - 1]][j - 1]; - } - for (auto& [j, w] : g[i]) { - if (j != p[i]) { - p[j] = i; - memcpy(cnt[j], cnt[i], sizeof(cnt[i])); - cnt[j][w]++; - depth[j] = depth[i] + 1; - q.push(j); - } - } - } - vector ans; - for (auto& qq : queries) { - int u = qq[0], v = qq[1]; - int x = u, y = v; - if (depth[x] < depth[y]) { - swap(x, y); - } - for (int j = m - 1; ~j; --j) { - if (depth[x] - depth[y] >= (1 << j)) { - x = f[x][j]; - } - } - for (int j = m - 1; ~j; --j) { - if (f[x][j] != f[y][j]) { - x = f[x][j]; - y = f[y][j]; - } - } - if (x != y) { - x = p[x]; - } - int mx = 0; - for (int j = 0; j < 26; ++j) { - mx = max(mx, cnt[u][j] + cnt[v][j] - 2 * cnt[x][j]); - } - ans.push_back(depth[u] + depth[v] - 2 * depth[x] - mx); - } - return ans; - } +class Solution { +public: + vector minOperationsQueries(int n, vector>& edges, vector>& queries) { + int m = 32 - __builtin_clz(n); + vector> g[n]; + int f[n][m]; + int p[n]; + int cnt[n][26]; + int depth[n]; + memset(f, 0, sizeof(f)); + memset(cnt, 0, sizeof(cnt)); + memset(depth, 0, sizeof(depth)); + memset(p, 0, sizeof(p)); + for (auto& e : edges) { + int u = e[0], v = e[1], w = e[2] - 1; + g[u].emplace_back(v, w); + g[v].emplace_back(u, w); + } + queue q; + q.push(0); + while (!q.empty()) { + int i = q.front(); + q.pop(); + f[i][0] = p[i]; + for (int j = 1; j < m; ++j) { + f[i][j] = f[f[i][j - 1]][j - 1]; + } + for (auto& [j, w] : g[i]) { + if (j != p[i]) { + p[j] = i; + memcpy(cnt[j], cnt[i], sizeof(cnt[i])); + cnt[j][w]++; + depth[j] = depth[i] + 1; + q.push(j); + } + } + } + vector ans; + for (auto& qq : queries) { + int u = qq[0], v = qq[1]; + int x = u, y = v; + if (depth[x] < depth[y]) { + swap(x, y); + } + for (int j = m - 1; ~j; --j) { + if (depth[x] - depth[y] >= (1 << j)) { + x = f[x][j]; + } + } + for (int j = m - 1; ~j; --j) { + if (f[x][j] != f[y][j]) { + x = f[x][j]; + y = f[y][j]; + } + } + if (x != y) { + x = p[x]; + } + int mx = 0; + for (int j = 0; j < 26; ++j) { + mx = max(mx, cnt[u][j] + cnt[v][j] - 2 * cnt[x][j]); + } + ans.push_back(depth[u] + depth[v] - 2 * depth[x] - mx); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/Solution.java b/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/Solution.java index 4b45ffed2c4e3..845e08d2bce16 100644 --- a/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/Solution.java +++ b/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/Solution.java @@ -1,67 +1,67 @@ -class Solution { - public int[] minOperationsQueries(int n, int[][] edges, int[][] queries) { - int m = 32 - Integer.numberOfLeadingZeros(n); - List[] g = new List[n]; - Arrays.setAll(g, i -> new ArrayList<>()); - int[][] f = new int[n][m]; - int[] p = new int[n]; - int[][] cnt = new int[n][0]; - int[] depth = new int[n]; - for (var e : edges) { - int u = e[0], v = e[1], w = e[2] - 1; - g[u].add(new int[] {v, w}); - g[v].add(new int[] {u, w}); - } - cnt[0] = new int[26]; - Deque q = new ArrayDeque<>(); - q.offer(0); - while (!q.isEmpty()) { - int i = q.poll(); - f[i][0] = p[i]; - for (int j = 1; j < m; ++j) { - f[i][j] = f[f[i][j - 1]][j - 1]; - } - for (var nxt : g[i]) { - int j = nxt[0], w = nxt[1]; - if (j != p[i]) { - p[j] = i; - cnt[j] = cnt[i].clone(); - cnt[j][w]++; - depth[j] = depth[i] + 1; - q.offer(j); - } - } - } - int k = queries.length; - int[] ans = new int[k]; - for (int i = 0; i < k; ++i) { - int u = queries[i][0], v = queries[i][1]; - int x = u, y = v; - if (depth[x] < depth[y]) { - int t = x; - x = y; - y = t; - } - for (int j = m - 1; j >= 0; --j) { - if (depth[x] - depth[y] >= (1 << j)) { - x = f[x][j]; - } - } - for (int j = m - 1; j >= 0; --j) { - if (f[x][j] != f[y][j]) { - x = f[x][j]; - y = f[y][j]; - } - } - if (x != y) { - x = p[x]; - } - int mx = 0; - for (int j = 0; j < 26; ++j) { - mx = Math.max(mx, cnt[u][j] + cnt[v][j] - 2 * cnt[x][j]); - } - ans[i] = depth[u] + depth[v] - 2 * depth[x] - mx; - } - return ans; - } +class Solution { + public int[] minOperationsQueries(int n, int[][] edges, int[][] queries) { + int m = 32 - Integer.numberOfLeadingZeros(n); + List[] g = new List[n]; + Arrays.setAll(g, i -> new ArrayList<>()); + int[][] f = new int[n][m]; + int[] p = new int[n]; + int[][] cnt = new int[n][0]; + int[] depth = new int[n]; + for (var e : edges) { + int u = e[0], v = e[1], w = e[2] - 1; + g[u].add(new int[] {v, w}); + g[v].add(new int[] {u, w}); + } + cnt[0] = new int[26]; + Deque q = new ArrayDeque<>(); + q.offer(0); + while (!q.isEmpty()) { + int i = q.poll(); + f[i][0] = p[i]; + for (int j = 1; j < m; ++j) { + f[i][j] = f[f[i][j - 1]][j - 1]; + } + for (var nxt : g[i]) { + int j = nxt[0], w = nxt[1]; + if (j != p[i]) { + p[j] = i; + cnt[j] = cnt[i].clone(); + cnt[j][w]++; + depth[j] = depth[i] + 1; + q.offer(j); + } + } + } + int k = queries.length; + int[] ans = new int[k]; + for (int i = 0; i < k; ++i) { + int u = queries[i][0], v = queries[i][1]; + int x = u, y = v; + if (depth[x] < depth[y]) { + int t = x; + x = y; + y = t; + } + for (int j = m - 1; j >= 0; --j) { + if (depth[x] - depth[y] >= (1 << j)) { + x = f[x][j]; + } + } + for (int j = m - 1; j >= 0; --j) { + if (f[x][j] != f[y][j]) { + x = f[x][j]; + y = f[y][j]; + } + } + if (x != y) { + x = p[x]; + } + int mx = 0; + for (int j = 0; j < 26; ++j) { + mx = Math.max(mx, cnt[u][j] + cnt[v][j] - 2 * cnt[x][j]); + } + ans[i] = depth[u] + depth[v] - 2 * depth[x] - mx; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/Solution.py b/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/Solution.py index 364c2e6e429b3..41626eb27c750 100644 --- a/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/Solution.py +++ b/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/Solution.py @@ -1,43 +1,43 @@ -class Solution: - def minOperationsQueries( - self, n: int, edges: List[List[int]], queries: List[List[int]] - ) -> List[int]: - m = n.bit_length() - g = [[] for _ in range(n)] - f = [[0] * m for _ in range(n)] - p = [0] * n - cnt = [None] * n - depth = [0] * n - for u, v, w in edges: - g[u].append((v, w - 1)) - g[v].append((u, w - 1)) - cnt[0] = [0] * 26 - q = deque([0]) - while q: - i = q.popleft() - f[i][0] = p[i] - for j in range(1, m): - f[i][j] = f[f[i][j - 1]][j - 1] - for j, w in g[i]: - if j != p[i]: - p[j] = i - cnt[j] = cnt[i][:] - cnt[j][w] += 1 - depth[j] = depth[i] + 1 - q.append(j) - ans = [] - for u, v in queries: - x, y = u, v - if depth[x] < depth[y]: - x, y = y, x - for j in reversed(range(m)): - if depth[x] - depth[y] >= (1 << j): - x = f[x][j] - for j in reversed(range(m)): - if f[x][j] != f[y][j]: - x, y = f[x][j], f[y][j] - if x != y: - x = p[x] - mx = max(cnt[u][j] + cnt[v][j] - 2 * cnt[x][j] for j in range(26)) - ans.append(depth[u] + depth[v] - 2 * depth[x] - mx) - return ans +class Solution: + def minOperationsQueries( + self, n: int, edges: List[List[int]], queries: List[List[int]] + ) -> List[int]: + m = n.bit_length() + g = [[] for _ in range(n)] + f = [[0] * m for _ in range(n)] + p = [0] * n + cnt = [None] * n + depth = [0] * n + for u, v, w in edges: + g[u].append((v, w - 1)) + g[v].append((u, w - 1)) + cnt[0] = [0] * 26 + q = deque([0]) + while q: + i = q.popleft() + f[i][0] = p[i] + for j in range(1, m): + f[i][j] = f[f[i][j - 1]][j - 1] + for j, w in g[i]: + if j != p[i]: + p[j] = i + cnt[j] = cnt[i][:] + cnt[j][w] += 1 + depth[j] = depth[i] + 1 + q.append(j) + ans = [] + for u, v in queries: + x, y = u, v + if depth[x] < depth[y]: + x, y = y, x + for j in reversed(range(m)): + if depth[x] - depth[y] >= (1 << j): + x = f[x][j] + for j in reversed(range(m)): + if f[x][j] != f[y][j]: + x, y = f[x][j], f[y][j] + if x != y: + x = p[x] + mx = max(cnt[u][j] + cnt[v][j] - 2 * cnt[x][j] for j in range(26)) + ans.append(depth[u] + depth[v] - 2 * depth[x] - mx) + return ans diff --git a/solution/2800-2899/2847.Smallest Number With Given Digit Product/Solution.cpp b/solution/2800-2899/2847.Smallest Number With Given Digit Product/Solution.cpp index 851d92e44e9ae..c32a3f9d7f7ef 100644 --- a/solution/2800-2899/2847.Smallest Number With Given Digit Product/Solution.cpp +++ b/solution/2800-2899/2847.Smallest Number With Given Digit Product/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - string smallestNumber(long long n) { - int cnt[10]{}; - for (int i = 9; i > 1; --i) { - while (n % i == 0) { - n /= i; - ++cnt[i]; - } - } - if (n > 1) { - return "-1"; - } - string ans; - for (int i = 2; i < 10; ++i) { - ans += string(cnt[i], '0' + i); - } - return ans == "" ? "1" : ans; - } +class Solution { +public: + string smallestNumber(long long n) { + int cnt[10]{}; + for (int i = 9; i > 1; --i) { + while (n % i == 0) { + n /= i; + ++cnt[i]; + } + } + if (n > 1) { + return "-1"; + } + string ans; + for (int i = 2; i < 10; ++i) { + ans += string(cnt[i], '0' + i); + } + return ans == "" ? "1" : ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2847.Smallest Number With Given Digit Product/Solution.java b/solution/2800-2899/2847.Smallest Number With Given Digit Product/Solution.java index f52cedcf145df..d0410c8c5ef56 100644 --- a/solution/2800-2899/2847.Smallest Number With Given Digit Product/Solution.java +++ b/solution/2800-2899/2847.Smallest Number With Given Digit Product/Solution.java @@ -1,23 +1,23 @@ -class Solution { - public String smallestNumber(long n) { - int[] cnt = new int[10]; - for (int i = 9; i > 1; --i) { - while (n % i == 0) { - ++cnt[i]; - n /= i; - } - } - if (n > 1) { - return "-1"; - } - StringBuilder sb = new StringBuilder(); - for (int i = 2; i < 10; ++i) { - while (cnt[i] > 0) { - sb.append(i); - --cnt[i]; - } - } - String ans = sb.toString(); - return ans.isEmpty() ? "1" : ans; - } +class Solution { + public String smallestNumber(long n) { + int[] cnt = new int[10]; + for (int i = 9; i > 1; --i) { + while (n % i == 0) { + ++cnt[i]; + n /= i; + } + } + if (n > 1) { + return "-1"; + } + StringBuilder sb = new StringBuilder(); + for (int i = 2; i < 10; ++i) { + while (cnt[i] > 0) { + sb.append(i); + --cnt[i]; + } + } + String ans = sb.toString(); + return ans.isEmpty() ? "1" : ans; + } } \ No newline at end of file diff --git a/solution/2800-2899/2847.Smallest Number With Given Digit Product/Solution.py b/solution/2800-2899/2847.Smallest Number With Given Digit Product/Solution.py index bdafd50fb2b77..b31c943f50cfd 100644 --- a/solution/2800-2899/2847.Smallest Number With Given Digit Product/Solution.py +++ b/solution/2800-2899/2847.Smallest Number With Given Digit Product/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def smallestNumber(self, n: int) -> str: - cnt = [0] * 10 - for i in range(9, 1, -1): - while n % i == 0: - n //= i - cnt[i] += 1 - if n > 1: - return "-1" - ans = "".join(str(i) * cnt[i] for i in range(2, 10)) - return ans if ans else "1" +class Solution: + def smallestNumber(self, n: int) -> str: + cnt = [0] * 10 + for i in range(9, 1, -1): + while n % i == 0: + n //= i + cnt[i] += 1 + if n > 1: + return "-1" + ans = "".join(str(i) * cnt[i] for i in range(2, 10)) + return ans if ans else "1" diff --git a/solution/2800-2899/2848.Points That Intersect With Cars/Solution.cpp b/solution/2800-2899/2848.Points That Intersect With Cars/Solution.cpp index d0affa06d1f9b..e2297454176b9 100644 --- a/solution/2800-2899/2848.Points That Intersect With Cars/Solution.cpp +++ b/solution/2800-2899/2848.Points That Intersect With Cars/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - int numberOfPoints(vector>& nums) { - int d[110]{}; - for (auto& e : nums) { - d[e[0]]++; - d[e[1] + 1]--; - } - int ans = 0, s = 0; - for (int x : d) { - s += x; - ans += s > 0; - } - return ans; - } +class Solution { +public: + int numberOfPoints(vector>& nums) { + int d[110]{}; + for (auto& e : nums) { + d[e[0]]++; + d[e[1] + 1]--; + } + int ans = 0, s = 0; + for (int x : d) { + s += x; + ans += s > 0; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2848.Points That Intersect With Cars/Solution.java b/solution/2800-2899/2848.Points That Intersect With Cars/Solution.java index 6d83890cebe70..8e1c6e41f5126 100644 --- a/solution/2800-2899/2848.Points That Intersect With Cars/Solution.java +++ b/solution/2800-2899/2848.Points That Intersect With Cars/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public int numberOfPoints(List> nums) { - int[] d = new int[110]; - for (var e : nums) { - d[e.get(0)]++; - d[e.get(1) + 1]--; - } - int ans = 0, s = 0; - for (int x : d) { - s += x; - if (s > 0) { - ans++; - } - } - return ans; - } +class Solution { + public int numberOfPoints(List> nums) { + int[] d = new int[110]; + for (var e : nums) { + d[e.get(0)]++; + d[e.get(1) + 1]--; + } + int ans = 0, s = 0; + for (int x : d) { + s += x; + if (s > 0) { + ans++; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2800-2899/2848.Points That Intersect With Cars/Solution.py b/solution/2800-2899/2848.Points That Intersect With Cars/Solution.py index ae67c079aacf4..787cef40ed9f6 100644 --- a/solution/2800-2899/2848.Points That Intersect With Cars/Solution.py +++ b/solution/2800-2899/2848.Points That Intersect With Cars/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def numberOfPoints(self, nums: List[List[int]]) -> int: - d = [0] * 110 - for a, b in nums: - d[a] += 1 - d[b + 1] -= 1 - return sum(s > 0 for s in accumulate(d)) +class Solution: + def numberOfPoints(self, nums: List[List[int]]) -> int: + d = [0] * 110 + for a, b in nums: + d[a] += 1 + d[b + 1] -= 1 + return sum(s > 0 for s in accumulate(d)) diff --git a/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/Solution.cpp b/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/Solution.cpp index 4578a9a715cdc..54300648e41f5 100644 --- a/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/Solution.cpp +++ b/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/Solution.cpp @@ -1,10 +1,10 @@ -class Solution { -public: - bool isReachableAtTime(int sx, int sy, int fx, int fy, int t) { - if (sx == fx && sy == fy) { - return t != 1; - } - int dx = abs(fx - sx), dy = abs(fy - sy); - return max(dx, dy) <= t; - } +class Solution { +public: + bool isReachableAtTime(int sx, int sy, int fx, int fy, int t) { + if (sx == fx && sy == fy) { + return t != 1; + } + int dx = abs(fx - sx), dy = abs(fy - sy); + return max(dx, dy) <= t; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/Solution.java b/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/Solution.java index ec8ac8c45f877..b460e9c064b8b 100644 --- a/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/Solution.java +++ b/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/Solution.java @@ -1,10 +1,10 @@ -class Solution { - public boolean isReachableAtTime(int sx, int sy, int fx, int fy, int t) { - if (sx == fx && sy == fy) { - return t != 1; - } - int dx = Math.abs(sx - fx); - int dy = Math.abs(sy - fy); - return Math.max(dx, dy) <= t; - } +class Solution { + public boolean isReachableAtTime(int sx, int sy, int fx, int fy, int t) { + if (sx == fx && sy == fy) { + return t != 1; + } + int dx = Math.abs(sx - fx); + int dy = Math.abs(sy - fy); + return Math.max(dx, dy) <= t; + } } \ No newline at end of file diff --git a/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/Solution.py b/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/Solution.py index 7c8fb80ec209a..176341b31d7c0 100644 --- a/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/Solution.py +++ b/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def isReachableAtTime(self, sx: int, sy: int, fx: int, fy: int, t: int) -> bool: - if sx == fx and sy == fy: - return t != 1 - dx = abs(sx - fx) - dy = abs(sy - fy) - return max(dx, dy) <= t +class Solution: + def isReachableAtTime(self, sx: int, sy: int, fx: int, fy: int, t: int) -> bool: + if sx == fx and sy == fy: + return t != 1 + dx = abs(sx - fx) + dy = abs(sy - fy) + return max(dx, dy) <= t diff --git a/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution.cpp b/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution.cpp index 6d7625b58e1b2..074f0180802b7 100644 --- a/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution.cpp +++ b/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution.cpp @@ -1,34 +1,34 @@ -class Solution { -public: - int minimumMoves(vector>& grid) { - using pii = pair; - vector left, right; - for (int i = 0; i < 3; ++i) { - for (int j = 0; j < 3; ++j) { - if (grid[i][j] == 0) { - left.emplace_back(i, j); - } else { - for (int k = 1; k < grid[i][j]; ++k) { - right.emplace_back(i, j); - } - } - } - } - auto cal = [](pii a, pii b) { - return abs(a.first - b.first) + abs(a.second - b.second); - }; - int n = left.size(); - int f[1 << n]; - memset(f, 0x3f, sizeof(f)); - f[0] = 0; - for (int i = 1; i < 1 << n; ++i) { - int k = __builtin_popcount(i); - for (int j = 0; j < n; ++j) { - if (i >> j & 1) { - f[i] = min(f[i], f[i ^ (1 << j)] + cal(left[k - 1], right[j])); - } - } - } - return f[(1 << n) - 1]; - } +class Solution { +public: + int minimumMoves(vector>& grid) { + using pii = pair; + vector left, right; + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) { + if (grid[i][j] == 0) { + left.emplace_back(i, j); + } else { + for (int k = 1; k < grid[i][j]; ++k) { + right.emplace_back(i, j); + } + } + } + } + auto cal = [](pii a, pii b) { + return abs(a.first - b.first) + abs(a.second - b.second); + }; + int n = left.size(); + int f[1 << n]; + memset(f, 0x3f, sizeof(f)); + f[0] = 0; + for (int i = 1; i < 1 << n; ++i) { + int k = __builtin_popcount(i); + for (int j = 0; j < n; ++j) { + if (i >> j & 1) { + f[i] = min(f[i], f[i ^ (1 << j)] + cal(left[k - 1], right[j])); + } + } + } + return f[(1 << n) - 1]; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution.java b/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution.java index 2e0a451329f0f..bc7d621aba954 100644 --- a/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution.java +++ b/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution.java @@ -1,34 +1,63 @@ -class Solution { - public int minimumMoves(int[][] grid) { - List left = new ArrayList<>(); - List right = new ArrayList<>(); - for (int i = 0; i < 3; ++i) { - for (int j = 0; j < 3; ++j) { - if (grid[i][j] == 0) { - left.add(new int[] {i, j}); - } else { - for (int k = 1; k < grid[i][j]; ++k) { - right.add(new int[] {i, j}); - } - } - } - } - int n = left.size(); - int[] f = new int[1 << n]; - Arrays.fill(f, 1 << 30); - f[0] = 0; - for (int i = 1; i < 1 << n; ++i) { - int k = Integer.bitCount(i); - for (int j = 0; j < n; ++j) { - if ((i >> j & 1) == 1) { - f[i] = Math.min(f[i], f[i ^ (1 << j)] + cal(left.get(k - 1), right.get(j))); - } - } - } - return f[(1 << n) - 1]; - } - - private int cal(int[] a, int[] b) { - return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]); - } +class Solution { + public int minimumMoves(int[][] grid) { + Deque q = new ArrayDeque<>(); + q.add(f(grid)); + Set vis = new HashSet<>(); + vis.add(f(grid)); + int[] dirs = {-1, 0, 1, 0, -1}; + for (int ans = 0;; ++ans) { + for (int k = q.size(); k > 0; --k) { + String p = q.poll(); + if ("111111111".equals(p)) { + return ans; + } + int[][] cur = g(p); + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) { + if (cur[i][j] > 1) { + for (int d = 0; d < 4; ++d) { + int x = i + dirs[d]; + int y = j + dirs[d + 1]; + if (x >= 0 && x < 3 && y >= 0 && y < 3 && cur[x][y] < 2) { + int[][] nxt = new int[3][3]; + for (int r = 0; r < 3; ++r) { + for (int c = 0; c < 3; ++c) { + nxt[r][c] = cur[r][c]; + } + } + nxt[i][j]--; + nxt[x][y]++; + String s = f(nxt); + if (!vis.contains(s)) { + vis.add(s); + q.add(s); + } + } + } + } + } + } + } + } + } + + private String f(int[][] grid) { + StringBuilder sb = new StringBuilder(); + for (int[] row : grid) { + for (int x : row) { + sb.append(x); + } + } + return sb.toString(); + } + + private int[][] g(String s) { + int[][] grid = new int[3][3]; + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) { + grid[i][j] = s.charAt(i * 3 + j) - '0'; + } + } + return grid; + } } \ No newline at end of file diff --git a/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution.py b/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution.py index 4e349f78e2032..9262d7c46d981 100644 --- a/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution.py +++ b/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution.py @@ -1,23 +1,25 @@ -class Solution: - def minimumMoves(self, grid: List[List[int]]) -> int: - def cal(a: tuple, b: tuple) -> int: - return abs(a[0] - b[0]) + abs(a[1] - b[1]) - - left, right = [], [] - for i in range(3): - for j in range(3): - if grid[i][j] == 0: - left.append((i, j)) - else: - for _ in range(grid[i][j] - 1): - right.append((i, j)) - - n = len(left) - f = [inf] * (1 << n) - f[0] = 0 - for i in range(1, 1 << n): - k = i.bit_count() - for j in range(n): - if i >> j & 1: - f[i] = min(f[i], f[i ^ (1 << j)] + cal(left[k - 1], right[j])) - return f[-1] +class Solution: + def minimumMoves(self, grid: List[List[int]]) -> int: + q = deque([tuple(tuple(row) for row in grid)]) + vis = set(q) + ans = 0 + dirs = (-1, 0, 1, 0, -1) + while 1: + for _ in range(len(q)): + cur = q.popleft() + if all(x for row in cur for x in row): + return ans + for i in range(3): + for j in range(3): + if cur[i][j] > 1: + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < 3 and 0 <= y < 3 and cur[x][y] < 2: + nxt = [list(row) for row in cur] + nxt[i][j] -= 1 + nxt[x][y] += 1 + nxt = tuple(tuple(row) for row in nxt) + if nxt not in vis: + vis.add(nxt) + q.append(nxt) + ans += 1 diff --git a/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution2.java b/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution2.java new file mode 100644 index 0000000000000..430d6234159ba --- /dev/null +++ b/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution2.java @@ -0,0 +1,34 @@ +class Solution { + public int minimumMoves(int[][] grid) { + List left = new ArrayList<>(); + List right = new ArrayList<>(); + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) { + if (grid[i][j] == 0) { + left.add(new int[] {i, j}); + } else { + for (int k = 1; k < grid[i][j]; ++k) { + right.add(new int[] {i, j}); + } + } + } + } + int n = left.size(); + int[] f = new int[1 << n]; + Arrays.fill(f, 1 << 30); + f[0] = 0; + for (int i = 1; i < 1 << n; ++i) { + int k = Integer.bitCount(i); + for (int j = 0; j < n; ++j) { + if ((i >> j & 1) == 1) { + f[i] = Math.min(f[i], f[i ^ (1 << j)] + cal(left.get(k - 1), right.get(j))); + } + } + } + return f[(1 << n) - 1]; + } + + private int cal(int[] a, int[] b) { + return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]); + } +} \ No newline at end of file diff --git a/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution2.py b/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution2.py new file mode 100644 index 0000000000000..919a06d6a915c --- /dev/null +++ b/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution2.py @@ -0,0 +1,23 @@ +class Solution: + def minimumMoves(self, grid: List[List[int]]) -> int: + def cal(a: tuple, b: tuple) -> int: + return abs(a[0] - b[0]) + abs(a[1] - b[1]) + + left, right = [], [] + for i in range(3): + for j in range(3): + if grid[i][j] == 0: + left.append((i, j)) + else: + for _ in range(grid[i][j] - 1): + right.append((i, j)) + + n = len(left) + f = [inf] * (1 << n) + f[0] = 0 + for i in range(1, 1 << n): + k = i.bit_count() + for j in range(n): + if i >> j & 1: + f[i] = min(f[i], f[i ^ (1 << j)] + cal(left[k - 1], right[j])) + return f[-1] diff --git a/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/Solution.cpp b/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/Solution.cpp index 4fd4630b66930..ab34091f07bc4 100644 --- a/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/Solution.cpp +++ b/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - int minimumRightShifts(vector& nums) { - int n = nums.size(); - int i = 1; - while (i < n && nums[i - 1] < nums[i]) { - ++i; - } - int k = i + 1; - while (k < n && nums[k - 1] < nums[k] && nums[k] < nums[0]) { - ++k; - } - return k < n ? -1 : n - i; - } +class Solution { +public: + int minimumRightShifts(vector& nums) { + int n = nums.size(); + int i = 1; + while (i < n && nums[i - 1] < nums[i]) { + ++i; + } + int k = i + 1; + while (k < n && nums[k - 1] < nums[k] && nums[k] < nums[0]) { + ++k; + } + return k < n ? -1 : n - i; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/Solution.java b/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/Solution.java index c26bde526d312..f493efec922bd 100644 --- a/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/Solution.java +++ b/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/Solution.java @@ -1,14 +1,14 @@ -class Solution { - public int minimumRightShifts(List nums) { - int n = nums.size(); - int i = 1; - while (i < n && nums.get(i - 1) < nums.get(i)) { - ++i; - } - int k = i + 1; - while (k < n && nums.get(k - 1) < nums.get(k) && nums.get(k) < nums.get(0)) { - ++k; - } - return k < n ? -1 : n - i; - } +class Solution { + public int minimumRightShifts(List nums) { + int n = nums.size(); + int i = 1; + while (i < n && nums.get(i - 1) < nums.get(i)) { + ++i; + } + int k = i + 1; + while (k < n && nums.get(k - 1) < nums.get(k) && nums.get(k) < nums.get(0)) { + ++k; + } + return k < n ? -1 : n - i; + } } \ No newline at end of file diff --git a/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/Solution.py b/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/Solution.py index eb0c6b19d492c..1a5b879efb9d0 100644 --- a/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/Solution.py +++ b/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def minimumRightShifts(self, nums: List[int]) -> int: - n = len(nums) - i = 1 - while i < n and nums[i - 1] < nums[i]: - i += 1 - k = i + 1 - while k < n and nums[k - 1] < nums[k] < nums[0]: - k += 1 - return -1 if k < n else n - i +class Solution: + def minimumRightShifts(self, nums: List[int]) -> int: + n = len(nums) + i = 1 + while i < n and nums[i - 1] < nums[i]: + i += 1 + k = i + 1 + while k < n and nums[k - 1] < nums[k] < nums[0]: + k += 1 + return -1 if k < n else n - i diff --git a/solution/2800-2899/2856.Minimum Array Length After Pair Removals/Solution.cpp b/solution/2800-2899/2856.Minimum Array Length After Pair Removals/Solution.cpp index e53c90dbbffde..ee6319b20ed30 100644 --- a/solution/2800-2899/2856.Minimum Array Length After Pair Removals/Solution.cpp +++ b/solution/2800-2899/2856.Minimum Array Length After Pair Removals/Solution.cpp @@ -1,30 +1,30 @@ -class Solution { -public: - int minLengthAfterRemovals(vector& nums) { - unordered_map cnt; - for (int x : nums) { - ++cnt[x]; - } - priority_queue pq; - for (auto& [_, v] : cnt) { - pq.push(v); - } - int ans = nums.size(); - while (pq.size() > 1) { - int x = pq.top(); - pq.pop(); - int y = pq.top(); - pq.pop(); - x--; - y--; - if (x > 0) { - pq.push(x); - } - if (y > 0) { - pq.push(y); - } - ans -= 2; - } - return ans; - } +class Solution { +public: + int minLengthAfterRemovals(vector& nums) { + unordered_map cnt; + for (int x : nums) { + ++cnt[x]; + } + priority_queue pq; + for (auto& [_, v] : cnt) { + pq.push(v); + } + int ans = nums.size(); + while (pq.size() > 1) { + int x = pq.top(); + pq.pop(); + int y = pq.top(); + pq.pop(); + x--; + y--; + if (x > 0) { + pq.push(x); + } + if (y > 0) { + pq.push(y); + } + ans -= 2; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2856.Minimum Array Length After Pair Removals/Solution.java b/solution/2800-2899/2856.Minimum Array Length After Pair Removals/Solution.java index 1e6385cf6aa0b..9cf26596e37f8 100644 --- a/solution/2800-2899/2856.Minimum Array Length After Pair Removals/Solution.java +++ b/solution/2800-2899/2856.Minimum Array Length After Pair Removals/Solution.java @@ -1,27 +1,27 @@ -class Solution { - public int minLengthAfterRemovals(List nums) { - Map cnt = new HashMap<>(); - for (int x : nums) { - cnt.merge(x, 1, Integer::sum); - } - PriorityQueue pq = new PriorityQueue<>(Comparator.reverseOrder()); - for (int x : cnt.values()) { - pq.offer(x); - } - int ans = nums.size(); - while (pq.size() > 1) { - int x = pq.poll(); - int y = pq.poll(); - x--; - y--; - if (x > 0) { - pq.offer(x); - } - if (y > 0) { - pq.offer(y); - } - ans -= 2; - } - return ans; - } +class Solution { + public int minLengthAfterRemovals(List nums) { + Map cnt = new HashMap<>(); + for (int x : nums) { + cnt.merge(x, 1, Integer::sum); + } + PriorityQueue pq = new PriorityQueue<>(Comparator.reverseOrder()); + for (int x : cnt.values()) { + pq.offer(x); + } + int ans = nums.size(); + while (pq.size() > 1) { + int x = pq.poll(); + int y = pq.poll(); + x--; + y--; + if (x > 0) { + pq.offer(x); + } + if (y > 0) { + pq.offer(y); + } + ans -= 2; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2800-2899/2856.Minimum Array Length After Pair Removals/Solution.py b/solution/2800-2899/2856.Minimum Array Length After Pair Removals/Solution.py index 5c9b4dc8b5037..eb3dbbb764093 100644 --- a/solution/2800-2899/2856.Minimum Array Length After Pair Removals/Solution.py +++ b/solution/2800-2899/2856.Minimum Array Length After Pair Removals/Solution.py @@ -1,16 +1,16 @@ -class Solution: - def minLengthAfterRemovals(self, nums: List[int]) -> int: - cnt = Counter(nums) - pq = [-x for x in cnt.values()] - heapify(pq) - ans = len(nums) - while len(pq) > 1: - x, y = -heappop(pq), -heappop(pq) - x -= 1 - y -= 1 - if x > 0: - heappush(pq, -x) - if y > 0: - heappush(pq, -y) - ans -= 2 - return ans +class Solution: + def minLengthAfterRemovals(self, nums: List[int]) -> int: + cnt = Counter(nums) + pq = [-x for x in cnt.values()] + heapify(pq) + ans = len(nums) + while len(pq) > 1: + x, y = -heappop(pq), -heappop(pq) + x -= 1 + y -= 1 + if x > 0: + heappush(pq, -x) + if y > 0: + heappush(pq, -y) + ans -= 2 + return ans diff --git a/solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution.cpp b/solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution.cpp index 0fee7d0432a81..0f0d8c5aef34e 100644 --- a/solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution.cpp +++ b/solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution.cpp @@ -1,20 +1,17 @@ -class Solution { -public: - int countPairs(vector>& coordinates, int k) { - unordered_map cnt; - auto f = [](int x, int y) { - return x * 1000000L + y; - }; - int ans = 0; - for (auto& c : coordinates) { - int x2 = c[0], y2 = c[1]; - for (int a = 0; a <= k; ++a) { - int b = k - a; - int x1 = a ^ x2, y1 = b ^ y2; - ans += cnt[f(x1, y1)]; - } - ++cnt[f(x2, y2)]; - } - return ans; - } +class Solution { +public: + int countPairs(vector>& coordinates, int k) { + map, int> cnt; + int ans = 0; + for (auto& c : coordinates) { + int x2 = c[0], y2 = c[1]; + for (int a = 0; a <= k; ++a) { + int b = k - a; + int x1 = a ^ x2, y1 = b ^ y2; + ans += cnt[{x1, y1}]; + } + ++cnt[{x2, y2}]; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution.go b/solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution.go new file mode 100644 index 0000000000000..27151bcbd5e3b --- /dev/null +++ b/solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution.go @@ -0,0 +1,13 @@ +func countPairs(coordinates [][]int, k int) (ans int) { + cnt := map[[2]int]int{} + for _, c := range coordinates { + x2, y2 := c[0], c[1] + for a := 0; a <= k; a++ { + b := k - a + x1, y1 := a^x2, b^y2 + ans += cnt[[2]int{x1, y1}] + } + cnt[[2]int{x2, y2}]++ + } + return +} \ No newline at end of file diff --git a/solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution.java b/solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution.java index 8de215445c58d..3b9d74a5a21a0 100644 --- a/solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution.java +++ b/solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution.java @@ -1,16 +1,16 @@ -class Solution { - public int countPairs(List> coordinates, int k) { - Map, Integer> cnt = new HashMap<>(); - int ans = 0; - for (var c : coordinates) { - int x2 = c.get(0), y2 = c.get(1); - for (int a = 0; a <= k; ++a) { - int b = k - a; - int x1 = a ^ x2, y1 = b ^ y2; - ans += cnt.getOrDefault(List.of(x1, y1), 0); - } - cnt.merge(c, 1, Integer::sum); - } - return ans; - } +class Solution { + public int countPairs(List> coordinates, int k) { + Map, Integer> cnt = new HashMap<>(); + int ans = 0; + for (var c : coordinates) { + int x2 = c.get(0), y2 = c.get(1); + for (int a = 0; a <= k; ++a) { + int b = k - a; + int x1 = a ^ x2, y1 = b ^ y2; + ans += cnt.getOrDefault(List.of(x1, y1), 0); + } + cnt.merge(c, 1, Integer::sum); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution.py b/solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution.py index 5b114a5ace1b4..725f671270bc3 100644 --- a/solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution.py +++ b/solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def countPairs(self, coordinates: List[List[int]], k: int) -> int: - cnt = Counter() - ans = 0 - for x2, y2 in coordinates: - for a in range(k + 1): - b = k - a - x1, y1 = a ^ x2, b ^ y2 - ans += cnt[(x1, y1)] - cnt[(x2, y2)] += 1 - return ans +class Solution: + def countPairs(self, coordinates: List[List[int]], k: int) -> int: + cnt = Counter() + ans = 0 + for x2, y2 in coordinates: + for a in range(k + 1): + b = k - a + x1, y1 = a ^ x2, b ^ y2 + ans += cnt[(x1, y1)] + cnt[(x2, y2)] += 1 + return ans diff --git a/solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution2.cpp b/solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution2.cpp new file mode 100644 index 0000000000000..cb1b0dacad760 --- /dev/null +++ b/solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution2.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int countPairs(vector>& coordinates, int k) { + unordered_map cnt; + auto f = [](int x, int y) { + return x * 1000000L + y; + }; + int ans = 0; + for (auto& c : coordinates) { + int x2 = c[0], y2 = c[1]; + for (int a = 0; a <= k; ++a) { + int b = k - a; + int x1 = a ^ x2, y1 = b ^ y2; + ans += cnt[f(x1, y1)]; + } + ++cnt[f(x2, y2)]; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/Solution.cpp b/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/Solution.cpp index 4ce382baef59a..4570ceea14fc5 100644 --- a/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/Solution.cpp +++ b/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/Solution.cpp @@ -1,31 +1,31 @@ -class Solution { -public: - vector minEdgeReversals(int n, vector>& edges) { - vector> g[n]; - vector ans(n); - for (auto& e : edges) { - int x = e[0], y = e[1]; - g[x].emplace_back(y, 1); - g[y].emplace_back(x, -1); - } - function dfs = [&](int i, int fa) { - for (auto& [j, k] : g[i]) { - if (j != fa) { - ans[0] += k < 0; - dfs(j, i); - } - } - }; - function dfs2 = [&](int i, int fa) { - for (auto& [j, k] : g[i]) { - if (j != fa) { - ans[j] = ans[i] + k; - dfs2(j, i); - } - } - }; - dfs(0, -1); - dfs2(0, -1); - return ans; - } +class Solution { +public: + vector minEdgeReversals(int n, vector>& edges) { + vector> g[n]; + vector ans(n); + for (auto& e : edges) { + int x = e[0], y = e[1]; + g[x].emplace_back(y, 1); + g[y].emplace_back(x, -1); + } + function dfs = [&](int i, int fa) { + for (auto& [j, k] : g[i]) { + if (j != fa) { + ans[0] += k < 0; + dfs(j, i); + } + } + }; + function dfs2 = [&](int i, int fa) { + for (auto& [j, k] : g[i]) { + if (j != fa) { + ans[j] = ans[i] + k; + dfs2(j, i); + } + } + }; + dfs(0, -1); + dfs2(0, -1); + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/Solution.java b/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/Solution.java index 5c4ba99ce072a..c8d90575deabd 100644 --- a/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/Solution.java +++ b/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/Solution.java @@ -1,38 +1,38 @@ -class Solution { - private List[] g; - private int[] ans; - - public int[] minEdgeReversals(int n, int[][] edges) { - ans = new int[n]; - g = new List[n]; - Arrays.setAll(g, i -> new ArrayList<>()); - for (var e : edges) { - int x = e[0], y = e[1]; - g[x].add(new int[] {y, 1}); - g[y].add(new int[] {x, -1}); - } - dfs(0, -1); - dfs2(0, -1); - return ans; - } - - private void dfs(int i, int fa) { - for (var ne : g[i]) { - int j = ne[0], k = ne[1]; - if (j != fa) { - ans[0] += k < 0 ? 1 : 0; - dfs(j, i); - } - } - } - - private void dfs2(int i, int fa) { - for (var ne : g[i]) { - int j = ne[0], k = ne[1]; - if (j != fa) { - ans[j] = ans[i] + k; - dfs2(j, i); - } - } - } +class Solution { + private List[] g; + private int[] ans; + + public int[] minEdgeReversals(int n, int[][] edges) { + ans = new int[n]; + g = new List[n]; + Arrays.setAll(g, i -> new ArrayList<>()); + for (var e : edges) { + int x = e[0], y = e[1]; + g[x].add(new int[] {y, 1}); + g[y].add(new int[] {x, -1}); + } + dfs(0, -1); + dfs2(0, -1); + return ans; + } + + private void dfs(int i, int fa) { + for (var ne : g[i]) { + int j = ne[0], k = ne[1]; + if (j != fa) { + ans[0] += k < 0 ? 1 : 0; + dfs(j, i); + } + } + } + + private void dfs2(int i, int fa) { + for (var ne : g[i]) { + int j = ne[0], k = ne[1]; + if (j != fa) { + ans[j] = ans[i] + k; + dfs2(j, i); + } + } + } } \ No newline at end of file diff --git a/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/Solution.py b/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/Solution.py index fe04256d8155c..296dd623c9a37 100644 --- a/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/Solution.py +++ b/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/Solution.py @@ -1,24 +1,24 @@ -class Solution: - def minEdgeReversals(self, n: int, edges: List[List[int]]) -> List[int]: - ans = [0] * n - g = [[] for _ in range(n)] - for x, y in edges: - g[x].append((y, 1)) - g[y].append((x, -1)) - - def dfs(i: int, fa: int): - for j, k in g[i]: - if j != fa: - ans[0] += int(k < 0) - dfs(j, i) - - dfs(0, -1) - - def dfs2(i: int, fa: int): - for j, k in g[i]: - if j != fa: - ans[j] = ans[i] + k - dfs2(j, i) - - dfs2(0, -1) - return ans +class Solution: + def minEdgeReversals(self, n: int, edges: List[List[int]]) -> List[int]: + ans = [0] * n + g = [[] for _ in range(n)] + for x, y in edges: + g[x].append((y, 1)) + g[y].append((x, -1)) + + def dfs(i: int, fa: int): + for j, k in g[i]: + if j != fa: + ans[0] += int(k < 0) + dfs(j, i) + + dfs(0, -1) + + def dfs2(i: int, fa: int): + for j, k in g[i]: + if j != fa: + ans[j] = ans[i] + k + dfs2(j, i) + + dfs2(0, -1) + return ans diff --git a/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/Solution.cpp b/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/Solution.cpp index bdc07d66a91e6..3ecf984fe3857 100644 --- a/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/Solution.cpp +++ b/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/Solution.cpp @@ -1,12 +1,12 @@ -class Solution { -public: - int sumIndicesWithKSetBits(vector& nums, int k) { - int ans = 0; - for (int i = 0; i < nums.size(); ++i) { - if (__builtin_popcount(i) == k) { - ans += nums[i]; - } - } - return ans; - } +class Solution { +public: + int sumIndicesWithKSetBits(vector& nums, int k) { + int ans = 0; + for (int i = 0; i < nums.size(); ++i) { + if (__builtin_popcount(i) == k) { + ans += nums[i]; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/Solution.java b/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/Solution.java new file mode 100644 index 0000000000000..382705fb8c505 --- /dev/null +++ b/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/Solution.java @@ -0,0 +1,11 @@ +class Solution { + public int sumIndicesWithKSetBits(List nums, int k) { + int ans = 0; + for (int i = 0; i < nums.size(); i++) { + if (Integer.bitCount(i) == k) { + ans += nums.get(i); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/Solution.py b/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/Solution.py index 3de0c9fd75b7e..a8787045df295 100644 --- a/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/Solution.py +++ b/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/Solution.py @@ -1,3 +1,3 @@ -class Solution: - def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int: - return sum(x for i, x in enumerate(nums) if i.bit_count() == k) +class Solution: + def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int: + return sum(x for i, x in enumerate(nums) if i.bit_count() == k) diff --git a/solution/2800-2899/2860.Happy Students/Solution.cpp b/solution/2800-2899/2860.Happy Students/Solution.cpp index bcb4f8ec97572..855d3aa4e898c 100644 --- a/solution/2800-2899/2860.Happy Students/Solution.cpp +++ b/solution/2800-2899/2860.Happy Students/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - int countWays(vector& nums) { - sort(nums.begin(), nums.end()); - int ans = 0; - int n = nums.size(); - for (int i = 0; i <= n; ++i) { - if ((i && nums[i - 1] >= i) || (i < n && nums[i] <= i)) { - continue; - } - ++ans; - } - return ans; - } +class Solution { +public: + int countWays(vector& nums) { + sort(nums.begin(), nums.end()); + int ans = 0; + int n = nums.size(); + for (int i = 0; i <= n; ++i) { + if ((i && nums[i - 1] >= i) || (i < n && nums[i] <= i)) { + continue; + } + ++ans; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2860.Happy Students/Solution.py b/solution/2800-2899/2860.Happy Students/Solution.py index 75a5e9623d8d0..a58b42d46e987 100644 --- a/solution/2800-2899/2860.Happy Students/Solution.py +++ b/solution/2800-2899/2860.Happy Students/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def countWays(self, nums: List[int]) -> int: - nums.sort() - n = len(nums) - ans = 0 - for i in range(n + 1): - if i and nums[i - 1] >= i: - continue - if i < n and nums[i] <= i: - continue - return ans +class Solution: + def countWays(self, nums: List[int]) -> int: + nums.sort() + n = len(nums) + ans = 0 + for i in range(n + 1): + if i and nums[i - 1] >= i: + continue + if i < n and nums[i] <= i: + continue + return ans diff --git a/solution/2800-2899/2861.Maximum Number of Alloys/Solution.cpp b/solution/2800-2899/2861.Maximum Number of Alloys/Solution.cpp index 1fa88708517cc..385437e9ae0c3 100644 --- a/solution/2800-2899/2861.Maximum Number of Alloys/Solution.cpp +++ b/solution/2800-2899/2861.Maximum Number of Alloys/Solution.cpp @@ -1,29 +1,29 @@ -class Solution { -public: - int maxNumberOfAlloys(int n, int k, int budget, vector>& composition, vector& stock, vector& cost) { - auto isValid = [&](long long target) { - for (int i = 0; i < k; i++) { - long long remain = budget; - auto currMachine = composition[i]; - for (int j = 0; j < n && remain >= 0; j++) { - long long need = max(0LL, target * currMachine[j] - stock[j]); - remain -= need * cost[j]; - } - if (remain >= 0) { - return true; - } - } - return false; - }; - long long l = 0, r = budget + stock[0]; - while (l < r) { - long long mid = (l + r + 1) >> 1; - if (isValid(mid)) { - l = mid; - } else { - r = mid - 1; - } - } - return l; - } +class Solution { +public: + int maxNumberOfAlloys(int n, int k, int budget, vector>& composition, vector& stock, vector& cost) { + auto isValid = [&](long long target) { + for (int i = 0; i < k; i++) { + long long remain = budget; + auto currMachine = composition[i]; + for (int j = 0; j < n && remain >= 0; j++) { + long long need = max(0LL, target * currMachine[j] - stock[j]); + remain -= need * cost[j]; + } + if (remain >= 0) { + return true; + } + } + return false; + }; + long long l = 0, r = budget + stock[0]; + while (l < r) { + long long mid = (l + r + 1) >> 1; + if (isValid(mid)) { + l = mid; + } else { + r = mid - 1; + } + } + return l; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2861.Maximum Number of Alloys/Solution.py b/solution/2800-2899/2861.Maximum Number of Alloys/Solution.py index 40ce831f74b15..4bf4691ea1123 100644 --- a/solution/2800-2899/2861.Maximum Number of Alloys/Solution.py +++ b/solution/2800-2899/2861.Maximum Number of Alloys/Solution.py @@ -1,22 +1,22 @@ -class Solution: - def maxNumberOfAlloys( - self, - n: int, - k: int, - budget: int, - composition: List[List[int]], - stock: List[int], - cost: List[int], - ) -> int: - ans = 0 - for c in composition: - l, r = 0, budget + stock[0] - while l < r: - mid = (l + r + 1) >> 1 - s = sum(max(0, mid * x - y) * z for x, y, z in zip(c, stock, cost)) - if s <= budget: - l = mid - else: - r = mid - 1 - ans = max(ans, l) - return ans +class Solution: + def maxNumberOfAlloys( + self, + n: int, + k: int, + budget: int, + composition: List[List[int]], + stock: List[int], + cost: List[int], + ) -> int: + ans = 0 + for c in composition: + l, r = 0, budget + stock[0] + while l < r: + mid = (l + r + 1) >> 1 + s = sum(max(0, mid * x - y) * z for x, y, z in zip(c, stock, cost)) + if s <= budget: + l = mid + else: + r = mid - 1 + ans = max(ans, l) + return ans diff --git a/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/Solution.cpp b/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/Solution.cpp index 06118c4f0c769..a9d6aba5204b4 100644 --- a/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/Solution.cpp +++ b/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - long long maximumSum(vector& nums) { - long long ans = 0; - int n = nums.size(); - for (int k = 1; k <= n; ++k) { - long long t = 0; - for (int j = 1; k * j * j <= n; ++j) { - t += nums[k * j * j - 1]; - } - ans = max(ans, t); - } - return ans; - } +class Solution { +public: + long long maximumSum(vector& nums) { + long long ans = 0; + int n = nums.size(); + for (int k = 1; k <= n; ++k) { + long long t = 0; + for (int j = 1; k * j * j <= n; ++j) { + t += nums[k * j * j - 1]; + } + ans = max(ans, t); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/Solution.java b/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/Solution.java index 30bc7770e0885..5f793ec0cf4f8 100644 --- a/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/Solution.java +++ b/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/Solution.java @@ -2,12 +2,21 @@ class Solution { public long maximumSum(List nums) { long ans = 0; int n = nums.size(); - for (int k = 1; k <= n; ++k) { - long t = 0; - for (int j = 1; k * j * j <= n; ++j) { - t += nums.get(k * j * j - 1); + boolean[] used = new boolean[n + 1]; + int bound = (int) Math.floor(Math.sqrt(n)); + int[] squares = new int[bound + 1]; + for (int i = 1; i <= bound + 1; i++) { + squares[i - 1] = i * i; + } + for (int i = 1; i <= n; i++) { + long res = 0; + int idx = 0; + int curr = i * squares[idx]; + while (curr <= n) { + res += nums.get(curr - 1); + curr = i * squares[++idx]; } - ans = Math.max(ans, t); + ans = Math.max(ans, res); } return ans; } diff --git a/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/Solution.py b/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/Solution.py index 9a2605c9a1427..c66742fe2d031 100644 --- a/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/Solution.py +++ b/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def maximumSum(self, nums: List[int]) -> int: - n = len(nums) - ans = 0 - for k in range(1, n + 1): - t = 0 - j = 1 - while k * j * j <= n: - t += nums[k * j * j - 1] - j += 1 - ans = max(ans, t) - return ans +class Solution: + def maximumSum(self, nums: List[int]) -> int: + n = len(nums) + ans = 0 + for k in range(1, n + 1): + t = 0 + j = 1 + while k * j * j <= n: + t += nums[k * j * j - 1] + j += 1 + ans = max(ans, t) + return ans diff --git a/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/Solution2.java b/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/Solution2.java new file mode 100644 index 0000000000000..30bc7770e0885 --- /dev/null +++ b/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public long maximumSum(List nums) { + long ans = 0; + int n = nums.size(); + for (int k = 1; k <= n; ++k) { + long t = 0; + for (int j = 1; k * j * j <= n; ++j) { + t += nums.get(k * j * j - 1); + } + ans = Math.max(ans, t); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2800-2899/2864.Maximum Odd Binary Number/Solution.cpp b/solution/2800-2899/2864.Maximum Odd Binary Number/Solution.cpp index cb6caa8afcede..bc23bb566c141 100644 --- a/solution/2800-2899/2864.Maximum Odd Binary Number/Solution.cpp +++ b/solution/2800-2899/2864.Maximum Odd Binary Number/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - string maximumOddBinaryNumber(string s) { - int cnt = count_if(s.begin(), s.end(), [](char c) { return c == '1'; }); - string ans; - for (int i = 1; i < cnt; ++i) { - ans.push_back('1'); - } - for (int i = 0; i < s.size() - cnt; ++i) { - ans.push_back('0'); - } - ans.push_back('1'); - return ans; - } +class Solution { +public: + string maximumOddBinaryNumber(string s) { + int cnt = count_if(s.begin(), s.end(), [](char c) { return c == '1'; }); + string ans; + for (int i = 1; i < cnt; ++i) { + ans.push_back('1'); + } + for (int i = 0; i < s.size() - cnt; ++i) { + ans.push_back('0'); + } + ans.push_back('1'); + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2864.Maximum Odd Binary Number/Solution.java b/solution/2800-2899/2864.Maximum Odd Binary Number/Solution.java index 699654d0897b4..24e4d233b3567 100644 --- a/solution/2800-2899/2864.Maximum Odd Binary Number/Solution.java +++ b/solution/2800-2899/2864.Maximum Odd Binary Number/Solution.java @@ -1,11 +1,11 @@ -class Solution { - public String maximumOddBinaryNumber(String s) { - int cnt = 0; - for (char c : s.toCharArray()) { - if (c == '1') { - ++cnt; - } - } - return "1".repeat(cnt - 1) + "0".repeat(s.length() - cnt) + "1"; - } +class Solution { + public String maximumOddBinaryNumber(String s) { + int cnt = 0; + for (char c : s.toCharArray()) { + if (c == '1') { + ++cnt; + } + } + return "1".repeat(cnt - 1) + "0".repeat(s.length() - cnt) + "1"; + } } \ No newline at end of file diff --git a/solution/2800-2899/2864.Maximum Odd Binary Number/Solution.py b/solution/2800-2899/2864.Maximum Odd Binary Number/Solution.py index 6beedc385d79b..fe2736b8a13e6 100644 --- a/solution/2800-2899/2864.Maximum Odd Binary Number/Solution.py +++ b/solution/2800-2899/2864.Maximum Odd Binary Number/Solution.py @@ -1,4 +1,4 @@ -class Solution: - def maximumOddBinaryNumber(self, s: str) -> str: - cnt = s.count("1") - return "1" * (cnt - 1) + (len(s) - cnt) * "0" + "1" +class Solution: + def maximumOddBinaryNumber(self, s: str) -> str: + cnt = s.count("1") + return "1" * (cnt - 1) + (len(s) - cnt) * "0" + "1" diff --git a/solution/2800-2899/2865.Beautiful Towers I/Solution.cpp b/solution/2800-2899/2865.Beautiful Towers I/Solution.cpp index 91cb9631dd967..cab37c1a1a5e9 100644 --- a/solution/2800-2899/2865.Beautiful Towers I/Solution.cpp +++ b/solution/2800-2899/2865.Beautiful Towers I/Solution.cpp @@ -1,22 +1,22 @@ -class Solution { -public: - long long maximumSumOfHeights(vector& maxHeights) { - long long ans = 0; - int n = maxHeights.size(); - for (int i = 0; i < n; ++i) { - long long t = maxHeights[i]; - int y = t; - for (int j = i - 1; ~j; --j) { - y = min(y, maxHeights[j]); - t += y; - } - y = maxHeights[i]; - for (int j = i + 1; j < n; ++j) { - y = min(y, maxHeights[j]); - t += y; - } - ans = max(ans, t); - } - return ans; - } +class Solution { +public: + long long maximumSumOfHeights(vector& maxHeights) { + long long ans = 0; + int n = maxHeights.size(); + for (int i = 0; i < n; ++i) { + long long t = maxHeights[i]; + int y = t; + for (int j = i - 1; ~j; --j) { + y = min(y, maxHeights[j]); + t += y; + } + y = maxHeights[i]; + for (int j = i + 1; j < n; ++j) { + y = min(y, maxHeights[j]); + t += y; + } + ans = max(ans, t); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2865.Beautiful Towers I/Solution.java b/solution/2800-2899/2865.Beautiful Towers I/Solution.java index 9cc531d57d376..6636726a1ef98 100644 --- a/solution/2800-2899/2865.Beautiful Towers I/Solution.java +++ b/solution/2800-2899/2865.Beautiful Towers I/Solution.java @@ -1,21 +1,21 @@ -class Solution { - public long maximumSumOfHeights(List maxHeights) { - long ans = 0; - int n = maxHeights.size(); - for (int i = 0; i < n; ++i) { - int y = maxHeights.get(i); - long t = y; - for (int j = i - 1; j >= 0; --j) { - y = Math.min(y, maxHeights.get(j)); - t += y; - } - y = maxHeights.get(i); - for (int j = i + 1; j < n; ++j) { - y = Math.min(y, maxHeights.get(j)); - t += y; - } - ans = Math.max(ans, t); - } - return ans; - } +class Solution { + public long maximumSumOfHeights(List maxHeights) { + long ans = 0; + int n = maxHeights.size(); + for (int i = 0; i < n; ++i) { + int y = maxHeights.get(i); + long t = y; + for (int j = i - 1; j >= 0; --j) { + y = Math.min(y, maxHeights.get(j)); + t += y; + } + y = maxHeights.get(i); + for (int j = i + 1; j < n; ++j) { + y = Math.min(y, maxHeights.get(j)); + t += y; + } + ans = Math.max(ans, t); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2800-2899/2865.Beautiful Towers I/Solution.py b/solution/2800-2899/2865.Beautiful Towers I/Solution.py index b5a1ba420fa1e..42f9605e556f1 100644 --- a/solution/2800-2899/2865.Beautiful Towers I/Solution.py +++ b/solution/2800-2899/2865.Beautiful Towers I/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def maximumSumOfHeights(self, maxHeights: List[int]) -> int: - ans, n = 0, len(maxHeights) - for i, x in enumerate(maxHeights): - y = t = x - for j in range(i - 1, -1, -1): - y = min(y, maxHeights[j]) - t += y - y = x - for j in range(i + 1, n): - y = min(y, maxHeights[j]) - t += y - ans = max(ans, t) - return ans +class Solution: + def maximumSumOfHeights(self, maxHeights: List[int]) -> int: + ans, n = 0, len(maxHeights) + for i, x in enumerate(maxHeights): + y = t = x + for j in range(i - 1, -1, -1): + y = min(y, maxHeights[j]) + t += y + y = x + for j in range(i + 1, n): + y = min(y, maxHeights[j]) + t += y + ans = max(ans, t) + return ans diff --git a/solution/2800-2899/2865.Beautiful Towers I/Solution2.cpp b/solution/2800-2899/2865.Beautiful Towers I/Solution2.cpp new file mode 100644 index 0000000000000..ce7575fef5b94 --- /dev/null +++ b/solution/2800-2899/2865.Beautiful Towers I/Solution2.cpp @@ -0,0 +1,54 @@ +class Solution { +public: + long long maximumSumOfHeights(vector& maxHeights) { + int n = maxHeights.size(); + stack stk; + vector left(n, -1); + vector right(n, n); + for (int i = 0; i < n; ++i) { + int x = maxHeights[i]; + while (!stk.empty() && maxHeights[stk.top()] > x) { + stk.pop(); + } + if (!stk.empty()) { + left[i] = stk.top(); + } + stk.push(i); + } + stk = stack(); + for (int i = n - 1; ~i; --i) { + int x = maxHeights[i]; + while (!stk.empty() && maxHeights[stk.top()] >= x) { + stk.pop(); + } + if (!stk.empty()) { + right[i] = stk.top(); + } + stk.push(i); + } + long long f[n], g[n]; + for (int i = 0; i < n; ++i) { + int x = maxHeights[i]; + if (i && x >= maxHeights[i - 1]) { + f[i] = f[i - 1] + x; + } else { + int j = left[i]; + f[i] = 1LL * x * (i - j) + (j != -1 ? f[j] : 0); + } + } + for (int i = n - 1; ~i; --i) { + int x = maxHeights[i]; + if (i < n - 1 && x >= maxHeights[i + 1]) { + g[i] = g[i + 1] + x; + } else { + int j = right[i]; + g[i] = 1LL * x * (j - i) + (j != n ? g[j] : 0); + } + } + long long ans = 0; + for (int i = 0; i < n; ++i) { + ans = max(ans, f[i] + g[i] - maxHeights[i]); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2800-2899/2865.Beautiful Towers I/Solution2.go b/solution/2800-2899/2865.Beautiful Towers I/Solution2.go new file mode 100644 index 0000000000000..25e58174dd015 --- /dev/null +++ b/solution/2800-2899/2865.Beautiful Towers I/Solution2.go @@ -0,0 +1,59 @@ +func maximumSumOfHeights(maxHeights []int) (ans int64) { + n := len(maxHeights) + stk := []int{} + left := make([]int, n) + right := make([]int, n) + for i := range left { + left[i] = -1 + right[i] = n + } + for i, x := range maxHeights { + for len(stk) > 0 && maxHeights[stk[len(stk)-1]] > x { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + left[i] = stk[len(stk)-1] + } + stk = append(stk, i) + } + stk = []int{} + for i := n - 1; i >= 0; i-- { + x := maxHeights[i] + for len(stk) > 0 && maxHeights[stk[len(stk)-1]] >= x { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + right[i] = stk[len(stk)-1] + } + stk = append(stk, i) + } + f := make([]int64, n) + g := make([]int64, n) + for i, x := range maxHeights { + if i > 0 && x >= maxHeights[i-1] { + f[i] = f[i-1] + int64(x) + } else { + j := left[i] + f[i] = int64(x) * int64(i-j) + if j != -1 { + f[i] += f[j] + } + } + } + for i := n - 1; i >= 0; i-- { + x := maxHeights[i] + if i < n-1 && x >= maxHeights[i+1] { + g[i] = g[i+1] + int64(x) + } else { + j := right[i] + g[i] = int64(x) * int64(j-i) + if j != n { + g[i] += g[j] + } + } + } + for i, x := range maxHeights { + ans = max(ans, f[i]+g[i]-int64(x)) + } + return +} \ No newline at end of file diff --git a/solution/2800-2899/2865.Beautiful Towers I/Solution2.java b/solution/2800-2899/2865.Beautiful Towers I/Solution2.java new file mode 100644 index 0000000000000..b0bf147a06ef5 --- /dev/null +++ b/solution/2800-2899/2865.Beautiful Towers I/Solution2.java @@ -0,0 +1,56 @@ +class Solution { + public long maximumSumOfHeights(List maxHeights) { + int n = maxHeights.size(); + Deque stk = new ArrayDeque<>(); + int[] left = new int[n]; + int[] right = new int[n]; + Arrays.fill(left, -1); + Arrays.fill(right, n); + for (int i = 0; i < n; ++i) { + int x = maxHeights.get(i); + while (!stk.isEmpty() && maxHeights.get(stk.peek()) > x) { + stk.pop(); + } + if (!stk.isEmpty()) { + left[i] = stk.peek(); + } + stk.push(i); + } + stk.clear(); + for (int i = n - 1; i >= 0; --i) { + int x = maxHeights.get(i); + while (!stk.isEmpty() && maxHeights.get(stk.peek()) >= x) { + stk.pop(); + } + if (!stk.isEmpty()) { + right[i] = stk.peek(); + } + stk.push(i); + } + long[] f = new long[n]; + long[] g = new long[n]; + for (int i = 0; i < n; ++i) { + int x = maxHeights.get(i); + if (i > 0 && x >= maxHeights.get(i - 1)) { + f[i] = f[i - 1] + x; + } else { + int j = left[i]; + f[i] = 1L * x * (i - j) + (j >= 0 ? f[j] : 0); + } + } + for (int i = n - 1; i >= 0; --i) { + int x = maxHeights.get(i); + if (i < n - 1 && x >= maxHeights.get(i + 1)) { + g[i] = g[i + 1] + x; + } else { + int j = right[i]; + g[i] = 1L * x * (j - i) + (j < n ? g[j] : 0); + } + } + long ans = 0; + for (int i = 0; i < n; ++i) { + ans = Math.max(ans, f[i] + g[i] - maxHeights.get(i)); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2800-2899/2865.Beautiful Towers I/Solution2.py b/solution/2800-2899/2865.Beautiful Towers I/Solution2.py new file mode 100644 index 0000000000000..f43702c3485cf --- /dev/null +++ b/solution/2800-2899/2865.Beautiful Towers I/Solution2.py @@ -0,0 +1,35 @@ +class Solution: + def maximumSumOfHeights(self, maxHeights: List[int]) -> int: + n = len(maxHeights) + stk = [] + left = [-1] * n + for i, x in enumerate(maxHeights): + while stk and maxHeights[stk[-1]] > x: + stk.pop() + if stk: + left[i] = stk[-1] + stk.append(i) + stk = [] + right = [n] * n + for i in range(n - 1, -1, -1): + x = maxHeights[i] + while stk and maxHeights[stk[-1]] >= x: + stk.pop() + if stk: + right[i] = stk[-1] + stk.append(i) + f = [0] * n + for i, x in enumerate(maxHeights): + if i and x >= maxHeights[i - 1]: + f[i] = f[i - 1] + x + else: + j = left[i] + f[i] = x * (i - j) + (f[j] if j != -1 else 0) + g = [0] * n + for i in range(n - 1, -1, -1): + if i < n - 1 and maxHeights[i] >= maxHeights[i + 1]: + g[i] = g[i + 1] + maxHeights[i] + else: + j = right[i] + g[i] = maxHeights[i] * (j - i) + (g[j] if j != n else 0) + return max(a + b - c for a, b, c in zip(f, g, maxHeights)) diff --git a/solution/2800-2899/2865.Beautiful Towers I/Solution2.ts b/solution/2800-2899/2865.Beautiful Towers I/Solution2.ts new file mode 100644 index 0000000000000..2fc5670d40843 --- /dev/null +++ b/solution/2800-2899/2865.Beautiful Towers I/Solution2.ts @@ -0,0 +1,52 @@ +function maximumSumOfHeights(maxHeights: number[]): number { + const n = maxHeights.length; + const stk: number[] = []; + const left: number[] = Array(n).fill(-1); + const right: number[] = Array(n).fill(n); + for (let i = 0; i < n; ++i) { + const x = maxHeights[i]; + while (stk.length && maxHeights[stk.at(-1)] > x) { + stk.pop(); + } + if (stk.length) { + left[i] = stk.at(-1); + } + stk.push(i); + } + stk.length = 0; + for (let i = n - 1; ~i; --i) { + const x = maxHeights[i]; + while (stk.length && maxHeights[stk.at(-1)] >= x) { + stk.pop(); + } + if (stk.length) { + right[i] = stk.at(-1); + } + stk.push(i); + } + const f: number[] = Array(n).fill(0); + const g: number[] = Array(n).fill(0); + for (let i = 0; i < n; ++i) { + const x = maxHeights[i]; + if (i && x >= maxHeights[i - 1]) { + f[i] = f[i - 1] + x; + } else { + const j = left[i]; + f[i] = x * (i - j) + (j >= 0 ? f[j] : 0); + } + } + for (let i = n - 1; ~i; --i) { + const x = maxHeights[i]; + if (i + 1 < n && x >= maxHeights[i + 1]) { + g[i] = g[i + 1] + x; + } else { + const j = right[i]; + g[i] = x * (j - i) + (j < n ? g[j] : 0); + } + } + let ans = 0; + for (let i = 0; i < n; ++i) { + ans = Math.max(ans, f[i] + g[i] - maxHeights[i]); + } + return ans; +} diff --git a/solution/2800-2899/2866.Beautiful Towers II/Solution.cpp b/solution/2800-2899/2866.Beautiful Towers II/Solution.cpp index 30f76fc4e000b..ce7575fef5b94 100644 --- a/solution/2800-2899/2866.Beautiful Towers II/Solution.cpp +++ b/solution/2800-2899/2866.Beautiful Towers II/Solution.cpp @@ -1,54 +1,54 @@ -class Solution { -public: - long long maximumSumOfHeights(vector& maxHeights) { - int n = maxHeights.size(); - stack stk; - vector left(n, -1); - vector right(n, n); - for (int i = 0; i < n; ++i) { - int x = maxHeights[i]; - while (!stk.empty() && maxHeights[stk.top()] > x) { - stk.pop(); - } - if (!stk.empty()) { - left[i] = stk.top(); - } - stk.push(i); - } - stk = stack(); - for (int i = n - 1; ~i; --i) { - int x = maxHeights[i]; - while (!stk.empty() && maxHeights[stk.top()] >= x) { - stk.pop(); - } - if (!stk.empty()) { - right[i] = stk.top(); - } - stk.push(i); - } - long long f[n], g[n]; - for (int i = 0; i < n; ++i) { - int x = maxHeights[i]; - if (i && x >= maxHeights[i - 1]) { - f[i] = f[i - 1] + x; - } else { - int j = left[i]; - f[i] = 1LL * x * (i - j) + (j != -1 ? f[j] : 0); - } - } - for (int i = n - 1; ~i; --i) { - int x = maxHeights[i]; - if (i < n - 1 && x >= maxHeights[i + 1]) { - g[i] = g[i + 1] + x; - } else { - int j = right[i]; - g[i] = 1LL * x * (j - i) + (j != n ? g[j] : 0); - } - } - long long ans = 0; - for (int i = 0; i < n; ++i) { - ans = max(ans, f[i] + g[i] - maxHeights[i]); - } - return ans; - } +class Solution { +public: + long long maximumSumOfHeights(vector& maxHeights) { + int n = maxHeights.size(); + stack stk; + vector left(n, -1); + vector right(n, n); + for (int i = 0; i < n; ++i) { + int x = maxHeights[i]; + while (!stk.empty() && maxHeights[stk.top()] > x) { + stk.pop(); + } + if (!stk.empty()) { + left[i] = stk.top(); + } + stk.push(i); + } + stk = stack(); + for (int i = n - 1; ~i; --i) { + int x = maxHeights[i]; + while (!stk.empty() && maxHeights[stk.top()] >= x) { + stk.pop(); + } + if (!stk.empty()) { + right[i] = stk.top(); + } + stk.push(i); + } + long long f[n], g[n]; + for (int i = 0; i < n; ++i) { + int x = maxHeights[i]; + if (i && x >= maxHeights[i - 1]) { + f[i] = f[i - 1] + x; + } else { + int j = left[i]; + f[i] = 1LL * x * (i - j) + (j != -1 ? f[j] : 0); + } + } + for (int i = n - 1; ~i; --i) { + int x = maxHeights[i]; + if (i < n - 1 && x >= maxHeights[i + 1]) { + g[i] = g[i + 1] + x; + } else { + int j = right[i]; + g[i] = 1LL * x * (j - i) + (j != n ? g[j] : 0); + } + } + long long ans = 0; + for (int i = 0; i < n; ++i) { + ans = max(ans, f[i] + g[i] - maxHeights[i]); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2866.Beautiful Towers II/Solution.java b/solution/2800-2899/2866.Beautiful Towers II/Solution.java index 6ec05124753f9..b0bf147a06ef5 100644 --- a/solution/2800-2899/2866.Beautiful Towers II/Solution.java +++ b/solution/2800-2899/2866.Beautiful Towers II/Solution.java @@ -1,56 +1,56 @@ -class Solution { - public long maximumSumOfHeights(List maxHeights) { - int n = maxHeights.size(); - Deque stk = new ArrayDeque<>(); - int[] left = new int[n]; - int[] right = new int[n]; - Arrays.fill(left, -1); - Arrays.fill(right, n); - for (int i = 0; i < n; ++i) { - int x = maxHeights.get(i); - while (!stk.isEmpty() && maxHeights.get(stk.peek()) > x) { - stk.pop(); - } - if (!stk.isEmpty()) { - left[i] = stk.peek(); - } - stk.push(i); - } - stk.clear(); - for (int i = n - 1; i >= 0; --i) { - int x = maxHeights.get(i); - while (!stk.isEmpty() && maxHeights.get(stk.peek()) >= x) { - stk.pop(); - } - if (!stk.isEmpty()) { - right[i] = stk.peek(); - } - stk.push(i); - } - long[] f = new long[n]; - long[] g = new long[n]; - for (int i = 0; i < n; ++i) { - int x = maxHeights.get(i); - if (i > 0 && x >= maxHeights.get(i - 1)) { - f[i] = f[i - 1] + x; - } else { - int j = left[i]; - f[i] = 1L * x * (i - j) + (j >= 0 ? f[j] : 0); - } - } - for (int i = n - 1; i >= 0; --i) { - int x = maxHeights.get(i); - if (i < n - 1 && x >= maxHeights.get(i + 1)) { - g[i] = g[i + 1] + x; - } else { - int j = right[i]; - g[i] = 1L * x * (j - i) + (j < n ? g[j] : 0); - } - } - long ans = 0; - for (int i = 0; i < n; ++i) { - ans = Math.max(ans, f[i] + g[i] - maxHeights.get(i)); - } - return ans; - } +class Solution { + public long maximumSumOfHeights(List maxHeights) { + int n = maxHeights.size(); + Deque stk = new ArrayDeque<>(); + int[] left = new int[n]; + int[] right = new int[n]; + Arrays.fill(left, -1); + Arrays.fill(right, n); + for (int i = 0; i < n; ++i) { + int x = maxHeights.get(i); + while (!stk.isEmpty() && maxHeights.get(stk.peek()) > x) { + stk.pop(); + } + if (!stk.isEmpty()) { + left[i] = stk.peek(); + } + stk.push(i); + } + stk.clear(); + for (int i = n - 1; i >= 0; --i) { + int x = maxHeights.get(i); + while (!stk.isEmpty() && maxHeights.get(stk.peek()) >= x) { + stk.pop(); + } + if (!stk.isEmpty()) { + right[i] = stk.peek(); + } + stk.push(i); + } + long[] f = new long[n]; + long[] g = new long[n]; + for (int i = 0; i < n; ++i) { + int x = maxHeights.get(i); + if (i > 0 && x >= maxHeights.get(i - 1)) { + f[i] = f[i - 1] + x; + } else { + int j = left[i]; + f[i] = 1L * x * (i - j) + (j >= 0 ? f[j] : 0); + } + } + for (int i = n - 1; i >= 0; --i) { + int x = maxHeights.get(i); + if (i < n - 1 && x >= maxHeights.get(i + 1)) { + g[i] = g[i + 1] + x; + } else { + int j = right[i]; + g[i] = 1L * x * (j - i) + (j < n ? g[j] : 0); + } + } + long ans = 0; + for (int i = 0; i < n; ++i) { + ans = Math.max(ans, f[i] + g[i] - maxHeights.get(i)); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2800-2899/2866.Beautiful Towers II/Solution.py b/solution/2800-2899/2866.Beautiful Towers II/Solution.py index dfd09de02718f..f43702c3485cf 100644 --- a/solution/2800-2899/2866.Beautiful Towers II/Solution.py +++ b/solution/2800-2899/2866.Beautiful Towers II/Solution.py @@ -1,35 +1,35 @@ -class Solution: - def maximumSumOfHeights(self, maxHeights: List[int]) -> int: - n = len(maxHeights) - stk = [] - left = [-1] * n - for i, x in enumerate(maxHeights): - while stk and maxHeights[stk[-1]] > x: - stk.pop() - if stk: - left[i] = stk[-1] - stk.append(i) - stk = [] - right = [n] * n - for i in range(n - 1, -1, -1): - x = maxHeights[i] - while stk and maxHeights[stk[-1]] >= x: - stk.pop() - if stk: - right[i] = stk[-1] - stk.append(i) - f = [0] * n - for i, x in enumerate(maxHeights): - if i and x >= maxHeights[i - 1]: - f[i] = f[i - 1] + x - else: - j = left[i] - f[i] = x * (i - j) + (f[j] if j != -1 else 0) - g = [0] * n - for i in range(n - 1, -1, -1): - if i < n - 1 and maxHeights[i] >= maxHeights[i + 1]: - g[i] = g[i + 1] + maxHeights[i] - else: - j = right[i] - g[i] = maxHeights[i] * (j - i) + (g[j] if j != n else 0) - return max(a + b - c for a, b, c in zip(f, g, maxHeights)) +class Solution: + def maximumSumOfHeights(self, maxHeights: List[int]) -> int: + n = len(maxHeights) + stk = [] + left = [-1] * n + for i, x in enumerate(maxHeights): + while stk and maxHeights[stk[-1]] > x: + stk.pop() + if stk: + left[i] = stk[-1] + stk.append(i) + stk = [] + right = [n] * n + for i in range(n - 1, -1, -1): + x = maxHeights[i] + while stk and maxHeights[stk[-1]] >= x: + stk.pop() + if stk: + right[i] = stk[-1] + stk.append(i) + f = [0] * n + for i, x in enumerate(maxHeights): + if i and x >= maxHeights[i - 1]: + f[i] = f[i - 1] + x + else: + j = left[i] + f[i] = x * (i - j) + (f[j] if j != -1 else 0) + g = [0] * n + for i in range(n - 1, -1, -1): + if i < n - 1 and maxHeights[i] >= maxHeights[i + 1]: + g[i] = g[i + 1] + maxHeights[i] + else: + j = right[i] + g[i] = maxHeights[i] * (j - i) + (g[j] if j != n else 0) + return max(a + b - c for a, b, c in zip(f, g, maxHeights)) diff --git a/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution.cpp b/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution.cpp index 61cda58e24057..8824ce2e083f7 100644 --- a/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution.cpp +++ b/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution.cpp @@ -1,51 +1,82 @@ -class Solution { - long long mul(long long x, long long y) { - return x * y; +const int mx = 1e5 + 10; +bool prime[mx + 1]; +int init = []() { + for (int i = 2; i <= mx; ++i) prime[i] = true; + for (int i = 2; i <= mx; ++i) { + if (prime[i]) { + for (int j = i + i; j <= mx; j += i) { + prime[j] = false; + } + } } + return 0; +}(); - pair dfs(int x, int f, const vector>& con, const vector& prime, long long& r) { - pair v = {!prime[x], prime[x]}; - for (int y : con[x]) { - if (y == f) continue; - const auto& p = dfs(y, x, con, prime, r); - r += mul(p.first, v.second) + mul(p.second, v.first); - if (prime[x]) { - v.second += p.first; - } else { - v.first += p.first; - v.second += p.second; - } +class UnionFind { +public: + UnionFind(int n) { + p = vector(n); + size = vector(n, 1); + iota(p.begin(), p.end(), 0); + } + + bool unite(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) { + return false; + } + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + return true; + } + + int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); } - return v; + return p[x]; } + int getSize(int x) { + return size[find(x)]; + } + +private: + vector p, size; +}; + +class Solution { public: long long countPaths(int n, vector>& edges) { - vector prime(n + 1, true); - prime[1] = false; - vector all; - for (int i = 2; i <= n; ++i) { - if (prime[i]) { - all.push_back(i); + vector g[n + 1]; + UnionFind uf(n + 1); + for (auto& e : edges) { + int u = e[0], v = e[1]; + g[u].push_back(v); + g[v].push_back(u); + if (!prime[u] && !prime[v]) { + uf.unite(u, v); } - for (int x : all) { - const int temp = i * x; - if (temp > n) { - break; - } - prime[temp] = false; - if (i % x == 0) { - break; + } + long long ans = 0; + for (int i = 1; i <= n; ++i) { + if (prime[i]) { + long long t = 0; + for (int j : g[i]) { + if (!prime[j]) { + long long cnt = uf.getSize(j); + ans += cnt; + ans += cnt * t; + t += cnt; + } } } } - vector> con(n + 1); - for (const auto& e : edges) { - con[e[0]].push_back(e[1]); - con[e[1]].push_back(e[0]); - } - long long r = 0; - dfs(1, 0, con, prime, r); - return r; + return ans; } -}; +}; \ No newline at end of file diff --git a/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution.java b/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution.java index c727227b6bb8d..d699bd8a7bc52 100644 --- a/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution.java +++ b/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution.java @@ -1,69 +1,94 @@ -class Solution { - public long countPaths(int n, int[][] edges) { - List prime = new ArrayList<>(n + 1); - for (int i = 0; i <= n; ++i) { - prime.add(true); - } - prime.set(1, false); +class PrimeTable { + private final boolean[] prime; - List all = new ArrayList<>(); + public PrimeTable(int n) { + prime = new boolean[n + 1]; + Arrays.fill(prime, true); + prime[0] = false; + prime[1] = false; for (int i = 2; i <= n; ++i) { - if (prime.get(i)) { - all.add(i); - } - for (int x : all) { - int temp = i * x; - if (temp > n) { - break; - } - prime.set(temp, false); - if (i % x == 0) { - break; + if (prime[i]) { + for (int j = i + i; j <= n; j += i) { + prime[j] = false; } } } + } - List> con = new ArrayList<>(n + 1); - for (int i = 0; i <= n; ++i) { - con.add(new ArrayList<>()); + public boolean isPrime(int x) { + return prime[x]; + } +} + +class UnionFind { + private final int[] p; + private final int[] size; + + public UnionFind(int n) { + p = new int[n]; + size = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + size[i] = 1; } - for (int[] e : edges) { - con.get(e[0]).add(e[1]); - con.get(e[1]).add(e[0]); + } + + public int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); } + return p[x]; + } - long[] r = {0}; - dfs(1, 0, con, prime, r); - return r[0]; + public boolean union(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) { + return false; + } + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + return true; } - private long mul(long x, long y) { - return x * y; + public int size(int x) { + return size[find(x)]; } +} - private class Pair { - int first; - int second; +class Solution { + private static final PrimeTable PT = new PrimeTable(100010); - Pair(int first, int second) { - this.first = first; - this.second = second; + public long countPaths(int n, int[][] edges) { + List[] g = new List[n + 1]; + Arrays.setAll(g, i -> new ArrayList<>()); + UnionFind uf = new UnionFind(n + 1); + for (int[] e : edges) { + int u = e[0], v = e[1]; + g[u].add(v); + g[v].add(u); + if (!PT.isPrime(u) && !PT.isPrime(v)) { + uf.union(u, v); + } } - } - - private Pair dfs(int x, int f, List> con, List prime, long[] r) { - Pair v = new Pair(!prime.get(x) ? 1 : 0, prime.get(x) ? 1 : 0); - for (int y : con.get(x)) { - if (y == f) continue; - Pair p = dfs(y, x, con, prime, r); - r[0] += mul(p.first, v.second) + mul(p.second, v.first); - if (prime.get(x)) { - v.second += p.first; - } else { - v.first += p.first; - v.second += p.second; + long ans = 0; + for (int i = 1; i <= n; ++i) { + if (PT.isPrime(i)) { + long t = 0; + for (int j : g[i]) { + if (!PT.isPrime(j)) { + long cnt = uf.size(j); + ans += cnt; + ans += cnt * t; + t += cnt; + } + } } } - return v; + return ans; } -} +} \ No newline at end of file diff --git a/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution.py b/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution.py index 51e89eeefa99f..4d12a6102dae7 100644 --- a/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution.py +++ b/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution.py @@ -1,42 +1,53 @@ -class Solution: - def countPaths(self, n: int, edges: List[List[int]]) -> int: - def mul(x, y): - return x * y +class UnionFind: + def __init__(self, n): + self.p = list(range(n)) + self.size = [1] * n - def dfs(x, f, con, prime, r): - v = [1 - prime[x], prime[x]] - for y in con[x]: - if y == f: - continue - p = dfs(y, x, con, prime, r) - r[0] += mul(p[0], v[1]) + mul(p[1], v[0]) - if prime[x]: - v[1] += p[0] - else: - v[0] += p[0] - v[1] += p[1] - return v + def find(self, x): + if self.p[x] != x: + self.p[x] = self.find(self.p[x]) + return self.p[x] - prime = [True] * (n + 1) - prime[1] = False + def union(self, a, b): + pa, pb = self.find(a), self.find(b) + if pa == pb: + return False + if self.size[pa] > self.size[pb]: + self.p[pb] = pa + self.size[pa] += self.size[pb] + else: + self.p[pa] = pb + self.size[pb] += self.size[pa] + return True - all_primes = [] - for i in range(2, n + 1): - if prime[i]: - all_primes.append(i) - for x in all_primes: - temp = i * x - if temp > n: - break - prime[temp] = False - if i % x == 0: - break - con = [[] for _ in range(n + 1)] - for e in edges: - con[e[0]].append(e[1]) - con[e[1]].append(e[0]) +mx = 10**5 + 10 +prime = [True] * (mx + 1) +prime[0] = prime[1] = False +for i in range(2, mx + 1): + if prime[i]: + for j in range(i * i, mx + 1, i): + prime[j] = False + - r = [0] - dfs(1, 0, con, prime, r) - return r[0] +class Solution: + def countPaths(self, n: int, edges: List[List[int]]) -> int: + g = [[] for _ in range(n + 1)] + uf = UnionFind(n + 1) + for u, v in edges: + g[u].append(v) + g[v].append(u) + if prime[u] + prime[v] == 0: + uf.union(u, v) + + ans = 0 + for i in range(1, n + 1): + if prime[i]: + t = 0 + for j in g[i]: + if not prime[j]: + cnt = uf.size[uf.find(j)] + ans += cnt + ans += t * cnt + t += cnt + return ans diff --git a/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution2.cpp b/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution2.cpp new file mode 100644 index 0000000000000..2f44d08fd9f8e --- /dev/null +++ b/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution2.cpp @@ -0,0 +1,51 @@ +class Solution { + long long mul(long long x, long long y) { + return x * y; + } + + pair dfs(int x, int f, const vector>& con, const vector& prime, long long& r) { + pair v = {!prime[x], prime[x]}; + for (int y : con[x]) { + if (y == f) continue; + const auto& p = dfs(y, x, con, prime, r); + r += mul(p.first, v.second) + mul(p.second, v.first); + if (prime[x]) { + v.second += p.first; + } else { + v.first += p.first; + v.second += p.second; + } + } + return v; + } + +public: + long long countPaths(int n, vector>& edges) { + vector prime(n + 1, true); + prime[1] = false; + vector all; + for (int i = 2; i <= n; ++i) { + if (prime[i]) { + all.push_back(i); + } + for (int x : all) { + const int temp = i * x; + if (temp > n) { + break; + } + prime[temp] = false; + if (i % x == 0) { + break; + } + } + } + vector> con(n + 1); + for (const auto& e : edges) { + con[e[0]].push_back(e[1]); + con[e[1]].push_back(e[0]); + } + long long r = 0; + dfs(1, 0, con, prime, r); + return r; + } +}; \ No newline at end of file diff --git a/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution2.java b/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution2.java new file mode 100644 index 0000000000000..0b57adb55c5ae --- /dev/null +++ b/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution2.java @@ -0,0 +1,69 @@ +class Solution { + public long countPaths(int n, int[][] edges) { + List prime = new ArrayList<>(n + 1); + for (int i = 0; i <= n; ++i) { + prime.add(true); + } + prime.set(1, false); + + List all = new ArrayList<>(); + for (int i = 2; i <= n; ++i) { + if (prime.get(i)) { + all.add(i); + } + for (int x : all) { + int temp = i * x; + if (temp > n) { + break; + } + prime.set(temp, false); + if (i % x == 0) { + break; + } + } + } + + List> con = new ArrayList<>(n + 1); + for (int i = 0; i <= n; ++i) { + con.add(new ArrayList<>()); + } + for (int[] e : edges) { + con.get(e[0]).add(e[1]); + con.get(e[1]).add(e[0]); + } + + long[] r = {0}; + dfs(1, 0, con, prime, r); + return r[0]; + } + + private long mul(long x, long y) { + return x * y; + } + + private class Pair { + int first; + int second; + + Pair(int first, int second) { + this.first = first; + this.second = second; + } + } + + private Pair dfs(int x, int f, List> con, List prime, long[] r) { + Pair v = new Pair(!prime.get(x) ? 1 : 0, prime.get(x) ? 1 : 0); + for (int y : con.get(x)) { + if (y == f) continue; + Pair p = dfs(y, x, con, prime, r); + r[0] += mul(p.first, v.second) + mul(p.second, v.first); + if (prime.get(x)) { + v.second += p.first; + } else { + v.first += p.first; + v.second += p.second; + } + } + return v; + } +} \ No newline at end of file diff --git a/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution2.py b/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution2.py new file mode 100644 index 0000000000000..51e89eeefa99f --- /dev/null +++ b/solution/2800-2899/2867.Count Valid Paths in a Tree/Solution2.py @@ -0,0 +1,42 @@ +class Solution: + def countPaths(self, n: int, edges: List[List[int]]) -> int: + def mul(x, y): + return x * y + + def dfs(x, f, con, prime, r): + v = [1 - prime[x], prime[x]] + for y in con[x]: + if y == f: + continue + p = dfs(y, x, con, prime, r) + r[0] += mul(p[0], v[1]) + mul(p[1], v[0]) + if prime[x]: + v[1] += p[0] + else: + v[0] += p[0] + v[1] += p[1] + return v + + prime = [True] * (n + 1) + prime[1] = False + + all_primes = [] + for i in range(2, n + 1): + if prime[i]: + all_primes.append(i) + for x in all_primes: + temp = i * x + if temp > n: + break + prime[temp] = False + if i % x == 0: + break + + con = [[] for _ in range(n + 1)] + for e in edges: + con[e[0]].append(e[1]) + con[e[1]].append(e[0]) + + r = [0] + dfs(1, 0, con, prime, r) + return r[0] diff --git a/solution/2800-2899/2869.Minimum Operations to Collect Elements/Solution.java b/solution/2800-2899/2869.Minimum Operations to Collect Elements/Solution.java index b8482dee00102..04c7a6c90f655 100644 --- a/solution/2800-2899/2869.Minimum Operations to Collect Elements/Solution.java +++ b/solution/2800-2899/2869.Minimum Operations to Collect Elements/Solution.java @@ -14,4 +14,4 @@ public int minOperations(List nums, int k) { } } } -} +} \ No newline at end of file diff --git a/solution/2800-2899/2872.Maximum Number of K-Divisible Components/Solution2.java b/solution/2800-2899/2872.Maximum Number of K-Divisible Components/Solution2.java new file mode 100644 index 0000000000000..c785cb5e31546 --- /dev/null +++ b/solution/2800-2899/2872.Maximum Number of K-Divisible Components/Solution2.java @@ -0,0 +1,34 @@ +class Solution { + int n, k; + int[] values; + int[] dfs(int curr, int parent, List> adj) { + int[] res = new int[] {0, values[curr] % k}; + for (int next : adj.get(curr)) { + if (next == parent) { + continue; + } + int[] update = dfs(next, curr, adj); + res[0] += update[0]; + res[1] += update[1]; + } + res[1] %= k; + res[0] += res[1] == 0 ? 1 : 0; + return res; + } + public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) { + this.n = n; + this.k = k; + this.values = values; + List> adj = new ArrayList<>(); + int[][] dp = new int[n][2]; + for (int i = 0; i < n; i++) { + adj.add(new ArrayList<>()); + } + for (int[] edge : edges) { + adj.get(edge[0]).add(edge[1]); + adj.get(edge[1]).add(edge[0]); + } + int[] ans = dfs(0, -1, adj); + return ans[1] == 0 ? ans[0] : 0; + } +} \ No newline at end of file diff --git a/solution/2800-2899/2875.Minimum Size Subarray in Infinite Array/Solution2.java b/solution/2800-2899/2875.Minimum Size Subarray in Infinite Array/Solution2.java new file mode 100644 index 0000000000000..20e2877c2ba5d --- /dev/null +++ b/solution/2800-2899/2875.Minimum Size Subarray in Infinite Array/Solution2.java @@ -0,0 +1,45 @@ +class Solution { + public int shortestSubarray(int[] nums, int k) { + int n = nums.length; + + int minLength = n * 2 + 1; + int l = 0; + int sum = 0; + + for (int r = 0; r < n * 2; r++) { + int start = l % n; + int end = r % n; + sum += nums[end]; + + while (sum > k && l <= r) { + start = l % n; + sum -= nums[start]; + l++; + } + + if (sum == k) { + minLength = Math.min(minLength, r - l + 1); + start = l % n; + sum -= nums[start]; + l++; + } + } + + return minLength == n * 2 + 1 ? -1 : minLength; + } + public int minSizeSubarray(int[] nums, int target) { + int n = nums.length; + int sum = 0; + + for (int num : nums) { + sum += num; + } + int k = target % sum; + int ans = target / sum * n; + if (k == 0) { + return ans; + } + int res = shortestSubarray(nums, k); + return res == -1 ? -1 : ans + res; + } +} \ No newline at end of file diff --git a/solution/2800-2899/2876.Count Visited Nodes in a Directed Graph/Solution2.java b/solution/2800-2899/2876.Count Visited Nodes in a Directed Graph/Solution2.java new file mode 100644 index 0000000000000..4bd3ed8bff1d8 --- /dev/null +++ b/solution/2800-2899/2876.Count Visited Nodes in a Directed Graph/Solution2.java @@ -0,0 +1,36 @@ +class Solution { + void dfs(int curr, List edges, int[] ans) { + + List path = new ArrayList<>(); + int prev = -1; + while (ans[curr] == 0) { + path.add(curr); + ans[curr] = prev == -1 ? -1 : ans[prev] - 1; + prev = curr; + curr = edges.get(curr); + } + int idx = path.size() - 1; + if (ans[curr] < 0) { + int cycle = ans[curr] - ans[path.get(idx)] + 1; + int start = ans[curr]; + for (; idx >= 0 && ans[path.get(idx)] <= start; idx--) { + ans[path.get(idx)] = cycle; + } + } + for (; idx >= 0; idx--) { + ans[path.get(idx)] = ans[edges.get(path.get(idx))] + 1; + } + } + + public int[] countVisitedNodes(List edges) { + int n = edges.size(); + int[] ans = new int[n]; + for (int i = 0; i < n; i++) { + if (ans[i] > 0) { + continue; + } + dfs(i, edges, ans); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2800-2899/2893.Calculate Orders Within Each Interval/Solution2.sql b/solution/2800-2899/2893.Calculate Orders Within Each Interval/Solution2.sql new file mode 100644 index 0000000000000..6544ba4ee3be5 --- /dev/null +++ b/solution/2800-2899/2893.Calculate Orders Within Each Interval/Solution2.sql @@ -0,0 +1,6 @@ +SELECT + FLOOR((minute + 5) / 6) AS interval_no, + SUM(order_count) AS total_orders +FROM Orders +GROUP BY 1 +ORDER BY 1; diff --git a/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution.cpp b/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution.cpp index c40a823aa3c9f..f7dab44da5707 100644 --- a/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution.cpp +++ b/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution.cpp @@ -1,10 +1,10 @@ -class Solution { -public: - int differenceOfSums(int n, int m) { - int ans = 0; - for (int i = 1; i <= n; ++i) { - ans += i % m ? i : -i; - } - return ans; - } +class Solution { +public: + int differenceOfSums(int n, int m) { + int ans = 0; + for (int i = 1; i <= n; ++i) { + ans += i % m ? i : -i; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution.java b/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution.java index 2641981332d41..ab683d83cfa9f 100644 --- a/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution.java +++ b/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution.java @@ -1,9 +1,9 @@ -class Solution { - public int differenceOfSums(int n, int m) { - int ans = 0; - for (int i = 1; i <= n; ++i) { - ans += i % m == 0 ? -i : i; - } - return ans; - } +class Solution { + public int differenceOfSums(int n, int m) { + int ans = 0; + for (int i = 1; i <= n; ++i) { + ans += i % m == 0 ? -i : i; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution.py b/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution.py index 536dd5344916f..89ffa2397d1a1 100644 --- a/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution.py +++ b/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution.py @@ -1,3 +1,3 @@ -class Solution: - def differenceOfSums(self, n: int, m: int) -> int: - return sum(i if i % m else -i for i in range(1, n + 1)) +class Solution: + def differenceOfSums(self, n: int, m: int) -> int: + return sum(i if i % m else -i for i in range(1, n + 1)) diff --git a/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution2.java b/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution2.java new file mode 100644 index 0000000000000..2c9c664c427da --- /dev/null +++ b/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution2.java @@ -0,0 +1,8 @@ +class Solution { + public int differenceOfSums(int n, int m) { + int sum = n * (n + 1) / 2; + int k = n / m; + int nums2 = k * (k + 1) / 2 * m; + return sum - nums2 * 2; + } +} \ No newline at end of file diff --git a/solution/2800-2899/2895.Minimum Processing Time/Solution.cpp b/solution/2800-2899/2895.Minimum Processing Time/Solution.cpp index e8a84adde64e6..e1ec52570efe3 100644 --- a/solution/2800-2899/2895.Minimum Processing Time/Solution.cpp +++ b/solution/2800-2899/2895.Minimum Processing Time/Solution.cpp @@ -1,13 +1,13 @@ -class Solution { -public: - int minProcessingTime(vector& processorTime, vector& tasks) { - sort(processorTime.begin(), processorTime.end()); - sort(tasks.begin(), tasks.end()); - int ans = 0, i = tasks.size() - 1; - for (int t : processorTime) { - ans = max(ans, t + tasks[i]); - i -= 4; - } - return ans; - } +class Solution { +public: + int minProcessingTime(vector& processorTime, vector& tasks) { + sort(processorTime.begin(), processorTime.end()); + sort(tasks.begin(), tasks.end()); + int ans = 0, i = tasks.size() - 1; + for (int t : processorTime) { + ans = max(ans, t + tasks[i]); + i -= 4; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2895.Minimum Processing Time/Solution.java b/solution/2800-2899/2895.Minimum Processing Time/Solution.java index ad573df3d7dc4..a2fc0eba79aff 100644 --- a/solution/2800-2899/2895.Minimum Processing Time/Solution.java +++ b/solution/2800-2899/2895.Minimum Processing Time/Solution.java @@ -1,12 +1,12 @@ -class Solution { - public int minProcessingTime(List processorTime, List tasks) { - processorTime.sort((a, b) -> a - b); - tasks.sort((a, b) -> a - b); - int ans = 0, i = tasks.size() - 1; - for (int t : processorTime) { - ans = Math.max(ans, t + tasks.get(i)); - i -= 4; - } - return ans; - } +class Solution { + public int minProcessingTime(List processorTime, List tasks) { + processorTime.sort((a, b) -> a - b); + tasks.sort((a, b) -> a - b); + int ans = 0, i = tasks.size() - 1; + for (int t : processorTime) { + ans = Math.max(ans, t + tasks.get(i)); + i -= 4; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2800-2899/2895.Minimum Processing Time/Solution.py b/solution/2800-2899/2895.Minimum Processing Time/Solution.py index 70d00d5f6f81b..af962003db194 100644 --- a/solution/2800-2899/2895.Minimum Processing Time/Solution.py +++ b/solution/2800-2899/2895.Minimum Processing Time/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def minProcessingTime(self, processorTime: List[int], tasks: List[int]) -> int: - processorTime.sort() - tasks.sort() - ans = 0 - i = len(tasks) - 1 - for t in processorTime: - ans = max(ans, t + tasks[i]) - i -= 4 - return ans +class Solution: + def minProcessingTime(self, processorTime: List[int], tasks: List[int]) -> int: + processorTime.sort() + tasks.sort() + ans = 0 + i = len(tasks) - 1 + for t in processorTime: + ans = max(ans, t + tasks[i]) + i -= 4 + return ans diff --git a/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/Solution.cpp b/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/Solution.cpp index 489c4ab6851f8..bd454994095f4 100644 --- a/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/Solution.cpp +++ b/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/Solution.cpp @@ -1,31 +1,31 @@ -class Solution { -public: - int minOperations(string s1, string s2, int x) { - vector idx; - for (int i = 0; i < s1.size(); ++i) { - if (s1[i] != s2[i]) { - idx.push_back(i); - } - } - int m = idx.size(); - if (m & 1) { - return -1; - } - if (m == 0) { - return 0; - } - int f[m][m]; - memset(f, -1, sizeof(f)); - function dfs = [&](int i, int j) { - if (i > j) { - return 0; - } - if (f[i][j] != -1) { - return f[i][j]; - } - f[i][j] = min({dfs(i + 1, j - 1) + x, dfs(i + 2, j) + idx[i + 1] - idx[i], dfs(i, j - 2) + idx[j] - idx[j - 1]}); - return f[i][j]; - }; - return dfs(0, m - 1); - } +class Solution { +public: + int minOperations(string s1, string s2, int x) { + vector idx; + for (int i = 0; i < s1.size(); ++i) { + if (s1[i] != s2[i]) { + idx.push_back(i); + } + } + int m = idx.size(); + if (m & 1) { + return -1; + } + if (m == 0) { + return 0; + } + int f[m][m]; + memset(f, -1, sizeof(f)); + function dfs = [&](int i, int j) { + if (i > j) { + return 0; + } + if (f[i][j] != -1) { + return f[i][j]; + } + f[i][j] = min({dfs(i + 1, j - 1) + x, dfs(i + 2, j) + idx[i + 1] - idx[i], dfs(i, j - 2) + idx[j] - idx[j - 1]}); + return f[i][j]; + }; + return dfs(0, m - 1); + } }; \ No newline at end of file diff --git a/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/Solution.java b/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/Solution.java index 44d3986f22eae..7778821407783 100644 --- a/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/Solution.java +++ b/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/Solution.java @@ -1,34 +1,34 @@ -class Solution { - private List idx = new ArrayList<>(); - private Integer[][] f; - private int x; - - public int minOperations(String s1, String s2, int x) { - int n = s1.length(); - for (int i = 0; i < n; ++i) { - if (s1.charAt(i) != s2.charAt(i)) { - idx.add(i); - } - } - int m = idx.size(); - if (m % 2 == 1) { - return -1; - } - this.x = x; - f = new Integer[m][m]; - return dfs(0, m - 1); - } - - private int dfs(int i, int j) { - if (i > j) { - return 0; - } - if (f[i][j] != null) { - return f[i][j]; - } - f[i][j] = dfs(i + 1, j - 1) + x; - f[i][j] = Math.min(f[i][j], dfs(i + 2, j) + idx.get(i + 1) - idx.get(i)); - f[i][j] = Math.min(f[i][j], dfs(i, j - 2) + idx.get(j) - idx.get(j - 1)); - return f[i][j]; - } +class Solution { + private List idx = new ArrayList<>(); + private Integer[][] f; + private int x; + + public int minOperations(String s1, String s2, int x) { + int n = s1.length(); + for (int i = 0; i < n; ++i) { + if (s1.charAt(i) != s2.charAt(i)) { + idx.add(i); + } + } + int m = idx.size(); + if (m % 2 == 1) { + return -1; + } + this.x = x; + f = new Integer[m][m]; + return dfs(0, m - 1); + } + + private int dfs(int i, int j) { + if (i > j) { + return 0; + } + if (f[i][j] != null) { + return f[i][j]; + } + f[i][j] = dfs(i + 1, j - 1) + x; + f[i][j] = Math.min(f[i][j], dfs(i + 2, j) + idx.get(i + 1) - idx.get(i)); + f[i][j] = Math.min(f[i][j], dfs(i, j - 2) + idx.get(j) - idx.get(j - 1)); + return f[i][j]; + } } \ No newline at end of file diff --git a/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/Solution.py b/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/Solution.py index b5a7c7be4fcdd..7e053e363c573 100644 --- a/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/Solution.py +++ b/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/Solution.py @@ -1,17 +1,17 @@ -class Solution: - def minOperations(self, s1: str, s2: str, x: int) -> int: - @cache - def dfs(i: int, j: int) -> int: - if i > j: - return 0 - a = dfs(i + 1, j - 1) + x - b = dfs(i + 2, j) + idx[i + 1] - idx[i] - c = dfs(i, j - 2) + idx[j] - idx[j - 1] - return min(a, b, c) - - n = len(s1) - idx = [i for i in range(n) if s1[i] != s2[i]] - m = len(idx) - if m & 1: - return -1 - return dfs(0, m - 1) +class Solution: + def minOperations(self, s1: str, s2: str, x: int) -> int: + @cache + def dfs(i: int, j: int) -> int: + if i > j: + return 0 + a = dfs(i + 1, j - 1) + x + b = dfs(i + 2, j) + idx[i + 1] - idx[i] + c = dfs(i, j - 2) + idx[j] - idx[j - 1] + return min(a, b, c) + + n = len(s1) + idx = [i for i in range(n) if s1[i] != s2[i]] + m = len(idx) + if m & 1: + return -1 + return dfs(0, m - 1) diff --git a/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/Solution2.java b/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/Solution2.java new file mode 100644 index 0000000000000..742a0c8f5a6ab --- /dev/null +++ b/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/Solution2.java @@ -0,0 +1,27 @@ +class Solution { + public int minOperations(String s1, String s2, int x) { + int n = s1.length(); + int inf = 50_000; + int one = inf, two = inf, last = inf; + int done = 0; + for (int i = 0; i < n; i++) { + if (s1.charAt(i) == s2.charAt(i)) { + one = Math.min(one, last); + last = last + 1; + two = two + 1; + continue; + } + if (done < n) { + one = Math.min(two + 1, done + x); + last = Math.min(two + x, done); + done = two = inf; + continue; + } + done = Math.min(one + x, last + 1); + two = one; + one = last = inf; + continue; + } + return done == inf ? -1 : done; + } +} \ No newline at end of file diff --git a/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/Solution.cpp b/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/Solution.cpp index 874f77513c122..c566f87771185 100644 --- a/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/Solution.cpp +++ b/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/Solution.cpp @@ -1,26 +1,26 @@ -class Solution { -public: - int maxSum(vector& nums, int k) { - int cnt[31]{}; - for (int x : nums) { - for (int i = 0; i < 31; ++i) { - if (x >> i & 1) { - ++cnt[i]; - } - } - } - long long ans = 0; - const int mod = 1e9 + 7; - while (k--) { - int x = 0; - for (int i = 0; i < 31; ++i) { - if (cnt[i]) { - x |= 1 << i; - --cnt[i]; - } - } - ans = (ans + 1LL * x * x) % mod; - } - return ans; - } +class Solution { +public: + int maxSum(vector& nums, int k) { + int cnt[31]{}; + for (int x : nums) { + for (int i = 0; i < 31; ++i) { + if (x >> i & 1) { + ++cnt[i]; + } + } + } + long long ans = 0; + const int mod = 1e9 + 7; + while (k--) { + int x = 0; + for (int i = 0; i < 31; ++i) { + if (cnt[i]) { + x |= 1 << i; + --cnt[i]; + } + } + ans = (ans + 1LL * x * x) % mod; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/Solution.java b/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/Solution.java index 3c36491b76594..764a4bfae3eb6 100644 --- a/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/Solution.java +++ b/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/Solution.java @@ -1,25 +1,25 @@ -class Solution { - public int maxSum(List nums, int k) { - final int mod = (int) 1e9 + 7; - int[] cnt = new int[31]; - for (int x : nums) { - for (int i = 0; i < 31; ++i) { - if ((x >> i & 1) == 1) { - ++cnt[i]; - } - } - } - long ans = 0; - while (k-- > 0) { - int x = 0; - for (int i = 0; i < 31; ++i) { - if (cnt[i] > 0) { - x |= 1 << i; - --cnt[i]; - } - } - ans = (ans + 1L * x * x) % mod; - } - return (int) ans; - } +class Solution { + public int maxSum(List nums, int k) { + final int mod = (int) 1e9 + 7; + int[] cnt = new int[31]; + for (int x : nums) { + for (int i = 0; i < 31; ++i) { + if ((x >> i & 1) == 1) { + ++cnt[i]; + } + } + } + long ans = 0; + while (k-- > 0) { + int x = 0; + for (int i = 0; i < 31; ++i) { + if (cnt[i] > 0) { + x |= 1 << i; + --cnt[i]; + } + } + ans = (ans + 1L * x * x) % mod; + } + return (int) ans; + } } \ No newline at end of file diff --git a/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/Solution.py b/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/Solution.py index 9410554ecf7e5..5138054a9f06c 100644 --- a/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/Solution.py +++ b/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/Solution.py @@ -1,17 +1,17 @@ -class Solution: - def maxSum(self, nums: List[int], k: int) -> int: - mod = 10**9 + 7 - cnt = [0] * 31 - for x in nums: - for i in range(31): - if x >> i & 1: - cnt[i] += 1 - ans = 0 - for _ in range(k): - x = 0 - for i in range(31): - if cnt[i]: - x |= 1 << i - cnt[i] -= 1 - ans = (ans + x * x) % mod - return ans +class Solution: + def maxSum(self, nums: List[int], k: int) -> int: + mod = 10**9 + 7 + cnt = [0] * 31 + for x in nums: + for i in range(31): + if x >> i & 1: + cnt[i] += 1 + ans = 0 + for _ in range(k): + x = 0 + for i in range(31): + if cnt[i]: + x |= 1 << i + cnt[i] -= 1 + ans = (ans + x * x) % mod + return ans diff --git a/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/Solution.cpp b/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/Solution.cpp index 38551ac4a8cf6..97ee1a7627352 100644 --- a/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/Solution.cpp +++ b/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/Solution.cpp @@ -1,38 +1,38 @@ -class Solution { -public: - vector getWordsInLongestSubsequence(int n, vector& words, vector& groups) { - auto check = [](string& s, string& t) { - if (s.size() != t.size()) { - return false; - } - int cnt = 0; - for (int i = 0; i < s.size(); ++i) { - cnt += s[i] != t[i]; - } - return cnt == 1; - }; - vector f(n, 1); - vector g(n, -1); - int mx = 1; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (groups[i] != groups[j] && f[i] < f[j] + 1 && check(words[i], words[j])) { - f[i] = f[j] + 1; - g[i] = j; - mx = max(mx, f[i]); - } - } - } - vector ans; - for (int i = 0; i < n; ++i) { - if (f[i] == mx) { - for (int j = i; ~j; j = g[j]) { - ans.emplace_back(words[j]); - } - break; - } - } - reverse(ans.begin(), ans.end()); - return ans; - } +class Solution { +public: + vector getWordsInLongestSubsequence(int n, vector& words, vector& groups) { + auto check = [](string& s, string& t) { + if (s.size() != t.size()) { + return false; + } + int cnt = 0; + for (int i = 0; i < s.size(); ++i) { + cnt += s[i] != t[i]; + } + return cnt == 1; + }; + vector f(n, 1); + vector g(n, -1); + int mx = 1; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (groups[i] != groups[j] && f[i] < f[j] + 1 && check(words[i], words[j])) { + f[i] = f[j] + 1; + g[i] = j; + mx = max(mx, f[i]); + } + } + } + vector ans; + for (int i = 0; i < n; ++i) { + if (f[i] == mx) { + for (int j = i; ~j; j = g[j]) { + ans.emplace_back(words[j]); + } + break; + } + } + reverse(ans.begin(), ans.end()); + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/Solution.java b/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/Solution.java index 06ece0ee09667..b105a52b10cb2 100644 --- a/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/Solution.java +++ b/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/Solution.java @@ -1,42 +1,42 @@ -class Solution { - public List getWordsInLongestSubsequence(int n, String[] words, int[] groups) { - int[] f = new int[n]; - int[] g = new int[n]; - Arrays.fill(f, 1); - Arrays.fill(g, -1); - int mx = 1; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (groups[i] != groups[j] && f[i] < f[j] + 1 && check(words[i], words[j])) { - f[i] = f[j] + 1; - g[i] = j; - mx = Math.max(mx, f[i]); - } - } - } - List ans = new ArrayList<>(); - for (int i = 0; i < n; ++i) { - if (f[i] == mx) { - for (int j = i; j >= 0; j = g[j]) { - ans.add(words[j]); - } - break; - } - } - Collections.reverse(ans); - return ans; - } - - private boolean check(String s, String t) { - if (s.length() != t.length()) { - return false; - } - int cnt = 0; - for (int i = 0; i < s.length(); ++i) { - if (s.charAt(i) != t.charAt(i)) { - ++cnt; - } - } - return cnt == 1; - } +class Solution { + public List getWordsInLongestSubsequence(int n, String[] words, int[] groups) { + int[] f = new int[n]; + int[] g = new int[n]; + Arrays.fill(f, 1); + Arrays.fill(g, -1); + int mx = 1; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (groups[i] != groups[j] && f[i] < f[j] + 1 && check(words[i], words[j])) { + f[i] = f[j] + 1; + g[i] = j; + mx = Math.max(mx, f[i]); + } + } + } + List ans = new ArrayList<>(); + for (int i = 0; i < n; ++i) { + if (f[i] == mx) { + for (int j = i; j >= 0; j = g[j]) { + ans.add(words[j]); + } + break; + } + } + Collections.reverse(ans); + return ans; + } + + private boolean check(String s, String t) { + if (s.length() != t.length()) { + return false; + } + int cnt = 0; + for (int i = 0; i < s.length(); ++i) { + if (s.charAt(i) != t.charAt(i)) { + ++cnt; + } + } + return cnt == 1; + } } \ No newline at end of file diff --git a/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/Solution.py b/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/Solution.py index 8ab328ca57aa7..6ebef77cca98a 100644 --- a/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/Solution.py +++ b/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/Solution.py @@ -1,25 +1,25 @@ -class Solution: - def getWordsInLongestSubsequence( - self, n: int, words: List[str], groups: List[int] - ) -> List[str]: - def check(s: str, t: str) -> bool: - return len(s) == len(t) and sum(a != b for a, b in zip(s, t)) == 1 - - f = [1] * n - g = [-1] * n - mx = 1 - for i, x in enumerate(groups): - for j, y in enumerate(groups[:i]): - if x != y and f[i] < f[j] + 1 and check(words[i], words[j]): - f[i] = f[j] + 1 - g[i] = j - mx = max(mx, f[i]) - ans = [] - for i in range(n): - if f[i] == mx: - j = i - while j >= 0: - ans.append(words[j]) - j = g[j] - break - return ans[::-1] +class Solution: + def getWordsInLongestSubsequence( + self, n: int, words: List[str], groups: List[int] + ) -> List[str]: + def check(s: str, t: str) -> bool: + return len(s) == len(t) and sum(a != b for a, b in zip(s, t)) == 1 + + f = [1] * n + g = [-1] * n + mx = 1 + for i, x in enumerate(groups): + for j, y in enumerate(groups[:i]): + if x != y and f[i] < f[j] + 1 and check(words[i], words[j]): + f[i] = f[j] + 1 + g[i] = j + mx = max(mx, f[i]) + ans = [] + for i in range(n): + if f[i] == mx: + j = i + while j >= 0: + ans.append(words[j]) + j = g[j] + break + return ans[::-1] diff --git a/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/Solution2.java b/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/Solution2.java new file mode 100644 index 0000000000000..60a36fe7e9627 --- /dev/null +++ b/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/Solution2.java @@ -0,0 +1,45 @@ +class Solution { + public List getWordsInLongestSubsequence(int n, String[] words, int[] groups) { + int[] dp = new int[n]; + int[] next = new int[n]; + Map> strToIdxMap = new HashMap<>(); + int maxIdx = n; + for (int i = n - 1; i >= 0; i--) { + int prevIdx = n; + char[] word = words[i].toCharArray(); + for (int j = 0; j < word.length; j++) { + // convert word to pattern with '*'. + char temp = word[j]; + word[j] = '*'; + String curr = new String(word); + + // search matches and update dp. + List prevList = strToIdxMap.getOrDefault(curr, List.of()); + for (int prev : prevList) { + if (groups[prev] == groups[i] || dp[prev] < dp[i]) { + continue; + } + dp[i] = dp[prev] + 1; + prevIdx = prev; + } + + // append current pattern to dictionary. + strToIdxMap.computeIfAbsent(curr, k -> new ArrayList<>()).add(i); + + // restore pattern to orignal word. + word[j] = temp; + } + if (maxIdx >= n || dp[i] > dp[maxIdx]) { + maxIdx = i; + } + next[i] = prevIdx; + } + int curr = maxIdx; + List ans = new ArrayList<>(); + while (curr < n) { + ans.add(words[curr]); + curr = next[curr]; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2900-2999/2902.Count of Sub-Multisets With Bounded Sum/Solution.java b/solution/2900-2999/2902.Count of Sub-Multisets With Bounded Sum/Solution.java index 80918f6a8bbd6..033c89a9c6308 100644 --- a/solution/2900-2999/2902.Count of Sub-Multisets With Bounded Sum/Solution.java +++ b/solution/2900-2999/2902.Count of Sub-Multisets With Bounded Sum/Solution.java @@ -1,4 +1,3 @@ - class Solution { static final int MOD = 1_000_000_007; public int countSubMultisets(List nums, int l, int r) { diff --git a/solution/2900-2999/2903.Find Indices With Index and Value Difference I/Solution.cpp b/solution/2900-2999/2903.Find Indices With Index and Value Difference I/Solution.cpp index d0d263b434a77..9b162a8881422 100644 --- a/solution/2900-2999/2903.Find Indices With Index and Value Difference I/Solution.cpp +++ b/solution/2900-2999/2903.Find Indices With Index and Value Difference I/Solution.cpp @@ -1,22 +1,22 @@ -class Solution { -public: - vector findIndices(vector& nums, int indexDifference, int valueDifference) { - int mi = 0, mx = 0; - for (int i = indexDifference; i < nums.size(); ++i) { - int j = i - indexDifference; - if (nums[j] < nums[mi]) { - mi = j; - } - if (nums[j] > nums[mx]) { - mx = j; - } - if (nums[i] - nums[mi] >= valueDifference) { - return {mi, i}; - } - if (nums[mx] - nums[i] >= valueDifference) { - return {mx, i}; - } - } - return {-1, -1}; - } +class Solution { +public: + vector findIndices(vector& nums, int indexDifference, int valueDifference) { + int mi = 0, mx = 0; + for (int i = indexDifference; i < nums.size(); ++i) { + int j = i - indexDifference; + if (nums[j] < nums[mi]) { + mi = j; + } + if (nums[j] > nums[mx]) { + mx = j; + } + if (nums[i] - nums[mi] >= valueDifference) { + return {mi, i}; + } + if (nums[mx] - nums[i] >= valueDifference) { + return {mx, i}; + } + } + return {-1, -1}; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2903.Find Indices With Index and Value Difference I/Solution.java b/solution/2900-2999/2903.Find Indices With Index and Value Difference I/Solution.java index f618f36872006..35927b1e30e0a 100644 --- a/solution/2900-2999/2903.Find Indices With Index and Value Difference I/Solution.java +++ b/solution/2900-2999/2903.Find Indices With Index and Value Difference I/Solution.java @@ -1,22 +1,22 @@ -class Solution { - public int[] findIndices(int[] nums, int indexDifference, int valueDifference) { - int mi = 0; - int mx = 0; - for (int i = indexDifference; i < nums.length; ++i) { - int j = i - indexDifference; - if (nums[j] < nums[mi]) { - mi = j; - } - if (nums[j] > nums[mx]) { - mx = j; - } - if (nums[i] - nums[mi] >= valueDifference) { - return new int[] {mi, i}; - } - if (nums[mx] - nums[i] >= valueDifference) { - return new int[] {mx, i}; - } - } - return new int[] {-1, -1}; - } +class Solution { + public int[] findIndices(int[] nums, int indexDifference, int valueDifference) { + int mi = 0; + int mx = 0; + for (int i = indexDifference; i < nums.length; ++i) { + int j = i - indexDifference; + if (nums[j] < nums[mi]) { + mi = j; + } + if (nums[j] > nums[mx]) { + mx = j; + } + if (nums[i] - nums[mi] >= valueDifference) { + return new int[] {mi, i}; + } + if (nums[mx] - nums[i] >= valueDifference) { + return new int[] {mx, i}; + } + } + return new int[] {-1, -1}; + } } \ No newline at end of file diff --git a/solution/2900-2999/2903.Find Indices With Index and Value Difference I/Solution.py b/solution/2900-2999/2903.Find Indices With Index and Value Difference I/Solution.py index f92fcb5251423..27583b20dc2f5 100644 --- a/solution/2900-2999/2903.Find Indices With Index and Value Difference I/Solution.py +++ b/solution/2900-2999/2903.Find Indices With Index and Value Difference I/Solution.py @@ -1,16 +1,16 @@ -class Solution: - def findIndices( - self, nums: List[int], indexDifference: int, valueDifference: int - ) -> List[int]: - mi = mx = 0 - for i in range(indexDifference, len(nums)): - j = i - indexDifference - if nums[j] < nums[mi]: - mi = j - if nums[j] > nums[mx]: - mx = j - if nums[i] - nums[mi] >= valueDifference: - return [mi, i] - if nums[mx] - nums[i] >= valueDifference: - return [mx, i] - return [-1, -1] +class Solution: + def findIndices( + self, nums: List[int], indexDifference: int, valueDifference: int + ) -> List[int]: + mi = mx = 0 + for i in range(indexDifference, len(nums)): + j = i - indexDifference + if nums[j] < nums[mi]: + mi = j + if nums[j] > nums[mx]: + mx = j + if nums[i] - nums[mi] >= valueDifference: + return [mi, i] + if nums[mx] - nums[i] >= valueDifference: + return [mx, i] + return [-1, -1] diff --git a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.cpp b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.cpp index f27a9222768b4..6bc9fbf68ec6e 100644 --- a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.cpp +++ b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.cpp @@ -1,20 +1,17 @@ -class Solution { -public: - string shortestBeautifulSubstring(string s, int k) { - int i = 0, j = 0, cnt = 0; - int n = s.size(); - string ans = ""; - while (j < n) { - cnt += s[j] == '1'; - while (cnt > k || (i < j && s[i] == '0')) { - cnt -= s[i++] == '1'; - } - ++j; - string t = s.substr(i, j - i); - if (cnt == k && (ans == "" || j - i < ans.size() || (j - i == ans.size() && t < ans))) { - ans = t; - } - } - return ans; - } +class Solution { +public: + string shortestBeautifulSubstring(string s, int k) { + int n = s.size(); + string ans = ""; + for (int i = 0; i < n; ++i) { + for (int j = i + k; j <= n; ++j) { + string t = s.substr(i, j - i); + int cnt = count(t.begin(), t.end(), '1'); + if (cnt == k && (ans == "" || j - i < ans.size() || (j - i == ans.size() && t < ans))) { + ans = t; + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.go b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.go index 075835b8a2b61..731e1ebee13e2 100644 --- a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.go +++ b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.go @@ -1,16 +1,17 @@ func shortestBeautifulSubstring(s string, k int) (ans string) { - i, j, cnt := 0, 0, 0 n := len(s) - for j < n { - cnt += int(s[j] - '0') - for cnt > k || (i < j && s[i] == '0') { - cnt -= int(s[i] - '0') - i++ - } - j++ - t := s[i:j] - if cnt == k && (ans == "" || j-i < len(ans) || (j-i == len(ans) && t < ans)) { - ans = t + for i := 0; i < n; i++ { + for j := i + k; j <= n; j++ { + t := s[i:j] + cnt := 0 + for _, c := range t { + if c == '1' { + cnt++ + } + } + if cnt == k && (ans == "" || j-i < len(ans) || (j-i == len(ans) && t < ans)) { + ans = t + } } } return diff --git a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.java b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.java index dd137444cb0da..bbe4d33ed5584 100644 --- a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.java +++ b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.java @@ -1,22 +1,21 @@ -class Solution { - public String shortestBeautifulSubstring(String s, int k) { - int i = 0, j = 0, cnt = 0; - int n = s.length(); - String ans = ""; - while (j < n) { - cnt += s.charAt(j) - '0'; - while (cnt > k || (i < j && s.charAt(i) == '0')) { - cnt -= s.charAt(i) - '0'; - ++i; - } - ++j; - String t = s.substring(i, j); - if (cnt == k - && ("".equals(ans) || j - i < ans.length() - || (j - i == ans.length() && t.compareTo(ans) < 0))) { - ans = t; - } - } - return ans; - } +class Solution { + public String shortestBeautifulSubstring(String s, int k) { + int n = s.length(); + String ans = ""; + for (int i = 0; i < n; ++i) { + for (int j = i + k; j <= n; ++j) { + String t = s.substring(i, j); + int cnt = 0; + for (char c : t.toCharArray()) { + cnt += c - '0'; + } + if (cnt == k + && ("".equals(ans) || j - i < ans.length() + || (j - i == ans.length() && t.compareTo(ans) < 0))) { + ans = t; + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.py b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.py index 60a22614ef512..1dd778ce5afb5 100644 --- a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.py +++ b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.py @@ -1,16 +1,12 @@ -class Solution: - def shortestBeautifulSubstring(self, s: str, k: int) -> str: - i = j = cnt = 0 - n = len(s) - ans = "" - while j < n: - cnt += s[j] == "1" - while cnt > k or (i < j and s[i] == "0"): - cnt -= s[i] == "1" - i += 1 - j += 1 - if cnt == k and ( - not ans or j - i < len(ans) or (j - i == len(ans) and s[i:j] < ans) - ): - ans = s[i:j] - return ans +class Solution: + def shortestBeautifulSubstring(self, s: str, k: int) -> str: + n = len(s) + ans = "" + for i in range(n): + for j in range(i + k, n + 1): + t = s[i:j] + if t.count("1") == k and ( + not ans or j - i < len(ans) or (j - i == len(ans) and t < ans) + ): + ans = t + return ans diff --git a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.rs b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.rs index d69f0aad21db3..df5c77484cf77 100644 --- a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.rs +++ b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.rs @@ -1,34 +1,19 @@ impl Solution { pub fn shortest_beautiful_substring(s: String, k: i32) -> String { - let s_chars: Vec = s.chars().collect(); - let mut i = 0; - let mut j = 0; - let mut cnt = 0; - let mut ans = String::new(); let n = s.len(); + let mut ans = String::new(); - while j < n { - if s_chars[j] == '1' { - cnt += 1; - } - - while cnt > k || (i < j && s_chars[i] == '0') { - if s_chars[i] == '1' { - cnt -= 1; + for i in 0..n { + for j in i + (k as usize)..=n { + let t = &s[i..j]; + if + (t.matches('1').count() as i32) == k && + (ans.is_empty() || j - i < ans.len() || (j - i == ans.len() && t < &ans)) + { + ans = t.to_string(); } - i += 1; - } - - j += 1; - - if - cnt == k && - (ans.is_empty() || j - i < ans.len() || (j - i == ans.len() && &s[i..j] < &ans)) - { - ans = s_chars[i..j].iter().collect(); } } - ans } } diff --git a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.ts b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.ts index 30c408a1588c2..949bfb95cad86 100644 --- a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.ts +++ b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution.ts @@ -1,16 +1,16 @@ function shortestBeautifulSubstring(s: string, k: number): string { - let [i, j, cnt] = [0, 0, 0]; const n = s.length; let ans: string = ''; - while (j < n) { - cnt += s[j] === '1' ? 1 : 0; - while (cnt > k || (i < j && s[i] === '0')) { - cnt -= s[i++] === '1' ? 1 : 0; - } - ++j; - const t = s.slice(i, j); - if (cnt === k && (ans === '' || j - i < ans.length || (j - i === ans.length && t < ans))) { - ans = t; + for (let i = 0; i < n; ++i) { + for (let j = i + k; j <= n; ++j) { + const t = s.slice(i, j); + const cnt = t.split('').filter(c => c === '1').length; + if ( + cnt === k && + (ans === '' || j - i < ans.length || (j - i === ans.length && t < ans)) + ) { + ans = t; + } } } return ans; diff --git a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution2.cpp b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution2.cpp new file mode 100644 index 0000000000000..14bcc2effaf0d --- /dev/null +++ b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution2.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + string shortestBeautifulSubstring(string s, int k) { + int i = 0, j = 0, cnt = 0; + int n = s.size(); + string ans = ""; + while (j < n) { + cnt += s[j] == '1'; + while (cnt > k || (i < j && s[i] == '0')) { + cnt -= s[i++] == '1'; + } + ++j; + string t = s.substr(i, j - i); + if (cnt == k && (ans == "" || j - i < ans.size() || (j - i == ans.size() && t < ans))) { + ans = t; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution2.go b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution2.go new file mode 100644 index 0000000000000..075835b8a2b61 --- /dev/null +++ b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution2.go @@ -0,0 +1,17 @@ +func shortestBeautifulSubstring(s string, k int) (ans string) { + i, j, cnt := 0, 0, 0 + n := len(s) + for j < n { + cnt += int(s[j] - '0') + for cnt > k || (i < j && s[i] == '0') { + cnt -= int(s[i] - '0') + i++ + } + j++ + t := s[i:j] + if cnt == k && (ans == "" || j-i < len(ans) || (j-i == len(ans) && t < ans)) { + ans = t + } + } + return +} \ No newline at end of file diff --git a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution2.java b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution2.java new file mode 100644 index 0000000000000..a24c1dd5a9f2c --- /dev/null +++ b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution2.java @@ -0,0 +1,22 @@ +class Solution { + public String shortestBeautifulSubstring(String s, int k) { + int i = 0, j = 0, cnt = 0; + int n = s.length(); + String ans = ""; + while (j < n) { + cnt += s.charAt(j) - '0'; + while (cnt > k || (i < j && s.charAt(i) == '0')) { + cnt -= s.charAt(i) - '0'; + ++i; + } + ++j; + String t = s.substring(i, j); + if (cnt == k + && ("".equals(ans) || j - i < ans.length() + || (j - i == ans.length() && t.compareTo(ans) < 0))) { + ans = t; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution2.py b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution2.py new file mode 100644 index 0000000000000..46b07b4cea200 --- /dev/null +++ b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution2.py @@ -0,0 +1,16 @@ +class Solution: + def shortestBeautifulSubstring(self, s: str, k: int) -> str: + i = j = cnt = 0 + n = len(s) + ans = "" + while j < n: + cnt += s[j] == "1" + while cnt > k or (i < j and s[i] == "0"): + cnt -= s[i] == "1" + i += 1 + j += 1 + if cnt == k and ( + not ans or j - i < len(ans) or (j - i == len(ans) and s[i:j] < ans) + ): + ans = s[i:j] + return ans diff --git a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution2.rs b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution2.rs new file mode 100644 index 0000000000000..d69f0aad21db3 --- /dev/null +++ b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution2.rs @@ -0,0 +1,34 @@ +impl Solution { + pub fn shortest_beautiful_substring(s: String, k: i32) -> String { + let s_chars: Vec = s.chars().collect(); + let mut i = 0; + let mut j = 0; + let mut cnt = 0; + let mut ans = String::new(); + let n = s.len(); + + while j < n { + if s_chars[j] == '1' { + cnt += 1; + } + + while cnt > k || (i < j && s_chars[i] == '0') { + if s_chars[i] == '1' { + cnt -= 1; + } + i += 1; + } + + j += 1; + + if + cnt == k && + (ans.is_empty() || j - i < ans.len() || (j - i == ans.len() && &s[i..j] < &ans)) + { + ans = s_chars[i..j].iter().collect(); + } + } + + ans + } +} diff --git a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution2.ts b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution2.ts new file mode 100644 index 0000000000000..30c408a1588c2 --- /dev/null +++ b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/Solution2.ts @@ -0,0 +1,17 @@ +function shortestBeautifulSubstring(s: string, k: number): string { + let [i, j, cnt] = [0, 0, 0]; + const n = s.length; + let ans: string = ''; + while (j < n) { + cnt += s[j] === '1' ? 1 : 0; + while (cnt > k || (i < j && s[i] === '0')) { + cnt -= s[i++] === '1' ? 1 : 0; + } + ++j; + const t = s.slice(i, j); + if (cnt === k && (ans === '' || j - i < ans.length || (j - i === ans.length && t < ans))) { + ans = t; + } + } + return ans; +} diff --git a/solution/2900-2999/2905.Find Indices With Index and Value Difference II/Solution.cpp b/solution/2900-2999/2905.Find Indices With Index and Value Difference II/Solution.cpp index d0d263b434a77..9b162a8881422 100644 --- a/solution/2900-2999/2905.Find Indices With Index and Value Difference II/Solution.cpp +++ b/solution/2900-2999/2905.Find Indices With Index and Value Difference II/Solution.cpp @@ -1,22 +1,22 @@ -class Solution { -public: - vector findIndices(vector& nums, int indexDifference, int valueDifference) { - int mi = 0, mx = 0; - for (int i = indexDifference; i < nums.size(); ++i) { - int j = i - indexDifference; - if (nums[j] < nums[mi]) { - mi = j; - } - if (nums[j] > nums[mx]) { - mx = j; - } - if (nums[i] - nums[mi] >= valueDifference) { - return {mi, i}; - } - if (nums[mx] - nums[i] >= valueDifference) { - return {mx, i}; - } - } - return {-1, -1}; - } +class Solution { +public: + vector findIndices(vector& nums, int indexDifference, int valueDifference) { + int mi = 0, mx = 0; + for (int i = indexDifference; i < nums.size(); ++i) { + int j = i - indexDifference; + if (nums[j] < nums[mi]) { + mi = j; + } + if (nums[j] > nums[mx]) { + mx = j; + } + if (nums[i] - nums[mi] >= valueDifference) { + return {mi, i}; + } + if (nums[mx] - nums[i] >= valueDifference) { + return {mx, i}; + } + } + return {-1, -1}; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2905.Find Indices With Index and Value Difference II/Solution.java b/solution/2900-2999/2905.Find Indices With Index and Value Difference II/Solution.java index f618f36872006..35927b1e30e0a 100644 --- a/solution/2900-2999/2905.Find Indices With Index and Value Difference II/Solution.java +++ b/solution/2900-2999/2905.Find Indices With Index and Value Difference II/Solution.java @@ -1,22 +1,22 @@ -class Solution { - public int[] findIndices(int[] nums, int indexDifference, int valueDifference) { - int mi = 0; - int mx = 0; - for (int i = indexDifference; i < nums.length; ++i) { - int j = i - indexDifference; - if (nums[j] < nums[mi]) { - mi = j; - } - if (nums[j] > nums[mx]) { - mx = j; - } - if (nums[i] - nums[mi] >= valueDifference) { - return new int[] {mi, i}; - } - if (nums[mx] - nums[i] >= valueDifference) { - return new int[] {mx, i}; - } - } - return new int[] {-1, -1}; - } +class Solution { + public int[] findIndices(int[] nums, int indexDifference, int valueDifference) { + int mi = 0; + int mx = 0; + for (int i = indexDifference; i < nums.length; ++i) { + int j = i - indexDifference; + if (nums[j] < nums[mi]) { + mi = j; + } + if (nums[j] > nums[mx]) { + mx = j; + } + if (nums[i] - nums[mi] >= valueDifference) { + return new int[] {mi, i}; + } + if (nums[mx] - nums[i] >= valueDifference) { + return new int[] {mx, i}; + } + } + return new int[] {-1, -1}; + } } \ No newline at end of file diff --git a/solution/2900-2999/2905.Find Indices With Index and Value Difference II/Solution.py b/solution/2900-2999/2905.Find Indices With Index and Value Difference II/Solution.py index f92fcb5251423..27583b20dc2f5 100644 --- a/solution/2900-2999/2905.Find Indices With Index and Value Difference II/Solution.py +++ b/solution/2900-2999/2905.Find Indices With Index and Value Difference II/Solution.py @@ -1,16 +1,16 @@ -class Solution: - def findIndices( - self, nums: List[int], indexDifference: int, valueDifference: int - ) -> List[int]: - mi = mx = 0 - for i in range(indexDifference, len(nums)): - j = i - indexDifference - if nums[j] < nums[mi]: - mi = j - if nums[j] > nums[mx]: - mx = j - if nums[i] - nums[mi] >= valueDifference: - return [mi, i] - if nums[mx] - nums[i] >= valueDifference: - return [mx, i] - return [-1, -1] +class Solution: + def findIndices( + self, nums: List[int], indexDifference: int, valueDifference: int + ) -> List[int]: + mi = mx = 0 + for i in range(indexDifference, len(nums)): + j = i - indexDifference + if nums[j] < nums[mi]: + mi = j + if nums[j] > nums[mx]: + mx = j + if nums[i] - nums[mi] >= valueDifference: + return [mi, i] + if nums[mx] - nums[i] >= valueDifference: + return [mx, i] + return [-1, -1] diff --git a/solution/2900-2999/2906.Construct Product Matrix/Solution.cpp b/solution/2900-2999/2906.Construct Product Matrix/Solution.cpp index dced7bd63c752..8a5a327b7b8b7 100644 --- a/solution/2900-2999/2906.Construct Product Matrix/Solution.cpp +++ b/solution/2900-2999/2906.Construct Product Matrix/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - vector> constructProductMatrix(vector>& grid) { - const int mod = 12345; - int n = grid.size(), m = grid[0].size(); - vector> p(n, vector(m)); - long long suf = 1; - for (int i = n - 1; i >= 0; --i) { - for (int j = m - 1; j >= 0; --j) { - p[i][j] = suf; - suf = suf * grid[i][j] % mod; - } - } - long long pre = 1; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < m; ++j) { - p[i][j] = p[i][j] * pre % mod; - pre = pre * grid[i][j] % mod; - } - } - return p; - } +class Solution { +public: + vector> constructProductMatrix(vector>& grid) { + const int mod = 12345; + int n = grid.size(), m = grid[0].size(); + vector> p(n, vector(m)); + long long suf = 1; + for (int i = n - 1; i >= 0; --i) { + for (int j = m - 1; j >= 0; --j) { + p[i][j] = suf; + suf = suf * grid[i][j] % mod; + } + } + long long pre = 1; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < m; ++j) { + p[i][j] = p[i][j] * pre % mod; + pre = pre * grid[i][j] % mod; + } + } + return p; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2906.Construct Product Matrix/Solution.java b/solution/2900-2999/2906.Construct Product Matrix/Solution.java index 5faf2fea45233..c9bb0f3f89731 100644 --- a/solution/2900-2999/2906.Construct Product Matrix/Solution.java +++ b/solution/2900-2999/2906.Construct Product Matrix/Solution.java @@ -1,22 +1,22 @@ -class Solution { - public int[][] constructProductMatrix(int[][] grid) { - final int mod = 12345; - int n = grid.length, m = grid[0].length; - int[][] p = new int[n][m]; - long suf = 1; - for (int i = n - 1; i >= 0; --i) { - for (int j = m - 1; j >= 0; --j) { - p[i][j] = (int) suf; - suf = suf * grid[i][j] % mod; - } - } - long pre = 1; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < m; ++j) { - p[i][j] = (int) (p[i][j] * pre % mod); - pre = pre * grid[i][j] % mod; - } - } - return p; - } +class Solution { + public int[][] constructProductMatrix(int[][] grid) { + final int mod = 12345; + int n = grid.length, m = grid[0].length; + int[][] p = new int[n][m]; + long suf = 1; + for (int i = n - 1; i >= 0; --i) { + for (int j = m - 1; j >= 0; --j) { + p[i][j] = (int) suf; + suf = suf * grid[i][j] % mod; + } + } + long pre = 1; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < m; ++j) { + p[i][j] = (int) (p[i][j] * pre % mod); + pre = pre * grid[i][j] % mod; + } + } + return p; + } } \ No newline at end of file diff --git a/solution/2900-2999/2906.Construct Product Matrix/Solution.py b/solution/2900-2999/2906.Construct Product Matrix/Solution.py index 89e7baeef2706..5cac9541ef178 100644 --- a/solution/2900-2999/2906.Construct Product Matrix/Solution.py +++ b/solution/2900-2999/2906.Construct Product Matrix/Solution.py @@ -1,16 +1,16 @@ -class Solution: - def constructProductMatrix(self, grid: List[List[int]]) -> List[List[int]]: - n, m = len(grid), len(grid[0]) - p = [[0] * m for _ in range(n)] - mod = 12345 - suf = 1 - for i in range(n - 1, -1, -1): - for j in range(m - 1, -1, -1): - p[i][j] = suf - suf = suf * grid[i][j] % mod - pre = 1 - for i in range(n): - for j in range(m): - p[i][j] = p[i][j] * pre % mod - pre = pre * grid[i][j] % mod - return p +class Solution: + def constructProductMatrix(self, grid: List[List[int]]) -> List[List[int]]: + n, m = len(grid), len(grid[0]) + p = [[0] * m for _ in range(n)] + mod = 12345 + suf = 1 + for i in range(n - 1, -1, -1): + for j in range(m - 1, -1, -1): + p[i][j] = suf + suf = suf * grid[i][j] % mod + pre = 1 + for i in range(n): + for j in range(m): + p[i][j] = p[i][j] * pre % mod + pre = pre * grid[i][j] % mod + return p diff --git a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution.cpp b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution.cpp index e577d866ef9c5..bc0d334778289 100644 --- a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution.cpp +++ b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution.cpp @@ -1,24 +1,24 @@ -class Solution { -public: - int maxProfit(vector& prices, vector& profits) { - int n = prices.size(); - int ans = -1; - for (int j = 0; j < n; ++j) { - int left = 0, right = 0; - for (int i = 0; i < j; ++i) { - if (prices[i] < prices[j]) { - left = max(left, profits[i]); - } - } - for (int k = j + 1; k < n; ++k) { - if (prices[j] < prices[k]) { - right = max(right, profits[k]); - } - } - if (left && right) { - ans = max(ans, left + profits[j] + right); - } - } - return ans; - } +class Solution { +public: + int maxProfit(vector& prices, vector& profits) { + int n = prices.size(); + int ans = -1; + for (int j = 0; j < n; ++j) { + int left = 0, right = 0; + for (int i = 0; i < j; ++i) { + if (prices[i] < prices[j]) { + left = max(left, profits[i]); + } + } + for (int k = j + 1; k < n; ++k) { + if (prices[j] < prices[k]) { + right = max(right, profits[k]); + } + } + if (left && right) { + ans = max(ans, left + profits[j] + right); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution.java b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution.java index 3241e4fdb5c10..cab4777c930dd 100644 --- a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution.java +++ b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution.java @@ -1,23 +1,23 @@ -class Solution { - public int maxProfit(int[] prices, int[] profits) { - int n = prices.length; - int ans = -1; - for (int j = 0; j < n; ++j) { - int left = 0, right = 0; - for (int i = 0; i < j; ++i) { - if (prices[i] < prices[j]) { - left = Math.max(left, profits[i]); - } - } - for (int k = j + 1; k < n; ++k) { - if (prices[j] < prices[k]) { - right = Math.max(right, profits[k]); - } - } - if (left > 0 && right > 0) { - ans = Math.max(ans, left + profits[j] + right); - } - } - return ans; - } +class Solution { + public int maxProfit(int[] prices, int[] profits) { + int n = prices.length; + int ans = -1; + for (int j = 0; j < n; ++j) { + int left = 0, right = 0; + for (int i = 0; i < j; ++i) { + if (prices[i] < prices[j]) { + left = Math.max(left, profits[i]); + } + } + for (int k = j + 1; k < n; ++k) { + if (prices[j] < prices[k]) { + right = Math.max(right, profits[k]); + } + } + if (left > 0 && right > 0) { + ans = Math.max(ans, left + profits[j] + right); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution.py b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution.py index 6009d16700f14..bba9c1a02ff4d 100644 --- a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution.py +++ b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution.py @@ -1,15 +1,15 @@ -class Solution: - def maxProfit(self, prices: List[int], profits: List[int]) -> int: - n = len(prices) - ans = -1 - for j, x in enumerate(profits): - left = right = 0 - for i in range(j): - if prices[i] < prices[j] and left < profits[i]: - left = profits[i] - for k in range(j + 1, n): - if prices[j] < prices[k] and right < profits[k]: - right = profits[k] - if left and right: - ans = max(ans, left + x + right) - return ans +class Solution: + def maxProfit(self, prices: List[int], profits: List[int]) -> int: + n = len(prices) + ans = -1 + for j, x in enumerate(profits): + left = right = 0 + for i in range(j): + if prices[i] < prices[j] and left < profits[i]: + left = profits[i] + for k in range(j + 1, n): + if prices[j] < prices[k] and right < profits[k]: + right = profits[k] + if left and right: + ans = max(ans, left + x + right) + return ans diff --git a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution2.cpp b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution2.cpp new file mode 100644 index 0000000000000..9888208ffdf0f --- /dev/null +++ b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution2.cpp @@ -0,0 +1,56 @@ +class BinaryIndexedTree { +private: + int n; + vector c; + +public: + BinaryIndexedTree(int n) { + this->n = n; + c.resize(n + 1, 0); + } + + void update(int x, int v) { + while (x <= n) { + c[x] = max(c[x], v); + x += x & -x; + } + } + + int query(int x) { + int mx = 0; + while (x > 0) { + mx = max(mx, c[x]); + x -= x & -x; + } + return mx; + } +}; + +class Solution { +public: + int maxProfit(vector& prices, vector& profits) { + int n = prices.size(); + vector left(n, 0); + vector right(n, 0); + int m = *max_element(prices.begin(), prices.end()); + BinaryIndexedTree tree1(m + 1); + BinaryIndexedTree tree2(m + 1); + for (int i = 0; i < n; ++i) { + int x = prices[i]; + left[i] = tree1.query(x - 1); + tree1.update(x, profits[i]); + } + for (int i = n - 1; i >= 0; --i) { + int x = m + 1 - prices[i]; + right[i] = tree2.query(x - 1); + tree2.update(x, profits[i]); + } + int ans = -1; + for (int i = 0; i < n; ++i) { + if (left[i] > 0 && right[i] > 0) { + ans = max(ans, left[i] + profits[i] + right[i]); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution2.go b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution2.go new file mode 100644 index 0000000000000..8e0b8633dd443 --- /dev/null +++ b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution2.go @@ -0,0 +1,56 @@ +type BinaryIndexedTree struct { + n int + c []int +} + +func NewBinaryIndexedTree(n int) BinaryIndexedTree { + c := make([]int, n+1) + return BinaryIndexedTree{n: n, c: c} +} + +func (bit *BinaryIndexedTree) update(x, v int) { + for x <= bit.n { + bit.c[x] = max(bit.c[x], v) + x += x & -x + } +} + +func (bit *BinaryIndexedTree) query(x int) int { + mx := 0 + for x > 0 { + mx = max(mx, bit.c[x]) + x -= x & -x + } + return mx +} + +func maxProfit(prices []int, profits []int) int { + n := len(prices) + left := make([]int, n) + right := make([]int, n) + m := slices.Max(prices) + + tree1 := NewBinaryIndexedTree(m + 1) + tree2 := NewBinaryIndexedTree(m + 1) + + for i, x := range prices { + left[i] = tree1.query(x - 1) + tree1.update(x, profits[i]) + } + + for i := n - 1; i >= 0; i-- { + x := m + 1 - prices[i] + right[i] = tree2.query(x - 1) + tree2.update(x, profits[i]) + } + + ans := -1 + + for i := 0; i < n; i++ { + if left[i] > 0 && right[i] > 0 { + ans = max(ans, left[i]+profits[i]+right[i]) + } + } + + return ans +} \ No newline at end of file diff --git a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution2.java b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution2.java new file mode 100644 index 0000000000000..b4ff26378b644 --- /dev/null +++ b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution2.java @@ -0,0 +1,56 @@ +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int v) { + while (x <= n) { + c[x] = Math.max(c[x], v); + x += x & -x; + } + } + + public int query(int x) { + int mx = 0; + while (x > 0) { + mx = Math.max(mx, c[x]); + x -= x & -x; + } + return mx; + } +} + +class Solution { + public int maxProfit(int[] prices, int[] profits) { + int n = prices.length; + int[] left = new int[n]; + int[] right = new int[n]; + int m = 0; + for (int x : prices) { + m = Math.max(m, x); + } + BinaryIndexedTree tree1 = new BinaryIndexedTree(m + 1); + BinaryIndexedTree tree2 = new BinaryIndexedTree(m + 1); + for (int i = 0; i < n; ++i) { + int x = prices[i]; + left[i] = tree1.query(x - 1); + tree1.update(x, profits[i]); + } + for (int i = n - 1; i >= 0; --i) { + int x = m + 1 - prices[i]; + right[i] = tree2.query(x - 1); + tree2.update(x, profits[i]); + } + int ans = -1; + for (int i = 0; i < n; ++i) { + if (left[i] > 0 && right[i] > 0) { + ans = Math.max(ans, left[i] + profits[i] + right[i]); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution2.py b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution2.py new file mode 100644 index 0000000000000..530712d97154e --- /dev/null +++ b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution2.py @@ -0,0 +1,39 @@ +class BinaryIndexedTree: + def __init__(self, n: int): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x: int, v: int): + while x <= self.n: + self.c[x] = max(self.c[x], v) + x += x & -x + + def query(self, x: int) -> int: + mx = 0 + while x: + mx = max(mx, self.c[x]) + x -= x & -x + return mx + + +class Solution: + def maxProfit(self, prices: List[int], profits: List[int]) -> int: + n = len(prices) + left = [0] * n + right = [0] * n + + m = max(prices) + tree1 = BinaryIndexedTree(m + 1) + tree2 = BinaryIndexedTree(m + 1) + + for i, x in enumerate(prices): + left[i] = tree1.query(x - 1) + tree1.update(x, profits[i]) + for i in range(n - 1, -1, -1): + x = m + 1 - prices[i] + right[i] = tree2.query(x - 1) + tree2.update(x, profits[i]) + + return max( + (l + x + r for l, x, r in zip(left, profits, right) if l and r), default=-1 + ) diff --git a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution2.rs b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution2.rs new file mode 100644 index 0000000000000..cb6ca4d4170f3 --- /dev/null +++ b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution2.rs @@ -0,0 +1,64 @@ +struct BinaryIndexedTree { + n: usize, + c: Vec, +} + +impl BinaryIndexedTree { + fn new(n: usize) -> BinaryIndexedTree { + BinaryIndexedTree { + n, + c: vec![0; n + 1], + } + } + + fn update(&mut self, x: usize, v: i32) { + let mut x = x; + while x <= self.n { + self.c[x] = self.c[x].max(v); + x += x & x.wrapping_neg(); + } + } + + fn query(&self, x: usize) -> i32 { + let mut x = x; + let mut mx = 0; + while x > 0 { + mx = mx.max(self.c[x]); + x -= x & x.wrapping_neg(); + } + mx + } +} + +impl Solution { + pub fn max_profit(prices: Vec, profits: Vec) -> i32 { + let n = prices.len(); + let mut left = vec![0; n]; + let mut right = vec![0; n]; + let m = prices.iter().cloned().max().unwrap_or(0); + + let mut tree1 = BinaryIndexedTree::new((m as usize) + 1); + let mut tree2 = BinaryIndexedTree::new((m as usize) + 1); + + for i in 0..n { + let x = prices[i] as usize; + left[i] = tree1.query(x - 1); + tree1.update(x, profits[i]); + } + + for i in (0..n).rev() { + let x = (m + 1 - prices[i]) as usize; + right[i] = tree2.query(x - 1); + tree2.update(x, profits[i]); + } + + let mut ans = -1; + for i in 0..n { + if left[i] > 0 && right[i] > 0 { + ans = ans.max(left[i] + profits[i] + right[i]); + } + } + + ans + } +} diff --git a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution2.ts b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution2.ts new file mode 100644 index 0000000000000..d719547a7186b --- /dev/null +++ b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution2.ts @@ -0,0 +1,57 @@ +class BinaryIndexedTree { + private n: number; + private c: number[]; + + constructor(n: number) { + this.n = n; + this.c = Array(n + 1).fill(0); + } + + update(x: number, v: number): void { + while (x <= this.n) { + this.c[x] = Math.max(this.c[x], v); + x += x & -x; + } + } + + query(x: number): number { + let mx = 0; + while (x > 0) { + mx = Math.max(mx, this.c[x]); + x -= x & -x; + } + return mx; + } +} + +function maxProfit(prices: number[], profits: number[]): number { + const n: number = prices.length; + const left: number[] = Array(n).fill(0); + const right: number[] = Array(n).fill(0); + const m = Math.max(...prices); + + const tree1: BinaryIndexedTree = new BinaryIndexedTree(m + 1); + const tree2: BinaryIndexedTree = new BinaryIndexedTree(m + 1); + + for (let i = 0; i < n; i++) { + const x: number = prices[i]; + left[i] = tree1.query(x - 1); + tree1.update(x, profits[i]); + } + + for (let i = n - 1; i >= 0; i--) { + const x: number = m + 1 - prices[i]; + right[i] = tree2.query(x - 1); + tree2.update(x, profits[i]); + } + + let ans: number = -1; + + for (let i = 0; i < n; i++) { + if (left[i] > 0 && right[i] > 0) { + ans = Math.max(ans, left[i] + profits[i] + right[i]); + } + } + + return ans; +} diff --git a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution3.cpp b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution3.cpp new file mode 100644 index 0000000000000..99cbaff261200 --- /dev/null +++ b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution3.cpp @@ -0,0 +1,59 @@ +class BinaryIndexedTree { +private: + int n; + vector c; + +public: + BinaryIndexedTree(int n) { + this->n = n; + c.resize(n + 1, 0); + } + + void update(int x, int v) { + while (x <= n) { + c[x] = max(c[x], v); + x += x & -x; + } + } + + int query(int x) { + int mx = 0; + while (x > 0) { + mx = max(mx, c[x]); + x -= x & -x; + } + return mx; + } +}; + +class Solution { +public: + int maxProfit(vector& prices, vector& profits) { + int n = prices.size(); + vector left(n); + vector right(n); + vector s = prices; + sort(s.begin(), s.end()); + s.erase(unique(s.begin(), s.end()), s.end()); + int m = s.size(); + BinaryIndexedTree tree1(m + 1); + BinaryIndexedTree tree2(m + 1); + for (int i = 0; i < n; ++i) { + int x = lower_bound(s.begin(), s.end(), prices[i]) - s.begin() + 1; + left[i] = tree1.query(x - 1); + tree1.update(x, profits[i]); + } + for (int i = n - 1; i >= 0; --i) { + int x = m + 1 - (lower_bound(s.begin(), s.end(), prices[i]) - s.begin() + 1); + right[i] = tree2.query(x - 1); + tree2.update(x, profits[i]); + } + int ans = -1; + for (int i = 0; i < n; ++i) { + if (left[i] > 0 && right[i] > 0) { + ans = max(ans, left[i] + profits[i] + right[i]); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution3.go b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution3.go new file mode 100644 index 0000000000000..b497575828523 --- /dev/null +++ b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution3.go @@ -0,0 +1,66 @@ +type BinaryIndexedTree struct { + n int + c []int +} + +func NewBinaryIndexedTree(n int) BinaryIndexedTree { + c := make([]int, n+1) + return BinaryIndexedTree{n: n, c: c} +} + +func (bit *BinaryIndexedTree) update(x, v int) { + for x <= bit.n { + bit.c[x] = max(bit.c[x], v) + x += x & -x + } +} + +func (bit *BinaryIndexedTree) query(x int) int { + mx := 0 + for x > 0 { + mx = max(mx, bit.c[x]) + x -= x & -x + } + return mx +} + +func maxProfit(prices []int, profits []int) int { + n := len(prices) + left := make([]int, n) + right := make([]int, n) + s := make([]int, n) + copy(s, prices) + sort.Ints(s) + m := 0 + for i, x := range s { + if i == 0 || x != s[i-1] { + s[m] = x + m++ + } + } + + tree1 := NewBinaryIndexedTree(m + 1) + tree2 := NewBinaryIndexedTree(m + 1) + + for i, x := range prices { + x = sort.SearchInts(s[:m], x) + 1 + left[i] = tree1.query(x - 1) + tree1.update(x, profits[i]) + } + + for i := n - 1; i >= 0; i-- { + x := m + 1 - (sort.SearchInts(s[:m], prices[i]) + 1) + right[i] = tree2.query(x - 1) + tree2.update(x, profits[i]) + } + + ans := -1 + + for i := 0; i < n; i++ { + if left[i] > 0 && right[i] > 0 { + ans = max(ans, left[i]+profits[i]+right[i]) + } + } + + return ans +} \ No newline at end of file diff --git a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution3.java b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution3.java new file mode 100644 index 0000000000000..12a2052b7a9ee --- /dev/null +++ b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution3.java @@ -0,0 +1,73 @@ +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int v) { + while (x <= n) { + c[x] = Math.max(c[x], v); + x += x & -x; + } + } + + public int query(int x) { + int mx = 0; + while (x > 0) { + mx = Math.max(mx, c[x]); + x -= x & -x; + } + return mx; + } +} + +class Solution { + public int maxProfit(int[] prices, int[] profits) { + int n = prices.length; + int[] left = new int[n]; + int[] right = new int[n]; + int[] s = prices.clone(); + Arrays.sort(s); + int m = 0; + for (int i = 0; i < n; ++i) { + if (i == 0 || s[i] != s[i - 1]) { + s[m++] = s[i]; + } + } + BinaryIndexedTree tree1 = new BinaryIndexedTree(m + 1); + BinaryIndexedTree tree2 = new BinaryIndexedTree(m + 1); + for (int i = 0; i < n; ++i) { + int x = search(s, prices[i], m); + left[i] = tree1.query(x - 1); + tree1.update(x, profits[i]); + } + for (int i = n - 1; i >= 0; --i) { + int x = m + 1 - search(s, prices[i], m); + right[i] = tree2.query(x - 1); + tree2.update(x, profits[i]); + } + int ans = -1; + for (int i = 0; i < n; ++i) { + if (left[i] > 0 && right[i] > 0) { + ans = Math.max(ans, left[i] + profits[i] + right[i]); + } + } + return ans; + } + + private int search(int[] nums, int x, int r) { + int l = 0; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l + 1; + } +} \ No newline at end of file diff --git a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution3.py b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution3.py new file mode 100644 index 0000000000000..e974ec366307a --- /dev/null +++ b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution3.py @@ -0,0 +1,41 @@ +class BinaryIndexedTree: + def __init__(self, n: int): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x: int, v: int): + while x <= self.n: + self.c[x] = max(self.c[x], v) + x += x & -x + + def query(self, x: int) -> int: + mx = 0 + while x: + mx = max(mx, self.c[x]) + x -= x & -x + return mx + + +class Solution: + def maxProfit(self, prices: List[int], profits: List[int]) -> int: + n = len(prices) + left = [0] * n + right = [0] * n + + s = sorted(set(prices)) + m = len(s) + tree1 = BinaryIndexedTree(m + 1) + tree2 = BinaryIndexedTree(m + 1) + + for i, x in enumerate(prices): + x = bisect_left(s, x) + 1 + left[i] = tree1.query(x - 1) + tree1.update(x, profits[i]) + for i in range(n - 1, -1, -1): + x = m + 1 - (bisect_left(s, prices[i]) + 1) + right[i] = tree2.query(x - 1) + tree2.update(x, profits[i]) + + return max( + (l + x + r for l, x, r in zip(left, profits, right) if l and r), default=-1 + ) diff --git a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution3.ts b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution3.ts new file mode 100644 index 0000000000000..5461040a4f6d5 --- /dev/null +++ b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution3.ts @@ -0,0 +1,78 @@ +class BinaryIndexedTree { + private n: number; + private c: number[]; + + constructor(n: number) { + this.n = n; + this.c = Array(n + 1).fill(0); + } + + update(x: number, v: number): void { + while (x <= this.n) { + this.c[x] = Math.max(this.c[x], v); + x += x & -x; + } + } + + query(x: number): number { + let mx = 0; + while (x > 0) { + mx = Math.max(mx, this.c[x]); + x -= x & -x; + } + return mx; + } +} + +function maxProfit(prices: number[], profits: number[]): number { + const n: number = prices.length; + const left: number[] = Array(n).fill(0); + const right: number[] = Array(n).fill(0); + + const s = [...prices].sort((a, b) => a - b); + let m = 0; + for (let i = 0; i < n; ++i) { + if (i === 0 || s[i] !== s[i - 1]) { + s[m++] = s[i]; + } + } + s.length = m; + + const tree1: BinaryIndexedTree = new BinaryIndexedTree(m + 1); + const tree2: BinaryIndexedTree = new BinaryIndexedTree(m + 1); + + const search = (nums: number[], x: number): number => { + let [l, r] = [0, nums.length]; + while (l < r) { + const mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + + for (let i = 0; i < n; ++i) { + const x = search(s, prices[i]) + 1; + left[i] = tree1.query(x - 1); + tree1.update(x, profits[i]); + } + + for (let i = n - 1; i >= 0; i--) { + const x: number = m + 1 - (search(s, prices[i]) + 1); + right[i] = tree2.query(x - 1); + tree2.update(x, profits[i]); + } + + let ans: number = -1; + + for (let i = 0; i < n; i++) { + if (left[i] > 0 && right[i] > 0) { + ans = Math.max(ans, left[i] + profits[i] + right[i]); + } + } + + return ans; +} diff --git a/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/Solution.cpp b/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/Solution.cpp index 59ae0892cef2f..79ecb83aa7d74 100644 --- a/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/Solution.cpp +++ b/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/Solution.cpp @@ -1,26 +1,26 @@ -class Solution { -public: - int minGroupsForValidAssignment(vector& nums) { - unordered_map cnt; - for (int x : nums) { - cnt[x]++; - } - int k = 1e9; - for (auto& [_, v] : cnt) { - ans = min(ans, v); - } - for (;; --k) { - int ans = 0; - for (auto& [_, v] : cnt) { - if (v / k < v % k) { - ans = 0; - break; - } - ans += (v + k) / (k + 1); - } - if (ans) { - return ans; - } - } - } +class Solution { +public: + int minGroupsForValidAssignment(vector& nums) { + unordered_map cnt; + for (int x : nums) { + cnt[x]++; + } + int k = 1e9; + for (auto& [_, v] : cnt) { + ans = min(ans, v); + } + for (;; --k) { + int ans = 0; + for (auto& [_, v] : cnt) { + if (v / k < v % k) { + ans = 0; + break; + } + ans += (v + k) / (k + 1); + } + if (ans) { + return ans; + } + } + } }; \ No newline at end of file diff --git a/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/Solution.java b/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/Solution.java index eaad7cd91ff05..51c3d43698a45 100644 --- a/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/Solution.java +++ b/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/Solution.java @@ -1,25 +1,25 @@ -class Solution { - public int minGroupsForValidAssignment(int[] nums) { - Map cnt = new HashMap<>(); - for (int x : nums) { - cnt.merge(x, 1, Integer::sum); - } - int k = nums.length; - for (int v : cnt.values()) { - k = Math.min(k, v); - } - for (;; --k) { - int ans = 0; - for (int v : cnt.values()) { - if (v / k < v % k) { - ans = 0; - break; - } - ans += (v + k) / (k + 1); - } - if (ans > 0) { - return ans; - } - } - } +class Solution { + public int minGroupsForValidAssignment(int[] nums) { + Map cnt = new HashMap<>(); + for (int x : nums) { + cnt.merge(x, 1, Integer::sum); + } + int k = nums.length; + for (int v : cnt.values()) { + k = Math.min(k, v); + } + for (;; --k) { + int ans = 0; + for (int v : cnt.values()) { + if (v / k < v % k) { + ans = 0; + break; + } + ans += (v + k) / (k + 1); + } + if (ans > 0) { + return ans; + } + } + } } \ No newline at end of file diff --git a/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/Solution.py b/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/Solution.py index 94c4c4b8197c2..bd9b0f55ae94d 100644 --- a/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/Solution.py +++ b/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def minGroupsForValidAssignment(self, nums: List[int]) -> int: - cnt = Counter(nums) - for k in range(min(cnt.values()), 0, -1): - ans = 0 - for v in cnt.values(): - if v // k < v % k: - ans = 0 - break - ans += (v + k) // (k + 1) - if ans: - return ans +class Solution: + def minGroupsForValidAssignment(self, nums: List[int]) -> int: + cnt = Counter(nums) + for k in range(min(cnt.values()), 0, -1): + ans = 0 + for v in cnt.values(): + if v // k < v % k: + ans = 0 + break + ans += (v + k) // (k + 1) + if ans: + return ans diff --git a/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/Solution.cpp b/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/Solution.cpp index 25f8a695f3ff4..d522ea9d39e2d 100644 --- a/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/Solution.cpp +++ b/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/Solution.cpp @@ -1,39 +1,39 @@ -class Solution { -public: - int minimumChanges(string s, int k) { - int n = s.size(); - int g[n + 1][n + 1]; - int f[n + 1][k + 1]; - memset(g, 0x3f, sizeof(g)); - memset(f, 0x3f, sizeof(f)); - f[0][0] = 0; - for (int i = 1; i <= n; ++i) { - for (int j = i; j <= n; ++j) { - int m = j - i + 1; - for (int d = 1; d < m; ++d) { - if (m % d == 0) { - int cnt = 0; - for (int l = 0; l < m; ++l) { - int r = (m / d - 1 - l / d) * d + l % d; - if (l >= r) { - break; - } - if (s[i - 1 + l] != s[i - 1 + r]) { - ++cnt; - } - } - g[i][j] = min(g[i][j], cnt); - } - } - } - } - for (int i = 1; i <= n; ++i) { - for (int j = 1; j <= k; ++j) { - for (int h = 0; h < i - 1; ++h) { - f[i][j] = min(f[i][j], f[h][j - 1] + g[h + 1][i]); - } - } - } - return f[n][k]; - } +class Solution { +public: + int minimumChanges(string s, int k) { + int n = s.size(); + int g[n + 1][n + 1]; + int f[n + 1][k + 1]; + memset(g, 0x3f, sizeof(g)); + memset(f, 0x3f, sizeof(f)); + f[0][0] = 0; + for (int i = 1; i <= n; ++i) { + for (int j = i; j <= n; ++j) { + int m = j - i + 1; + for (int d = 1; d < m; ++d) { + if (m % d == 0) { + int cnt = 0; + for (int l = 0; l < m; ++l) { + int r = (m / d - 1 - l / d) * d + l % d; + if (l >= r) { + break; + } + if (s[i - 1 + l] != s[i - 1 + r]) { + ++cnt; + } + } + g[i][j] = min(g[i][j], cnt); + } + } + } + } + for (int i = 1; i <= n; ++i) { + for (int j = 1; j <= k; ++j) { + for (int h = 0; h < i - 1; ++h) { + f[i][j] = min(f[i][j], f[h][j - 1] + g[h + 1][i]); + } + } + } + return f[n][k]; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/Solution.java b/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/Solution.java index ca035d3009c14..955220a910adc 100644 --- a/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/Solution.java +++ b/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/Solution.java @@ -1,41 +1,41 @@ -class Solution { - public int minimumChanges(String s, int k) { - int n = s.length(); - int[][] g = new int[n + 1][n + 1]; - int[][] f = new int[n + 1][k + 1]; - final int inf = 1 << 30; - for (int i = 0; i <= n; ++i) { - Arrays.fill(g[i], inf); - Arrays.fill(f[i], inf); - } - for (int i = 1; i <= n; ++i) { - for (int j = i; j <= n; ++j) { - int m = j - i + 1; - for (int d = 1; d < m; ++d) { - if (m % d == 0) { - int cnt = 0; - for (int l = 0; l < m; ++l) { - int r = (m / d - 1 - l / d) * d + l % d; - if (l >= r) { - break; - } - if (s.charAt(i - 1 + l) != s.charAt(i - 1 + r)) { - ++cnt; - } - } - g[i][j] = Math.min(g[i][j], cnt); - } - } - } - } - f[0][0] = 0; - for (int i = 1; i <= n; ++i) { - for (int j = 1; j <= k; ++j) { - for (int h = 0; h < i - 1; ++h) { - f[i][j] = Math.min(f[i][j], f[h][j - 1] + g[h + 1][i]); - } - } - } - return f[n][k]; - } +class Solution { + public int minimumChanges(String s, int k) { + int n = s.length(); + int[][] g = new int[n + 1][n + 1]; + int[][] f = new int[n + 1][k + 1]; + final int inf = 1 << 30; + for (int i = 0; i <= n; ++i) { + Arrays.fill(g[i], inf); + Arrays.fill(f[i], inf); + } + for (int i = 1; i <= n; ++i) { + for (int j = i; j <= n; ++j) { + int m = j - i + 1; + for (int d = 1; d < m; ++d) { + if (m % d == 0) { + int cnt = 0; + for (int l = 0; l < m; ++l) { + int r = (m / d - 1 - l / d) * d + l % d; + if (l >= r) { + break; + } + if (s.charAt(i - 1 + l) != s.charAt(i - 1 + r)) { + ++cnt; + } + } + g[i][j] = Math.min(g[i][j], cnt); + } + } + } + } + f[0][0] = 0; + for (int i = 1; i <= n; ++i) { + for (int j = 1; j <= k; ++j) { + for (int h = 0; h < i - 1; ++h) { + f[i][j] = Math.min(f[i][j], f[h][j - 1] + g[h + 1][i]); + } + } + } + return f[n][k]; + } } \ No newline at end of file diff --git a/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/Solution.py b/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/Solution.py index 90678b55a5e5e..cdec6315ae5bf 100644 --- a/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/Solution.py +++ b/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/Solution.py @@ -1,25 +1,25 @@ -class Solution: - def minimumChanges(self, s: str, k: int) -> int: - n = len(s) - g = [[inf] * (n + 1) for _ in range(n + 1)] - for i in range(1, n + 1): - for j in range(i, n + 1): - m = j - i + 1 - for d in range(1, m): - if m % d == 0: - cnt = 0 - for l in range(m): - r = (m // d - 1 - l // d) * d + l % d - if l >= r: - break - if s[i - 1 + l] != s[i - 1 + r]: - cnt += 1 - g[i][j] = min(g[i][j], cnt) - - f = [[inf] * (k + 1) for _ in range(n + 1)] - f[0][0] = 0 - for i in range(1, n + 1): - for j in range(1, k + 1): - for h in range(i - 1): - f[i][j] = min(f[i][j], f[h][j - 1] + g[h + 1][i]) - return f[n][k] +class Solution: + def minimumChanges(self, s: str, k: int) -> int: + n = len(s) + g = [[inf] * (n + 1) for _ in range(n + 1)] + for i in range(1, n + 1): + for j in range(i, n + 1): + m = j - i + 1 + for d in range(1, m): + if m % d == 0: + cnt = 0 + for l in range(m): + r = (m // d - 1 - l // d) * d + l % d + if l >= r: + break + if s[i - 1 + l] != s[i - 1 + r]: + cnt += 1 + g[i][j] = min(g[i][j], cnt) + + f = [[inf] * (k + 1) for _ in range(n + 1)] + f[0][0] = 0 + for i in range(1, n + 1): + for j in range(1, k + 1): + for h in range(i - 1): + f[i][j] = min(f[i][j], f[h][j - 1] + g[h + 1][i]) + return f[n][k] diff --git a/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/Solution2.java b/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/Solution2.java new file mode 100644 index 0000000000000..f074759ef4b8e --- /dev/null +++ b/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/Solution2.java @@ -0,0 +1,80 @@ +class Solution { + static int inf = 200; + List[] factorLists; + int n; + int k; + char[] ch; + Integer[][] cost; + public int minimumChanges(String s, int k) { + this.k = k; + n = s.length(); + ch = s.toCharArray(); + + factorLists = getFactorLists(n); + cost = new Integer[n + 1][n + 1]; + return calcDP(); + } + static List[] getFactorLists(int n) { + List[] l = new ArrayList[n + 1]; + for (int i = 1; i <= n; i++) { + l[i] = new ArrayList<>(); + l[i].add(1); + } + for (int factor = 2; factor < n; factor++) { + for (int num = factor + factor; num <= n; num += factor) { + l[num].add(factor); + } + } + return l; + } + int calcDP() { + int[] dp = new int[n]; + for (int i = n - k * 2 + 1; i >= 1; i--) { + dp[i] = getCost(0, i); + } + int bound = 0; + for (int subs = 2; subs <= k; subs++) { + bound = subs * 2; + for (int i = n - 1 - k * 2 + subs * 2; i >= bound - 1; i--) { + dp[i] = inf; + for (int prev = bound - 3; prev < i - 1; prev++) { + dp[i] = Math.min(dp[i], dp[prev] + getCost(prev + 1, i)); + } + } + } + return dp[n - 1]; + } + int getCost(int l, int r) { + if (l >= r) { + return inf; + } + if (cost[l][r] != null) { + return cost[l][r]; + } + cost[l][r] = inf; + for (int factor : factorLists[r - l + 1]) { + cost[l][r] = Math.min(cost[l][r], getStepwiseCost(l, r, factor)); + } + return cost[l][r]; + } + int getStepwiseCost(int l, int r, int stepsize) { + if (l >= r) { + return 0; + } + int left = 0; + int right = 0; + int count = 0; + for (int i = 0; i < stepsize; i++) { + left = l + i; + right = r - stepsize + 1 + i; + while (left + stepsize <= right) { + if (ch[left] != ch[right]) { + count++; + } + left += stepsize; + right -= stepsize; + } + } + return count; + } +} \ No newline at end of file diff --git a/solution/2900-2999/2912.Number of Ways to Reach Destination in the Grid/Solution.py b/solution/2900-2999/2912.Number of Ways to Reach Destination in the Grid/Solution.py index f5b44b94dd27a..9702c66f93c9b 100644 --- a/solution/2900-2999/2912.Number of Ways to Reach Destination in the Grid/Solution.py +++ b/solution/2900-2999/2912.Number of Ways to Reach Destination in the Grid/Solution.py @@ -3,14 +3,13 @@ def numberOfWays( self, n: int, m: int, k: int, source: List[int], dest: List[int] ) -> int: mod = 10**9 + 7 - f = [1, 0, 0, 0] + a, b, c, d = 1, 0, 0, 0 for _ in range(k): - g = [0] * 4 - g[0] = ((n - 1) * f[1] + (m - 1) * f[2]) % mod - g[1] = (f[0] + (n - 2) * f[1] + (m - 1) * f[3]) % mod - g[2] = (f[0] + (m - 2) * f[2] + (n - 1) * f[3]) % mod - g[3] = (f[1] + f[2] + (n - 2) * f[3] + (m - 2) * f[3]) % mod - f = g + aa = ((n - 1) * b + (m - 1) * c) % mod + bb = (a + (n - 2) * b + (m - 1) * d) % mod + cc = (a + (m - 2) * c + (n - 1) * d) % mod + dd = (b + c + (n - 2) * d + (m - 2) * d) % mod + a, b, c, d = aa, bb, cc, dd if source[0] == dest[0]: - return f[0] if source[1] == dest[1] else f[2] - return f[1] if source[1] == dest[1] else f[3] + return a if source[1] == dest[1] else c + return b if source[1] == dest[1] else d diff --git a/solution/2900-2999/2912.Number of Ways to Reach Destination in the Grid/Solution2.py b/solution/2900-2999/2912.Number of Ways to Reach Destination in the Grid/Solution2.py new file mode 100644 index 0000000000000..f5b44b94dd27a --- /dev/null +++ b/solution/2900-2999/2912.Number of Ways to Reach Destination in the Grid/Solution2.py @@ -0,0 +1,16 @@ +class Solution: + def numberOfWays( + self, n: int, m: int, k: int, source: List[int], dest: List[int] + ) -> int: + mod = 10**9 + 7 + f = [1, 0, 0, 0] + for _ in range(k): + g = [0] * 4 + g[0] = ((n - 1) * f[1] + (m - 1) * f[2]) % mod + g[1] = (f[0] + (n - 2) * f[1] + (m - 1) * f[3]) % mod + g[2] = (f[0] + (m - 2) * f[2] + (n - 1) * f[3]) % mod + g[3] = (f[1] + f[2] + (n - 2) * f[3] + (m - 2) * f[3]) % mod + f = g + if source[0] == dest[0]: + return f[0] if source[1] == dest[1] else f[2] + return f[1] if source[1] == dest[1] else f[3] diff --git a/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/Solution.cpp b/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/Solution.cpp index 5e59e40435c04..75283af3b9d49 100644 --- a/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/Solution.cpp +++ b/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/Solution.cpp @@ -1,18 +1,18 @@ -class Solution { -public: - int sumCounts(vector& nums) { - int ans = 0; - int n = nums.size(); - for (int i = 0; i < n; ++i) { - int s[101]{}; - int cnt = 0; - for (int j = i; j < n; ++j) { - if (++s[nums[j]] == 1) { - ++cnt; - } - ans += cnt * cnt; - } - } - return ans; - } +class Solution { +public: + int sumCounts(vector& nums) { + int ans = 0; + int n = nums.size(); + for (int i = 0; i < n; ++i) { + int s[101]{}; + int cnt = 0; + for (int j = i; j < n; ++j) { + if (++s[nums[j]] == 1) { + ++cnt; + } + ans += cnt * cnt; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/Solution.java b/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/Solution.java index c2b72d1199bfe..0d92480af17d4 100644 --- a/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/Solution.java +++ b/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public int sumCounts(List nums) { - int ans = 0; - int n = nums.size(); - for (int i = 0; i < n; ++i) { - int[] s = new int[101]; - int cnt = 0; - for (int j = i; j < n; ++j) { - if (++s[nums.get(j)] == 1) { - ++cnt; - } - ans += cnt * cnt; - } - } - return ans; - } +class Solution { + public int sumCounts(List nums) { + int ans = 0; + int n = nums.size(); + for (int i = 0; i < n; ++i) { + int[] s = new int[101]; + int cnt = 0; + for (int j = i; j < n; ++j) { + if (++s[nums.get(j)] == 1) { + ++cnt; + } + ans += cnt * cnt; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/Solution.py b/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/Solution.py index 9c8720ab45025..1a52a7a589b3e 100644 --- a/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/Solution.py +++ b/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def sumCounts(self, nums: List[int]) -> int: - ans, n = 0, len(nums) - for i in range(n): - s = set() - for j in range(i, n): - s.add(nums[j]) - ans += len(s) * len(s) - return ans +class Solution: + def sumCounts(self, nums: List[int]) -> int: + ans, n = 0, len(nums) + for i in range(n): + s = set() + for j in range(i, n): + s.add(nums[j]) + ans += len(s) * len(s) + return ans diff --git a/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/Solution.cpp b/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/Solution.cpp index 2e28922e7c939..61dc1cda2d043 100644 --- a/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/Solution.cpp +++ b/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/Solution.cpp @@ -1,11 +1,11 @@ -class Solution { -public: - int minChanges(string s) { - int ans = 0; - int n = s.size(); - for (int i = 1; i < n; i += 2) { - ans += s[i] != s[i - 1]; - } - return ans; - } +class Solution { +public: + int minChanges(string s) { + int ans = 0; + int n = s.size(); + for (int i = 1; i < n; i += 2) { + ans += s[i] != s[i - 1]; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/Solution.java b/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/Solution.java index 3064ac3a0b425..50aae6dc36c84 100644 --- a/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/Solution.java +++ b/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/Solution.java @@ -1,11 +1,11 @@ -class Solution { - public int minChanges(String s) { - int ans = 0; - for (int i = 1; i < s.length(); i += 2) { - if (s.charAt(i) != s.charAt(i - 1)) { - ++ans; - } - } - return ans; - } +class Solution { + public int minChanges(String s) { + int ans = 0; + for (int i = 1; i < s.length(); i += 2) { + if (s.charAt(i) != s.charAt(i - 1)) { + ++ans; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/Solution.py b/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/Solution.py index cbf348a9a4cf2..d7c869be98e35 100644 --- a/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/Solution.py +++ b/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/Solution.py @@ -1,3 +1,3 @@ -class Solution: - def minChanges(self, s: str) -> int: - return sum(s[i] != s[i - 1] for i in range(1, len(s), 2)) +class Solution: + def minChanges(self, s: str) -> int: + return sum(s[i] != s[i - 1] for i in range(1, len(s), 2)) diff --git a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.cpp b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.cpp index e4a127c0805a1..4b7677bc53529 100644 --- a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.cpp +++ b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.cpp @@ -1,14 +1,19 @@ -class Solution { -public: - int lengthOfLongestSubsequence(vector& nums, int target) { - int f[target + 1]; - memset(f, -0x3f, sizeof(f)); - f[0] = 0; - for (int x : nums) { - for (int j = target; j >= x; --j) { - f[j] = max(f[j], f[j - x] + 1); - } - } - return f[target] <= 0 ? -1 : f[target]; - } +class Solution { +public: + int lengthOfLongestSubsequence(vector& nums, int target) { + int n = nums.size(); + int f[n + 1][target + 1]; + memset(f, -0x3f, sizeof(f)); + f[0][0] = 0; + for (int i = 1; i <= n; ++i) { + int x = nums[i - 1]; + for (int j = 0; j <= target; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= x) { + f[i][j] = max(f[i][j], f[i - 1][j - x] + 1); + } + } + } + return f[n][target] <= 0 ? -1 : f[n][target]; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.go b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.go index ef03163e6ec18..2ca6f75182ffc 100644 --- a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.go +++ b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.go @@ -1,16 +1,24 @@ func lengthOfLongestSubsequence(nums []int, target int) int { - f := make([]int, target+1) + n := len(nums) + f := make([][]int, n+1) for i := range f { - f[i] = -(1 << 30) + f[i] = make([]int, target+1) + for j := range f[i] { + f[i][j] = -(1 << 30) + } } - f[0] = 0 - for _, x := range nums { - for j := target; j >= x; j-- { - f[j] = max(f[j], f[j-x]+1) + f[0][0] = 0 + for i := 1; i <= n; i++ { + x := nums[i-1] + for j := 0; j <= target; j++ { + f[i][j] = f[i-1][j] + if j >= x { + f[i][j] = max(f[i][j], f[i-1][j-x]+1) + } } } - if f[target] <= 0 { + if f[n][target] <= 0 { return -1 } - return f[target] + return f[n][target] } \ No newline at end of file diff --git a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.java b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.java index 1c1909a7fe881..d747369e895e1 100644 --- a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.java +++ b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.java @@ -1,14 +1,21 @@ -class Solution { - public int lengthOfLongestSubsequence(List nums, int target) { - int[] f = new int[target + 1]; - final int inf = 1 << 30; - Arrays.fill(f, -inf); - f[0] = 0; - for (int x : nums) { - for (int j = target; j >= x; --j) { - f[j] = Math.max(f[j], f[j - x] + 1); - } - } - return f[target] <= 0 ? -1 : f[target]; - } +class Solution { + public int lengthOfLongestSubsequence(List nums, int target) { + int n = nums.size(); + int[][] f = new int[n + 1][target + 1]; + final int inf = 1 << 30; + for (int[] g : f) { + Arrays.fill(g, -inf); + } + f[0][0] = 0; + for (int i = 1; i <= n; ++i) { + int x = nums.get(i - 1); + for (int j = 0; j <= target; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= x) { + f[i][j] = Math.max(f[i][j], f[i - 1][j - x] + 1); + } + } + } + return f[n][target] <= 0 ? -1 : f[n][target]; + } } \ No newline at end of file diff --git a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.py b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.py index 8e56867bf26f1..5e262373ee94d 100644 --- a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.py +++ b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.py @@ -1,7 +1,11 @@ -class Solution: - def lengthOfLongestSubsequence(self, nums: List[int], target: int) -> int: - f = [0] + [-inf] * target - for x in nums: - for j in range(target, x - 1, -1): - f[j] = max(f[j], f[j - x] + 1) - return -1 if f[-1] <= 0 else f[-1] +class Solution: + def lengthOfLongestSubsequence(self, nums: List[int], target: int) -> int: + n = len(nums) + f = [[-inf] * (target + 1) for _ in range(n + 1)] + f[0][0] = 0 + for i, x in enumerate(nums, 1): + for j in range(target + 1): + f[i][j] = f[i - 1][j] + if j >= x: + f[i][j] = max(f[i][j], f[i - 1][j - x] + 1) + return -1 if f[n][target] <= 0 else f[n][target] diff --git a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.ts b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.ts index ba01c68f4c0fb..fe82e66f64159 100644 --- a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.ts +++ b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.ts @@ -1,10 +1,15 @@ function lengthOfLongestSubsequence(nums: number[], target: number): number { - const f: number[] = Array(target + 1).fill(-Infinity); - f[0] = 0; - for (const x of nums) { - for (let j = target; j >= x; --j) { - f[j] = Math.max(f[j], f[j - x] + 1); + const n = nums.length; + const f: number[][] = Array.from({ length: n + 1 }, () => Array(target + 1).fill(-Infinity)); + f[0][0] = 0; + for (let i = 1; i <= n; ++i) { + const x = nums[i - 1]; + for (let j = 0; j <= target; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= x) { + f[i][j] = Math.max(f[i][j], f[i - 1][j - x] + 1); + } } } - return f[target] <= 0 ? -1 : f[target]; + return f[n][target] <= 0 ? -1 : f[n][target]; } diff --git a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution2.cpp b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution2.cpp new file mode 100644 index 0000000000000..76e55539d6e25 --- /dev/null +++ b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int lengthOfLongestSubsequence(vector& nums, int target) { + int f[target + 1]; + memset(f, -0x3f, sizeof(f)); + f[0] = 0; + for (int x : nums) { + for (int j = target; j >= x; --j) { + f[j] = max(f[j], f[j - x] + 1); + } + } + return f[target] <= 0 ? -1 : f[target]; + } +}; \ No newline at end of file diff --git a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution2.go b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution2.go new file mode 100644 index 0000000000000..ef03163e6ec18 --- /dev/null +++ b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution2.go @@ -0,0 +1,16 @@ +func lengthOfLongestSubsequence(nums []int, target int) int { + f := make([]int, target+1) + for i := range f { + f[i] = -(1 << 30) + } + f[0] = 0 + for _, x := range nums { + for j := target; j >= x; j-- { + f[j] = max(f[j], f[j-x]+1) + } + } + if f[target] <= 0 { + return -1 + } + return f[target] +} \ No newline at end of file diff --git a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution2.java b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution2.java new file mode 100644 index 0000000000000..0700956a78e4c --- /dev/null +++ b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution2.java @@ -0,0 +1,14 @@ +class Solution { + public int lengthOfLongestSubsequence(List nums, int target) { + int[] f = new int[target + 1]; + final int inf = 1 << 30; + Arrays.fill(f, -inf); + f[0] = 0; + for (int x : nums) { + for (int j = target; j >= x; --j) { + f[j] = Math.max(f[j], f[j - x] + 1); + } + } + return f[target] <= 0 ? -1 : f[target]; + } +} \ No newline at end of file diff --git a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution2.py b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution2.py new file mode 100644 index 0000000000000..e591fb71f2b6d --- /dev/null +++ b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution2.py @@ -0,0 +1,7 @@ +class Solution: + def lengthOfLongestSubsequence(self, nums: List[int], target: int) -> int: + f = [0] + [-inf] * target + for x in nums: + for j in range(target, x - 1, -1): + f[j] = max(f[j], f[j - x] + 1) + return -1 if f[-1] <= 0 else f[-1] diff --git a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution2.ts b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution2.ts new file mode 100644 index 0000000000000..ba01c68f4c0fb --- /dev/null +++ b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution2.ts @@ -0,0 +1,10 @@ +function lengthOfLongestSubsequence(nums: number[], target: number): number { + const f: number[] = Array(target + 1).fill(-Infinity); + f[0] = 0; + for (const x of nums) { + for (let j = target; j >= x; --j) { + f[j] = Math.max(f[j], f[j - x] + 1); + } + } + return f[target] <= 0 ? -1 : f[target]; +} diff --git a/solution/2900-2999/2917.Find the K-or of an Array/Solution.cpp b/solution/2900-2999/2917.Find the K-or of an Array/Solution.cpp index efd31148c4ad1..6c244a4ab5794 100644 --- a/solution/2900-2999/2917.Find the K-or of an Array/Solution.cpp +++ b/solution/2900-2999/2917.Find the K-or of an Array/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - int findKOr(vector& nums, int k) { - int ans = 0; - for (int i = 0; i < 32; ++i) { - int cnt = 0; - for (int x : nums) { - cnt += (x >> i & 1); - } - if (cnt >= k) { - ans |= 1 << i; - } - } - return ans; - } +class Solution { +public: + int findKOr(vector& nums, int k) { + int ans = 0; + for (int i = 0; i < 32; ++i) { + int cnt = 0; + for (int x : nums) { + cnt += (x >> i & 1); + } + if (cnt >= k) { + ans |= 1 << i; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2917.Find the K-or of an Array/Solution.java b/solution/2900-2999/2917.Find the K-or of an Array/Solution.java index 87ed497949f5e..9d48e263f2456 100644 --- a/solution/2900-2999/2917.Find the K-or of an Array/Solution.java +++ b/solution/2900-2999/2917.Find the K-or of an Array/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public int findKOr(int[] nums, int k) { - int ans = 0; - for (int i = 0; i < 32; ++i) { - int cnt = 0; - for (int x : nums) { - cnt += (x >> i & 1); - } - if (cnt >= k) { - ans |= 1 << i; - } - } - return ans; - } +class Solution { + public int findKOr(int[] nums, int k) { + int ans = 0; + for (int i = 0; i < 32; ++i) { + int cnt = 0; + for (int x : nums) { + cnt += (x >> i & 1); + } + if (cnt >= k) { + ans |= 1 << i; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2917.Find the K-or of an Array/Solution.py b/solution/2900-2999/2917.Find the K-or of an Array/Solution.py index 637f1b600e1bf..a8ca113a85fe1 100644 --- a/solution/2900-2999/2917.Find the K-or of an Array/Solution.py +++ b/solution/2900-2999/2917.Find the K-or of an Array/Solution.py @@ -1,8 +1,8 @@ -class Solution: - def findKOr(self, nums: List[int], k: int) -> int: - ans = 0 - for i in range(32): - cnt = sum(x >> i & 1 for x in nums) - if cnt >= k: - ans |= 1 << i - return ans +class Solution: + def findKOr(self, nums: List[int], k: int) -> int: + ans = 0 + for i in range(32): + cnt = sum(x >> i & 1 for x in nums) + if cnt >= k: + ans |= 1 << i + return ans diff --git a/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/Solution.cpp b/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/Solution.cpp index da269eff29b68..a3ffe1907a87b 100644 --- a/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/Solution.cpp +++ b/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - long long minSum(vector& nums1, vector& nums2) { - long long s1 = 0, s2 = 0; - bool hasZero = false; - for (int x : nums1) { - hasZero |= x == 0; - s1 += max(x, 1); - } - for (int x : nums2) { - s2 += max(x, 1); - } - if (s1 > s2) { - return minSum(nums2, nums1); - } - if (s1 == s2) { - return s1; - } - return hasZero ? s2 : -1; - } +class Solution { +public: + long long minSum(vector& nums1, vector& nums2) { + long long s1 = 0, s2 = 0; + bool hasZero = false; + for (int x : nums1) { + hasZero |= x == 0; + s1 += max(x, 1); + } + for (int x : nums2) { + s2 += max(x, 1); + } + if (s1 > s2) { + return minSum(nums2, nums1); + } + if (s1 == s2) { + return s1; + } + return hasZero ? s2 : -1; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/Solution.java b/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/Solution.java index adadf688e6ab8..680501dc011f6 100644 --- a/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/Solution.java +++ b/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/Solution.java @@ -1,20 +1,20 @@ -class Solution { - public long minSum(int[] nums1, int[] nums2) { - long s1 = 0, s2 = 0; - boolean hasZero = false; - for (int x : nums1) { - hasZero |= x == 0; - s1 += Math.max(x, 1); - } - for (int x : nums2) { - s2 += Math.max(x, 1); - } - if (s1 > s2) { - return minSum(nums2, nums1); - } - if (s1 == s2) { - return s1; - } - return hasZero ? s2 : -1; - } +class Solution { + public long minSum(int[] nums1, int[] nums2) { + long s1 = 0, s2 = 0; + boolean hasZero = false; + for (int x : nums1) { + hasZero |= x == 0; + s1 += Math.max(x, 1); + } + for (int x : nums2) { + s2 += Math.max(x, 1); + } + if (s1 > s2) { + return minSum(nums2, nums1); + } + if (s1 == s2) { + return s1; + } + return hasZero ? s2 : -1; + } } \ No newline at end of file diff --git a/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/Solution.py b/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/Solution.py index aa97facb4923b..4894a9731a3f6 100644 --- a/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/Solution.py +++ b/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def minSum(self, nums1: List[int], nums2: List[int]) -> int: - s1 = sum(nums1) + nums1.count(0) - s2 = sum(nums2) + nums2.count(0) - if s1 > s2: - return self.minSum(nums2, nums1) - if s1 == s2: - return s1 - return -1 if nums1.count(0) == 0 else s2 +class Solution: + def minSum(self, nums1: List[int], nums2: List[int]) -> int: + s1 = sum(nums1) + nums1.count(0) + s2 = sum(nums2) + nums2.count(0) + if s1 > s2: + return self.minSum(nums2, nums1) + if s1 == s2: + return s1 + return -1 if nums1.count(0) == 0 else s2 diff --git a/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/Solution.cpp b/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/Solution.cpp index 2f49155a8dfe2..17f5dc42c46e5 100644 --- a/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/Solution.cpp +++ b/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/Solution.cpp @@ -1,13 +1,13 @@ -class Solution { -public: - long long minIncrementOperations(vector& nums, int k) { - long long f = 0, g = 0, h = 0; - for (int x : nums) { - long long hh = min({f, g, h}) + max(k - x, 0); - f = g; - g = h; - h = hh; - } - return min({f, g, h}); - } +class Solution { +public: + long long minIncrementOperations(vector& nums, int k) { + long long f = 0, g = 0, h = 0; + for (int x : nums) { + long long hh = min({f, g, h}) + max(k - x, 0); + f = g; + g = h; + h = hh; + } + return min({f, g, h}); + } }; \ No newline at end of file diff --git a/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/Solution.java b/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/Solution.java index 6857f1923dccf..ca13abd270345 100644 --- a/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/Solution.java +++ b/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/Solution.java @@ -1,12 +1,12 @@ -class Solution { - public long minIncrementOperations(int[] nums, int k) { - long f = 0, g = 0, h = 0; - for (int x : nums) { - long hh = Math.min(Math.min(f, g), h) + Math.max(k - x, 0); - f = g; - g = h; - h = hh; - } - return Math.min(Math.min(f, g), h); - } +class Solution { + public long minIncrementOperations(int[] nums, int k) { + long f = 0, g = 0, h = 0; + for (int x : nums) { + long hh = Math.min(Math.min(f, g), h) + Math.max(k - x, 0); + f = g; + g = h; + h = hh; + } + return Math.min(Math.min(f, g), h); + } } \ No newline at end of file diff --git a/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/Solution.py b/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/Solution.py index db186a174ef00..4155980f0adf9 100644 --- a/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/Solution.py +++ b/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/Solution.py @@ -1,6 +1,6 @@ -class Solution: - def minIncrementOperations(self, nums: List[int], k: int) -> int: - f = g = h = 0 - for x in nums: - f, g, h = g, h, min(f, g, h) + max(k - x, 0) - return min(f, g, h) +class Solution: + def minIncrementOperations(self, nums: List[int], k: int) -> int: + f = g = h = 0 + for x in nums: + f, g, h = g, h, min(f, g, h) + max(k - x, 0) + return min(f, g, h) diff --git a/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/Solution.cpp b/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/Solution.cpp index 0fb1d37555066..9888208ffdf0f 100644 --- a/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/Solution.cpp +++ b/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/Solution.cpp @@ -1,56 +1,56 @@ -class BinaryIndexedTree { -private: - int n; - vector c; - -public: - BinaryIndexedTree(int n) { - this->n = n; - c.resize(n + 1, 0); - } - - void update(int x, int v) { - while (x <= n) { - c[x] = max(c[x], v); - x += x & -x; - } - } - - int query(int x) { - int mx = 0; - while (x > 0) { - mx = max(mx, c[x]); - x -= x & -x; - } - return mx; - } -}; - -class Solution { -public: - int maxProfit(vector& prices, vector& profits) { - int n = prices.size(); - vector left(n, 0); - vector right(n, 0); - int m = *max_element(prices.begin(), prices.end()); - BinaryIndexedTree tree1(m + 1); - BinaryIndexedTree tree2(m + 1); - for (int i = 0; i < n; ++i) { - int x = prices[i]; - left[i] = tree1.query(x - 1); - tree1.update(x, profits[i]); - } - for (int i = n - 1; i >= 0; --i) { - int x = m + 1 - prices[i]; - right[i] = tree2.query(x - 1); - tree2.update(x, profits[i]); - } - int ans = -1; - for (int i = 0; i < n; ++i) { - if (left[i] > 0 && right[i] > 0) { - ans = max(ans, left[i] + profits[i] + right[i]); - } - } - return ans; - } -}; +class BinaryIndexedTree { +private: + int n; + vector c; + +public: + BinaryIndexedTree(int n) { + this->n = n; + c.resize(n + 1, 0); + } + + void update(int x, int v) { + while (x <= n) { + c[x] = max(c[x], v); + x += x & -x; + } + } + + int query(int x) { + int mx = 0; + while (x > 0) { + mx = max(mx, c[x]); + x -= x & -x; + } + return mx; + } +}; + +class Solution { +public: + int maxProfit(vector& prices, vector& profits) { + int n = prices.size(); + vector left(n, 0); + vector right(n, 0); + int m = *max_element(prices.begin(), prices.end()); + BinaryIndexedTree tree1(m + 1); + BinaryIndexedTree tree2(m + 1); + for (int i = 0; i < n; ++i) { + int x = prices[i]; + left[i] = tree1.query(x - 1); + tree1.update(x, profits[i]); + } + for (int i = n - 1; i >= 0; --i) { + int x = m + 1 - prices[i]; + right[i] = tree2.query(x - 1); + tree2.update(x, profits[i]); + } + int ans = -1; + for (int i = 0; i < n; ++i) { + if (left[i] > 0 && right[i] > 0) { + ans = max(ans, left[i] + profits[i] + right[i]); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/Solution.java b/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/Solution.java index 816810b673ea1..b4ff26378b644 100644 --- a/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/Solution.java +++ b/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/Solution.java @@ -1,56 +1,56 @@ -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void update(int x, int v) { - while (x <= n) { - c[x] = Math.max(c[x], v); - x += x & -x; - } - } - - public int query(int x) { - int mx = 0; - while (x > 0) { - mx = Math.max(mx, c[x]); - x -= x & -x; - } - return mx; - } -} - -class Solution { - public int maxProfit(int[] prices, int[] profits) { - int n = prices.length; - int[] left = new int[n]; - int[] right = new int[n]; - int m = 0; - for (int x : prices) { - m = Math.max(m, x); - } - BinaryIndexedTree tree1 = new BinaryIndexedTree(m + 1); - BinaryIndexedTree tree2 = new BinaryIndexedTree(m + 1); - for (int i = 0; i < n; ++i) { - int x = prices[i]; - left[i] = tree1.query(x - 1); - tree1.update(x, profits[i]); - } - for (int i = n - 1; i >= 0; --i) { - int x = m + 1 - prices[i]; - right[i] = tree2.query(x - 1); - tree2.update(x, profits[i]); - } - int ans = -1; - for (int i = 0; i < n; ++i) { - if (left[i] > 0 && right[i] > 0) { - ans = Math.max(ans, left[i] + profits[i] + right[i]); - } - } - return ans; - } +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int v) { + while (x <= n) { + c[x] = Math.max(c[x], v); + x += x & -x; + } + } + + public int query(int x) { + int mx = 0; + while (x > 0) { + mx = Math.max(mx, c[x]); + x -= x & -x; + } + return mx; + } +} + +class Solution { + public int maxProfit(int[] prices, int[] profits) { + int n = prices.length; + int[] left = new int[n]; + int[] right = new int[n]; + int m = 0; + for (int x : prices) { + m = Math.max(m, x); + } + BinaryIndexedTree tree1 = new BinaryIndexedTree(m + 1); + BinaryIndexedTree tree2 = new BinaryIndexedTree(m + 1); + for (int i = 0; i < n; ++i) { + int x = prices[i]; + left[i] = tree1.query(x - 1); + tree1.update(x, profits[i]); + } + for (int i = n - 1; i >= 0; --i) { + int x = m + 1 - prices[i]; + right[i] = tree2.query(x - 1); + tree2.update(x, profits[i]); + } + int ans = -1; + for (int i = 0; i < n; ++i) { + if (left[i] > 0 && right[i] > 0) { + ans = Math.max(ans, left[i] + profits[i] + right[i]); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/Solution.py b/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/Solution.py index 6ab10306a6ecd..530712d97154e 100644 --- a/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/Solution.py +++ b/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/Solution.py @@ -1,39 +1,39 @@ -class BinaryIndexedTree: - def __init__(self, n: int): - self.n = n - self.c = [0] * (n + 1) - - def update(self, x: int, v: int): - while x <= self.n: - self.c[x] = max(self.c[x], v) - x += x & -x - - def query(self, x: int) -> int: - mx = 0 - while x: - mx = max(mx, self.c[x]) - x -= x & -x - return mx - - -class Solution: - def maxProfit(self, prices: List[int], profits: List[int]) -> int: - n = len(prices) - left = [0] * n - right = [0] * n - - m = max(prices) - tree1 = BinaryIndexedTree(m + 1) - tree2 = BinaryIndexedTree(m + 1) - - for i, x in enumerate(prices): - left[i] = tree1.query(x - 1) - tree1.update(x, profits[i]) - for i in range(n - 1, -1, -1): - x = m + 1 - prices[i] - right[i] = tree2.query(x - 1) - tree2.update(x, profits[i]) - - return max( - (l + x + r for l, x, r in zip(left, profits, right) if l and r), default=-1 - ) +class BinaryIndexedTree: + def __init__(self, n: int): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x: int, v: int): + while x <= self.n: + self.c[x] = max(self.c[x], v) + x += x & -x + + def query(self, x: int) -> int: + mx = 0 + while x: + mx = max(mx, self.c[x]) + x -= x & -x + return mx + + +class Solution: + def maxProfit(self, prices: List[int], profits: List[int]) -> int: + n = len(prices) + left = [0] * n + right = [0] * n + + m = max(prices) + tree1 = BinaryIndexedTree(m + 1) + tree2 = BinaryIndexedTree(m + 1) + + for i, x in enumerate(prices): + left[i] = tree1.query(x - 1) + tree1.update(x, profits[i]) + for i in range(n - 1, -1, -1): + x = m + 1 - prices[i] + right[i] = tree2.query(x - 1) + tree2.update(x, profits[i]) + + return max( + (l + x + r for l, x, r in zip(left, profits, right) if l and r), default=-1 + ) diff --git a/solution/2900-2999/2923.Find Champion I/Solution.cpp b/solution/2900-2999/2923.Find Champion I/Solution.cpp index 5f0ef8a6c829c..a4d1cb2346256 100644 --- a/solution/2900-2999/2923.Find Champion I/Solution.cpp +++ b/solution/2900-2999/2923.Find Champion I/Solution.cpp @@ -1,17 +1,17 @@ -class Solution { -public: - int findChampion(vector>& grid) { - int n = grid.size(); - for (int i = 0;; ++i) { - int cnt = 0; - for (int j = 0; j < n; ++j) { - if (i != j && grid[i][j] == 1) { - ++cnt; - } - } - if (cnt == n - 1) { - return i; - } - } - } +class Solution { +public: + int findChampion(vector>& grid) { + int n = grid.size(); + for (int i = 0;; ++i) { + int cnt = 0; + for (int j = 0; j < n; ++j) { + if (i != j && grid[i][j] == 1) { + ++cnt; + } + } + if (cnt == n - 1) { + return i; + } + } + } }; \ No newline at end of file diff --git a/solution/2900-2999/2923.Find Champion I/Solution.java b/solution/2900-2999/2923.Find Champion I/Solution.java index 07f8fcec83ca4..bd56705de8db9 100644 --- a/solution/2900-2999/2923.Find Champion I/Solution.java +++ b/solution/2900-2999/2923.Find Champion I/Solution.java @@ -1,16 +1,16 @@ -class Solution { - public int findChampion(int[][] grid) { - int n = grid.length; - for (int i = 0;; ++i) { - int cnt = 0; - for (int j = 0; j < n; ++j) { - if (i != j && grid[i][j] == 1) { - ++cnt; - } - } - if (cnt == n - 1) { - return i; - } - } - } +class Solution { + public int findChampion(int[][] grid) { + int n = grid.length; + for (int i = 0;; ++i) { + int cnt = 0; + for (int j = 0; j < n; ++j) { + if (i != j && grid[i][j] == 1) { + ++cnt; + } + } + if (cnt == n - 1) { + return i; + } + } + } } \ No newline at end of file diff --git a/solution/2900-2999/2923.Find Champion I/Solution.py b/solution/2900-2999/2923.Find Champion I/Solution.py index f90110196f316..08ea0874eee24 100644 --- a/solution/2900-2999/2923.Find Champion I/Solution.py +++ b/solution/2900-2999/2923.Find Champion I/Solution.py @@ -1,5 +1,5 @@ -class Solution: - def findChampion(self, grid: List[List[int]]) -> int: - for i, row in enumerate(grid): - if all(x == 1 for j, x in enumerate(row) if i != j): - return i +class Solution: + def findChampion(self, grid: List[List[int]]) -> int: + for i, row in enumerate(grid): + if all(x == 1 for j, x in enumerate(row) if i != j): + return i diff --git a/solution/2900-2999/2924.Find Champion II/Solution.cpp b/solution/2900-2999/2924.Find Champion II/Solution.cpp index afbf1aec6b4f3..d2c92c7a8776f 100644 --- a/solution/2900-2999/2924.Find Champion II/Solution.cpp +++ b/solution/2900-2999/2924.Find Champion II/Solution.cpp @@ -1,18 +1,18 @@ -class Solution { -public: - int findChampion(int n, vector>& edges) { - int indeg[n]; - memset(indeg, 0, sizeof(indeg)); - for (auto& e : edges) { - ++indeg[e[1]]; - } - int ans = -1, cnt = 0; - for (int i = 0; i < n; ++i) { - if (indeg[i] == 0) { - ++cnt; - ans = i; - } - } - return cnt == 1 ? ans : -1; - } +class Solution { +public: + int findChampion(int n, vector>& edges) { + int indeg[n]; + memset(indeg, 0, sizeof(indeg)); + for (auto& e : edges) { + ++indeg[e[1]]; + } + int ans = -1, cnt = 0; + for (int i = 0; i < n; ++i) { + if (indeg[i] == 0) { + ++cnt; + ans = i; + } + } + return cnt == 1 ? ans : -1; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2924.Find Champion II/Solution.java b/solution/2900-2999/2924.Find Champion II/Solution.java index 6d19919ae7605..2a1779d7e2250 100644 --- a/solution/2900-2999/2924.Find Champion II/Solution.java +++ b/solution/2900-2999/2924.Find Champion II/Solution.java @@ -1,16 +1,16 @@ -class Solution { - public int findChampion(int n, int[][] edges) { - int[] indeg = new int[n]; - for (var e : edges) { - ++indeg[e[1]]; - } - int ans = -1, cnt = 0; - for (int i = 0; i < n; ++i) { - if (indeg[i] == 0) { - ++cnt; - ans = i; - } - } - return cnt == 1 ? ans : -1; - } +class Solution { + public int findChampion(int n, int[][] edges) { + int[] indeg = new int[n]; + for (var e : edges) { + ++indeg[e[1]]; + } + int ans = -1, cnt = 0; + for (int i = 0; i < n; ++i) { + if (indeg[i] == 0) { + ++cnt; + ans = i; + } + } + return cnt == 1 ? ans : -1; + } } \ No newline at end of file diff --git a/solution/2900-2999/2924.Find Champion II/Solution.py b/solution/2900-2999/2924.Find Champion II/Solution.py index 4837d6837fed1..e250f7b083a50 100644 --- a/solution/2900-2999/2924.Find Champion II/Solution.py +++ b/solution/2900-2999/2924.Find Champion II/Solution.py @@ -1,6 +1,6 @@ -class Solution: - def findChampion(self, n: int, edges: List[List[int]]) -> int: - indeg = [0] * n - for _, v in edges: - indeg[v] += 1 - return -1 if indeg.count(0) != 1 else indeg.index(0) +class Solution: + def findChampion(self, n: int, edges: List[List[int]]) -> int: + indeg = [0] * n + for _, v in edges: + indeg[v] += 1 + return -1 if indeg.count(0) != 1 else indeg.index(0) diff --git a/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/Solution.cpp b/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/Solution.cpp index af97b58de4619..11050b1d11aeb 100644 --- a/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/Solution.cpp +++ b/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/Solution.cpp @@ -1,31 +1,31 @@ -class Solution { -public: - long long maximumScoreAfterOperations(vector>& edges, vector& values) { - int n = values.size(); - vector g[n]; - for (auto& e : edges) { - int a = e[0], b = e[1]; - g[a].emplace_back(b); - g[b].emplace_back(a); - } - using ll = long long; - function(int, int)> dfs = [&](int i, int fa) -> pair { - ll a = 0, b = 0; - bool leaf = true; - for (int j : g[i]) { - if (j != fa) { - auto [aa, bb] = dfs(j, i); - a += aa; - b += bb; - leaf = false; - } - } - if (leaf) { - return {values[i], 0LL}; - } - return {values[i] + a, max(values[i] + b, a)}; - }; - auto [_, b] = dfs(0, -1); - return b; - } +class Solution { +public: + long long maximumScoreAfterOperations(vector>& edges, vector& values) { + int n = values.size(); + vector g[n]; + for (auto& e : edges) { + int a = e[0], b = e[1]; + g[a].emplace_back(b); + g[b].emplace_back(a); + } + using ll = long long; + function(int, int)> dfs = [&](int i, int fa) -> pair { + ll a = 0, b = 0; + bool leaf = true; + for (int j : g[i]) { + if (j != fa) { + auto [aa, bb] = dfs(j, i); + a += aa; + b += bb; + leaf = false; + } + } + if (leaf) { + return {values[i], 0LL}; + } + return {values[i] + a, max(values[i] + b, a)}; + }; + auto [_, b] = dfs(0, -1); + return b; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/Solution.java b/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/Solution.java index 240a0519d0bec..ed17f220eb208 100644 --- a/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/Solution.java +++ b/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/Solution.java @@ -1,34 +1,34 @@ -class Solution { - private List[] g; - private int[] values; - - public long maximumScoreAfterOperations(int[][] edges, int[] values) { - int n = values.length; - g = new List[n]; - this.values = values; - Arrays.setAll(g, k -> new ArrayList<>()); - for (var e : edges) { - int a = e[0], b = e[1]; - g[a].add(b); - g[b].add(a); - } - return dfs(0, -1)[1]; - } - - private long[] dfs(int i, int fa) { - long a = 0, b = 0; - boolean leaf = true; - for (int j : g[i]) { - if (j != fa) { - leaf = false; - var t = dfs(j, i); - a += t[0]; - b += t[1]; - } - } - if (leaf) { - return new long[] {values[i], 0}; - } - return new long[] {values[i] + a, Math.max(values[i] + b, a)}; - } +class Solution { + private List[] g; + private int[] values; + + public long maximumScoreAfterOperations(int[][] edges, int[] values) { + int n = values.length; + g = new List[n]; + this.values = values; + Arrays.setAll(g, k -> new ArrayList<>()); + for (var e : edges) { + int a = e[0], b = e[1]; + g[a].add(b); + g[b].add(a); + } + return dfs(0, -1)[1]; + } + + private long[] dfs(int i, int fa) { + long a = 0, b = 0; + boolean leaf = true; + for (int j : g[i]) { + if (j != fa) { + leaf = false; + var t = dfs(j, i); + a += t[0]; + b += t[1]; + } + } + if (leaf) { + return new long[] {values[i], 0}; + } + return new long[] {values[i] + a, Math.max(values[i] + b, a)}; + } } \ No newline at end of file diff --git a/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/Solution.py b/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/Solution.py index cf52956ced0cb..04d568448a702 100644 --- a/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/Solution.py +++ b/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/Solution.py @@ -1,22 +1,22 @@ -class Solution: - def maximumScoreAfterOperations( - self, edges: List[List[int]], values: List[int] - ) -> int: - def dfs(i: int, fa: int = -1) -> (int, int): - a = b = 0 - leaf = True - for j in g[i]: - if j != fa: - leaf = False - aa, bb = dfs(j, i) - a += aa - b += bb - if leaf: - return values[i], 0 - return values[i] + a, max(values[i] + b, a) - - g = [[] for _ in range(len(values))] - for a, b in edges: - g[a].append(b) - g[b].append(a) - return dfs(0)[1] +class Solution: + def maximumScoreAfterOperations( + self, edges: List[List[int]], values: List[int] + ) -> int: + def dfs(i: int, fa: int = -1) -> (int, int): + a = b = 0 + leaf = True + for j in g[i]: + if j != fa: + leaf = False + aa, bb = dfs(j, i) + a += aa + b += bb + if leaf: + return values[i], 0 + return values[i] + a, max(values[i] + b, a) + + g = [[] for _ in range(len(values))] + for a, b in edges: + g[a].append(b) + g[b].append(a) + return dfs(0)[1] diff --git a/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/Solution.cpp b/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/Solution.cpp index 1cf74a14a4dbe..2cbe9241f789a 100644 --- a/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/Solution.cpp +++ b/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/Solution.cpp @@ -1,49 +1,49 @@ -class BinaryIndexedTree { -private: - int n; - vector c; - const long long inf = 1e18; - -public: - BinaryIndexedTree(int n) { - this->n = n; - c.resize(n + 1, -inf); - } - - void update(int x, long long v) { - while (x <= n) { - c[x] = max(c[x], v); - x += x & -x; - } - } - - long long query(int x) { - long long mx = -inf; - while (x > 0) { - mx = max(mx, c[x]); - x -= x & -x; - } - return mx; - } -}; - -class Solution { -public: - long long maxBalancedSubsequenceSum(vector& nums) { - int n = nums.size(); - vector arr(n); - for (int i = 0; i < n; ++i) { - arr[i] = nums[i] - i; - } - sort(arr.begin(), arr.end()); - arr.erase(unique(arr.begin(), arr.end()), arr.end()); - int m = arr.size(); - BinaryIndexedTree tree(m); - for (int i = 0; i < n; ++i) { - int j = lower_bound(arr.begin(), arr.end(), nums[i] - i) - arr.begin() + 1; - long long v = max(tree.query(j), 0LL) + nums[i]; - tree.update(j, v); - } - return tree.query(m); - } +class BinaryIndexedTree { +private: + int n; + vector c; + const long long inf = 1e18; + +public: + BinaryIndexedTree(int n) { + this->n = n; + c.resize(n + 1, -inf); + } + + void update(int x, long long v) { + while (x <= n) { + c[x] = max(c[x], v); + x += x & -x; + } + } + + long long query(int x) { + long long mx = -inf; + while (x > 0) { + mx = max(mx, c[x]); + x -= x & -x; + } + return mx; + } +}; + +class Solution { +public: + long long maxBalancedSubsequenceSum(vector& nums) { + int n = nums.size(); + vector arr(n); + for (int i = 0; i < n; ++i) { + arr[i] = nums[i] - i; + } + sort(arr.begin(), arr.end()); + arr.erase(unique(arr.begin(), arr.end()), arr.end()); + int m = arr.size(); + BinaryIndexedTree tree(m); + for (int i = 0; i < n; ++i) { + int j = lower_bound(arr.begin(), arr.end(), nums[i] - i) - arr.begin() + 1; + long long v = max(tree.query(j), 0LL) + nums[i]; + tree.update(j, v); + } + return tree.query(m); + } }; \ No newline at end of file diff --git a/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/Solution.java b/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/Solution.java index f9db775c2a597..14b699b1f0fc7 100644 --- a/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/Solution.java +++ b/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/Solution.java @@ -1,64 +1,64 @@ -class BinaryIndexedTree { - private int n; - private long[] c; - private final long inf = 1L << 60; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new long[n + 1]; - Arrays.fill(c, -inf); - } - - public void update(int x, long v) { - while (x <= n) { - c[x] = Math.max(c[x], v); - x += x & -x; - } - } - - public long query(int x) { - long mx = -inf; - while (x > 0) { - mx = Math.max(mx, c[x]); - x -= x & -x; - } - return mx; - } -} - -class Solution { - public long maxBalancedSubsequenceSum(int[] nums) { - int n = nums.length; - int[] arr = new int[n]; - for (int i = 0; i < n; ++i) { - arr[i] = nums[i] - i; - } - Arrays.sort(arr); - int m = 0; - for (int i = 0; i < n; ++i) { - if (i == 0 || arr[i] != arr[i - 1]) { - arr[m++] = arr[i]; - } - } - BinaryIndexedTree tree = new BinaryIndexedTree(m); - for (int i = 0; i < n; ++i) { - int j = search(arr, nums[i] - i, m) + 1; - long v = Math.max(tree.query(j), 0) + nums[i]; - tree.update(j, v); - } - return tree.query(m); - } - - private int search(int[] nums, int x, int r) { - int l = 0; - while (l < r) { - int mid = (l + r) >> 1; - if (nums[mid] >= x) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } +class BinaryIndexedTree { + private int n; + private long[] c; + private final long inf = 1L << 60; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new long[n + 1]; + Arrays.fill(c, -inf); + } + + public void update(int x, long v) { + while (x <= n) { + c[x] = Math.max(c[x], v); + x += x & -x; + } + } + + public long query(int x) { + long mx = -inf; + while (x > 0) { + mx = Math.max(mx, c[x]); + x -= x & -x; + } + return mx; + } +} + +class Solution { + public long maxBalancedSubsequenceSum(int[] nums) { + int n = nums.length; + int[] arr = new int[n]; + for (int i = 0; i < n; ++i) { + arr[i] = nums[i] - i; + } + Arrays.sort(arr); + int m = 0; + for (int i = 0; i < n; ++i) { + if (i == 0 || arr[i] != arr[i - 1]) { + arr[m++] = arr[i]; + } + } + BinaryIndexedTree tree = new BinaryIndexedTree(m); + for (int i = 0; i < n; ++i) { + int j = search(arr, nums[i] - i, m) + 1; + long v = Math.max(tree.query(j), 0) + nums[i]; + tree.update(j, v); + } + return tree.query(m); + } + + private int search(int[] nums, int x, int r) { + int l = 0; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } } \ No newline at end of file diff --git a/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/Solution.py b/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/Solution.py index d069bb1810434..6aeacbaa756f6 100644 --- a/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/Solution.py +++ b/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/Solution.py @@ -1,28 +1,28 @@ -class BinaryIndexedTree: - def __init__(self, n: int): - self.n = n - self.c = [-inf] * (n + 1) - - def update(self, x: int, v: int): - while x <= self.n: - self.c[x] = max(self.c[x], v) - x += x & -x - - def query(self, x: int) -> int: - mx = -inf - while x: - mx = max(mx, self.c[x]) - x -= x & -x - return mx - - -class Solution: - def maxBalancedSubsequenceSum(self, nums: List[int]) -> int: - arr = [x - i for i, x in enumerate(nums)] - s = sorted(set(arr)) - tree = BinaryIndexedTree(len(s)) - for i, x in enumerate(nums): - j = bisect_left(s, x - i) + 1 - v = max(tree.query(j), 0) + x - tree.update(j, v) - return tree.query(len(s)) +class BinaryIndexedTree: + def __init__(self, n: int): + self.n = n + self.c = [-inf] * (n + 1) + + def update(self, x: int, v: int): + while x <= self.n: + self.c[x] = max(self.c[x], v) + x += x & -x + + def query(self, x: int) -> int: + mx = -inf + while x: + mx = max(mx, self.c[x]) + x -= x & -x + return mx + + +class Solution: + def maxBalancedSubsequenceSum(self, nums: List[int]) -> int: + arr = [x - i for i, x in enumerate(nums)] + s = sorted(set(arr)) + tree = BinaryIndexedTree(len(s)) + for i, x in enumerate(nums): + j = bisect_left(s, x - i) + 1 + v = max(tree.query(j), 0) + x + tree.update(j, v) + return tree.query(len(s)) diff --git a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.cpp b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.cpp index 111d7c1c1ff77..ac73d14a9a9bb 100644 --- a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.cpp +++ b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.cpp @@ -1,26 +1,23 @@ -class Solution { -public: - int stringCount(int n) { - const int mod = 1e9 + 7; - using ll = long long; - auto qpow = [&](ll a, int n) { - ll ans = 1; - for (; n; n >>= 1) { - if (n & 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return ans; - }; - ll a = qpow(25, n); - ll b = a; - ll c = (qpow(25, n) + n * qpow(25, n - 1) % mod) % mod; - ll ab = qpow(24, n); - ll ac = (qpow(24, n) + n * qpow(24, n - 1) % mod) % mod; - ll bc = ac; - ll abc = (qpow(23, n) + n * qpow(23, n - 1) % mod) % mod; - ll tot = qpow(26, n); - return ((tot - (a + b + c - ab - ac - bc + abc)) % mod + mod) % mod; - } +class Solution { +public: + int stringCount(int n) { + const int mod = 1e9 + 7; + using ll = long long; + ll f[n + 1][2][3][2]; + memset(f, -1, sizeof(f)); + function dfs = [&](int i, int l, int e, int t) -> ll { + if (i == 0) { + return l == 1 && e == 2 && t == 1 ? 1 : 0; + } + if (f[i][l][e][t] != -1) { + return f[i][l][e][t]; + } + ll a = dfs(i - 1, l, e, t) * 23 % mod; + ll b = dfs(i - 1, min(1, l + 1), e, t) % mod; + ll c = dfs(i - 1, l, min(2, e + 1), t) % mod; + ll d = dfs(i - 1, l, e, min(1, t + 1)) % mod; + return f[i][l][e][t] = (a + b + c + d) % mod; + }; + return dfs(n, 0, 0, 0); + } }; \ No newline at end of file diff --git a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.go b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.go index efc876fbcea4d..99bf6eb5a64b6 100644 --- a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.go +++ b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.go @@ -1,22 +1,31 @@ func stringCount(n int) int { const mod int = 1e9 + 7 - qpow := func(a, n int) int { - ans := 1 - for ; n > 0; n >>= 1 { - if n&1 == 1 { - ans = ans * a % mod + f := make([][2][3][2]int, n+1) + for i := range f { + for j := range f[i] { + for k := range f[i][j] { + for l := range f[i][j][k] { + f[i][j][k][l] = -1 + } } - a = a * a % mod } - return ans } - a := qpow(25, n) - b := a - c := qpow(25, n) + n*qpow(25, n-1) - ab := qpow(24, n) - ac := (qpow(24, n) + n*qpow(24, n-1)) % mod - bc := ac - abc := (qpow(23, n) + n*qpow(23, n-1)) % mod - tot := qpow(26, n) - return ((tot-(a+b+c-ab-ac-bc+abc))%mod + mod) % mod + var dfs func(i, l, e, t int) int + dfs = func(i, l, e, t int) int { + if i == 0 { + if l == 1 && e == 2 && t == 1 { + return 1 + } + return 0 + } + if f[i][l][e][t] == -1 { + a := dfs(i-1, l, e, t) * 23 % mod + b := dfs(i-1, min(1, l+1), e, t) + c := dfs(i-1, l, min(2, e+1), t) + d := dfs(i-1, l, e, min(1, t+1)) + f[i][l][e][t] = (a + b + c + d) % mod + } + return f[i][l][e][t] + } + return dfs(n, 0, 0, 0) } \ No newline at end of file diff --git a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.java b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.java index f38e4381dffcf..a25585b5fe192 100644 --- a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.java +++ b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.java @@ -1,26 +1,23 @@ -class Solution { - private final int mod = (int) 1e9 + 7; - - public int stringCount(int n) { - long a = qpow(25, n); - long b = a; - long c = (qpow(25, n) + n * qpow(25, n - 1) % mod) % mod; - long ab = qpow(24, n); - long ac = (qpow(24, n) + n * qpow(24, n - 1) % mod) % mod; - long bc = ac; - long abc = (qpow(23, n) + n * qpow(23, n - 1) % mod) % mod; - long tot = qpow(26, n); - return (int) ((tot - (a + b + c - ab - ac - bc + abc)) % mod + mod) % mod; - } - - private long qpow(long a, int n) { - long ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return ans; - } +class Solution { + private final int mod = (int) 1e9 + 7; + private Long[][][][] f; + + public int stringCount(int n) { + f = new Long[n + 1][2][3][2]; + return (int) dfs(n, 0, 0, 0); + } + + private long dfs(int i, int l, int e, int t) { + if (i == 0) { + return l == 1 && e == 2 && t == 1 ? 1 : 0; + } + if (f[i][l][e][t] != null) { + return f[i][l][e][t]; + } + long a = dfs(i - 1, l, e, t) * 23 % mod; + long b = dfs(i - 1, Math.min(1, l + 1), e, t); + long c = dfs(i - 1, l, Math.min(2, e + 1), t); + long d = dfs(i - 1, l, e, Math.min(1, t + 1)); + return f[i][l][e][t] = (a + b + c + d) % mod; + } } \ No newline at end of file diff --git a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.py b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.py index 32ba3853603f6..e9e832d24ec19 100644 --- a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.py +++ b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.py @@ -1,10 +1,14 @@ -class Solution: - def stringCount(self, n: int) -> int: - mod = 10**9 + 7 - a = b = pow(25, n, mod) - c = pow(25, n, mod) + n * pow(25, n - 1, mod) - ab = pow(24, n, mod) - ac = bc = (pow(24, n, mod) + n * pow(24, n - 1, mod)) % mod - abc = (pow(23, n, mod) + n * pow(23, n - 1, mod)) % mod - tot = pow(26, n, mod) - return (tot - (a + b + c - ab - ac - bc + abc)) % mod +class Solution: + def stringCount(self, n: int) -> int: + @cache + def dfs(i: int, l: int, e: int, t: int) -> int: + if i == 0: + return int(l == 1 and e == 2 and t == 1) + a = dfs(i - 1, l, e, t) * 23 % mod + b = dfs(i - 1, min(1, l + 1), e, t) + c = dfs(i - 1, l, min(2, e + 1), t) + d = dfs(i - 1, l, e, min(1, t + 1)) + return (a + b + c + d) % mod + + mod = 10**9 + 7 + return dfs(n, 0, 0, 0) diff --git a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.ts b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.ts index 745655b6c5a77..b48dd7753ef81 100644 --- a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.ts +++ b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution.ts @@ -1,22 +1,22 @@ function stringCount(n: number): number { - const mod = BigInt(10 ** 9 + 7); - const qpow = (a: bigint, n: number): bigint => { - let ans = 1n; - for (; n; n >>>= 1) { - if (n & 1) { - ans = (ans * a) % mod; - } - a = (a * a) % mod; + const mod = 10 ** 9 + 7; + const f: number[][][][] = Array.from({ length: n + 1 }, () => + Array.from({ length: 2 }, () => + Array.from({ length: 3 }, () => Array.from({ length: 2 }, () => -1)), + ), + ); + const dfs = (i: number, l: number, e: number, t: number): number => { + if (i === 0) { + return l === 1 && e === 2 && t === 1 ? 1 : 0; } - return ans; + if (f[i][l][e][t] !== -1) { + return f[i][l][e][t]; + } + const a = (dfs(i - 1, l, e, t) * 23) % mod; + const b = dfs(i - 1, Math.min(1, l + 1), e, t); + const c = dfs(i - 1, l, Math.min(2, e + 1), t); + const d = dfs(i - 1, l, e, Math.min(1, t + 1)); + return (f[i][l][e][t] = (a + b + c + d) % mod); }; - const a = qpow(25n, n); - const b = a; - const c = (qpow(25n, n) + ((BigInt(n) * qpow(25n, n - 1)) % mod)) % mod; - const ab = qpow(24n, n); - const ac = (qpow(24n, n) + ((BigInt(n) * qpow(24n, n - 1)) % mod)) % mod; - const bc = ac; - const abc = (qpow(23n, n) + ((BigInt(n) * qpow(23n, n - 1)) % mod)) % mod; - const tot = qpow(26n, n); - return Number((((tot - (a + b + c - ab - ac - bc + abc)) % mod) + mod) % mod); + return dfs(n, 0, 0, 0); } diff --git a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution2.cpp b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution2.cpp new file mode 100644 index 0000000000000..54ff5be2347ce --- /dev/null +++ b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution2.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int stringCount(int n) { + const int mod = 1e9 + 7; + using ll = long long; + auto qpow = [&](ll a, int n) { + ll ans = 1; + for (; n; n >>= 1) { + if (n & 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return ans; + }; + ll a = qpow(25, n); + ll b = a; + ll c = (qpow(25, n) + n * qpow(25, n - 1) % mod) % mod; + ll ab = qpow(24, n); + ll ac = (qpow(24, n) + n * qpow(24, n - 1) % mod) % mod; + ll bc = ac; + ll abc = (qpow(23, n) + n * qpow(23, n - 1) % mod) % mod; + ll tot = qpow(26, n); + return ((tot - (a + b + c - ab - ac - bc + abc)) % mod + mod) % mod; + } +}; \ No newline at end of file diff --git a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution2.go b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution2.go new file mode 100644 index 0000000000000..efc876fbcea4d --- /dev/null +++ b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution2.go @@ -0,0 +1,22 @@ +func stringCount(n int) int { + const mod int = 1e9 + 7 + qpow := func(a, n int) int { + ans := 1 + for ; n > 0; n >>= 1 { + if n&1 == 1 { + ans = ans * a % mod + } + a = a * a % mod + } + return ans + } + a := qpow(25, n) + b := a + c := qpow(25, n) + n*qpow(25, n-1) + ab := qpow(24, n) + ac := (qpow(24, n) + n*qpow(24, n-1)) % mod + bc := ac + abc := (qpow(23, n) + n*qpow(23, n-1)) % mod + tot := qpow(26, n) + return ((tot-(a+b+c-ab-ac-bc+abc))%mod + mod) % mod +} \ No newline at end of file diff --git a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution2.java b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution2.java new file mode 100644 index 0000000000000..74051fe767ebb --- /dev/null +++ b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution2.java @@ -0,0 +1,26 @@ +class Solution { + private final int mod = (int) 1e9 + 7; + + public int stringCount(int n) { + long a = qpow(25, n); + long b = a; + long c = (qpow(25, n) + n * qpow(25, n - 1) % mod) % mod; + long ab = qpow(24, n); + long ac = (qpow(24, n) + n * qpow(24, n - 1) % mod) % mod; + long bc = ac; + long abc = (qpow(23, n) + n * qpow(23, n - 1) % mod) % mod; + long tot = qpow(26, n); + return (int) ((tot - (a + b + c - ab - ac - bc + abc)) % mod + mod) % mod; + } + + private long qpow(long a, int n) { + long ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution2.py b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution2.py new file mode 100644 index 0000000000000..131123434c365 --- /dev/null +++ b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def stringCount(self, n: int) -> int: + mod = 10**9 + 7 + a = b = pow(25, n, mod) + c = pow(25, n, mod) + n * pow(25, n - 1, mod) + ab = pow(24, n, mod) + ac = bc = (pow(24, n, mod) + n * pow(24, n - 1, mod)) % mod + abc = (pow(23, n, mod) + n * pow(23, n - 1, mod)) % mod + tot = pow(26, n, mod) + return (tot - (a + b + c - ab - ac - bc + abc)) % mod diff --git a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution2.ts b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution2.ts new file mode 100644 index 0000000000000..745655b6c5a77 --- /dev/null +++ b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution2.ts @@ -0,0 +1,22 @@ +function stringCount(n: number): number { + const mod = BigInt(10 ** 9 + 7); + const qpow = (a: bigint, n: number): bigint => { + let ans = 1n; + for (; n; n >>>= 1) { + if (n & 1) { + ans = (ans * a) % mod; + } + a = (a * a) % mod; + } + return ans; + }; + const a = qpow(25n, n); + const b = a; + const c = (qpow(25n, n) + ((BigInt(n) * qpow(25n, n - 1)) % mod)) % mod; + const ab = qpow(24n, n); + const ac = (qpow(24n, n) + ((BigInt(n) * qpow(24n, n - 1)) % mod)) % mod; + const bc = ac; + const abc = (qpow(23n, n) + ((BigInt(n) * qpow(23n, n - 1)) % mod)) % mod; + const tot = qpow(26n, n); + return Number((((tot - (a + b + c - ab - ac - bc + abc)) % mod) + mod) % mod); +} diff --git a/solution/2900-2999/2931.Maximum Spending After Buying Items/Solution.cpp b/solution/2900-2999/2931.Maximum Spending After Buying Items/Solution.cpp index 5d0ebf9ede711..a7f3af6c3b79a 100644 --- a/solution/2900-2999/2931.Maximum Spending After Buying Items/Solution.cpp +++ b/solution/2900-2999/2931.Maximum Spending After Buying Items/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - long long maxSpending(vector>& values) { - priority_queue, vector>, greater>> pq; - int m = values.size(), n = values[0].size(); - for (int i = 0; i < m; ++i) { - pq.emplace(values[i][n - 1], i, n - 1); - } - long long ans = 0; - for (int d = 1; pq.size(); ++d) { - auto [v, i, j] = pq.top(); - pq.pop(); - ans += 1LL * v * d; - if (j) { - pq.emplace(values[i][j - 1], i, j - 1); - } - } - return ans; - } +class Solution { +public: + long long maxSpending(vector>& values) { + priority_queue, vector>, greater>> pq; + int m = values.size(), n = values[0].size(); + for (int i = 0; i < m; ++i) { + pq.emplace(values[i][n - 1], i, n - 1); + } + long long ans = 0; + for (int d = 1; pq.size(); ++d) { + auto [v, i, j] = pq.top(); + pq.pop(); + ans += 1LL * v * d; + if (j) { + pq.emplace(values[i][j - 1], i, j - 1); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2931.Maximum Spending After Buying Items/Solution.java b/solution/2900-2999/2931.Maximum Spending After Buying Items/Solution.java index 5c710193e01c3..091b6d8cc14c8 100644 --- a/solution/2900-2999/2931.Maximum Spending After Buying Items/Solution.java +++ b/solution/2900-2999/2931.Maximum Spending After Buying Items/Solution.java @@ -1,19 +1,19 @@ -class Solution { - public long maxSpending(int[][] values) { - int m = values.length, n = values[0].length; - PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); - for (int i = 0; i < m; ++i) { - pq.offer(new int[] {values[i][n - 1], i, n - 1}); - } - long ans = 0; - for (int d = 1; !pq.isEmpty(); ++d) { - var p = pq.poll(); - int v = p[0], i = p[1], j = p[2]; - ans += (long) v * d; - if (j > 0) { - pq.offer(new int[] {values[i][j - 1], i, j - 1}); - } - } - return ans; - } +class Solution { + public long maxSpending(int[][] values) { + int m = values.length, n = values[0].length; + PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); + for (int i = 0; i < m; ++i) { + pq.offer(new int[] {values[i][n - 1], i, n - 1}); + } + long ans = 0; + for (int d = 1; !pq.isEmpty(); ++d) { + var p = pq.poll(); + int v = p[0], i = p[1], j = p[2]; + ans += (long) v * d; + if (j > 0) { + pq.offer(new int[] {values[i][j - 1], i, j - 1}); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2931.Maximum Spending After Buying Items/Solution.py b/solution/2900-2999/2931.Maximum Spending After Buying Items/Solution.py index 58f3c569ef8c0..847d3c2ab359a 100644 --- a/solution/2900-2999/2931.Maximum Spending After Buying Items/Solution.py +++ b/solution/2900-2999/2931.Maximum Spending After Buying Items/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def maxSpending(self, values: List[List[int]]) -> int: - n = len(values[0]) - pq = [(row[-1], i, n - 1) for i, row in enumerate(values)] - heapify(pq) - ans = d = 0 - while pq: - d += 1 - v, i, j = heappop(pq) - ans += v * d - if j: - heappush(pq, (values[i][j - 1], i, j - 1)) - return ans +class Solution: + def maxSpending(self, values: List[List[int]]) -> int: + n = len(values[0]) + pq = [(row[-1], i, n - 1) for i, row in enumerate(values)] + heapify(pq) + ans = d = 0 + while pq: + d += 1 + v, i, j = heappop(pq) + ans += v * d + if j: + heappush(pq, (values[i][j - 1], i, j - 1)) + return ans diff --git a/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.cpp b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.cpp index 14e2b0a7b8915..af1ce3424766d 100644 --- a/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.cpp +++ b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.cpp @@ -1,64 +1,14 @@ -class Trie { -public: - Trie* children[2]; - int cnt; - - Trie() - : cnt(0) { - children[0] = nullptr; - children[1] = nullptr; - } - - void insert(int x) { - Trie* node = this; - for (int i = 7; ~i; --i) { - int v = (x >> i) & 1; - if (node->children[v] == nullptr) { - node->children[v] = new Trie(); - } - node = node->children[v]; - ++node->cnt; - } - } - - int search(int x) { - Trie* node = this; - int ans = 0; - for (int i = 7; ~i; --i) { - int v = (x >> i) & 1; - if (node->children[v ^ 1] != nullptr && node->children[v ^ 1]->cnt > 0) { - ans |= 1 << i; - node = node->children[v ^ 1]; - } else { - node = node->children[v]; - } - } - return ans; - } - - void remove(int x) { - Trie* node = this; - for (int i = 7; ~i; --i) { - int v = (x >> i) & 1; - node = node->children[v]; - --node->cnt; - } - } -}; - -class Solution { -public: - int maximumStrongPairXor(vector& nums) { - sort(nums.begin(), nums.end()); - Trie* tree = new Trie(); - int ans = 0, i = 0; - for (int y : nums) { - tree->insert(y); - while (y > nums[i] * 2) { - tree->remove(nums[i++]); - } - ans = max(ans, tree->search(y)); - } - return ans; - } +class Solution { +public: + int maximumStrongPairXor(vector& nums) { + int ans = 0; + for (int x : nums) { + for (int y : nums) { + if (abs(x - y) <= min(x, y)) { + ans = max(ans, x ^ y); + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.go b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.go index 77fcaa2665535..e7a043197b3e5 100644 --- a/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.go +++ b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.go @@ -1,58 +1,17 @@ -type Trie struct { - children [2]*Trie - cnt int -} - -func newTrie() *Trie { - return &Trie{} -} - -func (t *Trie) insert(x int) { - node := t - for i := 7; i >= 0; i-- { - v := (x >> uint(i)) & 1 - if node.children[v] == nil { - node.children[v] = newTrie() - } - node = node.children[v] - node.cnt++ - } -} - -func (t *Trie) search(x int) int { - node := t - ans := 0 - for i := 7; i >= 0; i-- { - v := (x >> uint(i)) & 1 - if node.children[v^1] != nil && node.children[v^1].cnt > 0 { - ans |= 1 << uint(i) - node = node.children[v^1] - } else { - node = node.children[v] +func maximumStrongPairXor(nums []int) (ans int) { + for _, x := range nums { + for _, y := range nums { + if abs(x-y) <= min(x, y) { + ans = max(ans, x^y) + } } } - return ans + return } -func (t *Trie) remove(x int) { - node := t - for i := 7; i >= 0; i-- { - v := (x >> uint(i)) & 1 - node = node.children[v] - node.cnt-- - } -} - -func maximumStrongPairXor(nums []int) (ans int) { - sort.Ints(nums) - tree := newTrie() - i := 0 - for _, y := range nums { - tree.insert(y) - for ; y > nums[i]*2; i++ { - tree.remove(nums[i]) - } - ans = max(ans, tree.search(y)) +func abs(x int) int { + if x < 0 { + return -x } - return ans + return x } \ No newline at end of file diff --git a/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.java b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.java index 0be053f73af2d..0b23e5dee0420 100644 --- a/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.java +++ b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.java @@ -1,59 +1,13 @@ -class Trie { - private Trie[] children = new Trie[2]; - private int cnt = 0; - - public Trie() { - } - - public void insert(int x) { - Trie node = this; - for (int i = 7; i >= 0; --i) { - int v = x >> i & 1; - if (node.children[v] == null) { - node.children[v] = new Trie(); - } - node = node.children[v]; - ++node.cnt; - } - } - - public int search(int x) { - Trie node = this; - int ans = 0; - for (int i = 7; i >= 0; --i) { - int v = x >> i & 1; - if (node.children[v ^ 1] != null && node.children[v ^ 1].cnt > 0) { - ans |= 1 << i; - node = node.children[v ^ 1]; - } else { - node = node.children[v]; - } - } - return ans; - } - - public void remove(int x) { - Trie node = this; - for (int i = 7; i >= 0; --i) { - int v = x >> i & 1; - node = node.children[v]; - --node.cnt; - } - } -} - -class Solution { - public int maximumStrongPairXor(int[] nums) { - Arrays.sort(nums); - Trie tree = new Trie(); - int ans = 0, i = 0; - for (int y : nums) { - tree.insert(y); - while (y > nums[i] * 2) { - tree.remove(nums[i++]); - } - ans = Math.max(ans, tree.search(y)); - } - return ans; - } +class Solution { + public int maximumStrongPairXor(int[] nums) { + int ans = 0; + for (int x : nums) { + for (int y : nums) { + if (Math.abs(x - y) <= Math.min(x, y)) { + ans = Math.max(ans, x ^ y); + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.py b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.py index c5f241aef66e8..28a7b1c789a40 100644 --- a/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.py +++ b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.py @@ -1,48 +1,3 @@ -class Trie: - __slots__ = ("children", "cnt") - - def __init__(self): - self.children: List[Trie | None] = [None, None] - self.cnt = 0 - - def insert(self, x: int): - node = self - for i in range(7, -1, -1): - v = x >> i & 1 - if node.children[v] is None: - node.children[v] = Trie() - node = node.children[v] - node.cnt += 1 - - def search(self, x: int) -> int: - node = self - ans = 0 - for i in range(7, -1, -1): - v = x >> i & 1 - if node.children[v ^ 1] and node.children[v ^ 1].cnt: - ans |= 1 << i - node = node.children[v ^ 1] - else: - node = node.children[v] - return ans - - def remove(self, x: int): - node = self - for i in range(7, -1, -1): - v = x >> i & 1 - node = node.children[v] - node.cnt -= 1 - - -class Solution: - def maximumStrongPairXor(self, nums: List[int]) -> int: - nums.sort() - tree = Trie() - ans = i = 0 - for y in nums: - tree.insert(y) - while y > nums[i] * 2: - tree.remove(nums[i]) - i += 1 - ans = max(ans, tree.search(y)) - return ans +class Solution: + def maximumStrongPairXor(self, nums: List[int]) -> int: + return max(x ^ y for x in nums for y in nums if abs(x - y) <= min(x, y)) diff --git a/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.ts b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.ts index 299c21391f55f..b9713cc2e82f7 100644 --- a/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.ts +++ b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution.ts @@ -1,64 +1,11 @@ -class Trie { - children: (Trie | null)[]; - cnt: number; - - constructor() { - this.children = [null, null]; - this.cnt = 0; - } - - insert(x: number): void { - let node: Trie | null = this; - for (let i = 7; i >= 0; i--) { - const v = (x >> i) & 1; - if (node.children[v] === null) { - node.children[v] = new Trie(); - } - node = node.children[v] as Trie; - node.cnt++; - } - } - - search(x: number): number { - let node: Trie | null = this; - let ans = 0; - for (let i = 7; i >= 0; i--) { - const v = (x >> i) & 1; - if (node.children[v ^ 1] !== null && (node.children[v ^ 1] as Trie).cnt > 0) { - ans |= 1 << i; - node = node.children[v ^ 1] as Trie; - } else { - node = node.children[v] as Trie; - } - } - return ans; - } - - remove(x: number): void { - let node: Trie | null = this; - for (let i = 7; i >= 0; i--) { - const v = (x >> i) & 1; - node = node.children[v] as Trie; - node.cnt--; - } - } -} - function maximumStrongPairXor(nums: number[]): number { - nums.sort((a, b) => a - b); - const tree = new Trie(); let ans = 0; - let i = 0; - - for (const y of nums) { - tree.insert(y); - - while (y > nums[i] * 2) { - tree.remove(nums[i++]); + for (const x of nums) { + for (const y of nums) { + if (Math.abs(x - y) <= Math.min(x, y)) { + ans = Math.max(ans, x ^ y); + } } - - ans = Math.max(ans, tree.search(y)); } - return ans; } diff --git a/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution2.cpp b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution2.cpp new file mode 100644 index 0000000000000..76e536841f170 --- /dev/null +++ b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution2.cpp @@ -0,0 +1,64 @@ +class Trie { +public: + Trie* children[2]; + int cnt; + + Trie() + : cnt(0) { + children[0] = nullptr; + children[1] = nullptr; + } + + void insert(int x) { + Trie* node = this; + for (int i = 7; ~i; --i) { + int v = (x >> i) & 1; + if (node->children[v] == nullptr) { + node->children[v] = new Trie(); + } + node = node->children[v]; + ++node->cnt; + } + } + + int search(int x) { + Trie* node = this; + int ans = 0; + for (int i = 7; ~i; --i) { + int v = (x >> i) & 1; + if (node->children[v ^ 1] != nullptr && node->children[v ^ 1]->cnt > 0) { + ans |= 1 << i; + node = node->children[v ^ 1]; + } else { + node = node->children[v]; + } + } + return ans; + } + + void remove(int x) { + Trie* node = this; + for (int i = 7; ~i; --i) { + int v = (x >> i) & 1; + node = node->children[v]; + --node->cnt; + } + } +}; + +class Solution { +public: + int maximumStrongPairXor(vector& nums) { + sort(nums.begin(), nums.end()); + Trie* tree = new Trie(); + int ans = 0, i = 0; + for (int y : nums) { + tree->insert(y); + while (y > nums[i] * 2) { + tree->remove(nums[i++]); + } + ans = max(ans, tree->search(y)); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution2.go b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution2.go new file mode 100644 index 0000000000000..77fcaa2665535 --- /dev/null +++ b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution2.go @@ -0,0 +1,58 @@ +type Trie struct { + children [2]*Trie + cnt int +} + +func newTrie() *Trie { + return &Trie{} +} + +func (t *Trie) insert(x int) { + node := t + for i := 7; i >= 0; i-- { + v := (x >> uint(i)) & 1 + if node.children[v] == nil { + node.children[v] = newTrie() + } + node = node.children[v] + node.cnt++ + } +} + +func (t *Trie) search(x int) int { + node := t + ans := 0 + for i := 7; i >= 0; i-- { + v := (x >> uint(i)) & 1 + if node.children[v^1] != nil && node.children[v^1].cnt > 0 { + ans |= 1 << uint(i) + node = node.children[v^1] + } else { + node = node.children[v] + } + } + return ans +} + +func (t *Trie) remove(x int) { + node := t + for i := 7; i >= 0; i-- { + v := (x >> uint(i)) & 1 + node = node.children[v] + node.cnt-- + } +} + +func maximumStrongPairXor(nums []int) (ans int) { + sort.Ints(nums) + tree := newTrie() + i := 0 + for _, y := range nums { + tree.insert(y) + for ; y > nums[i]*2; i++ { + tree.remove(nums[i]) + } + ans = max(ans, tree.search(y)) + } + return ans +} \ No newline at end of file diff --git a/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution2.java b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution2.java new file mode 100644 index 0000000000000..01e024e00de0a --- /dev/null +++ b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution2.java @@ -0,0 +1,59 @@ +class Trie { + private Trie[] children = new Trie[2]; + private int cnt = 0; + + public Trie() { + } + + public void insert(int x) { + Trie node = this; + for (int i = 7; i >= 0; --i) { + int v = x >> i & 1; + if (node.children[v] == null) { + node.children[v] = new Trie(); + } + node = node.children[v]; + ++node.cnt; + } + } + + public int search(int x) { + Trie node = this; + int ans = 0; + for (int i = 7; i >= 0; --i) { + int v = x >> i & 1; + if (node.children[v ^ 1] != null && node.children[v ^ 1].cnt > 0) { + ans |= 1 << i; + node = node.children[v ^ 1]; + } else { + node = node.children[v]; + } + } + return ans; + } + + public void remove(int x) { + Trie node = this; + for (int i = 7; i >= 0; --i) { + int v = x >> i & 1; + node = node.children[v]; + --node.cnt; + } + } +} + +class Solution { + public int maximumStrongPairXor(int[] nums) { + Arrays.sort(nums); + Trie tree = new Trie(); + int ans = 0, i = 0; + for (int y : nums) { + tree.insert(y); + while (y > nums[i] * 2) { + tree.remove(nums[i++]); + } + ans = Math.max(ans, tree.search(y)); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution2.py b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution2.py new file mode 100644 index 0000000000000..e2e2d1a39082e --- /dev/null +++ b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution2.py @@ -0,0 +1,48 @@ +class Trie: + __slots__ = ("children", "cnt") + + def __init__(self): + self.children: List[Trie | None] = [None, None] + self.cnt = 0 + + def insert(self, x: int): + node = self + for i in range(7, -1, -1): + v = x >> i & 1 + if node.children[v] is None: + node.children[v] = Trie() + node = node.children[v] + node.cnt += 1 + + def search(self, x: int) -> int: + node = self + ans = 0 + for i in range(7, -1, -1): + v = x >> i & 1 + if node.children[v ^ 1] and node.children[v ^ 1].cnt: + ans |= 1 << i + node = node.children[v ^ 1] + else: + node = node.children[v] + return ans + + def remove(self, x: int): + node = self + for i in range(7, -1, -1): + v = x >> i & 1 + node = node.children[v] + node.cnt -= 1 + + +class Solution: + def maximumStrongPairXor(self, nums: List[int]) -> int: + nums.sort() + tree = Trie() + ans = i = 0 + for y in nums: + tree.insert(y) + while y > nums[i] * 2: + tree.remove(nums[i]) + i += 1 + ans = max(ans, tree.search(y)) + return ans diff --git a/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution2.ts b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution2.ts new file mode 100644 index 0000000000000..299c21391f55f --- /dev/null +++ b/solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution2.ts @@ -0,0 +1,64 @@ +class Trie { + children: (Trie | null)[]; + cnt: number; + + constructor() { + this.children = [null, null]; + this.cnt = 0; + } + + insert(x: number): void { + let node: Trie | null = this; + for (let i = 7; i >= 0; i--) { + const v = (x >> i) & 1; + if (node.children[v] === null) { + node.children[v] = new Trie(); + } + node = node.children[v] as Trie; + node.cnt++; + } + } + + search(x: number): number { + let node: Trie | null = this; + let ans = 0; + for (let i = 7; i >= 0; i--) { + const v = (x >> i) & 1; + if (node.children[v ^ 1] !== null && (node.children[v ^ 1] as Trie).cnt > 0) { + ans |= 1 << i; + node = node.children[v ^ 1] as Trie; + } else { + node = node.children[v] as Trie; + } + } + return ans; + } + + remove(x: number): void { + let node: Trie | null = this; + for (let i = 7; i >= 0; i--) { + const v = (x >> i) & 1; + node = node.children[v] as Trie; + node.cnt--; + } + } +} + +function maximumStrongPairXor(nums: number[]): number { + nums.sort((a, b) => a - b); + const tree = new Trie(); + let ans = 0; + let i = 0; + + for (const y of nums) { + tree.insert(y); + + while (y > nums[i] * 2) { + tree.remove(nums[i++]); + } + + ans = Math.max(ans, tree.search(y)); + } + + return ans; +} diff --git a/solution/2900-2999/2933.High-Access Employees/Solution.cpp b/solution/2900-2999/2933.High-Access Employees/Solution.cpp index bc6280bd6bf11..14ef58af314aa 100644 --- a/solution/2900-2999/2933.High-Access Employees/Solution.cpp +++ b/solution/2900-2999/2933.High-Access Employees/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - vector findHighAccessEmployees(vector>& access_times) { - unordered_map> d; - for (auto& e : access_times) { - auto name = e[0]; - auto s = e[1]; - int t = stoi(s.substr(0, 2)) * 60 + stoi(s.substr(2, 2)); - d[name].emplace_back(t); - } - vector ans; - for (auto& [name, ts] : d) { - sort(ts.begin(), ts.end()); - for (int i = 2; i < ts.size(); ++i) { - if (ts[i] - ts[i - 2] < 60) { - ans.emplace_back(name); - break; - } - } - } - return ans; - } +class Solution { +public: + vector findHighAccessEmployees(vector>& access_times) { + unordered_map> d; + for (auto& e : access_times) { + auto name = e[0]; + auto s = e[1]; + int t = stoi(s.substr(0, 2)) * 60 + stoi(s.substr(2, 2)); + d[name].emplace_back(t); + } + vector ans; + for (auto& [name, ts] : d) { + sort(ts.begin(), ts.end()); + for (int i = 2; i < ts.size(); ++i) { + if (ts[i] - ts[i - 2] < 60) { + ans.emplace_back(name); + break; + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2933.High-Access Employees/Solution.java b/solution/2900-2999/2933.High-Access Employees/Solution.java index c1e6a906db718..d5e8111a3848f 100644 --- a/solution/2900-2999/2933.High-Access Employees/Solution.java +++ b/solution/2900-2999/2933.High-Access Employees/Solution.java @@ -1,23 +1,23 @@ -class Solution { - public List findHighAccessEmployees(List> access_times) { - Map> d = new HashMap<>(); - for (var e : access_times) { - String name = e.get(0), s = e.get(1); - int t = Integer.valueOf(s.substring(0, 2)) * 60 + Integer.valueOf(s.substring(2)); - d.computeIfAbsent(name, k -> new ArrayList<>()).add(t); - } - List ans = new ArrayList<>(); - for (var e : d.entrySet()) { - String name = e.getKey(); - var ts = e.getValue(); - Collections.sort(ts); - for (int i = 2; i < ts.size(); ++i) { - if (ts.get(i) - ts.get(i - 2) < 60) { - ans.add(name); - break; - } - } - } - return ans; - } +class Solution { + public List findHighAccessEmployees(List> access_times) { + Map> d = new HashMap<>(); + for (var e : access_times) { + String name = e.get(0), s = e.get(1); + int t = Integer.valueOf(s.substring(0, 2)) * 60 + Integer.valueOf(s.substring(2)); + d.computeIfAbsent(name, k -> new ArrayList<>()).add(t); + } + List ans = new ArrayList<>(); + for (var e : d.entrySet()) { + String name = e.getKey(); + var ts = e.getValue(); + Collections.sort(ts); + for (int i = 2; i < ts.size(); ++i) { + if (ts.get(i) - ts.get(i - 2) < 60) { + ans.add(name); + break; + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2933.High-Access Employees/Solution.py b/solution/2900-2999/2933.High-Access Employees/Solution.py index 969a75374b0da..4499e153d5d12 100644 --- a/solution/2900-2999/2933.High-Access Employees/Solution.py +++ b/solution/2900-2999/2933.High-Access Employees/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def findHighAccessEmployees(self, access_times: List[List[str]]) -> List[str]: - d = defaultdict(list) - for name, t in access_times: - d[name].append(int(t[:2]) * 60 + int(t[2:])) - ans = [] - for name, ts in d.items(): - ts.sort() - if any(ts[i] - ts[i - 2] < 60 for i in range(2, len(ts))): - ans.append(name) - return ans +class Solution: + def findHighAccessEmployees(self, access_times: List[List[str]]) -> List[str]: + d = defaultdict(list) + for name, t in access_times: + d[name].append(int(t[:2]) * 60 + int(t[2:])) + ans = [] + for name, ts in d.items(): + ts.sort() + if any(ts[i] - ts[i - 2] < 60 for i in range(2, len(ts))): + ans.append(name) + return ans diff --git a/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/Solution.cpp b/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/Solution.cpp index 7ed2b7efdbb2d..66fd1606a36b3 100644 --- a/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/Solution.cpp +++ b/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/Solution.cpp @@ -1,22 +1,22 @@ -class Solution { -public: - int minOperations(vector& nums1, vector& nums2) { - int n = nums1.size(); - auto f = [&](int x, int y) { - int cnt = 0; - for (int i = 0; i < n - 1; ++i) { - if (nums1[i] <= x && nums2[i] <= y) { - continue; - } - if (!(nums1[i] <= y && nums2[i] <= x)) { - return -1; - } - ++cnt; - } - return cnt; - }; - int a = f(nums1.back(), nums2.back()); - int b = f(nums2.back(), nums1.back()); - return a + b == -2 ? -1 : min(a, b + 1); - } +class Solution { +public: + int minOperations(vector& nums1, vector& nums2) { + int n = nums1.size(); + auto f = [&](int x, int y) { + int cnt = 0; + for (int i = 0; i < n - 1; ++i) { + if (nums1[i] <= x && nums2[i] <= y) { + continue; + } + if (!(nums1[i] <= y && nums2[i] <= x)) { + return -1; + } + ++cnt; + } + return cnt; + }; + int a = f(nums1.back(), nums2.back()); + int b = f(nums2.back(), nums1.back()); + return a + b == -2 ? -1 : min(a, b + 1); + } }; \ No newline at end of file diff --git a/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/Solution.java b/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/Solution.java index 03f1e03f04a68..2f37b29c70b14 100644 --- a/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/Solution.java +++ b/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/Solution.java @@ -1,24 +1,24 @@ -class Solution { - private int n; - - public int minOperations(int[] nums1, int[] nums2) { - n = nums1.length; - int a = f(nums1, nums2, nums1[n - 1], nums2[n - 1]); - int b = f(nums1, nums2, nums2[n - 1], nums1[n - 1]); - return a + b == -2 ? -1 : Math.min(a, b + 1); - } - - private int f(int[] nums1, int[] nums2, int x, int y) { - int cnt = 0; - for (int i = 0; i < n - 1; ++i) { - if (nums1[i] <= x && nums2[i] <= y) { - continue; - } - if (!(nums1[i] <= y && nums2[i] <= x)) { - return -1; - } - ++cnt; - } - return cnt; - } +class Solution { + private int n; + + public int minOperations(int[] nums1, int[] nums2) { + n = nums1.length; + int a = f(nums1, nums2, nums1[n - 1], nums2[n - 1]); + int b = f(nums1, nums2, nums2[n - 1], nums1[n - 1]); + return a + b == -2 ? -1 : Math.min(a, b + 1); + } + + private int f(int[] nums1, int[] nums2, int x, int y) { + int cnt = 0; + for (int i = 0; i < n - 1; ++i) { + if (nums1[i] <= x && nums2[i] <= y) { + continue; + } + if (!(nums1[i] <= y && nums2[i] <= x)) { + return -1; + } + ++cnt; + } + return cnt; + } } \ No newline at end of file diff --git a/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/Solution.py b/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/Solution.py index bbf54bbcc9be4..3a6b897515f25 100644 --- a/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/Solution.py +++ b/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def minOperations(self, nums1: List[int], nums2: List[int]) -> int: - def f(x: int, y: int) -> int: - cnt = 0 - for a, b in zip(nums1[:-1], nums2[:-1]): - if a <= x and b <= y: - continue - if not (a <= y and b <= x): - return -1 - cnt += 1 - return cnt - - a, b = f(nums1[-1], nums2[-1]), f(nums2[-1], nums1[-1]) - return -1 if a + b == -2 else min(a, b + 1) +class Solution: + def minOperations(self, nums1: List[int], nums2: List[int]) -> int: + def f(x: int, y: int) -> int: + cnt = 0 + for a, b in zip(nums1[:-1], nums2[:-1]): + if a <= x and b <= y: + continue + if not (a <= y and b <= x): + return -1 + cnt += 1 + return cnt + + a, b = f(nums1[-1], nums2[-1]), f(nums2[-1], nums1[-1]) + return -1 if a + b == -2 else min(a, b + 1) diff --git a/solution/2900-2999/2935.Maximum Strong Pair XOR II/Solution.cpp b/solution/2900-2999/2935.Maximum Strong Pair XOR II/Solution.cpp index b3137cd4cf273..37bdae4a66b97 100644 --- a/solution/2900-2999/2935.Maximum Strong Pair XOR II/Solution.cpp +++ b/solution/2900-2999/2935.Maximum Strong Pair XOR II/Solution.cpp @@ -1,64 +1,64 @@ -class Trie { -public: - Trie* children[2]; - int cnt; - - Trie() - : cnt(0) { - children[0] = nullptr; - children[1] = nullptr; - } - - void insert(int x) { - Trie* node = this; - for (int i = 20; ~i; --i) { - int v = (x >> i) & 1; - if (node->children[v] == nullptr) { - node->children[v] = new Trie(); - } - node = node->children[v]; - ++node->cnt; - } - } - - int search(int x) { - Trie* node = this; - int ans = 0; - for (int i = 20; ~i; --i) { - int v = (x >> i) & 1; - if (node->children[v ^ 1] != nullptr && node->children[v ^ 1]->cnt > 0) { - ans |= 1 << i; - node = node->children[v ^ 1]; - } else { - node = node->children[v]; - } - } - return ans; - } - - void remove(int x) { - Trie* node = this; - for (int i = 20; ~i; --i) { - int v = (x >> i) & 1; - node = node->children[v]; - --node->cnt; - } - } -}; - -class Solution { -public: - int maximumStrongPairXor(vector& nums) { - sort(nums.begin(), nums.end()); - Trie* tree = new Trie(); - int ans = 0, i = 0; - for (int y : nums) { - tree->insert(y); - while (y > nums[i] * 2) { - tree->remove(nums[i++]); - } - ans = max(ans, tree->search(y)); - } - return ans; - } +class Trie { +public: + Trie* children[2]; + int cnt; + + Trie() + : cnt(0) { + children[0] = nullptr; + children[1] = nullptr; + } + + void insert(int x) { + Trie* node = this; + for (int i = 20; ~i; --i) { + int v = (x >> i) & 1; + if (node->children[v] == nullptr) { + node->children[v] = new Trie(); + } + node = node->children[v]; + ++node->cnt; + } + } + + int search(int x) { + Trie* node = this; + int ans = 0; + for (int i = 20; ~i; --i) { + int v = (x >> i) & 1; + if (node->children[v ^ 1] != nullptr && node->children[v ^ 1]->cnt > 0) { + ans |= 1 << i; + node = node->children[v ^ 1]; + } else { + node = node->children[v]; + } + } + return ans; + } + + void remove(int x) { + Trie* node = this; + for (int i = 20; ~i; --i) { + int v = (x >> i) & 1; + node = node->children[v]; + --node->cnt; + } + } +}; + +class Solution { +public: + int maximumStrongPairXor(vector& nums) { + sort(nums.begin(), nums.end()); + Trie* tree = new Trie(); + int ans = 0, i = 0; + for (int y : nums) { + tree->insert(y); + while (y > nums[i] * 2) { + tree->remove(nums[i++]); + } + ans = max(ans, tree->search(y)); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2935.Maximum Strong Pair XOR II/Solution.java b/solution/2900-2999/2935.Maximum Strong Pair XOR II/Solution.java index 2680593e9012d..5aa69f5060a0b 100644 --- a/solution/2900-2999/2935.Maximum Strong Pair XOR II/Solution.java +++ b/solution/2900-2999/2935.Maximum Strong Pair XOR II/Solution.java @@ -1,59 +1,59 @@ -class Trie { - private Trie[] children = new Trie[2]; - private int cnt = 0; - - public Trie() { - } - - public void insert(int x) { - Trie node = this; - for (int i = 20; i >= 0; --i) { - int v = x >> i & 1; - if (node.children[v] == null) { - node.children[v] = new Trie(); - } - node = node.children[v]; - ++node.cnt; - } - } - - public int search(int x) { - Trie node = this; - int ans = 0; - for (int i = 20; i >= 0; --i) { - int v = x >> i & 1; - if (node.children[v ^ 1] != null && node.children[v ^ 1].cnt > 0) { - ans |= 1 << i; - node = node.children[v ^ 1]; - } else { - node = node.children[v]; - } - } - return ans; - } - - public void remove(int x) { - Trie node = this; - for (int i = 20; i >= 0; --i) { - int v = x >> i & 1; - node = node.children[v]; - --node.cnt; - } - } -} - -class Solution { - public int maximumStrongPairXor(int[] nums) { - Arrays.sort(nums); - Trie tree = new Trie(); - int ans = 0, i = 0; - for (int y : nums) { - tree.insert(y); - while (y > nums[i] * 2) { - tree.remove(nums[i++]); - } - ans = Math.max(ans, tree.search(y)); - } - return ans; - } +class Trie { + private Trie[] children = new Trie[2]; + private int cnt = 0; + + public Trie() { + } + + public void insert(int x) { + Trie node = this; + for (int i = 20; i >= 0; --i) { + int v = x >> i & 1; + if (node.children[v] == null) { + node.children[v] = new Trie(); + } + node = node.children[v]; + ++node.cnt; + } + } + + public int search(int x) { + Trie node = this; + int ans = 0; + for (int i = 20; i >= 0; --i) { + int v = x >> i & 1; + if (node.children[v ^ 1] != null && node.children[v ^ 1].cnt > 0) { + ans |= 1 << i; + node = node.children[v ^ 1]; + } else { + node = node.children[v]; + } + } + return ans; + } + + public void remove(int x) { + Trie node = this; + for (int i = 20; i >= 0; --i) { + int v = x >> i & 1; + node = node.children[v]; + --node.cnt; + } + } +} + +class Solution { + public int maximumStrongPairXor(int[] nums) { + Arrays.sort(nums); + Trie tree = new Trie(); + int ans = 0, i = 0; + for (int y : nums) { + tree.insert(y); + while (y > nums[i] * 2) { + tree.remove(nums[i++]); + } + ans = Math.max(ans, tree.search(y)); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2935.Maximum Strong Pair XOR II/Solution.py b/solution/2900-2999/2935.Maximum Strong Pair XOR II/Solution.py index 6a855332f2be8..205b8ef3bb314 100644 --- a/solution/2900-2999/2935.Maximum Strong Pair XOR II/Solution.py +++ b/solution/2900-2999/2935.Maximum Strong Pair XOR II/Solution.py @@ -1,48 +1,48 @@ -class Trie: - __slots__ = ("children", "cnt") - - def __init__(self): - self.children: List[Trie | None] = [None, None] - self.cnt = 0 - - def insert(self, x: int): - node = self - for i in range(20, -1, -1): - v = x >> i & 1 - if node.children[v] is None: - node.children[v] = Trie() - node = node.children[v] - node.cnt += 1 - - def search(self, x: int) -> int: - node = self - ans = 0 - for i in range(20, -1, -1): - v = x >> i & 1 - if node.children[v ^ 1] and node.children[v ^ 1].cnt: - ans |= 1 << i - node = node.children[v ^ 1] - else: - node = node.children[v] - return ans - - def remove(self, x: int): - node = self - for i in range(20, -1, -1): - v = x >> i & 1 - node = node.children[v] - node.cnt -= 1 - - -class Solution: - def maximumStrongPairXor(self, nums: List[int]) -> int: - nums.sort() - tree = Trie() - ans = i = 0 - for y in nums: - tree.insert(y) - while y > nums[i] * 2: - tree.remove(nums[i]) - i += 1 - ans = max(ans, tree.search(y)) - return ans +class Trie: + __slots__ = ("children", "cnt") + + def __init__(self): + self.children: List[Trie | None] = [None, None] + self.cnt = 0 + + def insert(self, x: int): + node = self + for i in range(20, -1, -1): + v = x >> i & 1 + if node.children[v] is None: + node.children[v] = Trie() + node = node.children[v] + node.cnt += 1 + + def search(self, x: int) -> int: + node = self + ans = 0 + for i in range(20, -1, -1): + v = x >> i & 1 + if node.children[v ^ 1] and node.children[v ^ 1].cnt: + ans |= 1 << i + node = node.children[v ^ 1] + else: + node = node.children[v] + return ans + + def remove(self, x: int): + node = self + for i in range(20, -1, -1): + v = x >> i & 1 + node = node.children[v] + node.cnt -= 1 + + +class Solution: + def maximumStrongPairXor(self, nums: List[int]) -> int: + nums.sort() + tree = Trie() + ans = i = 0 + for y in nums: + tree.insert(y) + while y > nums[i] * 2: + tree.remove(nums[i]) + i += 1 + ans = max(ans, tree.search(y)) + return ans diff --git a/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution.cpp b/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution.cpp index cc55273b462dd..07ce98ab6841a 100644 --- a/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution.cpp +++ b/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution.cpp @@ -1,34 +1,34 @@ -/** - * Definition for BigArray. - * class BigArray { - * public: - * BigArray(vector elements); - * int at(long long index); - * long long size(); - * }; - */ -class Solution { -public: - int countBlocks(BigArray* nums) { - int ans = 0; - using ll = long long; - ll n = nums->size(); - auto search = [&](ll l) { - ll r = n; - int x = nums->at(l); - while (l < r) { - ll mid = (l + r) >> 1; - if (nums->at(mid) != x) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - }; - for (long long i = 0; i < n; ++ans) { - i = search(i); - } - return ans; - } +/** + * Definition for BigArray. + * class BigArray { + * public: + * BigArray(vector elements); + * int at(long long index); + * long long size(); + * }; + */ +class Solution { +public: + int countBlocks(BigArray* nums) { + int ans = 0; + using ll = long long; + ll n = nums->size(); + auto search = [&](ll l) { + ll r = n; + int x = nums->at(l); + while (l < r) { + ll mid = (l + r) >> 1; + if (nums->at(mid) != x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + for (long long i = 0; i < n; ++ans) { + i = search(i); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution.java b/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution.java index 397989c40257f..900e3ab650c16 100644 --- a/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution.java +++ b/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution.java @@ -1,31 +1,31 @@ -/** - * Definition for BigArray. - * class BigArray { - * public BigArray(int[] elements); - * public int at(long index); - * public long size(); - * } - */ -class Solution { - public int countBlocks(BigArray nums) { - int ans = 0; - for (long i = 0, n = nums.size(); i < n; ++ans) { - i = search(nums, i, n); - } - return ans; - } - - private long search(BigArray nums, long l, long n) { - long r = n; - int x = nums.at(l); - while (l < r) { - long mid = (l + r) >> 1; - if (nums.at(mid) != x) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } +/** + * Definition for BigArray. + * class BigArray { + * public BigArray(int[] elements); + * public int at(long index); + * public long size(); + * } + */ +class Solution { + public int countBlocks(BigArray nums) { + int ans = 0; + for (long i = 0, n = nums.size(); i < n; ++ans) { + i = search(nums, i, n); + } + return ans; + } + + private long search(BigArray nums, long l, long n) { + long r = n; + int x = nums.at(l); + while (l < r) { + long mid = (l + r) >> 1; + if (nums.at(mid) != x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } } \ No newline at end of file diff --git a/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution.py b/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution.py index 01f1576e6cc8f..0da4075e0e245 100644 --- a/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution.py +++ b/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution.py @@ -1,18 +1,18 @@ -# Definition for BigArray. -# class BigArray: -# def at(self, index: long) -> int: -# pass -# def size(self) -> long: -# pass -class Solution(object): - def countBlocks(self, nums: Optional["BigArray"]) -> int: - i, n = 0, nums.size() - ans = 0 - while i < n: - ans += 1 - x = nums.at(i) - if i + 1 < n and nums.at(i + 1) != x: - i += 1 - else: - i += bisect_left(range(i, n), True, key=lambda j: nums.at(j) != x) - return ans +# Definition for BigArray. +# class BigArray: +# def at(self, index: long) -> int: +# pass +# def size(self) -> long: +# pass +class Solution(object): + def countBlocks(self, nums: Optional["BigArray"]) -> int: + i, n = 0, nums.size() + ans = 0 + while i < n: + ans += 1 + x = nums.at(i) + if i + 1 < n and nums.at(i + 1) != x: + i += 1 + else: + i += bisect_left(range(i, n), True, key=lambda j: nums.at(j) != x) + return ans diff --git a/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution2.cpp b/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution2.cpp new file mode 100644 index 0000000000000..2e0e078671117 --- /dev/null +++ b/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution2.cpp @@ -0,0 +1,25 @@ +/** + * Definition for BigArray. + * class BigArray { + * public: + * BigArray(vector elements); + * int at(long long index); + * long long size(); + * }; + */ +class Solution { +public: + int countBlocks(BigArray* nums) { + using ll = long long; + function f = [&](ll l, ll r) { + if (nums->at(l) == nums->at(r)) { + return 1; + } + ll mid = (l + r) >> 1; + int a = f(l, mid); + int b = f(mid + 1, r); + return a + b - (nums->at(mid) == nums->at(mid + 1)); + }; + return f(0, nums->size() - 1); + } +}; \ No newline at end of file diff --git a/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution2.java b/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution2.java new file mode 100644 index 0000000000000..bec793916fabc --- /dev/null +++ b/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution2.java @@ -0,0 +1,23 @@ +/** + * Definition for BigArray. + * class BigArray { + * public BigArray(int[] elements); + * public int at(long index); + * public long size(); + * } + */ +class Solution { + public int countBlocks(BigArray nums) { + return f(nums, 0, nums.size() - 1); + } + + private int f(BigArray nums, long l, long r) { + if (nums.at(l) == nums.at(r)) { + return 1; + } + long mid = (l + r) >> 1; + int a = f(nums, l, mid); + int b = f(nums, mid + 1, r); + return a + b - (nums.at(mid) == nums.at(mid + 1) ? 1 : 0); + } +} \ No newline at end of file diff --git a/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution2.ts b/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution2.ts new file mode 100644 index 0000000000000..81b1ec0d3d8ab --- /dev/null +++ b/solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution2.ts @@ -0,0 +1,20 @@ +/** + * Definition for BigArray. + * class BigArray { + * constructor(elements: number[]); + * public at(index: number): number; + * public size(): number; + * } + */ +function countBlocks(nums: BigArray | null): number { + const f = (l: number, r: number): number => { + if (nums.at(l) === nums.at(r)) { + return 1; + } + const mid = l + Math.floor((r - l) / 2); + const a = f(l, mid); + const b = f(mid + 1, r); + return a + b - (nums.at(mid) === nums.at(mid + 1) ? 1 : 0); + }; + return f(0, nums.size() - 1); +} diff --git a/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/Solution.cpp b/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/Solution.cpp index b6f6c20a23887..eb8500d132462 100644 --- a/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/Solution.cpp +++ b/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/Solution.cpp @@ -1,30 +1,30 @@ -class Solution { -public: - long long maxGcdSum(vector& nums, int k) { - int n = nums.size(); - long long s[n + 1]; - s[0] = 0; - for (int i = 1; i <= n; ++i) { - s[i] = s[i - 1] + nums[i - 1]; - } - vector> f; - long long ans = 0; - for (int i = 0; i < n; ++i) { - vector> g; - for (auto [j, x] : f) { - int y = gcd(x, nums[i]); - if (g.empt() || g.back().second != y) { - g.emplace_back(j, y); - } - } - f = move(g); - f.emplace_back(i, nums[i]); - for (auto [j, x] : f) { - if (i - j + 1 >= k) { - ans = max(ans, (s[i + 1] - s[j]) * x); - } - } - } - return ans; - } +class Solution { +public: + long long maxGcdSum(vector& nums, int k) { + int n = nums.size(); + long long s[n + 1]; + s[0] = 0; + for (int i = 1; i <= n; ++i) { + s[i] = s[i - 1] + nums[i - 1]; + } + vector> f; + long long ans = 0; + for (int i = 0; i < n; ++i) { + vector> g; + for (auto [j, x] : f) { + int y = gcd(x, nums[i]); + if (g.empt() || g.back().second != y) { + g.emplace_back(j, y); + } + } + f = move(g); + f.emplace_back(i, nums[i]); + for (auto [j, x] : f) { + if (i - j + 1 >= k) { + ans = max(ans, (s[i + 1] - s[j]) * x); + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/Solution.java b/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/Solution.java index d0336be5518a5..3422a34f110a7 100644 --- a/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/Solution.java +++ b/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/Solution.java @@ -1,34 +1,34 @@ -class Solution { - public long maxGcdSum(int[] nums, int k) { - int n = nums.length; - long[] s = new long[n + 1]; - for (int i = 1; i <= n; ++i) { - s[i] = s[i - 1] + nums[i - 1]; - } - List f = new ArrayList<>(); - long ans = 0; - for (int i = 0; i < n; ++i) { - List g = new ArrayList<>(); - for (var e : f) { - int j = e[0], x = e[1]; - int y = gcd(x, nums[i]); - if (g.isEmpty() || g.get(g.size() - 1)[1] != y) { - g.add(new int[] {j, y}); - } - } - f = g; - f.add(new int[] {i, nums[i]}); - for (var e : f) { - int j = e[0], x = e[1]; - if (i - j + 1 >= k) { - ans = Math.max(ans, (s[i + 1] - s[j]) * x); - } - } - } - return ans; - } - - private int gcd(int a, int b) { - return b == 0 ? a : gcd(b, a % b); - } +class Solution { + public long maxGcdSum(int[] nums, int k) { + int n = nums.length; + long[] s = new long[n + 1]; + for (int i = 1; i <= n; ++i) { + s[i] = s[i - 1] + nums[i - 1]; + } + List f = new ArrayList<>(); + long ans = 0; + for (int i = 0; i < n; ++i) { + List g = new ArrayList<>(); + for (var e : f) { + int j = e[0], x = e[1]; + int y = gcd(x, nums[i]); + if (g.isEmpty() || g.get(g.size() - 1)[1] != y) { + g.add(new int[] {j, y}); + } + } + f = g; + f.add(new int[] {i, nums[i]}); + for (var e : f) { + int j = e[0], x = e[1]; + if (i - j + 1 >= k) { + ans = Math.max(ans, (s[i + 1] - s[j]) * x); + } + } + } + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } } \ No newline at end of file diff --git a/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/Solution.py b/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/Solution.py index decb594525126..45e542623e35d 100644 --- a/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/Solution.py +++ b/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/Solution.py @@ -1,17 +1,17 @@ -class Solution: - def maxGcdSum(self, nums: List[int], k: int) -> int: - s = list(accumulate(nums, initial=0)) - f = [] - ans = 0 - for i, v in enumerate(nums): - g = [] - for j, x in f: - y = gcd(x, v) - if not g or g[-1][1] != y: - g.append((j, y)) - f = g - f.append((i, v)) - for j, x in f: - if i - j + 1 >= k: - ans = max(ans, (s[i + 1] - s[j]) * x) - return ans +class Solution: + def maxGcdSum(self, nums: List[int], k: int) -> int: + s = list(accumulate(nums, initial=0)) + f = [] + ans = 0 + for i, v in enumerate(nums): + g = [] + for j, x in f: + y = gcd(x, v) + if not g or g[-1][1] != y: + g.append((j, y)) + f = g + f.append((i, v)) + for j, x in f: + if i - j + 1 >= k: + ans = max(ans, (s[i + 1] - s[j]) * x) + return ans diff --git a/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/Solution2.ts b/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/Solution2.ts new file mode 100644 index 0000000000000..4ffd30854c208 --- /dev/null +++ b/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/Solution2.ts @@ -0,0 +1,33 @@ +function maxGcdSum(nums: number[], k: number): number { + const n: number = nums.length; + const s: number[] = Array(n + 1).fill(0); + for (let i = 1; i <= n; i++) { + s[i] = s[i - 1] + nums[i - 1]; + } + + let f: [number, number][] = []; + let ans: number = 0; + + for (let i = 0; i < n; ++i) { + const g: [number, number][] = []; + for (const [j, x] of f) { + const y: number = gcd(x, nums[i]); + if (g.length === 0 || g.at(-1)[1] !== y) { + g.push([j, y]); + } + } + f = g; + f.push([i, nums[i]]); + for (const [j, x] of f) { + if (i - j + 1 >= k) { + ans = Math.max(ans, (s[i + 1] - s[j]) * x); + } + } + } + + return ans; +} + +function gcd(a: number, b: number): number { + return b === 0 ? a : gcd(b, a % b); +} diff --git a/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/Solution.cpp b/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/Solution.cpp index 32c9b5097a36c..a1856998ee82d 100644 --- a/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/Solution.cpp +++ b/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/Solution.cpp @@ -1,19 +1,19 @@ -class Solution { -public: - int maximizeSquareHoleArea(int n, int m, vector& hBars, vector& vBars) { - auto f = [](vector& nums) { - int ans = 1, cnt = 1; - sort(nums.begin(), nums.end()); - for (int i = 1; i < nums.size(); ++i) { - if (nums[i] == nums[i - 1] + 1) { - ans = max(ans, ++cnt); - } else { - cnt = 1; - } - } - return ans + 1; - }; - int x = min(f(hBars), f(vBars)); - return x * x; - } +class Solution { +public: + int maximizeSquareHoleArea(int n, int m, vector& hBars, vector& vBars) { + auto f = [](vector& nums) { + int ans = 1, cnt = 1; + sort(nums.begin(), nums.end()); + for (int i = 1; i < nums.size(); ++i) { + if (nums[i] == nums[i - 1] + 1) { + ans = max(ans, ++cnt); + } else { + cnt = 1; + } + } + return ans + 1; + }; + int x = min(f(hBars), f(vBars)); + return x * x; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/Solution.java b/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/Solution.java index 9c0aa4783f080..99a562f5c8a6f 100644 --- a/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/Solution.java +++ b/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/Solution.java @@ -1,19 +1,19 @@ -class Solution { - public int maximizeSquareHoleArea(int n, int m, int[] hBars, int[] vBars) { - int x = Math.min(f(hBars), f(vBars)); - return x * x; - } - - private int f(int[] nums) { - Arrays.sort(nums); - int ans = 1, cnt = 1; - for (int i = 1; i < nums.length; ++i) { - if (nums[i] == nums[i - 1] + 1) { - ans = Math.max(ans, ++cnt); - } else { - cnt = 1; - } - } - return ans + 1; - } +class Solution { + public int maximizeSquareHoleArea(int n, int m, int[] hBars, int[] vBars) { + int x = Math.min(f(hBars), f(vBars)); + return x * x; + } + + private int f(int[] nums) { + Arrays.sort(nums); + int ans = 1, cnt = 1; + for (int i = 1; i < nums.length; ++i) { + if (nums[i] == nums[i - 1] + 1) { + ans = Math.max(ans, ++cnt); + } else { + cnt = 1; + } + } + return ans + 1; + } } \ No newline at end of file diff --git a/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/Solution.py b/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/Solution.py index efc3bcb6d0176..5ea51894fdb15 100644 --- a/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/Solution.py +++ b/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/Solution.py @@ -1,16 +1,16 @@ -class Solution: - def maximizeSquareHoleArea( - self, n: int, m: int, hBars: List[int], vBars: List[int] - ) -> int: - def f(nums: List[int]) -> int: - nums.sort() - ans = cnt = 1 - for i in range(1, len(nums)): - if nums[i] == nums[i - 1] + 1: - cnt += 1 - ans = max(ans, cnt) - else: - cnt = 1 - return ans + 1 - - return min(f(hBars), f(vBars)) ** 2 +class Solution: + def maximizeSquareHoleArea( + self, n: int, m: int, hBars: List[int], vBars: List[int] + ) -> int: + def f(nums: List[int]) -> int: + nums.sort() + ans = cnt = 1 + for i in range(1, len(nums)): + if nums[i] == nums[i - 1] + 1: + cnt += 1 + ans = max(ans, cnt) + else: + cnt = 1 + return ans + 1 + + return min(f(hBars), f(vBars)) ** 2 diff --git a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.cpp b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.cpp index bc08a9d286478..762871a1a1743 100644 --- a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.cpp +++ b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - int minimumCoins(vector& prices) { - int n = prices.size(); - deque q; - for (int i = n; i; --i) { - while (q.size() && q.front() > i * 2 + 1) { - q.pop_front(); - } - if (i <= (n - 1) / 2) { - prices[i - 1] += prices[q.front() - 1]; - } - while (q.size() && prices[q.back() - 1] >= prices[i - 1]) { - q.pop_back(); - } - q.push_back(i); - } - return prices[0]; - } +class Solution { +public: + int minimumCoins(vector& prices) { + int n = prices.size(); + int f[n + 1]; + memset(f, 0x3f, sizeof(f)); + function dfs = [&](int i) { + if (i * 2 >= n) { + return prices[i - 1]; + } + if (f[i] == 0x3f3f3f3f) { + for (int j = i + 1; j <= i * 2 + 1; ++j) { + f[i] = min(f[i], prices[i - 1] + dfs(j)); + } + } + return f[i]; + }; + return dfs(1); + } }; \ No newline at end of file diff --git a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.go b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.go index b51f1408db690..74f13e6a58e34 100644 --- a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.go +++ b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.go @@ -1,75 +1,18 @@ func minimumCoins(prices []int) int { n := len(prices) - q := Deque{} - for i := n; i > 0; i-- { - for q.Size() > 0 && q.Front() > i*2+1 { - q.PopFront() + f := make([]int, n+1) + var dfs func(int) int + dfs = func(i int) int { + if i*2 >= n { + return prices[i-1] } - if i <= (n-1)/2 { - prices[i-1] += prices[q.Front()-1] + if f[i] == 0 { + f[i] = 1 << 30 + for j := i + 1; j <= i*2+1; j++ { + f[i] = min(f[i], dfs(j)+prices[i-1]) + } } - for q.Size() > 0 && prices[q.Back()-1] >= prices[i-1] { - q.PopBack() - } - q.PushBack(i) - } - return prices[0] -} - -// template -type Deque struct{ l, r []int } - -func (q Deque) Empty() bool { - return len(q.l) == 0 && len(q.r) == 0 -} - -func (q Deque) Size() int { - return len(q.l) + len(q.r) -} - -func (q *Deque) PushFront(v int) { - q.l = append(q.l, v) -} - -func (q *Deque) PushBack(v int) { - q.r = append(q.r, v) -} - -func (q *Deque) PopFront() (v int) { - if len(q.l) > 0 { - q.l, v = q.l[:len(q.l)-1], q.l[len(q.l)-1] - } else { - v, q.r = q.r[0], q.r[1:] - } - return -} - -func (q *Deque) PopBack() (v int) { - if len(q.r) > 0 { - q.r, v = q.r[:len(q.r)-1], q.r[len(q.r)-1] - } else { - v, q.l = q.l[0], q.l[1:] - } - return -} - -func (q Deque) Front() int { - if len(q.l) > 0 { - return q.l[len(q.l)-1] - } - return q.r[0] -} - -func (q Deque) Back() int { - if len(q.r) > 0 { - return q.r[len(q.r)-1] - } - return q.l[0] -} - -func (q Deque) Get(i int) int { - if i < len(q.l) { - return q.l[len(q.l)-1-i] + return f[i] } - return q.r[i-len(q.l)] + return dfs(1) } \ No newline at end of file diff --git a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.java b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.java index 9bb813265fb1d..949c0510ba0ee 100644 --- a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.java +++ b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.java @@ -1,19 +1,25 @@ -class Solution { - public int minimumCoins(int[] prices) { - int n = prices.length; - Deque q = new ArrayDeque<>(); - for (int i = n; i > 0; --i) { - while (!q.isEmpty() && q.peek() > i * 2 + 1) { - q.poll(); - } - if (i <= (n - 1) / 2) { - prices[i - 1] += prices[q.peek() - 1]; - } - while (!q.isEmpty() && prices[q.peekLast() - 1] >= prices[i - 1]) { - q.pollLast(); - } - q.offer(i); - } - return prices[0]; - } +class Solution { + private int[] prices; + private int[] f; + private int n; + + public int minimumCoins(int[] prices) { + n = prices.length; + f = new int[n + 1]; + this.prices = prices; + return dfs(1); + } + + private int dfs(int i) { + if (i * 2 >= n) { + return prices[i - 1]; + } + if (f[i] == 0) { + f[i] = 1 << 30; + for (int j = i + 1; j <= i * 2 + 1; ++j) { + f[i] = Math.min(f[i], prices[i - 1] + dfs(j)); + } + } + return f[i]; + } } \ No newline at end of file diff --git a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.py b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.py index 84d6cbab58ecf..64d4e583f6451 100644 --- a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.py +++ b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.py @@ -1,13 +1,9 @@ -class Solution: - def minimumCoins(self, prices: List[int]) -> int: - n = len(prices) - q = deque() - for i in range(n, 0, -1): - while q and q[0] > i * 2 + 1: - q.popleft() - if i <= (n - 1) // 2: - prices[i - 1] += prices[q[0] - 1] - while q and prices[q[-1] - 1] >= prices[i - 1]: - q.pop() - q.append(i) - return prices[0] +class Solution: + def minimumCoins(self, prices: List[int]) -> int: + @cache + def dfs(i: int) -> int: + if i * 2 >= len(prices): + return prices[i - 1] + return prices[i - 1] + min(dfs(j) for j in range(i + 1, i * 2 + 2)) + + return dfs(1) diff --git a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.ts b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.ts index dbf047ad18135..49bdd49a0c113 100644 --- a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.ts +++ b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.ts @@ -1,113 +1,17 @@ function minimumCoins(prices: number[]): number { const n = prices.length; - const q = new Deque(); - for (let i = n; i; --i) { - while (q.getSize() && q.frontValue()! > i * 2 + 1) { - q.popFront(); - } - if (i <= (n - 1) >> 1) { - prices[i - 1] += prices[q.frontValue()! - 1]; - } - while (q.getSize() && prices[q.backValue()! - 1] >= prices[i - 1]) { - q.popBack(); - } - q.pushBack(i); - } - return prices[0]; -} - -class Node { - value: T; - next: Node | null; - prev: Node | null; - - constructor(value: T) { - this.value = value; - this.next = null; - this.prev = null; - } -} - -class Deque { - private front: Node | null; - private back: Node | null; - private size: number; - - constructor() { - this.front = null; - this.back = null; - this.size = 0; - } - - pushFront(val: T): void { - const newNode = new Node(val); - if (this.isEmpty()) { - this.front = newNode; - this.back = newNode; - } else { - newNode.next = this.front; - this.front!.prev = newNode; - this.front = newNode; - } - this.size++; - } - - pushBack(val: T): void { - const newNode = new Node(val); - if (this.isEmpty()) { - this.front = newNode; - this.back = newNode; - } else { - newNode.prev = this.back; - this.back!.next = newNode; - this.back = newNode; - } - this.size++; - } - - popFront(): T | undefined { - if (this.isEmpty()) { - return undefined; - } - const value = this.front!.value; - this.front = this.front!.next; - if (this.front !== null) { - this.front.prev = null; - } else { - this.back = null; - } - this.size--; - return value; - } - - popBack(): T | undefined { - if (this.isEmpty()) { - return undefined; - } - const value = this.back!.value; - this.back = this.back!.prev; - if (this.back !== null) { - this.back.next = null; - } else { - this.front = null; - } - this.size--; - return value; - } - - frontValue(): T | undefined { - return this.front?.value; - } - - backValue(): T | undefined { - return this.back?.value; - } - - getSize(): number { - return this.size; - } - - isEmpty(): boolean { - return this.size === 0; - } + const f: number[] = Array(n + 1).fill(0); + const dfs = (i: number): number => { + if (i * 2 >= n) { + return prices[i - 1]; + } + if (f[i] === 0) { + f[i] = 1 << 30; + for (let j = i + 1; j <= i * 2 + 1; ++j) { + f[i] = Math.min(f[i], prices[i - 1] + dfs(j)); + } + } + return f[i]; + }; + return dfs(1); } diff --git a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution2.cpp b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution2.cpp new file mode 100644 index 0000000000000..025139ac4ebb7 --- /dev/null +++ b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution2.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + int minimumCoins(vector& prices) { + int n = prices.size(); + for (int i = (n - 1) / 2; i; --i) { + prices[i - 1] += *min_element(prices.begin() + i, prices.begin() + 2 * i + 1); + } + return prices[0]; + } +}; \ No newline at end of file diff --git a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution2.go b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution2.go new file mode 100644 index 0000000000000..b99db5d462c87 --- /dev/null +++ b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution2.go @@ -0,0 +1,6 @@ +func minimumCoins(prices []int) int { + for i := (len(prices) - 1) / 2; i > 0; i-- { + prices[i-1] += slices.Min(prices[i : i*2+1]) + } + return prices[0] +} \ No newline at end of file diff --git a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution2.java b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution2.java new file mode 100644 index 0000000000000..0ae40238e52e2 --- /dev/null +++ b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution2.java @@ -0,0 +1,13 @@ +class Solution { + public int minimumCoins(int[] prices) { + int n = prices.length; + for (int i = (n - 1) / 2; i > 0; --i) { + int mi = 1 << 30; + for (int j = i; j <= i * 2; ++j) { + mi = Math.min(mi, prices[j]); + } + prices[i - 1] += mi; + } + return prices[0]; + } +} \ No newline at end of file diff --git a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution2.py b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution2.py new file mode 100644 index 0000000000000..84ea0542da878 --- /dev/null +++ b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution2.py @@ -0,0 +1,6 @@ +class Solution: + def minimumCoins(self, prices: List[int]) -> int: + n = len(prices) + for i in range((n - 1) // 2, 0, -1): + prices[i - 1] += min(prices[i : i * 2 + 1]) + return prices[0] diff --git a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution2.ts b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution2.ts new file mode 100644 index 0000000000000..d27f0665b7938 --- /dev/null +++ b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution2.ts @@ -0,0 +1,6 @@ +function minimumCoins(prices: number[]): number { + for (let i = (prices.length - 1) >> 1; i; --i) { + prices[i - 1] += Math.min(...prices.slice(i, i * 2 + 1)); + } + return prices[0]; +} diff --git a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution3.cpp b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution3.cpp new file mode 100644 index 0000000000000..f5c64a192ddb5 --- /dev/null +++ b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution3.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int minimumCoins(vector& prices) { + int n = prices.size(); + deque q; + for (int i = n; i; --i) { + while (q.size() && q.front() > i * 2 + 1) { + q.pop_front(); + } + if (i <= (n - 1) / 2) { + prices[i - 1] += prices[q.front() - 1]; + } + while (q.size() && prices[q.back() - 1] >= prices[i - 1]) { + q.pop_back(); + } + q.push_back(i); + } + return prices[0]; + } +}; \ No newline at end of file diff --git a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution3.go b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution3.go new file mode 100644 index 0000000000000..b51f1408db690 --- /dev/null +++ b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution3.go @@ -0,0 +1,75 @@ +func minimumCoins(prices []int) int { + n := len(prices) + q := Deque{} + for i := n; i > 0; i-- { + for q.Size() > 0 && q.Front() > i*2+1 { + q.PopFront() + } + if i <= (n-1)/2 { + prices[i-1] += prices[q.Front()-1] + } + for q.Size() > 0 && prices[q.Back()-1] >= prices[i-1] { + q.PopBack() + } + q.PushBack(i) + } + return prices[0] +} + +// template +type Deque struct{ l, r []int } + +func (q Deque) Empty() bool { + return len(q.l) == 0 && len(q.r) == 0 +} + +func (q Deque) Size() int { + return len(q.l) + len(q.r) +} + +func (q *Deque) PushFront(v int) { + q.l = append(q.l, v) +} + +func (q *Deque) PushBack(v int) { + q.r = append(q.r, v) +} + +func (q *Deque) PopFront() (v int) { + if len(q.l) > 0 { + q.l, v = q.l[:len(q.l)-1], q.l[len(q.l)-1] + } else { + v, q.r = q.r[0], q.r[1:] + } + return +} + +func (q *Deque) PopBack() (v int) { + if len(q.r) > 0 { + q.r, v = q.r[:len(q.r)-1], q.r[len(q.r)-1] + } else { + v, q.l = q.l[0], q.l[1:] + } + return +} + +func (q Deque) Front() int { + if len(q.l) > 0 { + return q.l[len(q.l)-1] + } + return q.r[0] +} + +func (q Deque) Back() int { + if len(q.r) > 0 { + return q.r[len(q.r)-1] + } + return q.l[0] +} + +func (q Deque) Get(i int) int { + if i < len(q.l) { + return q.l[len(q.l)-1-i] + } + return q.r[i-len(q.l)] +} \ No newline at end of file diff --git a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution3.java b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution3.java new file mode 100644 index 0000000000000..735143f139a0b --- /dev/null +++ b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution3.java @@ -0,0 +1,19 @@ +class Solution { + public int minimumCoins(int[] prices) { + int n = prices.length; + Deque q = new ArrayDeque<>(); + for (int i = n; i > 0; --i) { + while (!q.isEmpty() && q.peek() > i * 2 + 1) { + q.poll(); + } + if (i <= (n - 1) / 2) { + prices[i - 1] += prices[q.peek() - 1]; + } + while (!q.isEmpty() && prices[q.peekLast() - 1] >= prices[i - 1]) { + q.pollLast(); + } + q.offer(i); + } + return prices[0]; + } +} \ No newline at end of file diff --git a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution3.py b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution3.py new file mode 100644 index 0000000000000..00e61cb0b4849 --- /dev/null +++ b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution3.py @@ -0,0 +1,13 @@ +class Solution: + def minimumCoins(self, prices: List[int]) -> int: + n = len(prices) + q = deque() + for i in range(n, 0, -1): + while q and q[0] > i * 2 + 1: + q.popleft() + if i <= (n - 1) // 2: + prices[i - 1] += prices[q[0] - 1] + while q and prices[q[-1] - 1] >= prices[i - 1]: + q.pop() + q.append(i) + return prices[0] diff --git a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution3.ts b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution3.ts new file mode 100644 index 0000000000000..dbf047ad18135 --- /dev/null +++ b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution3.ts @@ -0,0 +1,113 @@ +function minimumCoins(prices: number[]): number { + const n = prices.length; + const q = new Deque(); + for (let i = n; i; --i) { + while (q.getSize() && q.frontValue()! > i * 2 + 1) { + q.popFront(); + } + if (i <= (n - 1) >> 1) { + prices[i - 1] += prices[q.frontValue()! - 1]; + } + while (q.getSize() && prices[q.backValue()! - 1] >= prices[i - 1]) { + q.popBack(); + } + q.pushBack(i); + } + return prices[0]; +} + +class Node { + value: T; + next: Node | null; + prev: Node | null; + + constructor(value: T) { + this.value = value; + this.next = null; + this.prev = null; + } +} + +class Deque { + private front: Node | null; + private back: Node | null; + private size: number; + + constructor() { + this.front = null; + this.back = null; + this.size = 0; + } + + pushFront(val: T): void { + const newNode = new Node(val); + if (this.isEmpty()) { + this.front = newNode; + this.back = newNode; + } else { + newNode.next = this.front; + this.front!.prev = newNode; + this.front = newNode; + } + this.size++; + } + + pushBack(val: T): void { + const newNode = new Node(val); + if (this.isEmpty()) { + this.front = newNode; + this.back = newNode; + } else { + newNode.prev = this.back; + this.back!.next = newNode; + this.back = newNode; + } + this.size++; + } + + popFront(): T | undefined { + if (this.isEmpty()) { + return undefined; + } + const value = this.front!.value; + this.front = this.front!.next; + if (this.front !== null) { + this.front.prev = null; + } else { + this.back = null; + } + this.size--; + return value; + } + + popBack(): T | undefined { + if (this.isEmpty()) { + return undefined; + } + const value = this.back!.value; + this.back = this.back!.prev; + if (this.back !== null) { + this.back.next = null; + } else { + this.front = null; + } + this.size--; + return value; + } + + frontValue(): T | undefined { + return this.front?.value; + } + + backValue(): T | undefined { + return this.back?.value; + } + + getSize(): number { + return this.size; + } + + isEmpty(): boolean { + return this.size === 0; + } +} diff --git a/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/Solution.cpp b/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/Solution.cpp index 2fde9333bc673..f31a30caafc4e 100644 --- a/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/Solution.cpp +++ b/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - int findMaximumLength(vector& nums) { - int n = nums.size(); - int f[n + 1]; - int pre[n + 2]; - long long s[n + 1]; - for (int i = 0; i < n; ++i) { - s[i + 1] = s[i] + nums[i]; - } - memset(f, 0, sizeof(f)); - memset(pre, 0, sizeof(pre)); - for (int i = 1; i <= n; ++i) { - pre[i] = max(pre[i], pre[i - 1]); - f[i] = f[pre[i]] + 1; - int j = lower_bound(s, s + n + 1, s[i] * 2 - s[pre[i]]) - s; - pre[j] = i; - } - return f[n]; - } +class Solution { +public: + int findMaximumLength(vector& nums) { + int n = nums.size(); + int f[n + 1]; + int pre[n + 2]; + long long s[n + 1]; + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + memset(f, 0, sizeof(f)); + memset(pre, 0, sizeof(pre)); + for (int i = 1; i <= n; ++i) { + pre[i] = max(pre[i], pre[i - 1]); + f[i] = f[pre[i]] + 1; + int j = lower_bound(s, s + n + 1, s[i] * 2 - s[pre[i]]) - s; + pre[j] = i; + } + return f[n]; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/Solution.java b/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/Solution.java index a6cefcba0ec4e..7b7ca443baf69 100644 --- a/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/Solution.java +++ b/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/Solution.java @@ -1,18 +1,18 @@ -class Solution { - public int findMaximumLength(int[] nums) { - int n = nums.length; - long[] s = new long[n + 1]; - for (int i = 0; i < n; ++i) { - s[i + 1] = s[i] + nums[i]; - } - int[] f = new int[n + 1]; - int[] pre = new int[n + 2]; - for (int i = 1; i <= n; ++i) { - pre[i] = Math.max(pre[i], pre[i - 1]); - f[i] = f[pre[i]] + 1; - int j = Arrays.binarySearch(s, s[i] * 2 - s[pre[i]]); - pre[j < 0 ? -j - 1 : j] = i; - } - return f[n]; - } +class Solution { + public int findMaximumLength(int[] nums) { + int n = nums.length; + long[] s = new long[n + 1]; + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + int[] f = new int[n + 1]; + int[] pre = new int[n + 2]; + for (int i = 1; i <= n; ++i) { + pre[i] = Math.max(pre[i], pre[i - 1]); + f[i] = f[pre[i]] + 1; + int j = Arrays.binarySearch(s, s[i] * 2 - s[pre[i]]); + pre[j < 0 ? -j - 1 : j] = i; + } + return f[n]; + } } \ No newline at end of file diff --git a/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/Solution.py b/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/Solution.py index c9addc37ef0aa..ee4ac87e90a89 100644 --- a/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/Solution.py +++ b/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/Solution.py @@ -1,12 +1,12 @@ -class Solution: - def findMaximumLength(self, nums: List[int]) -> int: - n = len(nums) - s = list(accumulate(nums, initial=0)) - f = [0] * (n + 1) - pre = [0] * (n + 2) - for i in range(1, n + 1): - pre[i] = max(pre[i], pre[i - 1]) - f[i] = f[pre[i]] + 1 - j = bisect_left(s, s[i] * 2 - s[pre[i]]) - pre[j] = i - return f[n] +class Solution: + def findMaximumLength(self, nums: List[int]) -> int: + n = len(nums) + s = list(accumulate(nums, initial=0)) + f = [0] * (n + 1) + pre = [0] * (n + 2) + for i in range(1, n + 1): + pre[i] = max(pre[i], pre[i - 1]) + f[i] = f[pre[i]] + 1 + j = bisect_left(s, s[i] * 2 - s[pre[i]]) + pre[j] = i + return f[n] diff --git a/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/Solution.cpp b/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/Solution.cpp index e22722d08cb37..7baa8c0cdefcd 100644 --- a/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/Solution.cpp +++ b/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/Solution.cpp @@ -1,18 +1,18 @@ -class Solution { -public: - bool areSimilar(vector>& mat, int k) { - int m = mat.size(), n = mat[0].size(); - k %= n; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (i % 2 == 1 && mat[i][j] != mat[i][(j + k) % n]) { - return false; - } - if (i % 2 == 0 && mat[i][j] != mat[i][(j - k + n) % n]) { - return false; - } - } - } - return true; - } +class Solution { +public: + bool areSimilar(vector>& mat, int k) { + int m = mat.size(), n = mat[0].size(); + k %= n; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (i % 2 == 1 && mat[i][j] != mat[i][(j + k) % n]) { + return false; + } + if (i % 2 == 0 && mat[i][j] != mat[i][(j - k + n) % n]) { + return false; + } + } + } + return true; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/Solution.java b/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/Solution.java index d7adaeb9d4cea..3005bb8e6efe3 100644 --- a/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/Solution.java +++ b/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public boolean areSimilar(int[][] mat, int k) { - int m = mat.length, n = mat[0].length; - k %= n; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (i % 2 == 1 && mat[i][j] != mat[i][(j + k) % n]) { - return false; - } - if (i % 2 == 0 && mat[i][j] != mat[i][(j - k + n) % n]) { - return false; - } - } - } - return true; - } +class Solution { + public boolean areSimilar(int[][] mat, int k) { + int m = mat.length, n = mat[0].length; + k %= n; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (i % 2 == 1 && mat[i][j] != mat[i][(j + k) % n]) { + return false; + } + if (i % 2 == 0 && mat[i][j] != mat[i][(j - k + n) % n]) { + return false; + } + } + } + return true; + } } \ No newline at end of file diff --git a/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/Solution.py b/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/Solution.py index 08091d3128692..e3e0a18201cca 100644 --- a/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/Solution.py +++ b/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def areSimilar(self, mat: List[List[int]], k: int) -> bool: - n = len(mat[0]) - for i, row in enumerate(mat): - for j, x in enumerate(row): - if i % 2 == 1 and x != mat[i][(j + k) % n]: - return False - if i % 2 == 0 and x != mat[i][(j - k + n) % n]: - return False - return True +class Solution: + def areSimilar(self, mat: List[List[int]], k: int) -> bool: + n = len(mat[0]) + for i, row in enumerate(mat): + for j, x in enumerate(row): + if i % 2 == 1 and x != mat[i][(j + k) % n]: + return False + if i % 2 == 0 and x != mat[i][(j - k + n) % n]: + return False + return True diff --git a/solution/2900-2999/2947.Count Beautiful Substrings I/Solution.cpp b/solution/2900-2999/2947.Count Beautiful Substrings I/Solution.cpp index e9b9309a5ca0b..25c9f7ebbfe42 100644 --- a/solution/2900-2999/2947.Count Beautiful Substrings I/Solution.cpp +++ b/solution/2900-2999/2947.Count Beautiful Substrings I/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - int beautifulSubstrings(string s, int k) { - int n = s.size(); - int vs[26]{}; - string t = "aeiou"; - for (char c : t) { - vs[c - 'a'] = 1; - } - int ans = 0; - for (int i = 0; i < n; ++i) { - int vowels = 0; - for (int j = i; j < n; ++j) { - vowels += vs[s[j] - 'a']; - int consonants = j - i + 1 - vowels; - if (vowels == consonants && vowels * consonants % k == 0) { - ++ans; - } - } - } - return ans; - } +class Solution { +public: + int beautifulSubstrings(string s, int k) { + int n = s.size(); + int vs[26]{}; + string t = "aeiou"; + for (char c : t) { + vs[c - 'a'] = 1; + } + int ans = 0; + for (int i = 0; i < n; ++i) { + int vowels = 0; + for (int j = i; j < n; ++j) { + vowels += vs[s[j] - 'a']; + int consonants = j - i + 1 - vowels; + if (vowels == consonants && vowels * consonants % k == 0) { + ++ans; + } + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2947.Count Beautiful Substrings I/Solution.java b/solution/2900-2999/2947.Count Beautiful Substrings I/Solution.java index a36dfcb094820..b5bf7b24d5fe0 100644 --- a/solution/2900-2999/2947.Count Beautiful Substrings I/Solution.java +++ b/solution/2900-2999/2947.Count Beautiful Substrings I/Solution.java @@ -1,21 +1,21 @@ -class Solution { - public int beautifulSubstrings(String s, int k) { - int n = s.length(); - int[] vs = new int[26]; - for (char c : "aeiou".toCharArray()) { - vs[c - 'a'] = 1; - } - int ans = 0; - for (int i = 0; i < n; ++i) { - int vowels = 0; - for (int j = i; j < n; ++j) { - vowels += vs[s.charAt(j) - 'a']; - int consonants = j - i + 1 - vowels; - if (vowels == consonants && vowels * consonants % k == 0) { - ++ans; - } - } - } - return ans; - } +class Solution { + public int beautifulSubstrings(String s, int k) { + int n = s.length(); + int[] vs = new int[26]; + for (char c : "aeiou".toCharArray()) { + vs[c - 'a'] = 1; + } + int ans = 0; + for (int i = 0; i < n; ++i) { + int vowels = 0; + for (int j = i; j < n; ++j) { + vowels += vs[s.charAt(j) - 'a']; + int consonants = j - i + 1 - vowels; + if (vowels == consonants && vowels * consonants % k == 0) { + ++ans; + } + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2947.Count Beautiful Substrings I/Solution.py b/solution/2900-2999/2947.Count Beautiful Substrings I/Solution.py index 6bdb6465a0af7..23762f1e85c7e 100644 --- a/solution/2900-2999/2947.Count Beautiful Substrings I/Solution.py +++ b/solution/2900-2999/2947.Count Beautiful Substrings I/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def beautifulSubstrings(self, s: str, k: int) -> int: - n = len(s) - vs = set("aeiou") - ans = 0 - for i in range(n): - vowels = 0 - for j in range(i, n): - vowels += s[j] in vs - consonants = j - i + 1 - vowels - if vowels == consonants and vowels * consonants % k == 0: - ans += 1 - return ans +class Solution: + def beautifulSubstrings(self, s: str, k: int) -> int: + n = len(s) + vs = set("aeiou") + ans = 0 + for i in range(n): + vowels = 0 + for j in range(i, n): + vowels += s[j] in vs + consonants = j - i + 1 - vowels + if vowels == consonants and vowels * consonants % k == 0: + ans += 1 + return ans diff --git a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.cpp b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.cpp index 7e7ec5fd661fd..620e4b306cee3 100644 --- a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.cpp +++ b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.cpp @@ -1,25 +1,25 @@ -class Solution { -public: - vector lexicographicallySmallestArray(vector& nums, int limit) { - int n = nums.size(); - vector idx(n); - iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) { - return nums[i] < nums[j]; - }); - vector ans(n); - for (int i = 0; i < n;) { - int j = i + 1; - while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) { - ++j; - } - vector t(idx.begin() + i, idx.begin() + j); - sort(t.begin(), t.end()); - for (int k = i; k < j; ++k) { - ans[t[k - i]] = nums[idx[k]]; - } - i = j; - } - return ans; - } +class Solution { +public: + vector lexicographicallySmallestArray(vector& nums, int limit) { + int n = nums.size(); + vector idx(n); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { + return nums[i] < nums[j]; + }); + vector ans(n); + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) { + ++j; + } + vector t(idx.begin() + i, idx.begin() + j); + sort(t.begin(), t.end()); + for (int k = i; k < j; ++k) { + ans[t[k - i]] = nums[idx[k]]; + } + i = j; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.java b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.java index 632b45ece4031..1138b649ab386 100644 --- a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.java +++ b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.java @@ -1,24 +1,24 @@ -class Solution { - public int[] lexicographicallySmallestArray(int[] nums, int limit) { - int n = nums.length; - Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } - Arrays.sort(idx, (i, j) -> nums[i] - nums[j]); - int[] ans = new int[n]; - for (int i = 0; i < n;) { - int j = i + 1; - while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) { - ++j; - } - Integer[] t = Arrays.copyOfRange(idx, i, j); - Arrays.sort(t, (x, y) -> x - y); - for (int k = i; k < j; ++k) { - ans[t[k - i]] = nums[idx[k]]; - } - i = j; - } - return ans; - } +class Solution { + public int[] lexicographicallySmallestArray(int[] nums, int limit) { + int n = nums.length; + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; ++i) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> nums[i] - nums[j]); + int[] ans = new int[n]; + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) { + ++j; + } + Integer[] t = Arrays.copyOfRange(idx, i, j); + Arrays.sort(t, (x, y) -> x - y); + for (int k = i; k < j; ++k) { + ans[t[k - i]] = nums[idx[k]]; + } + i = j; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.py b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.py index d7ea61bd24f4a..4d4a6a7e238d5 100644 --- a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.py +++ b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.py @@ -1,15 +1,15 @@ -class Solution: - def lexicographicallySmallestArray(self, nums: List[int], limit: int) -> List[int]: - n = len(nums) - arr = sorted(zip(nums, range(n))) - ans = [0] * n - i = 0 - while i < n: - j = i + 1 - while j < n and arr[j][0] - arr[j - 1][0] <= limit: - j += 1 - idx = sorted(k for _, k in arr[i:j]) - for k, (x, _) in zip(idx, arr[i:j]): - ans[k] = x - i = j - return ans +class Solution: + def lexicographicallySmallestArray(self, nums: List[int], limit: int) -> List[int]: + n = len(nums) + arr = sorted(zip(nums, range(n))) + ans = [0] * n + i = 0 + while i < n: + j = i + 1 + while j < n and arr[j][0] - arr[j - 1][0] <= limit: + j += 1 + idx = sorted(k for _, k in arr[i:j]) + for k, (x, _) in zip(idx, arr[i:j]): + ans[k] = x + i = j + return ans diff --git a/solution/2900-2999/2950.Number of Divisible Substrings/Solution.cpp b/solution/2900-2999/2950.Number of Divisible Substrings/Solution.cpp index 19ffa457f33fc..ad06d6b5cc66a 100644 --- a/solution/2900-2999/2950.Number of Divisible Substrings/Solution.cpp +++ b/solution/2900-2999/2950.Number of Divisible Substrings/Solution.cpp @@ -9,12 +9,12 @@ class Solution { } } int ans = 0; - for (int i = 1; i < 10; ++i) { - unordered_map cnt{{0, 1}}; + int n = word.size(); + for (int i = 0; i < n; ++i) { int s = 0; - for (char& c : word) { - s += mp[c - 'a'] - i; - ans += cnt[s]++; + for (int j = i; j < n; ++j) { + s += mp[word[j] - 'a']; + ans += s % (j - i + 1) == 0 ? 1 : 0; } } return ans; diff --git a/solution/2900-2999/2950.Number of Divisible Substrings/Solution.go b/solution/2900-2999/2950.Number of Divisible Substrings/Solution.go index a561b5df7a565..eaa61d80b2eb4 100644 --- a/solution/2900-2999/2950.Number of Divisible Substrings/Solution.go +++ b/solution/2900-2999/2950.Number of Divisible Substrings/Solution.go @@ -6,13 +6,14 @@ func countDivisibleSubstrings(word string) (ans int) { mp[c-'a'] = i + 1 } } - for i := 0; i < 10; i++ { - cnt := map[int]int{0: 1} + n := len(word) + for i := 0; i < n; i++ { s := 0 - for _, c := range word { - s += mp[c-'a'] - i - ans += cnt[s] - cnt[s]++ + for j := i; j < n; j++ { + s += mp[word[j]-'a'] + if s%(j-i+1) == 0 { + ans++ + } } } return diff --git a/solution/2900-2999/2950.Number of Divisible Substrings/Solution.java b/solution/2900-2999/2950.Number of Divisible Substrings/Solution.java index b076fd8bf3feb..59944aa0a56cf 100644 --- a/solution/2900-2999/2950.Number of Divisible Substrings/Solution.java +++ b/solution/2900-2999/2950.Number of Divisible Substrings/Solution.java @@ -8,15 +8,12 @@ public int countDivisibleSubstrings(String word) { } } int ans = 0; - char[] cs = word.toCharArray(); - for (int i = 1; i < 10; ++i) { - Map cnt = new HashMap<>(); - cnt.put(0, 1); + int n = word.length(); + for (int i = 0; i < n; ++i) { int s = 0; - for (char c : cs) { - s += mp[c - 'a'] - i; - ans += cnt.getOrDefault(s, 0); - cnt.merge(s, 1, Integer::sum); + for (int j = i; j < n; ++j) { + s += mp[word.charAt(j) - 'a']; + ans += s % (j - i + 1) == 0 ? 1 : 0; } } return ans; diff --git a/solution/2900-2999/2950.Number of Divisible Substrings/Solution.py b/solution/2900-2999/2950.Number of Divisible Substrings/Solution.py index 30f447cb8a53a..4a8a16893b6d2 100644 --- a/solution/2900-2999/2950.Number of Divisible Substrings/Solution.py +++ b/solution/2900-2999/2950.Number of Divisible Substrings/Solution.py @@ -6,12 +6,10 @@ def countDivisibleSubstrings(self, word: str) -> int: for c in s: mp[c] = i ans = 0 - for i in range(1, 10): - cnt = defaultdict(int) - cnt[0] = 1 + n = len(word) + for i in range(n): s = 0 - for c in word: - s += mp[c] - i - ans += cnt[s] - cnt[s] += 1 + for j in range(i, n): + s += mp[word[j]] + ans += s % (j - i + 1) == 0 return ans diff --git a/solution/2900-2999/2950.Number of Divisible Substrings/Solution.rs b/solution/2900-2999/2950.Number of Divisible Substrings/Solution.rs index 86b5614202d92..4457e5ac57821 100644 --- a/solution/2900-2999/2950.Number of Divisible Substrings/Solution.rs +++ b/solution/2900-2999/2950.Number of Divisible Substrings/Solution.rs @@ -1,25 +1,26 @@ -use std::collections::HashMap; - impl Solution { pub fn count_divisible_substrings(word: String) -> i32 { let d = vec!["ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"]; - let mut mp: Vec = vec![0; 26]; + let mut mp = vec![0; 26]; + for (i, s) in d.iter().enumerate() { - for c in s.chars() { - mp[(c as usize) - ('a' as usize)] = i + 1; - } + s.chars().for_each(|c| { + mp[(c as usize) - ('a' as usize)] = (i + 1) as i32; + }); } + let mut ans = 0; - for i in 0..10 { - let mut cnt: HashMap = HashMap::new(); - cnt.insert(0, 1); + let n = word.len(); + + for i in 0..n { let mut s = 0; - for c in word.chars() { - s += (mp[(c as usize) - ('a' as usize)] - i) as i32; - ans += cnt.get(&s).cloned().unwrap_or(0); - *cnt.entry(s).or_insert(0) += 1; + + for j in i..n { + s += mp[(word.as_bytes()[j] as usize) - ('a' as usize)]; + ans += (s % ((j - i + 1) as i32) == 0) as i32; } } + ans } } diff --git a/solution/2900-2999/2950.Number of Divisible Substrings/Solution.ts b/solution/2900-2999/2950.Number of Divisible Substrings/Solution.ts index cac31d82912e0..20d7b055b636f 100644 --- a/solution/2900-2999/2950.Number of Divisible Substrings/Solution.ts +++ b/solution/2900-2999/2950.Number of Divisible Substrings/Solution.ts @@ -1,21 +1,20 @@ function countDivisibleSubstrings(word: string): number { - const d = ['ab', 'cde', 'fgh', 'ijk', 'lmn', 'opq', 'rst', 'uvw', 'xyz']; + const d: string[] = ['ab', 'cde', 'fgh', 'ijk', 'lmn', 'opq', 'rst', 'uvw', 'xyz']; const mp: number[] = Array(26).fill(0); - - d.forEach((s, i) => { - for (const c of s) { + for (let i = 0; i < d.length; ++i) { + for (const c of d[i]) { mp[c.charCodeAt(0) - 'a'.charCodeAt(0)] = i + 1; } - }); - + } + const n = word.length; let ans = 0; - for (let i = 0; i < 10; i++) { - const cnt: { [key: number]: number } = { 0: 1 }; + for (let i = 0; i < n; ++i) { let s = 0; - for (const c of word) { - s += mp[c.charCodeAt(0) - 'a'.charCodeAt(0)] - i; - ans += cnt[s] || 0; - cnt[s] = (cnt[s] || 0) + 1; + for (let j = i; j < n; ++j) { + s += mp[word.charCodeAt(j) - 'a'.charCodeAt(0)]; + if (s % (j - i + 1) === 0) { + ++ans; + } } } return ans; diff --git a/solution/2900-2999/2950.Number of Divisible Substrings/Solution2.cpp b/solution/2900-2999/2950.Number of Divisible Substrings/Solution2.cpp new file mode 100644 index 0000000000000..19ffa457f33fc --- /dev/null +++ b/solution/2900-2999/2950.Number of Divisible Substrings/Solution2.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int countDivisibleSubstrings(string word) { + string d[9] = {"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"}; + int mp[26]{}; + for (int i = 0; i < 9; ++i) { + for (char& c : d[i]) { + mp[c - 'a'] = i + 1; + } + } + int ans = 0; + for (int i = 1; i < 10; ++i) { + unordered_map cnt{{0, 1}}; + int s = 0; + for (char& c : word) { + s += mp[c - 'a'] - i; + ans += cnt[s]++; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2900-2999/2950.Number of Divisible Substrings/Solution2.go b/solution/2900-2999/2950.Number of Divisible Substrings/Solution2.go new file mode 100644 index 0000000000000..a561b5df7a565 --- /dev/null +++ b/solution/2900-2999/2950.Number of Divisible Substrings/Solution2.go @@ -0,0 +1,19 @@ +func countDivisibleSubstrings(word string) (ans int) { + d := []string{"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"} + mp := [26]int{} + for i, s := range d { + for _, c := range s { + mp[c-'a'] = i + 1 + } + } + for i := 0; i < 10; i++ { + cnt := map[int]int{0: 1} + s := 0 + for _, c := range word { + s += mp[c-'a'] - i + ans += cnt[s] + cnt[s]++ + } + } + return +} \ No newline at end of file diff --git a/solution/2900-2999/2950.Number of Divisible Substrings/Solution2.java b/solution/2900-2999/2950.Number of Divisible Substrings/Solution2.java new file mode 100644 index 0000000000000..b076fd8bf3feb --- /dev/null +++ b/solution/2900-2999/2950.Number of Divisible Substrings/Solution2.java @@ -0,0 +1,24 @@ +class Solution { + public int countDivisibleSubstrings(String word) { + String[] d = {"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"}; + int[] mp = new int[26]; + for (int i = 0; i < d.length; ++i) { + for (char c : d[i].toCharArray()) { + mp[c - 'a'] = i + 1; + } + } + int ans = 0; + char[] cs = word.toCharArray(); + for (int i = 1; i < 10; ++i) { + Map cnt = new HashMap<>(); + cnt.put(0, 1); + int s = 0; + for (char c : cs) { + s += mp[c - 'a'] - i; + ans += cnt.getOrDefault(s, 0); + cnt.merge(s, 1, Integer::sum); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2900-2999/2950.Number of Divisible Substrings/Solution2.py b/solution/2900-2999/2950.Number of Divisible Substrings/Solution2.py new file mode 100644 index 0000000000000..30f447cb8a53a --- /dev/null +++ b/solution/2900-2999/2950.Number of Divisible Substrings/Solution2.py @@ -0,0 +1,17 @@ +class Solution: + def countDivisibleSubstrings(self, word: str) -> int: + d = ["ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"] + mp = {} + for i, s in enumerate(d, 1): + for c in s: + mp[c] = i + ans = 0 + for i in range(1, 10): + cnt = defaultdict(int) + cnt[0] = 1 + s = 0 + for c in word: + s += mp[c] - i + ans += cnt[s] + cnt[s] += 1 + return ans diff --git a/solution/2900-2999/2950.Number of Divisible Substrings/Solution2.rs b/solution/2900-2999/2950.Number of Divisible Substrings/Solution2.rs new file mode 100644 index 0000000000000..86b5614202d92 --- /dev/null +++ b/solution/2900-2999/2950.Number of Divisible Substrings/Solution2.rs @@ -0,0 +1,25 @@ +use std::collections::HashMap; + +impl Solution { + pub fn count_divisible_substrings(word: String) -> i32 { + let d = vec!["ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"]; + let mut mp: Vec = vec![0; 26]; + for (i, s) in d.iter().enumerate() { + for c in s.chars() { + mp[(c as usize) - ('a' as usize)] = i + 1; + } + } + let mut ans = 0; + for i in 0..10 { + let mut cnt: HashMap = HashMap::new(); + cnt.insert(0, 1); + let mut s = 0; + for c in word.chars() { + s += (mp[(c as usize) - ('a' as usize)] - i) as i32; + ans += cnt.get(&s).cloned().unwrap_or(0); + *cnt.entry(s).or_insert(0) += 1; + } + } + ans + } +} diff --git a/solution/2900-2999/2950.Number of Divisible Substrings/Solution2.ts b/solution/2900-2999/2950.Number of Divisible Substrings/Solution2.ts new file mode 100644 index 0000000000000..cac31d82912e0 --- /dev/null +++ b/solution/2900-2999/2950.Number of Divisible Substrings/Solution2.ts @@ -0,0 +1,22 @@ +function countDivisibleSubstrings(word: string): number { + const d = ['ab', 'cde', 'fgh', 'ijk', 'lmn', 'opq', 'rst', 'uvw', 'xyz']; + const mp: number[] = Array(26).fill(0); + + d.forEach((s, i) => { + for (const c of s) { + mp[c.charCodeAt(0) - 'a'.charCodeAt(0)] = i + 1; + } + }); + + let ans = 0; + for (let i = 0; i < 10; i++) { + const cnt: { [key: number]: number } = { 0: 1 }; + let s = 0; + for (const c of word) { + s += mp[c.charCodeAt(0) - 'a'.charCodeAt(0)] - i; + ans += cnt[s] || 0; + cnt[s] = (cnt[s] || 0) + 1; + } + } + return ans; +} diff --git a/solution/2900-2999/2954.Count the Number of Infection Sequences/Solution.cpp b/solution/2900-2999/2954.Count the Number of Infection Sequences/Solution.cpp index eb31593022080..da152e6324daf 100644 --- a/solution/2900-2999/2954.Count the Number of Infection Sequences/Solution.cpp +++ b/solution/2900-2999/2954.Count the Number of Infection Sequences/Solution.cpp @@ -1,50 +1,50 @@ -const int MX = 1e5; -const int MOD = 1e9 + 7; -int fac[MX + 1]; - -auto init = [] { - fac[0] = 1; - for (int i = 1; i <= MX; ++i) { - fac[i] = 1LL * fac[i - 1] * i % MOD; - } - return 0; -}(); - -int qpow(long long a, long long n) { - long long ans = 1; - for (; n > 0; n >>= 1) { - if (n & 1) { - ans = (ans * a) % MOD; - } - a = (a * a) % MOD; - } - return ans; -} - -class Solution { -public: - int numberOfSequence(int n, vector& sick) { - int m = sick.size(); - vector nums(m + 1); - - nums[0] = sick[0]; - nums[m] = n - sick[m - 1] - 1; - for (int i = 1; i < m; i++) { - nums[i] = sick[i] - sick[i - 1] - 1; - } - - int s = accumulate(nums.begin(), nums.end(), 0); - long long ans = fac[s]; - for (int x : nums) { - if (x > 0) { - ans = ans * qpow(fac[x], MOD - 2) % MOD; - } - } - for (int i = 1; i < nums.size() - 1; ++i) { - if (nums[i] > 1) { - ans = ans * qpow(2, nums[i] - 1) % MOD; - } - } - return ans; - } -}; +const int MX = 1e5; +const int MOD = 1e9 + 7; +int fac[MX + 1]; + +auto init = [] { + fac[0] = 1; + for (int i = 1; i <= MX; ++i) { + fac[i] = 1LL * fac[i - 1] * i % MOD; + } + return 0; +}(); + +int qpow(long long a, long long n) { + long long ans = 1; + for (; n > 0; n >>= 1) { + if (n & 1) { + ans = (ans * a) % MOD; + } + a = (a * a) % MOD; + } + return ans; +} + +class Solution { +public: + int numberOfSequence(int n, vector& sick) { + int m = sick.size(); + vector nums(m + 1); + + nums[0] = sick[0]; + nums[m] = n - sick[m - 1] - 1; + for (int i = 1; i < m; i++) { + nums[i] = sick[i] - sick[i - 1] - 1; + } + + int s = accumulate(nums.begin(), nums.end(), 0); + long long ans = fac[s]; + for (int x : nums) { + if (x > 0) { + ans = ans * qpow(fac[x], MOD - 2) % MOD; + } + } + for (int i = 1; i < nums.size() - 1; ++i) { + if (nums[i] > 1) { + ans = ans * qpow(2, nums[i] - 1) % MOD; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2900-2999/2954.Count the Number of Infection Sequences/Solution.java b/solution/2900-2999/2954.Count the Number of Infection Sequences/Solution.java index 7ccab4d2517d0..962c7427aa208 100644 --- a/solution/2900-2999/2954.Count the Number of Infection Sequences/Solution.java +++ b/solution/2900-2999/2954.Count the Number of Infection Sequences/Solution.java @@ -1,49 +1,49 @@ -class Solution { - private static final int MOD = (int) (1e9 + 7); - private static final int MX = 100000; - private static final int[] FAC = new int[MX + 1]; - - static { - FAC[0] = 1; - for (int i = 1; i <= MX; i++) { - FAC[i] = (int) ((long) FAC[i - 1] * i % MOD); - } - } - - public int numberOfSequence(int n, int[] sick) { - int m = sick.length; - int[] nums = new int[m + 1]; - nums[0] = sick[0]; - nums[m] = n - sick[m - 1] - 1; - for (int i = 1; i < m; i++) { - nums[i] = sick[i] - sick[i - 1] - 1; - } - int s = 0; - for (int x : nums) { - s += x; - } - int ans = FAC[s]; - for (int x : nums) { - if (x > 0) { - ans = (int) ((long) ans * qpow(FAC[x], MOD - 2) % MOD); - } - } - for (int i = 1; i < nums.length - 1; ++i) { - if (nums[i] > 1) { - ans = (int) ((long) ans * qpow(2, nums[i] - 1) % MOD); - } - } - return ans; - } - - private int qpow(long a, long n) { - long ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans = ans * a % MOD; - } - a = a * a % MOD; - } - return (int) ans; - } +class Solution { + private static final int MOD = (int) (1e9 + 7); + private static final int MX = 100000; + private static final int[] FAC = new int[MX + 1]; + + static { + FAC[0] = 1; + for (int i = 1; i <= MX; i++) { + FAC[i] = (int) ((long) FAC[i - 1] * i % MOD); + } + } + + public int numberOfSequence(int n, int[] sick) { + int m = sick.length; + int[] nums = new int[m + 1]; + nums[0] = sick[0]; + nums[m] = n - sick[m - 1] - 1; + for (int i = 1; i < m; i++) { + nums[i] = sick[i] - sick[i - 1] - 1; + } + int s = 0; + for (int x : nums) { + s += x; + } + int ans = FAC[s]; + for (int x : nums) { + if (x > 0) { + ans = (int) ((long) ans * qpow(FAC[x], MOD - 2) % MOD); + } + } + for (int i = 1; i < nums.length - 1; ++i) { + if (nums[i] > 1) { + ans = (int) ((long) ans * qpow(2, nums[i] - 1) % MOD); + } + } + return ans; + } + + private int qpow(long a, long n) { + long ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans = ans * a % MOD; + } + a = a * a % MOD; + } + return (int) ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2954.Count the Number of Infection Sequences/Solution.py b/solution/2900-2999/2954.Count the Number of Infection Sequences/Solution.py index 561b7b8e49e23..3808798bb9450 100644 --- a/solution/2900-2999/2954.Count the Number of Infection Sequences/Solution.py +++ b/solution/2900-2999/2954.Count the Number of Infection Sequences/Solution.py @@ -1,20 +1,20 @@ -mod = 10**9 + 7 -mx = 10**5 -fac = [1] * (mx + 1) -for i in range(2, mx + 1): - fac[i] = fac[i - 1] * i % mod - - -class Solution: - def numberOfSequence(self, n: int, sick: List[int]) -> int: - nums = [b - a - 1 for a, b in pairwise([-1] + sick + [n])] - ans = 1 - s = sum(nums) - ans = fac[s] - for x in nums: - if x: - ans = ans * pow(fac[x], mod - 2, mod) % mod - for x in nums[1:-1]: - if x > 1: - ans = ans * pow(2, x - 1, mod) % mod - return ans +mod = 10**9 + 7 +mx = 10**5 +fac = [1] * (mx + 1) +for i in range(2, mx + 1): + fac[i] = fac[i - 1] * i % mod + + +class Solution: + def numberOfSequence(self, n: int, sick: List[int]) -> int: + nums = [b - a - 1 for a, b in pairwise([-1] + sick + [n])] + ans = 1 + s = sum(nums) + ans = fac[s] + for x in nums: + if x: + ans = ans * pow(fac[x], mod - 2, mod) % mod + for x in nums[1:-1]: + if x > 1: + ans = ans * pow(2, x - 1, mod) % mod + return ans diff --git a/solution/2900-2999/2955.Number of Same-End Substrings/Solution.cpp b/solution/2900-2999/2955.Number of Same-End Substrings/Solution.cpp index fe031797bc4c3..fe2f13281d78a 100644 --- a/solution/2900-2999/2955.Number of Same-End Substrings/Solution.cpp +++ b/solution/2900-2999/2955.Number of Same-End Substrings/Solution.cpp @@ -1,24 +1,24 @@ -class Solution { -public: - vector sameEndSubstringCount(string s, vector>& queries) { - int n = s.size(); - int cnt[26][n + 1]; - memset(cnt, 0, sizeof(cnt)); - for (int j = 1; j <= n; ++j) { - for (int i = 0; i < 26; ++i) { - cnt[i][j] = cnt[i][j - 1]; - } - cnt[s[j - 1] - 'a'][j]++; - } - vector ans; - for (auto& q : queries) { - int l = q[0], r = q[1]; - ans.push_back(r - l + 1); - for (int i = 0; i < 26; ++i) { - int x = cnt[i][r + 1] - cnt[i][l]; - ans.back() += x * (x - 1) / 2; - } - } - return ans; - } +class Solution { +public: + vector sameEndSubstringCount(string s, vector>& queries) { + int n = s.size(); + int cnt[26][n + 1]; + memset(cnt, 0, sizeof(cnt)); + for (int j = 1; j <= n; ++j) { + for (int i = 0; i < 26; ++i) { + cnt[i][j] = cnt[i][j - 1]; + } + cnt[s[j - 1] - 'a'][j]++; + } + vector ans; + for (auto& q : queries) { + int l = q[0], r = q[1]; + ans.push_back(r - l + 1); + for (int i = 0; i < 26; ++i) { + int x = cnt[i][r + 1] - cnt[i][l]; + ans.back() += x * (x - 1) / 2; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2955.Number of Same-End Substrings/Solution.java b/solution/2900-2999/2955.Number of Same-End Substrings/Solution.java index de53839c7348c..3f5d534fe2e6e 100644 --- a/solution/2900-2999/2955.Number of Same-End Substrings/Solution.java +++ b/solution/2900-2999/2955.Number of Same-End Substrings/Solution.java @@ -1,23 +1,23 @@ -class Solution { - public int[] sameEndSubstringCount(String s, int[][] queries) { - int n = s.length(); - int[][] cnt = new int[26][n + 1]; - for (int j = 1; j <= n; ++j) { - for (int i = 0; i < 26; ++i) { - cnt[i][j] = cnt[i][j - 1]; - } - cnt[s.charAt(j - 1) - 'a'][j]++; - } - int m = queries.length; - int[] ans = new int[m]; - for (int k = 0; k < m; ++k) { - int l = queries[k][0], r = queries[k][1]; - ans[k] = r - l + 1; - for (int i = 0; i < 26; ++i) { - int x = cnt[i][r + 1] - cnt[i][l]; - ans[k] += x * (x - 1) / 2; - } - } - return ans; - } +class Solution { + public int[] sameEndSubstringCount(String s, int[][] queries) { + int n = s.length(); + int[][] cnt = new int[26][n + 1]; + for (int j = 1; j <= n; ++j) { + for (int i = 0; i < 26; ++i) { + cnt[i][j] = cnt[i][j - 1]; + } + cnt[s.charAt(j - 1) - 'a'][j]++; + } + int m = queries.length; + int[] ans = new int[m]; + for (int k = 0; k < m; ++k) { + int l = queries[k][0], r = queries[k][1]; + ans[k] = r - l + 1; + for (int i = 0; i < 26; ++i) { + int x = cnt[i][r + 1] - cnt[i][l]; + ans[k] += x * (x - 1) / 2; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2955.Number of Same-End Substrings/Solution.py b/solution/2900-2999/2955.Number of Same-End Substrings/Solution.py index aa3062a6a91e1..47a258a4782eb 100644 --- a/solution/2900-2999/2955.Number of Same-End Substrings/Solution.py +++ b/solution/2900-2999/2955.Number of Same-End Substrings/Solution.py @@ -1,17 +1,17 @@ -class Solution: - def sameEndSubstringCount(self, s: str, queries: List[List[int]]) -> List[int]: - n = len(s) - cs = set(s) - cnt = {c: [0] * (n + 1) for c in cs} - for i, a in enumerate(s, 1): - for c in cs: - cnt[c][i] = cnt[c][i - 1] - cnt[a][i] += 1 - ans = [] - for l, r in queries: - t = r - l + 1 - for c in cs: - x = cnt[c][r + 1] - cnt[c][l] - t += x * (x - 1) // 2 - ans.append(t) - return ans +class Solution: + def sameEndSubstringCount(self, s: str, queries: List[List[int]]) -> List[int]: + n = len(s) + cs = set(s) + cnt = {c: [0] * (n + 1) for c in cs} + for i, a in enumerate(s, 1): + for c in cs: + cnt[c][i] = cnt[c][i - 1] + cnt[a][i] += 1 + ans = [] + for l, r in queries: + t = r - l + 1 + for c in cs: + x = cnt[c][r + 1] - cnt[c][l] + t += x * (x - 1) // 2 + ans.append(t) + return ans diff --git a/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/Solution.cpp b/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/Solution.cpp index ccf9b66944375..901a1cbf121b5 100644 --- a/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/Solution.cpp +++ b/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/Solution.cpp @@ -1,37 +1,37 @@ -class Solution { -public: - int numberOfSets(int n, int maxDistance, vector>& roads) { - int ans = 0; - for (int mask = 0; mask < 1 << n; ++mask) { - int g[n][n]; - memset(g, 0x3f, sizeof(g)); - for (auto& e : roads) { - int u = e[0], v = e[1], w = e[2]; - if ((mask >> u & 1) & (mask >> v & 1)) { - g[u][v] = min(g[u][v], w); - g[v][u] = min(g[v][u], w); - } - } - for (int k = 0; k < n; ++k) { - if (mask >> k & 1) { - g[k][k] = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - g[i][j] = min(g[i][j], g[i][k] + g[k][j]); - } - } - } - } - int ok = 1; - for (int i = 0; i < n && ok == 1; ++i) { - for (int j = 0; j < n && ok == 1; ++j) { - if ((mask >> i & 1) & (mask >> j & 1) && g[i][j] > maxDistance) { - ok = 0; - } - } - } - ans += ok; - } - return ans; - } +class Solution { +public: + int numberOfSets(int n, int maxDistance, vector>& roads) { + int ans = 0; + for (int mask = 0; mask < 1 << n; ++mask) { + int g[n][n]; + memset(g, 0x3f, sizeof(g)); + for (auto& e : roads) { + int u = e[0], v = e[1], w = e[2]; + if ((mask >> u & 1) & (mask >> v & 1)) { + g[u][v] = min(g[u][v], w); + g[v][u] = min(g[v][u], w); + } + } + for (int k = 0; k < n; ++k) { + if (mask >> k & 1) { + g[k][k] = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + g[i][j] = min(g[i][j], g[i][k] + g[k][j]); + } + } + } + } + int ok = 1; + for (int i = 0; i < n && ok == 1; ++i) { + for (int j = 0; j < n && ok == 1; ++j) { + if ((mask >> i & 1) & (mask >> j & 1) && g[i][j] > maxDistance) { + ok = 0; + } + } + } + ans += ok; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/Solution.java b/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/Solution.java index 4cfe7461b4a4e..fb5d8de411423 100644 --- a/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/Solution.java +++ b/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/Solution.java @@ -1,40 +1,40 @@ -class Solution { - public int numberOfSets(int n, int maxDistance, int[][] roads) { - int ans = 0; - for (int mask = 0; mask < 1 << n; ++mask) { - int[][] g = new int[n][n]; - for (var e : g) { - Arrays.fill(e, 1 << 29); - } - for (var e : roads) { - int u = e[0], v = e[1], w = e[2]; - if ((mask >> u & 1) == 1 && (mask >> v & 1) == 1) { - g[u][v] = Math.min(g[u][v], w); - g[v][u] = Math.min(g[v][u], w); - } - } - for (int k = 0; k < n; ++k) { - if ((mask >> k & 1) == 1) { - g[k][k] = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); - } - } - } - } - int ok = 1; - for (int i = 0; i < n && ok == 1; ++i) { - for (int j = 0; j < n && ok == 1; ++j) { - if ((mask >> i & 1) == 1 && (mask >> j & 1) == 1) { - if (g[i][j] > maxDistance) { - ok = 0; - } - } - } - } - ans += ok; - } - return ans; - } +class Solution { + public int numberOfSets(int n, int maxDistance, int[][] roads) { + int ans = 0; + for (int mask = 0; mask < 1 << n; ++mask) { + int[][] g = new int[n][n]; + for (var e : g) { + Arrays.fill(e, 1 << 29); + } + for (var e : roads) { + int u = e[0], v = e[1], w = e[2]; + if ((mask >> u & 1) == 1 && (mask >> v & 1) == 1) { + g[u][v] = Math.min(g[u][v], w); + g[v][u] = Math.min(g[v][u], w); + } + } + for (int k = 0; k < n; ++k) { + if ((mask >> k & 1) == 1) { + g[k][k] = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); + } + } + } + } + int ok = 1; + for (int i = 0; i < n && ok == 1; ++i) { + for (int j = 0; j < n && ok == 1; ++j) { + if ((mask >> i & 1) == 1 && (mask >> j & 1) == 1) { + if (g[i][j] > maxDistance) { + ok = 0; + } + } + } + } + ans += ok; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/Solution.py b/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/Solution.py index 4f230d896c338..3ab1fdac62623 100644 --- a/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/Solution.py +++ b/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/Solution.py @@ -1,25 +1,25 @@ -class Solution: - def numberOfSets(self, n: int, maxDistance: int, roads: List[List[int]]) -> int: - ans = 0 - for mask in range(1 << n): - g = [[inf] * n for _ in range(n)] - for u, v, w in roads: - if mask >> u & 1 and mask > v & 1: - g[u][v] = min(g[u][v], w) - g[v][u] = min(g[v][u], w) - for k in range(n): - if mask >> k & 1: - g[k][k] = 0 - for i in range(n): - for j in range(n): - # g[i][j] = min(g[i][j], g[i][k] + g[k][j]) - if g[i][k] + g[k][j] < g[i][j]: - g[i][j] = g[i][k] + g[k][j] - if all( - g[i][j] <= maxDistance - for i in range(n) - for j in range(n) - if mask >> i & 1 and mask >> j & 1 - ): - ans += 1 - return ans +class Solution: + def numberOfSets(self, n: int, maxDistance: int, roads: List[List[int]]) -> int: + ans = 0 + for mask in range(1 << n): + g = [[inf] * n for _ in range(n)] + for u, v, w in roads: + if mask >> u & 1 and mask > v & 1: + g[u][v] = min(g[u][v], w) + g[v][u] = min(g[v][u], w) + for k in range(n): + if mask >> k & 1: + g[k][k] = 0 + for i in range(n): + for j in range(n): + # g[i][j] = min(g[i][j], g[i][k] + g[k][j]) + if g[i][k] + g[k][j] < g[i][j]: + g[i][j] = g[i][k] + g[k][j] + if all( + g[i][j] <= maxDistance + for i in range(n) + for j in range(n) + if mask >> i & 1 and mask >> j & 1 + ): + ans += 1 + return ans diff --git a/solution/2900-2999/2960.Count Tested Devices After Test Operations/Solution.cpp b/solution/2900-2999/2960.Count Tested Devices After Test Operations/Solution.cpp index 4d0a559c365ec..ab6cbf747a8e8 100644 --- a/solution/2900-2999/2960.Count Tested Devices After Test Operations/Solution.cpp +++ b/solution/2900-2999/2960.Count Tested Devices After Test Operations/Solution.cpp @@ -1,13 +1,13 @@ -class Solution { -public: - int countTestedDevices(vector& batteryPercentages) { - int ans = 0; - for (int x : batteryPercentages) { - x -= ans; - if (x > 0) { - ++ans; - } - } - return ans; - } +class Solution { +public: + int countTestedDevices(vector& batteryPercentages) { + int ans = 0; + for (int x : batteryPercentages) { + x -= ans; + if (x > 0) { + ++ans; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2960.Count Tested Devices After Test Operations/Solution.java b/solution/2900-2999/2960.Count Tested Devices After Test Operations/Solution.java index 93ac3c105b2f7..2cb276bfc7ae7 100644 --- a/solution/2900-2999/2960.Count Tested Devices After Test Operations/Solution.java +++ b/solution/2900-2999/2960.Count Tested Devices After Test Operations/Solution.java @@ -1,12 +1,12 @@ -class Solution { - public int countTestedDevices(int[] batteryPercentages) { - int ans = 0; - for (int x : batteryPercentages) { - x -= ans; - if (x > 0) { - ++ans; - } - } - return ans; - } +class Solution { + public int countTestedDevices(int[] batteryPercentages) { + int ans = 0; + for (int x : batteryPercentages) { + x -= ans; + if (x > 0) { + ++ans; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2960.Count Tested Devices After Test Operations/Solution.py b/solution/2900-2999/2960.Count Tested Devices After Test Operations/Solution.py index bf95721ce9c6e..524b879f5cc50 100644 --- a/solution/2900-2999/2960.Count Tested Devices After Test Operations/Solution.py +++ b/solution/2900-2999/2960.Count Tested Devices After Test Operations/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def countTestedDevices(self, batteryPercentages: List[int]) -> int: - ans = 0 - for x in batteryPercentages: - x -= ans - ans += x > 0 - return ans +class Solution: + def countTestedDevices(self, batteryPercentages: List[int]) -> int: + ans = 0 + for x in batteryPercentages: + x -= ans + ans += x > 0 + return ans diff --git a/solution/2900-2999/2961.Double Modular Exponentiation/Solution.cpp b/solution/2900-2999/2961.Double Modular Exponentiation/Solution.cpp index 369f5b75127b8..379fd604bd2af 100644 --- a/solution/2900-2999/2961.Double Modular Exponentiation/Solution.cpp +++ b/solution/2900-2999/2961.Double Modular Exponentiation/Solution.cpp @@ -1,24 +1,24 @@ -class Solution { -public: - vector getGoodIndices(vector>& variables, int target) { - vector ans; - auto qpow = [&](long long a, int n, int mod) { - long long ans = 1; - for (; n; n >>= 1) { - if (n & 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return (int) ans; - }; - for (int i = 0; i < variables.size(); ++i) { - auto e = variables[i]; - int a = e[0], b = e[1], c = e[2], m = e[3]; - if (qpow(qpow(a, b, 10), c, m) == target) { - ans.push_back(i); - } - } - return ans; - } +class Solution { +public: + vector getGoodIndices(vector>& variables, int target) { + vector ans; + auto qpow = [&](long long a, int n, int mod) { + long long ans = 1; + for (; n; n >>= 1) { + if (n & 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return (int) ans; + }; + for (int i = 0; i < variables.size(); ++i) { + auto e = variables[i]; + int a = e[0], b = e[1], c = e[2], m = e[3]; + if (qpow(qpow(a, b, 10), c, m) == target) { + ans.push_back(i); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2961.Double Modular Exponentiation/Solution.java b/solution/2900-2999/2961.Double Modular Exponentiation/Solution.java index 7618aecd76480..b675a4476d699 100644 --- a/solution/2900-2999/2961.Double Modular Exponentiation/Solution.java +++ b/solution/2900-2999/2961.Double Modular Exponentiation/Solution.java @@ -1,24 +1,24 @@ -class Solution { - public List getGoodIndices(int[][] variables, int target) { - List ans = new ArrayList<>(); - for (int i = 0; i < variables.length; ++i) { - var e = variables[i]; - int a = e[0], b = e[1], c = e[2], m = e[3]; - if (qpow(qpow(a, b, 10), c, m) == target) { - ans.add(i); - } - } - return ans; - } - - private int qpow(long a, int n, int mod) { - long ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return (int) ans; - } +class Solution { + public List getGoodIndices(int[][] variables, int target) { + List ans = new ArrayList<>(); + for (int i = 0; i < variables.length; ++i) { + var e = variables[i]; + int a = e[0], b = e[1], c = e[2], m = e[3]; + if (qpow(qpow(a, b, 10), c, m) == target) { + ans.add(i); + } + } + return ans; + } + + private int qpow(long a, int n, int mod) { + long ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return (int) ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2961.Double Modular Exponentiation/Solution.py b/solution/2900-2999/2961.Double Modular Exponentiation/Solution.py index 03c4cb37dbb95..4a749f42bcc5b 100644 --- a/solution/2900-2999/2961.Double Modular Exponentiation/Solution.py +++ b/solution/2900-2999/2961.Double Modular Exponentiation/Solution.py @@ -1,7 +1,7 @@ -class Solution: - def getGoodIndices(self, variables: List[List[int]], target: int) -> List[int]: - return [ - i - for i, (a, b, c, m) in enumerate(variables) - if pow(pow(a, b, 10), c, m) == target - ] +class Solution: + def getGoodIndices(self, variables: List[List[int]], target: int) -> List[int]: + return [ + i + for i, (a, b, c, m) in enumerate(variables) + if pow(pow(a, b, 10), c, m) == target + ] diff --git a/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/Solution.cpp b/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/Solution.cpp index c3b64b9cca4a9..296b90824eaf7 100644 --- a/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/Solution.cpp +++ b/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - long long countSubarrays(vector& nums, int k) { - int mx = *max_element(nums.begin(), nums.end()); - int n = nums.size(); - long long ans = 0; - int cnt = 0, j = 0; - for (int x : nums) { - while (j < n && cnt < k) { - cnt += nums[j++] == mx; - } - if (cnt < k) { - break; - } - ans += n - j + 1; - cnt -= x == mx; - } - return ans; - } +class Solution { +public: + long long countSubarrays(vector& nums, int k) { + int mx = *max_element(nums.begin(), nums.end()); + int n = nums.size(); + long long ans = 0; + int cnt = 0, j = 0; + for (int x : nums) { + while (j < n && cnt < k) { + cnt += nums[j++] == mx; + } + if (cnt < k) { + break; + } + ans += n - j + 1; + cnt -= x == mx; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/Solution.java b/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/Solution.java index 3be67ba5d5aa6..f12c4a03b7d1c 100644 --- a/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/Solution.java +++ b/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/Solution.java @@ -1,19 +1,19 @@ -class Solution { - public long countSubarrays(int[] nums, int k) { - int mx = Arrays.stream(nums).max().getAsInt(); - int n = nums.length; - long ans = 0; - int cnt = 0, j = 0; - for (int x : nums) { - while (j < n && cnt < k) { - cnt += nums[j++] == mx ? 1 : 0; - } - if (cnt < k) { - break; - } - ans += n - j + 1; - cnt -= x == mx ? 1 : 0; - } - return ans; - } +class Solution { + public long countSubarrays(int[] nums, int k) { + int mx = Arrays.stream(nums).max().getAsInt(); + int n = nums.length; + long ans = 0; + int cnt = 0, j = 0; + for (int x : nums) { + while (j < n && cnt < k) { + cnt += nums[j++] == mx ? 1 : 0; + } + if (cnt < k) { + break; + } + ans += n - j + 1; + cnt -= x == mx ? 1 : 0; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/Solution.py b/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/Solution.py index 57295ad6d1f00..b9e6cc3c95f79 100644 --- a/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/Solution.py +++ b/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def countSubarrays(self, nums: List[int], k: int) -> int: - mx = max(nums) - n = len(nums) - ans = cnt = j = 0 - for x in nums: - while j < n and cnt < k: - cnt += nums[j] == mx - j += 1 - if cnt < k: - break - ans += n - j + 1 - cnt -= x == mx - return ans +class Solution: + def countSubarrays(self, nums: List[int], k: int) -> int: + mx = max(nums) + n = len(nums) + ans = cnt = j = 0 + for x in nums: + while j < n and cnt < k: + cnt += nums[j] == mx + j += 1 + if cnt < k: + break + ans += n - j + 1 + cnt -= x == mx + return ans diff --git a/solution/2900-2999/2963.Count the Number of Good Partitions/Solution.cpp b/solution/2900-2999/2963.Count the Number of Good Partitions/Solution.cpp index 01d8b6dc11c2a..83785b20ae15b 100644 --- a/solution/2900-2999/2963.Count the Number of Good Partitions/Solution.cpp +++ b/solution/2900-2999/2963.Count the Number of Good Partitions/Solution.cpp @@ -1,27 +1,27 @@ -class Solution { -public: - int numberOfGoodPartitions(vector& nums) { - unordered_map last; - int n = nums.size(); - for (int i = 0; i < n; ++i) { - last[nums[i]] = i; - } - const int mod = 1e9 + 7; - int j = -1, k = 0; - for (int i = 0; i < n; ++i) { - j = max(j, last[nums[i]]); - k += i == j; - } - auto qpow = [&](long long a, int n, int mod) { - long long ans = 1; - for (; n; n >>= 1) { - if (n & 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return (int) ans; - }; - return qpow(2, k - 1, mod); - } +class Solution { +public: + int numberOfGoodPartitions(vector& nums) { + unordered_map last; + int n = nums.size(); + for (int i = 0; i < n; ++i) { + last[nums[i]] = i; + } + const int mod = 1e9 + 7; + int j = -1, k = 0; + for (int i = 0; i < n; ++i) { + j = max(j, last[nums[i]]); + k += i == j; + } + auto qpow = [&](long long a, int n, int mod) { + long long ans = 1; + for (; n; n >>= 1) { + if (n & 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return (int) ans; + }; + return qpow(2, k - 1, mod); + } }; \ No newline at end of file diff --git a/solution/2900-2999/2963.Count the Number of Good Partitions/Solution.java b/solution/2900-2999/2963.Count the Number of Good Partitions/Solution.java index 176acc9a58dda..f0db2b89a2e25 100644 --- a/solution/2900-2999/2963.Count the Number of Good Partitions/Solution.java +++ b/solution/2900-2999/2963.Count the Number of Good Partitions/Solution.java @@ -1,28 +1,28 @@ -class Solution { - public int numberOfGoodPartitions(int[] nums) { - Map last = new HashMap<>(); - int n = nums.length; - for (int i = 0; i < n; ++i) { - last.put(nums[i], i); - } - final int mod = (int) 1e9 + 7; - int j = -1; - int k = 0; - for (int i = 0; i < n; ++i) { - j = Math.max(j, last.get(nums[i])); - k += i == j ? 1 : 0; - } - return qpow(2, k - 1, mod); - } - - private int qpow(long a, int n, int mod) { - long ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return (int) ans; - } +class Solution { + public int numberOfGoodPartitions(int[] nums) { + Map last = new HashMap<>(); + int n = nums.length; + for (int i = 0; i < n; ++i) { + last.put(nums[i], i); + } + final int mod = (int) 1e9 + 7; + int j = -1; + int k = 0; + for (int i = 0; i < n; ++i) { + j = Math.max(j, last.get(nums[i])); + k += i == j ? 1 : 0; + } + return qpow(2, k - 1, mod); + } + + private int qpow(long a, int n, int mod) { + long ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return (int) ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2963.Count the Number of Good Partitions/Solution.py b/solution/2900-2999/2963.Count the Number of Good Partitions/Solution.py index f4ec00970e7c3..4f83c6c31a3d3 100644 --- a/solution/2900-2999/2963.Count the Number of Good Partitions/Solution.py +++ b/solution/2900-2999/2963.Count the Number of Good Partitions/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def numberOfGoodPartitions(self, nums: List[int]) -> int: - last = {x: i for i, x in enumerate(nums)} - mod = 10**9 + 7 - j, k = -1, 0 - for i, x in enumerate(nums): - j = max(j, last[x]) - k += i == j - return pow(2, k - 1, mod) +class Solution: + def numberOfGoodPartitions(self, nums: List[int]) -> int: + last = {x: i for i, x in enumerate(nums)} + mod = 10**9 + 7 + j, k = -1, 0 + for i, x in enumerate(nums): + j = max(j, last[x]) + k += i == j + return pow(2, k - 1, mod) diff --git a/solution/2900-2999/2964.Number of Divisible Triplet Sums/Solution.cpp b/solution/2900-2999/2964.Number of Divisible Triplet Sums/Solution.cpp index 391d2539d89f0..c354a5a93a8dc 100644 --- a/solution/2900-2999/2964.Number of Divisible Triplet Sums/Solution.cpp +++ b/solution/2900-2999/2964.Number of Divisible Triplet Sums/Solution.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - int divisibleTripletCount(vector& nums, int d) { - unordered_map cnt; - int ans = 0, n = nums.size(); - for (int j = 0; j < n; ++j) { - for (int k = j + 1; k < n; ++k) { - int x = (d - (nums[j] + nums[k]) % d) % d; - ans += cnt[x]; - } - cnt[nums[j] % d]++; - } - return ans; - } +class Solution { +public: + int divisibleTripletCount(vector& nums, int d) { + unordered_map cnt; + int ans = 0, n = nums.size(); + for (int j = 0; j < n; ++j) { + for (int k = j + 1; k < n; ++k) { + int x = (d - (nums[j] + nums[k]) % d) % d; + ans += cnt[x]; + } + cnt[nums[j] % d]++; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2964.Number of Divisible Triplet Sums/Solution.java b/solution/2900-2999/2964.Number of Divisible Triplet Sums/Solution.java index 5a6e3883e7b5c..518aba2fabeba 100644 --- a/solution/2900-2999/2964.Number of Divisible Triplet Sums/Solution.java +++ b/solution/2900-2999/2964.Number of Divisible Triplet Sums/Solution.java @@ -1,14 +1,14 @@ -class Solution { - public int divisibleTripletCount(int[] nums, int d) { - Map cnt = new HashMap<>(); - int ans = 0, n = nums.length; - for (int j = 0; j < n; ++j) { - for (int k = j + 1; k < n; ++k) { - int x = (d - (nums[j] + nums[k]) % d) % d; - ans += cnt.getOrDefault(x, 0); - } - cnt.merge(nums[j] % d, 1, Integer::sum); - } - return ans; - } +class Solution { + public int divisibleTripletCount(int[] nums, int d) { + Map cnt = new HashMap<>(); + int ans = 0, n = nums.length; + for (int j = 0; j < n; ++j) { + for (int k = j + 1; k < n; ++k) { + int x = (d - (nums[j] + nums[k]) % d) % d; + ans += cnt.getOrDefault(x, 0); + } + cnt.merge(nums[j] % d, 1, Integer::sum); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2964.Number of Divisible Triplet Sums/Solution.py b/solution/2900-2999/2964.Number of Divisible Triplet Sums/Solution.py index 07436b2ea1c28..cab1e0286553c 100644 --- a/solution/2900-2999/2964.Number of Divisible Triplet Sums/Solution.py +++ b/solution/2900-2999/2964.Number of Divisible Triplet Sums/Solution.py @@ -1,10 +1,10 @@ -class Solution: - def divisibleTripletCount(self, nums: List[int], d: int) -> int: - cnt = defaultdict(int) - ans, n = 0, len(nums) - for j in range(n): - for k in range(j + 1, n): - x = (d - (nums[j] + nums[k]) % d) % d - ans += cnt[x] - cnt[nums[j] % d] += 1 - return ans +class Solution: + def divisibleTripletCount(self, nums: List[int], d: int) -> int: + cnt = defaultdict(int) + ans, n = 0, len(nums) + for j in range(n): + for k in range(j + 1, n): + x = (d - (nums[j] + nums[k]) % d) % d + ans += cnt[x] + cnt[nums[j] % d] += 1 + return ans diff --git a/solution/2900-2999/2965.Find Missing and Repeated Values/Solution.cpp b/solution/2900-2999/2965.Find Missing and Repeated Values/Solution.cpp index a94e3d15225cc..ddfb8ec288f18 100644 --- a/solution/2900-2999/2965.Find Missing and Repeated Values/Solution.cpp +++ b/solution/2900-2999/2965.Find Missing and Repeated Values/Solution.cpp @@ -1,21 +1,21 @@ -class Solution { -public: - vector findMissingAndRepeatedValues(vector>& grid) { - int n = grid.size(); - vector cnt(n * n + 1); - vector ans(2); - for (auto& row : grid) { - for (int x : row) { - if (++cnt[x] == 2) { - ans[0] = x; - } - } - } - for (int x = 1;; ++x) { - if (cnt[x] == 0) { - ans[1] = x; - return ans; - } - } - } +class Solution { +public: + vector findMissingAndRepeatedValues(vector>& grid) { + int n = grid.size(); + vector cnt(n * n + 1); + vector ans(2); + for (auto& row : grid) { + for (int x : row) { + if (++cnt[x] == 2) { + ans[0] = x; + } + } + } + for (int x = 1;; ++x) { + if (cnt[x] == 0) { + ans[1] = x; + return ans; + } + } + } }; \ No newline at end of file diff --git a/solution/2900-2999/2965.Find Missing and Repeated Values/Solution.java b/solution/2900-2999/2965.Find Missing and Repeated Values/Solution.java index 6e16f6e31d662..6836710af4ac8 100644 --- a/solution/2900-2999/2965.Find Missing and Repeated Values/Solution.java +++ b/solution/2900-2999/2965.Find Missing and Repeated Values/Solution.java @@ -1,20 +1,20 @@ -class Solution { - public int[] findMissingAndRepeatedValues(int[][] grid) { - int n = grid.length; - int[] cnt = new int[n * n + 1]; - int[] ans = new int[2]; - for (int[] row : grid) { - for (int x : row) { - if (++cnt[x] == 2) { - ans[0] = x; - } - } - } - for (int x = 1;; ++x) { - if (cnt[x] == 0) { - ans[1] = x; - return ans; - } - } - } +class Solution { + public int[] findMissingAndRepeatedValues(int[][] grid) { + int n = grid.length; + int[] cnt = new int[n * n + 1]; + int[] ans = new int[2]; + for (int[] row : grid) { + for (int x : row) { + if (++cnt[x] == 2) { + ans[0] = x; + } + } + } + for (int x = 1;; ++x) { + if (cnt[x] == 0) { + ans[1] = x; + return ans; + } + } + } } \ No newline at end of file diff --git a/solution/2900-2999/2965.Find Missing and Repeated Values/Solution.py b/solution/2900-2999/2965.Find Missing and Repeated Values/Solution.py index 71e02fe1cf02f..c065ea2ed3496 100644 --- a/solution/2900-2999/2965.Find Missing and Repeated Values/Solution.py +++ b/solution/2900-2999/2965.Find Missing and Repeated Values/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]: - n = len(grid) - cnt = [0] * (n * n + 1) - for row in grid: - for v in row: - cnt[v] += 1 - ans = [0] * 2 - for i in range(1, n * n + 1): - if cnt[i] == 2: - ans[0] = i - if cnt[i] == 0: - ans[1] = i - return ans +class Solution: + def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]: + n = len(grid) + cnt = [0] * (n * n + 1) + for row in grid: + for v in row: + cnt[v] += 1 + ans = [0] * 2 + for i in range(1, n * n + 1): + if cnt[i] == 2: + ans[0] = i + if cnt[i] == 0: + ans[1] = i + return ans diff --git a/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/Solution.cpp b/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/Solution.cpp index 9eba2fe563175..d26714eecdc3a 100644 --- a/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/Solution.cpp +++ b/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/Solution.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - vector> divideArray(vector& nums, int k) { - sort(nums.begin(), nums.end()); - vector> ans; - int n = nums.size(); - for (int i = 0; i < n; i += 3) { - vector t = {nums[i], nums[i + 1], nums[i + 2]}; - if (t[2] - t[0] > k) { - return {}; - } - ans.emplace_back(t); - } - return ans; - } +class Solution { +public: + vector> divideArray(vector& nums, int k) { + sort(nums.begin(), nums.end()); + vector> ans; + int n = nums.size(); + for (int i = 0; i < n; i += 3) { + vector t = {nums[i], nums[i + 1], nums[i + 2]}; + if (t[2] - t[0] > k) { + return {}; + } + ans.emplace_back(t); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/Solution.java b/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/Solution.java index 0497818388191..306dac971993b 100644 --- a/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/Solution.java +++ b/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/Solution.java @@ -1,15 +1,15 @@ -class Solution { - public int[][] divideArray(int[] nums, int k) { - Arrays.sort(nums); - int n = nums.length; - int[][] ans = new int[n / 3][]; - for (int i = 0; i < n; i += 3) { - int[] t = Arrays.copyOfRange(nums, i, i + 3); - if (t[2] - t[0] > k) { - return new int[][] {}; - } - ans[i / 3] = t; - } - return ans; - } +class Solution { + public int[][] divideArray(int[] nums, int k) { + Arrays.sort(nums); + int n = nums.length; + int[][] ans = new int[n / 3][]; + for (int i = 0; i < n; i += 3) { + int[] t = Arrays.copyOfRange(nums, i, i + 3); + if (t[2] - t[0] > k) { + return new int[][] {}; + } + ans[i / 3] = t; + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/Solution.py b/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/Solution.py index 9b1bd2b3f8c1e..8c6496d28af4b 100644 --- a/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/Solution.py +++ b/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/Solution.py @@ -1,11 +1,11 @@ -class Solution: - def divideArray(self, nums: List[int], k: int) -> List[List[int]]: - nums.sort() - ans = [] - n = len(nums) - for i in range(0, n, 3): - t = nums[i : i + 3] - if t[2] - t[0] > k: - return [] - ans.append(t) - return ans +class Solution: + def divideArray(self, nums: List[int], k: int) -> List[List[int]]: + nums.sort() + ans = [] + n = len(nums) + for i in range(0, n, 3): + t = nums[i : i + 3] + if t[2] - t[0] > k: + return [] + ans.append(t) + return ans diff --git a/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/Solution.cpp b/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/Solution.cpp index 923c31f196570..3d3026343ff59 100644 --- a/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/Solution.cpp +++ b/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/Solution.cpp @@ -1,39 +1,39 @@ -using ll = long long; - -ll ps[2 * 100000]; - -int init = [] { - for (int i = 1; i <= 100000; i++) { - string s = to_string(i); - string t1 = s; - reverse(t1.begin(), t1.end()); - string t2 = s.substr(0, s.length() - 1); - reverse(t2.begin(), t2.end()); - ps[2 * i - 2] = stoll(s + t1); - ps[2 * i - 1] = stoll(s + t2); - } - sort(ps, ps + 2 * 100000); - return 0; -}(); - -class Solution { -public: - long long minimumCost(vector& nums) { - sort(nums.begin(), nums.end()); - int i = lower_bound(ps, ps + 2 * 100000, nums[nums.size() / 2]) - ps; - auto f = [&](ll x) { - ll ans = 0; - for (int& v : nums) { - ans += abs(v - x); - } - return ans; - }; - ll ans = LLONG_MAX; - for (int j = i - 1; j <= i + 1; j++) { - if (0 <= j && j < 2 * 100000) { - ans = min(ans, f(ps[j])); - } - } - return ans; - } +using ll = long long; + +ll ps[2 * 100000]; + +int init = [] { + for (int i = 1; i <= 100000; i++) { + string s = to_string(i); + string t1 = s; + reverse(t1.begin(), t1.end()); + string t2 = s.substr(0, s.length() - 1); + reverse(t2.begin(), t2.end()); + ps[2 * i - 2] = stoll(s + t1); + ps[2 * i - 1] = stoll(s + t2); + } + sort(ps, ps + 2 * 100000); + return 0; +}(); + +class Solution { +public: + long long minimumCost(vector& nums) { + sort(nums.begin(), nums.end()); + int i = lower_bound(ps, ps + 2 * 100000, nums[nums.size() / 2]) - ps; + auto f = [&](ll x) { + ll ans = 0; + for (int& v : nums) { + ans += abs(v - x); + } + return ans; + }; + ll ans = LLONG_MAX; + for (int j = i - 1; j <= i + 1; j++) { + if (0 <= j && j < 2 * 100000) { + ans = min(ans, f(ps[j])); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/Solution.java b/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/Solution.java index a5fcc83957b9c..3ac1fcb5d2d27 100644 --- a/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/Solution.java +++ b/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/Solution.java @@ -1,38 +1,38 @@ -public class Solution { - private static long[] ps; - private int[] nums; - - static { - ps = new long[2 * (int) 1e5]; - for (int i = 1; i <= 1e5; i++) { - String s = Integer.toString(i); - String t1 = new StringBuilder(s).reverse().toString(); - String t2 = new StringBuilder(s.substring(0, s.length() - 1)).reverse().toString(); - ps[2 * i - 2] = Long.parseLong(s + t1); - ps[2 * i - 1] = Long.parseLong(s + t2); - } - Arrays.sort(ps); - } - - public long minimumCost(int[] nums) { - this.nums = nums; - Arrays.sort(nums); - int i = Arrays.binarySearch(ps, nums[nums.length / 2]); - i = i < 0 ? -i - 1 : i; - long ans = 1L << 60; - for (int j = i - 1; j <= i + 1; j++) { - if (0 <= j && j < ps.length) { - ans = Math.min(ans, f(ps[j])); - } - } - return ans; - } - - private long f(long x) { - long ans = 0; - for (int v : nums) { - ans += Math.abs(v - x); - } - return ans; - } +public class Solution { + private static long[] ps; + private int[] nums; + + static { + ps = new long[2 * (int) 1e5]; + for (int i = 1; i <= 1e5; i++) { + String s = Integer.toString(i); + String t1 = new StringBuilder(s).reverse().toString(); + String t2 = new StringBuilder(s.substring(0, s.length() - 1)).reverse().toString(); + ps[2 * i - 2] = Long.parseLong(s + t1); + ps[2 * i - 1] = Long.parseLong(s + t2); + } + Arrays.sort(ps); + } + + public long minimumCost(int[] nums) { + this.nums = nums; + Arrays.sort(nums); + int i = Arrays.binarySearch(ps, nums[nums.length / 2]); + i = i < 0 ? -i - 1 : i; + long ans = 1L << 60; + for (int j = i - 1; j <= i + 1; j++) { + if (0 <= j && j < ps.length) { + ans = Math.min(ans, f(ps[j])); + } + } + return ans; + } + + private long f(long x) { + long ans = 0; + for (int v : nums) { + ans += Math.abs(v - x); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/Solution.py b/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/Solution.py index 602f8df4810ee..e2954772a038f 100644 --- a/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/Solution.py +++ b/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/Solution.py @@ -1,18 +1,18 @@ -ps = [] -for i in range(1, 10**5 + 1): - s = str(i) - t1 = s[::-1] - t2 = s[:-1][::-1] - ps.append(int(s + t1)) - ps.append(int(s + t2)) -ps.sort() - - -class Solution: - def minimumCost(self, nums: List[int]) -> int: - def f(x: int) -> int: - return sum(abs(v - x) for v in nums) - - nums.sort() - i = bisect_left(ps, nums[len(nums) // 2]) - return min(f(ps[j]) for j in range(i - 1, i + 2) if 0 <= j < len(ps)) +ps = [] +for i in range(1, 10**5 + 1): + s = str(i) + t1 = s[::-1] + t2 = s[:-1][::-1] + ps.append(int(s + t1)) + ps.append(int(s + t2)) +ps.sort() + + +class Solution: + def minimumCost(self, nums: List[int]) -> int: + def f(x: int) -> int: + return sum(abs(v - x) for v in nums) + + nums.sort() + i = bisect_left(ps, nums[len(nums) // 2]) + return min(f(ps[j]) for j in range(i - 1, i + 2) if 0 <= j < len(ps)) diff --git a/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/Solution.cpp b/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/Solution.cpp index 4f8653ba8856a..b3335b42c2156 100644 --- a/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/Solution.cpp +++ b/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/Solution.cpp @@ -1,37 +1,37 @@ -class Solution { -public: - int maxFrequencyScore(vector& nums, long long k) { - sort(nums.begin(), nums.end()); - int n = nums.size(); - vector s(n + 1, 0); - for (int i = 1; i <= n; i++) { - s[i] = s[i - 1] + nums[i - 1]; - } - - int l = 0, r = n; - while (l < r) { - int mid = (l + r + 1) >> 1; - bool ok = false; - - for (int i = 0; i <= n - mid; i++) { - int j = i + mid; - int x = nums[(i + j) / 2]; - long long left = ((i + j) / 2 - i) * (long long) x - (s[(i + j) / 2] - s[i]); - long long right = (s[j] - s[(i + j) / 2]) - ((j - (i + j) / 2) * (long long) x); - - if (left + right <= k) { - ok = true; - break; - } - } - - if (ok) { - l = mid; - } else { - r = mid - 1; - } - } - - return l; - } +class Solution { +public: + int maxFrequencyScore(vector& nums, long long k) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + vector s(n + 1, 0); + for (int i = 1; i <= n; i++) { + s[i] = s[i - 1] + nums[i - 1]; + } + + int l = 0, r = n; + while (l < r) { + int mid = (l + r + 1) >> 1; + bool ok = false; + + for (int i = 0; i <= n - mid; i++) { + int j = i + mid; + int x = nums[(i + j) / 2]; + long long left = ((i + j) / 2 - i) * (long long) x - (s[(i + j) / 2] - s[i]); + long long right = (s[j] - s[(i + j) / 2]) - ((j - (i + j) / 2) * (long long) x); + + if (left + right <= k) { + ok = true; + break; + } + } + + if (ok) { + l = mid; + } else { + r = mid - 1; + } + } + + return l; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/Solution.java b/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/Solution.java index 4419fce9c5fbb..45cfdd8021c4e 100644 --- a/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/Solution.java +++ b/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/Solution.java @@ -1,34 +1,34 @@ -class Solution { - public int maxFrequencyScore(int[] nums, long k) { - Arrays.sort(nums); - int n = nums.length; - long[] s = new long[n + 1]; - for (int i = 1; i <= n; i++) { - s[i] = s[i - 1] + nums[i - 1]; - } - int l = 0, r = n; - while (l < r) { - int mid = (l + r + 1) >> 1; - boolean ok = false; - - for (int i = 0; i <= n - mid; i++) { - int j = i + mid; - int x = nums[(i + j) / 2]; - long left = ((i + j) / 2 - i) * (long) x - (s[(i + j) / 2] - s[i]); - long right = (s[j] - s[(i + j) / 2]) - ((j - (i + j) / 2) * (long) x); - if (left + right <= k) { - ok = true; - break; - } - } - - if (ok) { - l = mid; - } else { - r = mid - 1; - } - } - - return l; - } +class Solution { + public int maxFrequencyScore(int[] nums, long k) { + Arrays.sort(nums); + int n = nums.length; + long[] s = new long[n + 1]; + for (int i = 1; i <= n; i++) { + s[i] = s[i - 1] + nums[i - 1]; + } + int l = 0, r = n; + while (l < r) { + int mid = (l + r + 1) >> 1; + boolean ok = false; + + for (int i = 0; i <= n - mid; i++) { + int j = i + mid; + int x = nums[(i + j) / 2]; + long left = ((i + j) / 2 - i) * (long) x - (s[(i + j) / 2] - s[i]); + long right = (s[j] - s[(i + j) / 2]) - ((j - (i + j) / 2) * (long) x); + if (left + right <= k) { + ok = true; + break; + } + } + + if (ok) { + l = mid; + } else { + r = mid - 1; + } + } + + return l; + } } \ No newline at end of file diff --git a/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/Solution.py b/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/Solution.py index 5ac1360566fcc..9b6199eb0d63e 100644 --- a/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/Solution.py +++ b/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/Solution.py @@ -1,22 +1,22 @@ -class Solution: - def maxFrequencyScore(self, nums: List[int], k: int) -> int: - nums.sort() - s = list(accumulate(nums, initial=0)) - n = len(nums) - l, r = 0, n - while l < r: - mid = (l + r + 1) >> 1 - ok = False - for i in range(n - mid + 1): - j = i + mid - x = nums[(i + j) // 2] - left = ((i + j) // 2 - i) * x - (s[(i + j) // 2] - s[i]) - right = (s[j] - s[(i + j) // 2]) - ((j - (i + j) // 2) * x) - if left + right <= k: - ok = True - break - if ok: - l = mid - else: - r = mid - 1 - return l +class Solution: + def maxFrequencyScore(self, nums: List[int], k: int) -> int: + nums.sort() + s = list(accumulate(nums, initial=0)) + n = len(nums) + l, r = 0, n + while l < r: + mid = (l + r + 1) >> 1 + ok = False + for i in range(n - mid + 1): + j = i + mid + x = nums[(i + j) // 2] + left = ((i + j) // 2 - i) * x - (s[(i + j) // 2] - s[i]) + right = (s[j] - s[(i + j) // 2]) - ((j - (i + j) // 2) * x) + if left + right <= k: + ok = True + break + if ok: + l = mid + else: + r = mid - 1 + return l diff --git a/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/Solution.cpp b/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/Solution.cpp index bc08a9d286478..f5c64a192ddb5 100644 --- a/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/Solution.cpp +++ b/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/Solution.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - int minimumCoins(vector& prices) { - int n = prices.size(); - deque q; - for (int i = n; i; --i) { - while (q.size() && q.front() > i * 2 + 1) { - q.pop_front(); - } - if (i <= (n - 1) / 2) { - prices[i - 1] += prices[q.front() - 1]; - } - while (q.size() && prices[q.back() - 1] >= prices[i - 1]) { - q.pop_back(); - } - q.push_back(i); - } - return prices[0]; - } +class Solution { +public: + int minimumCoins(vector& prices) { + int n = prices.size(); + deque q; + for (int i = n; i; --i) { + while (q.size() && q.front() > i * 2 + 1) { + q.pop_front(); + } + if (i <= (n - 1) / 2) { + prices[i - 1] += prices[q.front() - 1]; + } + while (q.size() && prices[q.back() - 1] >= prices[i - 1]) { + q.pop_back(); + } + q.push_back(i); + } + return prices[0]; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/Solution.java b/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/Solution.java index 9bb813265fb1d..735143f139a0b 100644 --- a/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/Solution.java +++ b/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/Solution.java @@ -1,19 +1,19 @@ -class Solution { - public int minimumCoins(int[] prices) { - int n = prices.length; - Deque q = new ArrayDeque<>(); - for (int i = n; i > 0; --i) { - while (!q.isEmpty() && q.peek() > i * 2 + 1) { - q.poll(); - } - if (i <= (n - 1) / 2) { - prices[i - 1] += prices[q.peek() - 1]; - } - while (!q.isEmpty() && prices[q.peekLast() - 1] >= prices[i - 1]) { - q.pollLast(); - } - q.offer(i); - } - return prices[0]; - } +class Solution { + public int minimumCoins(int[] prices) { + int n = prices.length; + Deque q = new ArrayDeque<>(); + for (int i = n; i > 0; --i) { + while (!q.isEmpty() && q.peek() > i * 2 + 1) { + q.poll(); + } + if (i <= (n - 1) / 2) { + prices[i - 1] += prices[q.peek() - 1]; + } + while (!q.isEmpty() && prices[q.peekLast() - 1] >= prices[i - 1]) { + q.pollLast(); + } + q.offer(i); + } + return prices[0]; + } } \ No newline at end of file diff --git a/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/Solution.py b/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/Solution.py index 84d6cbab58ecf..00e61cb0b4849 100644 --- a/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/Solution.py +++ b/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def minimumCoins(self, prices: List[int]) -> int: - n = len(prices) - q = deque() - for i in range(n, 0, -1): - while q and q[0] > i * 2 + 1: - q.popleft() - if i <= (n - 1) // 2: - prices[i - 1] += prices[q[0] - 1] - while q and prices[q[-1] - 1] >= prices[i - 1]: - q.pop() - q.append(i) - return prices[0] +class Solution: + def minimumCoins(self, prices: List[int]) -> int: + n = len(prices) + q = deque() + for i in range(n, 0, -1): + while q and q[0] > i * 2 + 1: + q.popleft() + if i <= (n - 1) // 2: + prices[i - 1] += prices[q[0] - 1] + while q and prices[q[-1] - 1] >= prices[i - 1]: + q.pop() + q.append(i) + return prices[0] diff --git a/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/Solution.cpp b/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/Solution.cpp index 0552b41161087..10bfd4ee5dc24 100644 --- a/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/Solution.cpp +++ b/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - int incremovableSubarrayCount(vector& nums) { - int i = 0, n = nums.size(); - while (i + 1 < n && nums[i] < nums[i + 1]) { - ++i; - } - if (i == n - 1) { - return n * (n + 1) / 2; - } - int ans = i + 2; - for (int j = n - 1; j > 0; --j) { - while (i >= 0 && nums[i] >= nums[j]) { - --i; - } - ans += i + 2; - if (nums[j - 1] >= nums[j]) { - break; - } - } - return ans; - } +class Solution { +public: + int incremovableSubarrayCount(vector& nums) { + int i = 0, n = nums.size(); + while (i + 1 < n && nums[i] < nums[i + 1]) { + ++i; + } + if (i == n - 1) { + return n * (n + 1) / 2; + } + int ans = i + 2; + for (int j = n - 1; j > 0; --j) { + while (i >= 0 && nums[i] >= nums[j]) { + --i; + } + ans += i + 2; + if (nums[j - 1] >= nums[j]) { + break; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/Solution.java b/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/Solution.java index be32703d17742..bbccac6001bf1 100644 --- a/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/Solution.java +++ b/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/Solution.java @@ -1,22 +1,22 @@ -class Solution { - public int incremovableSubarrayCount(int[] nums) { - int i = 0, n = nums.length; - while (i + 1 < n && nums[i] < nums[i + 1]) { - ++i; - } - if (i == n - 1) { - return n * (n + 1) / 2; - } - int ans = i + 2; - for (int j = n - 1; j > 0; --j) { - while (i >= 0 && nums[i] >= nums[j]) { - --i; - } - ans += i + 2; - if (nums[j - 1] >= nums[j]) { - break; - } - } - return ans; - } +class Solution { + public int incremovableSubarrayCount(int[] nums) { + int i = 0, n = nums.length; + while (i + 1 < n && nums[i] < nums[i + 1]) { + ++i; + } + if (i == n - 1) { + return n * (n + 1) / 2; + } + int ans = i + 2; + for (int j = n - 1; j > 0; --j) { + while (i >= 0 && nums[i] >= nums[j]) { + --i; + } + ans += i + 2; + if (nums[j - 1] >= nums[j]) { + break; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/Solution.py b/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/Solution.py index 725e275250eac..a7c78027911d6 100644 --- a/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/Solution.py +++ b/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/Solution.py @@ -1,17 +1,17 @@ -class Solution: - def incremovableSubarrayCount(self, nums: List[int]) -> int: - i, n = 0, len(nums) - while i + 1 < n and nums[i] < nums[i + 1]: - i += 1 - if i == n - 1: - return n * (n + 1) // 2 - ans = i + 2 - j = n - 1 - while j: - while i >= 0 and nums[i] >= nums[j]: - i -= 1 - ans += i + 2 - if nums[j - 1] >= nums[j]: - break - j -= 1 - return ans +class Solution: + def incremovableSubarrayCount(self, nums: List[int]) -> int: + i, n = 0, len(nums) + while i + 1 < n and nums[i] < nums[i + 1]: + i += 1 + if i == n - 1: + return n * (n + 1) // 2 + ans = i + 2 + j = n - 1 + while j: + while i >= 0 and nums[i] >= nums[j]: + i -= 1 + ans += i + 2 + if nums[j - 1] >= nums[j]: + break + j -= 1 + return ans diff --git a/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/Solution.cpp b/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/Solution.cpp index 0b89a458a5e72..c2e27236195ba 100644 --- a/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/Solution.cpp +++ b/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/Solution.cpp @@ -1,18 +1,18 @@ -class Solution { -public: - long long largestPerimeter(vector& nums) { - sort(nums.begin(), nums.end()); - int n = nums.size(); - vector s(n + 1); - for (int i = 1; i <= n; ++i) { - s[i] = s[i - 1] + nums[i - 1]; - } - long long ans = -1; - for (int k = 3; k <= n; ++k) { - if (s[k - 1] > nums[k - 1]) { - ans = max(ans, s[k]); - } - } - return ans; - } +class Solution { +public: + long long largestPerimeter(vector& nums) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + vector s(n + 1); + for (int i = 1; i <= n; ++i) { + s[i] = s[i - 1] + nums[i - 1]; + } + long long ans = -1; + for (int k = 3; k <= n; ++k) { + if (s[k - 1] > nums[k - 1]) { + ans = max(ans, s[k]); + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/Solution.java b/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/Solution.java index 53f7f6db2e747..f826c5e455aef 100644 --- a/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/Solution.java +++ b/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/Solution.java @@ -1,17 +1,17 @@ -class Solution { - public long largestPerimeter(int[] nums) { - Arrays.sort(nums); - int n = nums.length; - long[] s = new long[n + 1]; - for (int i = 1; i <= n; ++i) { - s[i] = s[i - 1] + nums[i - 1]; - } - long ans = -1; - for (int k = 3; k <= n; ++k) { - if (s[k - 1] > nums[k - 1]) { - ans = Math.max(ans, s[k]); - } - } - return ans; - } +class Solution { + public long largestPerimeter(int[] nums) { + Arrays.sort(nums); + int n = nums.length; + long[] s = new long[n + 1]; + for (int i = 1; i <= n; ++i) { + s[i] = s[i - 1] + nums[i - 1]; + } + long ans = -1; + for (int k = 3; k <= n; ++k) { + if (s[k - 1] > nums[k - 1]) { + ans = Math.max(ans, s[k]); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/Solution.py b/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/Solution.py index f7665aaf24b86..05a6b4c4f1eed 100644 --- a/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/Solution.py +++ b/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/Solution.py @@ -1,9 +1,9 @@ -class Solution: - def largestPerimeter(self, nums: List[int]) -> int: - nums.sort() - s = list(accumulate(nums, initial=0)) - ans = -1 - for k in range(3, len(nums) + 1): - if s[k - 1] > nums[k - 1]: - ans = max(ans, s[k]) - return ans +class Solution: + def largestPerimeter(self, nums: List[int]) -> int: + nums.sort() + s = list(accumulate(nums, initial=0)) + ans = -1 + for k in range(3, len(nums) + 1): + if s[k - 1] > nums[k - 1]: + ans = max(ans, s[k]) + return ans diff --git a/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/Solution.cpp b/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/Solution.cpp index f35a835d0a07c..e4c21ed656121 100644 --- a/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/Solution.cpp +++ b/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/Solution.cpp @@ -1,23 +1,23 @@ -class Solution { -public: - long long incremovableSubarrayCount(vector& nums) { - int i = 0, n = nums.size(); - while (i + 1 < n && nums[i] < nums[i + 1]) { - ++i; - } - if (i == n - 1) { - return n * (n + 1LL) / 2; - } - long long ans = i + 2; - for (int j = n - 1; j > 0; --j) { - while (i >= 0 && nums[i] >= nums[j]) { - --i; - } - ans += i + 2; - if (nums[j - 1] >= nums[j]) { - break; - } - } - return ans; - } +class Solution { +public: + long long incremovableSubarrayCount(vector& nums) { + int i = 0, n = nums.size(); + while (i + 1 < n && nums[i] < nums[i + 1]) { + ++i; + } + if (i == n - 1) { + return n * (n + 1LL) / 2; + } + long long ans = i + 2; + for (int j = n - 1; j > 0; --j) { + while (i >= 0 && nums[i] >= nums[j]) { + --i; + } + ans += i + 2; + if (nums[j - 1] >= nums[j]) { + break; + } + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/Solution.java b/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/Solution.java index e3d7354b5ae2a..3ea6ae1c1b158 100644 --- a/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/Solution.java +++ b/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/Solution.java @@ -1,22 +1,22 @@ -class Solution { - public long incremovableSubarrayCount(int[] nums) { - int i = 0, n = nums.length; - while (i + 1 < n && nums[i] < nums[i + 1]) { - ++i; - } - if (i == n - 1) { - return n * (n + 1L) / 2; - } - long ans = i + 2; - for (int j = n - 1; j > 0; --j) { - while (i >= 0 && nums[i] >= nums[j]) { - --i; - } - ans += i + 2; - if (nums[j - 1] >= nums[j]) { - break; - } - } - return ans; - } +class Solution { + public long incremovableSubarrayCount(int[] nums) { + int i = 0, n = nums.length; + while (i + 1 < n && nums[i] < nums[i + 1]) { + ++i; + } + if (i == n - 1) { + return n * (n + 1L) / 2; + } + long ans = i + 2; + for (int j = n - 1; j > 0; --j) { + while (i >= 0 && nums[i] >= nums[j]) { + --i; + } + ans += i + 2; + if (nums[j - 1] >= nums[j]) { + break; + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/Solution.py b/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/Solution.py index 725e275250eac..a7c78027911d6 100644 --- a/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/Solution.py +++ b/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/Solution.py @@ -1,17 +1,17 @@ -class Solution: - def incremovableSubarrayCount(self, nums: List[int]) -> int: - i, n = 0, len(nums) - while i + 1 < n and nums[i] < nums[i + 1]: - i += 1 - if i == n - 1: - return n * (n + 1) // 2 - ans = i + 2 - j = n - 1 - while j: - while i >= 0 and nums[i] >= nums[j]: - i -= 1 - ans += i + 2 - if nums[j - 1] >= nums[j]: - break - j -= 1 - return ans +class Solution: + def incremovableSubarrayCount(self, nums: List[int]) -> int: + i, n = 0, len(nums) + while i + 1 < n and nums[i] < nums[i + 1]: + i += 1 + if i == n - 1: + return n * (n + 1) // 2 + ans = i + 2 + j = n - 1 + while j: + while i >= 0 and nums[i] >= nums[j]: + i -= 1 + ans += i + 2 + if nums[j - 1] >= nums[j]: + break + j -= 1 + return ans diff --git a/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/Solution.cpp b/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/Solution.cpp index ee70fab9eee45..9d1eb68c7c761 100644 --- a/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/Solution.cpp +++ b/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/Solution.cpp @@ -1,35 +1,35 @@ -class Solution { -public: - vector placedCoins(vector>& edges, vector& cost) { - int n = cost.size(); - vector ans(n, 1); - vector g[n]; - for (auto& e : edges) { - int a = e[0], b = e[1]; - g[a].push_back(b); - g[b].push_back(a); - } - function(int, int)> dfs = [&](int a, int fa) -> vector { - vector res = {cost[a]}; - for (int b : g[a]) { - if (b != fa) { - auto t = dfs(b, a); - res.insert(res.end(), t.begin(), t.end()); - } - } - sort(res.begin(), res.end()); - int m = res.size(); - if (m >= 3) { - long long x = 1LL * res[m - 1] * res[m - 2] * res[m - 3]; - long long y = 1LL * res[0] * res[1] * res[m - 1]; - ans[a] = max({0LL, x, y}); - } - if (m >= 5) { - res = {res[0], res[1], res[m - 1], res[m - 2], res[m - 3]}; - } - return res; - }; - dfs(0, -1); - return ans; - } +class Solution { +public: + vector placedCoins(vector>& edges, vector& cost) { + int n = cost.size(); + vector ans(n, 1); + vector g[n]; + for (auto& e : edges) { + int a = e[0], b = e[1]; + g[a].push_back(b); + g[b].push_back(a); + } + function(int, int)> dfs = [&](int a, int fa) -> vector { + vector res = {cost[a]}; + for (int b : g[a]) { + if (b != fa) { + auto t = dfs(b, a); + res.insert(res.end(), t.begin(), t.end()); + } + } + sort(res.begin(), res.end()); + int m = res.size(); + if (m >= 3) { + long long x = 1LL * res[m - 1] * res[m - 2] * res[m - 3]; + long long y = 1LL * res[0] * res[1] * res[m - 1]; + ans[a] = max({0LL, x, y}); + } + if (m >= 5) { + res = {res[0], res[1], res[m - 1], res[m - 2], res[m - 3]}; + } + return res; + }; + dfs(0, -1); + return ans; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/Solution.java b/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/Solution.java index 18c9c59645e08..ffabfc6692fae 100644 --- a/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/Solution.java +++ b/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/Solution.java @@ -1,42 +1,42 @@ -class Solution { - private int[] cost; - private List[] g; - private long[] ans; - - public long[] placedCoins(int[][] edges, int[] cost) { - int n = cost.length; - this.cost = cost; - ans = new long[n]; - g = new List[n]; - Arrays.fill(ans, 1); - Arrays.setAll(g, i -> new ArrayList<>()); - for (int[] e : edges) { - int a = e[0], b = e[1]; - g[a].add(b); - g[b].add(a); - } - dfs(0, -1); - return ans; - } - - private List dfs(int a, int fa) { - List res = new ArrayList<>(); - res.add(cost[a]); - for (int b : g[a]) { - if (b != fa) { - res.addAll(dfs(b, a)); - } - } - Collections.sort(res); - int m = res.size(); - if (m >= 3) { - long x = (long) res.get(m - 1) * res.get(m - 2) * res.get(m - 3); - long y = (long) res.get(0) * res.get(1) * res.get(m - 1); - ans[a] = Math.max(0, Math.max(x, y)); - } - if (m >= 5) { - res = List.of(res.get(0), res.get(1), res.get(m - 3), res.get(m - 2), res.get(m - 1)); - } - return res; - } +class Solution { + private int[] cost; + private List[] g; + private long[] ans; + + public long[] placedCoins(int[][] edges, int[] cost) { + int n = cost.length; + this.cost = cost; + ans = new long[n]; + g = new List[n]; + Arrays.fill(ans, 1); + Arrays.setAll(g, i -> new ArrayList<>()); + for (int[] e : edges) { + int a = e[0], b = e[1]; + g[a].add(b); + g[b].add(a); + } + dfs(0, -1); + return ans; + } + + private List dfs(int a, int fa) { + List res = new ArrayList<>(); + res.add(cost[a]); + for (int b : g[a]) { + if (b != fa) { + res.addAll(dfs(b, a)); + } + } + Collections.sort(res); + int m = res.size(); + if (m >= 3) { + long x = (long) res.get(m - 1) * res.get(m - 2) * res.get(m - 3); + long y = (long) res.get(0) * res.get(1) * res.get(m - 1); + ans[a] = Math.max(0, Math.max(x, y)); + } + if (m >= 5) { + res = List.of(res.get(0), res.get(1), res.get(m - 3), res.get(m - 2), res.get(m - 1)); + } + return res; + } } \ No newline at end of file diff --git a/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/Solution.py b/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/Solution.py index 64e34a120712c..f535dd6c7f645 100644 --- a/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/Solution.py +++ b/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/Solution.py @@ -1,22 +1,22 @@ -class Solution: - def placedCoins(self, edges: List[List[int]], cost: List[int]) -> List[int]: - def dfs(a: int, fa: int) -> List[int]: - res = [cost[a]] - for b in g[a]: - if b != fa: - res.extend(dfs(b, a)) - res.sort() - if len(res) >= 3: - ans[a] = max(res[-3] * res[-2] * res[-1], res[0] * res[1] * res[-1], 0) - if len(res) > 5: - res = res[:2] + res[-3:] - return res - - n = len(cost) - g = [[] for _ in range(n)] - for a, b in edges: - g[a].append(b) - g[b].append(a) - ans = [1] * n - dfs(0, -1) - return ans +class Solution: + def placedCoins(self, edges: List[List[int]], cost: List[int]) -> List[int]: + def dfs(a: int, fa: int) -> List[int]: + res = [cost[a]] + for b in g[a]: + if b != fa: + res.extend(dfs(b, a)) + res.sort() + if len(res) >= 3: + ans[a] = max(res[-3] * res[-2] * res[-1], res[0] * res[1] * res[-1], 0) + if len(res) > 5: + res = res[:2] + res[-3:] + return res + + n = len(cost) + g = [[] for _ in range(n)] + for a, b in edges: + g[a].append(b) + g[b].append(a) + ans = [1] * n + dfs(0, -1) + return ans diff --git a/solution/2900-2999/2974.Minimum Number Game/Solution.cpp b/solution/2900-2999/2974.Minimum Number Game/Solution.cpp index a0dda318cda5c..c18b438b58cef 100644 --- a/solution/2900-2999/2974.Minimum Number Game/Solution.cpp +++ b/solution/2900-2999/2974.Minimum Number Game/Solution.cpp @@ -1,11 +1,19 @@ class Solution { public: vector numberGame(vector& nums) { - sort(nums.begin(), nums.end()); - int n = nums.size(); - for (int i = 0; i < n; i += 2) { - swap(nums[i], nums[i + 1]); + priority_queue, greater> pq; + for (int x : nums) { + pq.push(x); } - return nums; + vector ans; + while (pq.size()) { + int a = pq.top(); + pq.pop(); + int b = pq.top(); + pq.pop(); + ans.push_back(b); + ans.push_back(a); + } + return ans; } }; \ No newline at end of file diff --git a/solution/2900-2999/2974.Minimum Number Game/Solution.go b/solution/2900-2999/2974.Minimum Number Game/Solution.go index 3fbf2a35ca2cd..64f7e0e0c83ec 100644 --- a/solution/2900-2999/2974.Minimum Number Game/Solution.go +++ b/solution/2900-2999/2974.Minimum Number Game/Solution.go @@ -1,7 +1,25 @@ -func numberGame(nums []int) []int { - sort.Ints(nums) - for i := 0; i < len(nums); i += 2 { - nums[i], nums[i+1] = nums[i+1], nums[i] +func numberGame(nums []int) (ans []int) { + pq := &hp{nums} + heap.Init(pq) + for pq.Len() > 0 { + a := heap.Pop(pq).(int) + b := heap.Pop(pq).(int) + ans = append(ans, b) + ans = append(ans, a) } - return nums + return +} + +type hp struct{ sort.IntSlice } + +func (h *hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] } +func (h *hp) Pop() interface{} { + old := h.IntSlice + n := len(old) + x := old[n-1] + h.IntSlice = old[0 : n-1] + return x +} +func (h *hp) Push(x interface{}) { + h.IntSlice = append(h.IntSlice, x.(int)) } \ No newline at end of file diff --git a/solution/2900-2999/2974.Minimum Number Game/Solution.java b/solution/2900-2999/2974.Minimum Number Game/Solution.java index a67ccc54bb8f6..05f40ee14d9ac 100644 --- a/solution/2900-2999/2974.Minimum Number Game/Solution.java +++ b/solution/2900-2999/2974.Minimum Number Game/Solution.java @@ -1,11 +1,16 @@ class Solution { public int[] numberGame(int[] nums) { - Arrays.sort(nums); - for (int i = 0; i < nums.length; i += 2) { - int t = nums[i]; - nums[i] = nums[i + 1]; - nums[i + 1] = t; + PriorityQueue pq = new PriorityQueue<>(); + for (int x : nums) { + pq.offer(x); } - return nums; + int[] ans = new int[nums.length]; + int i = 0; + while (!pq.isEmpty()) { + int a = pq.poll(); + ans[i++] = pq.poll(); + ans[i++] = a; + } + return ans; } } \ No newline at end of file diff --git a/solution/2900-2999/2974.Minimum Number Game/Solution.py b/solution/2900-2999/2974.Minimum Number Game/Solution.py index 658bc473527f6..d4aec2fc91d4d 100644 --- a/solution/2900-2999/2974.Minimum Number Game/Solution.py +++ b/solution/2900-2999/2974.Minimum Number Game/Solution.py @@ -1,6 +1,9 @@ class Solution: def numberGame(self, nums: List[int]) -> List[int]: - nums.sort() - for i in range(0, len(nums), 2): - nums[i], nums[i + 1] = nums[i + 1], nums[i] - return nums + heapify(nums) + ans = [] + while nums: + a, b = heappop(nums), heappop(nums) + ans.append(b) + ans.append(a) + return ans diff --git a/solution/2900-2999/2974.Minimum Number Game/Solution.rs b/solution/2900-2999/2974.Minimum Number Game/Solution.rs index 272c7356370c6..fe93c8da6760f 100644 --- a/solution/2900-2999/2974.Minimum Number Game/Solution.rs +++ b/solution/2900-2999/2974.Minimum Number Game/Solution.rs @@ -1,10 +1,23 @@ +use std::collections::BinaryHeap; +use std::cmp::Reverse; + impl Solution { pub fn number_game(nums: Vec) -> Vec { - let mut nums = nums; - nums.sort_unstable(); - for i in (0..nums.len()).step_by(2) { - nums.swap(i, i + 1); + let mut pq = BinaryHeap::new(); + + for &x in &nums { + pq.push(Reverse(x)); } - nums + + let mut ans = Vec::new(); + + while let Some(Reverse(a)) = pq.pop() { + if let Some(Reverse(b)) = pq.pop() { + ans.push(b); + ans.push(a); + } + } + + ans } } diff --git a/solution/2900-2999/2974.Minimum Number Game/Solution.ts b/solution/2900-2999/2974.Minimum Number Game/Solution.ts index f975ce0a6397f..f64671fb0df50 100644 --- a/solution/2900-2999/2974.Minimum Number Game/Solution.ts +++ b/solution/2900-2999/2974.Minimum Number Game/Solution.ts @@ -1,7 +1,13 @@ function numberGame(nums: number[]): number[] { - nums.sort((a, b) => a - b); - for (let i = 0; i < nums.length; i += 2) { - [nums[i], nums[i + 1]] = [nums[i + 1], nums[i]]; + const pq = new MinPriorityQueue(); + for (const x of nums) { + pq.enqueue(x); } - return nums; + const ans: number[] = []; + while (pq.size()) { + const a = pq.dequeue().element; + const b = pq.dequeue().element; + ans.push(b, a); + } + return ans; } diff --git a/solution/2900-2999/2974.Minimum Number Game/Solution2.cpp b/solution/2900-2999/2974.Minimum Number Game/Solution2.cpp new file mode 100644 index 0000000000000..a0dda318cda5c --- /dev/null +++ b/solution/2900-2999/2974.Minimum Number Game/Solution2.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + vector numberGame(vector& nums) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + for (int i = 0; i < n; i += 2) { + swap(nums[i], nums[i + 1]); + } + return nums; + } +}; \ No newline at end of file diff --git a/solution/2900-2999/2974.Minimum Number Game/Solution2.go b/solution/2900-2999/2974.Minimum Number Game/Solution2.go new file mode 100644 index 0000000000000..3fbf2a35ca2cd --- /dev/null +++ b/solution/2900-2999/2974.Minimum Number Game/Solution2.go @@ -0,0 +1,7 @@ +func numberGame(nums []int) []int { + sort.Ints(nums) + for i := 0; i < len(nums); i += 2 { + nums[i], nums[i+1] = nums[i+1], nums[i] + } + return nums +} \ No newline at end of file diff --git a/solution/2900-2999/2974.Minimum Number Game/Solution2.java b/solution/2900-2999/2974.Minimum Number Game/Solution2.java new file mode 100644 index 0000000000000..a67ccc54bb8f6 --- /dev/null +++ b/solution/2900-2999/2974.Minimum Number Game/Solution2.java @@ -0,0 +1,11 @@ +class Solution { + public int[] numberGame(int[] nums) { + Arrays.sort(nums); + for (int i = 0; i < nums.length; i += 2) { + int t = nums[i]; + nums[i] = nums[i + 1]; + nums[i + 1] = t; + } + return nums; + } +} \ No newline at end of file diff --git a/solution/2900-2999/2974.Minimum Number Game/Solution2.py b/solution/2900-2999/2974.Minimum Number Game/Solution2.py new file mode 100644 index 0000000000000..658bc473527f6 --- /dev/null +++ b/solution/2900-2999/2974.Minimum Number Game/Solution2.py @@ -0,0 +1,6 @@ +class Solution: + def numberGame(self, nums: List[int]) -> List[int]: + nums.sort() + for i in range(0, len(nums), 2): + nums[i], nums[i + 1] = nums[i + 1], nums[i] + return nums diff --git a/solution/2900-2999/2974.Minimum Number Game/Solution2.rs b/solution/2900-2999/2974.Minimum Number Game/Solution2.rs new file mode 100644 index 0000000000000..272c7356370c6 --- /dev/null +++ b/solution/2900-2999/2974.Minimum Number Game/Solution2.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn number_game(nums: Vec) -> Vec { + let mut nums = nums; + nums.sort_unstable(); + for i in (0..nums.len()).step_by(2) { + nums.swap(i, i + 1); + } + nums + } +} diff --git a/solution/2900-2999/2974.Minimum Number Game/Solution2.ts b/solution/2900-2999/2974.Minimum Number Game/Solution2.ts new file mode 100644 index 0000000000000..f975ce0a6397f --- /dev/null +++ b/solution/2900-2999/2974.Minimum Number Game/Solution2.ts @@ -0,0 +1,7 @@ +function numberGame(nums: number[]): number[] { + nums.sort((a, b) => a - b); + for (let i = 0; i < nums.length; i += 2) { + [nums[i], nums[i + 1]] = [nums[i + 1], nums[i]]; + } + return nums; +} diff --git a/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/Solution.cpp b/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/Solution.cpp index d017451070b01..764b52bda8b2e 100644 --- a/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/Solution.cpp +++ b/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/Solution.cpp @@ -1,27 +1,27 @@ -class Solution { -public: - int maximizeSquareArea(int m, int n, vector& hFences, vector& vFences) { - auto f = [](vector& nums, int k) { - nums.push_back(k); - nums.push_back(1); - sort(nums.begin(), nums.end()); - unordered_set s; - for (int i = 0; i < nums.size(); ++i) { - for (int j = 0; j < i; ++j) { - s.insert(nums[i] - nums[j]); - } - } - return s; - }; - auto hs = f(hFences, m); - auto vs = f(vFences, n); - int ans = 0; - for (int h : hs) { - if (vs.count(h)) { - ans = max(ans, h); - } - } - const int mod = 1e9 + 7; - return ans > 0 ? 1LL * ans * ans % mod : -1; - } +class Solution { +public: + int maximizeSquareArea(int m, int n, vector& hFences, vector& vFences) { + auto f = [](vector& nums, int k) { + nums.push_back(k); + nums.push_back(1); + sort(nums.begin(), nums.end()); + unordered_set s; + for (int i = 0; i < nums.size(); ++i) { + for (int j = 0; j < i; ++j) { + s.insert(nums[i] - nums[j]); + } + } + return s; + }; + auto hs = f(hFences, m); + auto vs = f(vFences, n); + int ans = 0; + for (int h : hs) { + if (vs.count(h)) { + ans = max(ans, h); + } + } + const int mod = 1e9 + 7; + return ans > 0 ? 1LL * ans * ans % mod : -1; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/Solution.java b/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/Solution.java index e651a9dd354c5..075ee4d0923f5 100644 --- a/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/Solution.java +++ b/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/Solution.java @@ -1,28 +1,28 @@ -class Solution { - public int maximizeSquareArea(int m, int n, int[] hFences, int[] vFences) { - Set hs = f(hFences, m); - Set vs = f(vFences, n); - hs.retainAll(vs); - int ans = -1; - final int mod = (int) 1e9 + 7; - for (int x : hs) { - ans = Math.max(ans, x); - } - return ans > 0 ? (int) (1L * ans * ans % mod) : -1; - } - - private Set f(int[] nums, int k) { - int n = nums.length; - nums = Arrays.copyOf(nums, n + 2); - nums[n] = 1; - nums[n + 1] = k; - Arrays.sort(nums); - Set s = new HashSet<>(); - for (int i = 0; i < nums.length; ++i) { - for (int j = 0; j < i; ++j) { - s.add(nums[i] - nums[j]); - } - } - return s; - } +class Solution { + public int maximizeSquareArea(int m, int n, int[] hFences, int[] vFences) { + Set hs = f(hFences, m); + Set vs = f(vFences, n); + hs.retainAll(vs); + int ans = -1; + final int mod = (int) 1e9 + 7; + for (int x : hs) { + ans = Math.max(ans, x); + } + return ans > 0 ? (int) (1L * ans * ans % mod) : -1; + } + + private Set f(int[] nums, int k) { + int n = nums.length; + nums = Arrays.copyOf(nums, n + 2); + nums[n] = 1; + nums[n + 1] = k; + Arrays.sort(nums); + Set s = new HashSet<>(); + for (int i = 0; i < nums.length; ++i) { + for (int j = 0; j < i; ++j) { + s.add(nums[i] - nums[j]); + } + } + return s; + } } \ No newline at end of file diff --git a/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/Solution.py b/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/Solution.py index 7d7a935c91681..1cb2da9d18412 100644 --- a/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/Solution.py +++ b/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/Solution.py @@ -1,14 +1,14 @@ -class Solution: - def maximizeSquareArea( - self, m: int, n: int, hFences: List[int], vFences: List[int] - ) -> int: - def f(nums: List[int], k: int) -> Set[int]: - nums.extend([1, k]) - nums.sort() - return {b - a for a, b in combinations(nums, 2)} - - mod = 10**9 + 7 - hs = f(hFences, m) - vs = f(vFences, n) - ans = max(hs & vs, default=0) - return ans**2 % mod if ans else -1 +class Solution: + def maximizeSquareArea( + self, m: int, n: int, hFences: List[int], vFences: List[int] + ) -> int: + def f(nums: List[int], k: int) -> Set[int]: + nums.extend([1, k]) + nums.sort() + return {b - a for a, b in combinations(nums, 2)} + + mod = 10**9 + 7 + hs = f(hFences, m) + vs = f(vFences, n) + ans = max(hs & vs, default=0) + return ans**2 % mod if ans else -1 diff --git a/solution/2900-2999/2977.Minimum Cost to Convert String II/Solution.cpp b/solution/2900-2999/2977.Minimum Cost to Convert String II/Solution.cpp index 8f87143fa6707..251bcc0567a51 100644 --- a/solution/2900-2999/2977.Minimum Cost to Convert String II/Solution.cpp +++ b/solution/2900-2999/2977.Minimum Cost to Convert String II/Solution.cpp @@ -1,96 +1,96 @@ -class Node { -public: - Node* children[26]; - int v = -1; - Node() { - fill(children, children + 26, nullptr); - } -}; - -class Solution { -private: - const long long inf = 1LL << 60; - Node* root = new Node(); - int idx; - - vector> g; - string s; - string t; - vector f; - -public: - long long minimumCost(string source, string target, vector& original, vector& changed, vector& cost) { - int m = cost.size(); - g = vector>(m << 1, vector(m << 1, inf)); - s = source; - t = target; - - for (int i = 0; i < g.size(); ++i) { - g[i][i] = 0; - } - - for (int i = 0; i < m; ++i) { - int x = insert(original[i]); - int y = insert(changed[i]); - g[x][y] = min(g[x][y], static_cast(cost[i])); - } - - for (int k = 0; k < idx; ++k) { - for (int i = 0; i < idx; ++i) { - if (g[i][k] >= inf) { - continue; - } - for (int j = 0; j < idx; ++j) { - g[i][j] = min(g[i][j], g[i][k] + g[k][j]); - } - } - } - - f = vector(s.length(), -1); - long long ans = dfs(0); - return ans >= inf ? -1 : ans; - } - -private: - int insert(const string& w) { - Node* node = root; - for (char c : w) { - int i = c - 'a'; - if (node->children[i] == nullptr) { - node->children[i] = new Node(); - } - node = node->children[i]; - } - if (node->v < 0) { - node->v = idx++; - } - return node->v; - } - - long long dfs(int i) { - if (i >= s.length()) { - return 0; - } - if (f[i] != -1) { - return f[i]; - } - long long res = (s[i] == t[i]) ? dfs(i + 1) : inf; - Node* p = root; - Node* q = root; - for (int j = i; j < s.length(); ++j) { - p = p->children[s[j] - 'a']; - q = q->children[t[j] - 'a']; - if (p == nullptr || q == nullptr) { - break; - } - if (p->v < 0 || q->v < 0) { - continue; - } - long long temp = g[p->v][q->v]; - if (temp < inf) { - res = min(res, temp + dfs(j + 1)); - } - } - return f[i] = res; - } +class Node { +public: + Node* children[26]; + int v = -1; + Node() { + fill(children, children + 26, nullptr); + } +}; + +class Solution { +private: + const long long inf = 1LL << 60; + Node* root = new Node(); + int idx; + + vector> g; + string s; + string t; + vector f; + +public: + long long minimumCost(string source, string target, vector& original, vector& changed, vector& cost) { + int m = cost.size(); + g = vector>(m << 1, vector(m << 1, inf)); + s = source; + t = target; + + for (int i = 0; i < g.size(); ++i) { + g[i][i] = 0; + } + + for (int i = 0; i < m; ++i) { + int x = insert(original[i]); + int y = insert(changed[i]); + g[x][y] = min(g[x][y], static_cast(cost[i])); + } + + for (int k = 0; k < idx; ++k) { + for (int i = 0; i < idx; ++i) { + if (g[i][k] >= inf) { + continue; + } + for (int j = 0; j < idx; ++j) { + g[i][j] = min(g[i][j], g[i][k] + g[k][j]); + } + } + } + + f = vector(s.length(), -1); + long long ans = dfs(0); + return ans >= inf ? -1 : ans; + } + +private: + int insert(const string& w) { + Node* node = root; + for (char c : w) { + int i = c - 'a'; + if (node->children[i] == nullptr) { + node->children[i] = new Node(); + } + node = node->children[i]; + } + if (node->v < 0) { + node->v = idx++; + } + return node->v; + } + + long long dfs(int i) { + if (i >= s.length()) { + return 0; + } + if (f[i] != -1) { + return f[i]; + } + long long res = (s[i] == t[i]) ? dfs(i + 1) : inf; + Node* p = root; + Node* q = root; + for (int j = i; j < s.length(); ++j) { + p = p->children[s[j] - 'a']; + q = q->children[t[j] - 'a']; + if (p == nullptr || q == nullptr) { + break; + } + if (p->v < 0 || q->v < 0) { + continue; + } + long long temp = g[p->v][q->v]; + if (temp < inf) { + res = min(res, temp + dfs(j + 1)); + } + } + return f[i] = res; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2977.Minimum Cost to Convert String II/Solution.java b/solution/2900-2999/2977.Minimum Cost to Convert String II/Solution.java index a66d0b13f167d..c75ea7bf19758 100644 --- a/solution/2900-2999/2977.Minimum Cost to Convert String II/Solution.java +++ b/solution/2900-2999/2977.Minimum Cost to Convert String II/Solution.java @@ -1,86 +1,86 @@ -class Node { - Node[] children = new Node[26]; - int v = -1; -} - -class Solution { - private final long inf = 1L << 60; - private Node root = new Node(); - private int idx; - - private long[][] g; - private char[] s; - private char[] t; - private Long[] f; - - public long minimumCost( - String source, String target, String[] original, String[] changed, int[] cost) { - int m = cost.length; - g = new long[m << 1][m << 1]; - s = source.toCharArray(); - t = target.toCharArray(); - for (int i = 0; i < g.length; ++i) { - Arrays.fill(g[i], inf); - g[i][i] = 0; - } - for (int i = 0; i < m; ++i) { - int x = insert(original[i]); - int y = insert(changed[i]); - g[x][y] = Math.min(g[x][y], cost[i]); - } - for (int k = 0; k < idx; ++k) { - for (int i = 0; i < idx; ++i) { - if (g[i][k] >= inf) { - continue; - } - for (int j = 0; j < idx; ++j) { - g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); - } - } - } - f = new Long[s.length]; - long ans = dfs(0); - return ans >= inf ? -1 : ans; - } - - private int insert(String w) { - Node node = root; - for (char c : w.toCharArray()) { - int i = c - 'a'; - if (node.children[i] == null) { - node.children[i] = new Node(); - } - node = node.children[i]; - } - if (node.v < 0) { - node.v = idx++; - } - return node.v; - } - - private long dfs(int i) { - if (i >= s.length) { - return 0; - } - if (f[i] != null) { - return f[i]; - } - long res = s[i] == t[i] ? dfs(i + 1) : inf; - Node p = root, q = root; - for (int j = i; j < s.length; ++j) { - p = p.children[s[j] - 'a']; - q = q.children[t[j] - 'a']; - if (p == null || q == null) { - break; - } - if (p.v < 0 || q.v < 0) { - continue; - } - long t = g[p.v][q.v]; - if (t < inf) { - res = Math.min(res, t + dfs(j + 1)); - } - } - return f[i] = res; - } +class Node { + Node[] children = new Node[26]; + int v = -1; +} + +class Solution { + private final long inf = 1L << 60; + private Node root = new Node(); + private int idx; + + private long[][] g; + private char[] s; + private char[] t; + private Long[] f; + + public long minimumCost( + String source, String target, String[] original, String[] changed, int[] cost) { + int m = cost.length; + g = new long[m << 1][m << 1]; + s = source.toCharArray(); + t = target.toCharArray(); + for (int i = 0; i < g.length; ++i) { + Arrays.fill(g[i], inf); + g[i][i] = 0; + } + for (int i = 0; i < m; ++i) { + int x = insert(original[i]); + int y = insert(changed[i]); + g[x][y] = Math.min(g[x][y], cost[i]); + } + for (int k = 0; k < idx; ++k) { + for (int i = 0; i < idx; ++i) { + if (g[i][k] >= inf) { + continue; + } + for (int j = 0; j < idx; ++j) { + g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); + } + } + } + f = new Long[s.length]; + long ans = dfs(0); + return ans >= inf ? -1 : ans; + } + + private int insert(String w) { + Node node = root; + for (char c : w.toCharArray()) { + int i = c - 'a'; + if (node.children[i] == null) { + node.children[i] = new Node(); + } + node = node.children[i]; + } + if (node.v < 0) { + node.v = idx++; + } + return node.v; + } + + private long dfs(int i) { + if (i >= s.length) { + return 0; + } + if (f[i] != null) { + return f[i]; + } + long res = s[i] == t[i] ? dfs(i + 1) : inf; + Node p = root, q = root; + for (int j = i; j < s.length; ++j) { + p = p.children[s[j] - 'a']; + q = q.children[t[j] - 'a']; + if (p == null || q == null) { + break; + } + if (p.v < 0 || q.v < 0) { + continue; + } + long t = g[p.v][q.v]; + if (t < inf) { + res = Math.min(res, t + dfs(j + 1)); + } + } + return f[i] = res; + } } \ No newline at end of file diff --git a/solution/2900-2999/2977.Minimum Cost to Convert String II/Solution.py b/solution/2900-2999/2977.Minimum Cost to Convert String II/Solution.py index 07411d52ba0c3..482884f3a49ac 100644 --- a/solution/2900-2999/2977.Minimum Cost to Convert String II/Solution.py +++ b/solution/2900-2999/2977.Minimum Cost to Convert String II/Solution.py @@ -1,68 +1,68 @@ -class Node: - __slots__ = ["children", "v"] - - def __init__(self): - self.children: List[Node | None] = [None] * 26 - self.v = -1 - - -class Solution: - def minimumCost( - self, - source: str, - target: str, - original: List[str], - changed: List[str], - cost: List[int], - ) -> int: - m = len(cost) - g = [[inf] * (m << 1) for _ in range(m << 1)] - for i in range(m << 1): - g[i][i] = 0 - root = Node() - idx = 0 - - def insert(w: str) -> int: - node = root - for c in w: - i = ord(c) - ord("a") - if node.children[i] is None: - node.children[i] = Node() - node = node.children[i] - if node.v < 0: - nonlocal idx - node.v = idx - idx += 1 - return node.v - - @cache - def dfs(i: int) -> int: - if i >= len(source): - return 0 - res = dfs(i + 1) if source[i] == target[i] else inf - p = q = root - for j in range(i, len(source)): - p = p.children[ord(source[j]) - ord("a")] - q = q.children[ord(target[j]) - ord("a")] - if p is None or q is None: - break - if p.v < 0 or q.v < 0: - continue - res = min(res, dfs(j + 1) + g[p.v][q.v]) - return res - - for x, y, z in zip(original, changed, cost): - x = insert(x) - y = insert(y) - g[x][y] = min(g[x][y], z) - for k in range(idx): - for i in range(idx): - if g[i][k] >= inf: - continue - for j in range(idx): - # g[i][j] = min(g[i][j], g[i][k] + g[k][j]) - if g[i][k] + g[k][j] < g[i][j]: - g[i][j] = g[i][k] + g[k][j] - - ans = dfs(0) - return -1 if ans >= inf else ans +class Node: + __slots__ = ["children", "v"] + + def __init__(self): + self.children: List[Node | None] = [None] * 26 + self.v = -1 + + +class Solution: + def minimumCost( + self, + source: str, + target: str, + original: List[str], + changed: List[str], + cost: List[int], + ) -> int: + m = len(cost) + g = [[inf] * (m << 1) for _ in range(m << 1)] + for i in range(m << 1): + g[i][i] = 0 + root = Node() + idx = 0 + + def insert(w: str) -> int: + node = root + for c in w: + i = ord(c) - ord("a") + if node.children[i] is None: + node.children[i] = Node() + node = node.children[i] + if node.v < 0: + nonlocal idx + node.v = idx + idx += 1 + return node.v + + @cache + def dfs(i: int) -> int: + if i >= len(source): + return 0 + res = dfs(i + 1) if source[i] == target[i] else inf + p = q = root + for j in range(i, len(source)): + p = p.children[ord(source[j]) - ord("a")] + q = q.children[ord(target[j]) - ord("a")] + if p is None or q is None: + break + if p.v < 0 or q.v < 0: + continue + res = min(res, dfs(j + 1) + g[p.v][q.v]) + return res + + for x, y, z in zip(original, changed, cost): + x = insert(x) + y = insert(y) + g[x][y] = min(g[x][y], z) + for k in range(idx): + for i in range(idx): + if g[i][k] >= inf: + continue + for j in range(idx): + # g[i][j] = min(g[i][j], g[i][k] + g[k][j]) + if g[i][k] + g[k][j] < g[i][j]: + g[i][j] = g[i][k] + g[k][j] + + ans = dfs(0) + return -1 if ans >= inf else ans diff --git a/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/Solution.cpp b/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/Solution.cpp index b30f6c705adc4..031413442f872 100644 --- a/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/Solution.cpp +++ b/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/Solution.cpp @@ -1,6 +1,6 @@ -class Solution { -public: - int mostExpensiveItem(int primeOne, int primeTwo) { - return primeOne * primeTwo - primeOne - primeTwo; - } +class Solution { +public: + int mostExpensiveItem(int primeOne, int primeTwo) { + return primeOne * primeTwo - primeOne - primeTwo; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/Solution.java b/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/Solution.java index 296268fd1f121..3b2b943fc89c2 100644 --- a/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/Solution.java +++ b/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/Solution.java @@ -1,5 +1,5 @@ -class Solution { - public int mostExpensiveItem(int primeOne, int primeTwo) { - return primeOne * primeTwo - primeOne - primeTwo; - } +class Solution { + public int mostExpensiveItem(int primeOne, int primeTwo) { + return primeOne * primeTwo - primeOne - primeTwo; + } } \ No newline at end of file diff --git a/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/Solution.py b/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/Solution.py index 2d946d8c7e680..3472c5157c6a2 100644 --- a/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/Solution.py +++ b/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/Solution.py @@ -1,3 +1,3 @@ -class Solution: - def mostExpensiveItem(self, primeOne: int, primeTwo: int) -> int: - return primeOne * primeTwo - primeOne - primeTwo +class Solution: + def mostExpensiveItem(self, primeOne: int, primeTwo: int) -> int: + return primeOne * primeTwo - primeOne - primeTwo diff --git a/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/Solution.cpp b/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/Solution.cpp index 8257e8c083c03..b456cba22d05c 100644 --- a/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/Solution.cpp +++ b/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/Solution.cpp @@ -1,10 +1,10 @@ -class Solution { -public: - bool hasTrailingZeros(vector& nums) { - int cnt = 0; - for (int x : nums) { - cnt += (x & 1 ^ 1); - } - return cnt >= 2; - } +class Solution { +public: + bool hasTrailingZeros(vector& nums) { + int cnt = 0; + for (int x : nums) { + cnt += (x & 1 ^ 1); + } + return cnt >= 2; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/Solution.java b/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/Solution.java index 25892ae7c2829..0cfc09f9b4365 100644 --- a/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/Solution.java +++ b/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/Solution.java @@ -1,9 +1,9 @@ -class Solution { - public boolean hasTrailingZeros(int[] nums) { - int cnt = 0; - for (int x : nums) { - cnt += (x & 1 ^ 1); - } - return cnt >= 2; - } +class Solution { + public boolean hasTrailingZeros(int[] nums) { + int cnt = 0; + for (int x : nums) { + cnt += (x & 1 ^ 1); + } + return cnt >= 2; + } } \ No newline at end of file diff --git a/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/Solution.py b/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/Solution.py index a8cb97dc8967d..67e0a12368501 100644 --- a/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/Solution.py +++ b/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/Solution.py @@ -1,3 +1,3 @@ -class Solution: - def hasTrailingZeros(self, nums: List[int]) -> bool: - return sum(x & 1 ^ 1 for x in nums) >= 2 +class Solution: + def hasTrailingZeros(self, nums: List[int]) -> bool: + return sum(x & 1 ^ 1 for x in nums) >= 2 diff --git a/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/Solution.cpp b/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/Solution.cpp index cc67a747769d8..1125019efb2e8 100644 --- a/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/Solution.cpp +++ b/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/Solution.cpp @@ -1,32 +1,32 @@ -class Solution { -public: - int maximumLength(string s) { - int n = s.size(); - int l = 0, r = n; - auto check = [&](int x) { - int cnt[26]{}; - for (int i = 0; i < n;) { - int j = i + 1; - while (j < n && s[j] == s[i]) { - ++j; - } - int k = s[i] - 'a'; - cnt[k] += max(0, j - i - x + 1); - if (cnt[k] >= 3) { - return true; - } - i = j; - } - return false; - }; - while (l < r) { - int mid = (l + r + 1) >> 1; - if (check(mid)) { - l = mid; - } else { - r = mid - 1; - } - } - return l == 0 ? -1 : l; - } +class Solution { +public: + int maximumLength(string s) { + int n = s.size(); + int l = 0, r = n; + auto check = [&](int x) { + int cnt[26]{}; + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && s[j] == s[i]) { + ++j; + } + int k = s[i] - 'a'; + cnt[k] += max(0, j - i - x + 1); + if (cnt[k] >= 3) { + return true; + } + i = j; + } + return false; + }; + while (l < r) { + int mid = (l + r + 1) >> 1; + if (check(mid)) { + l = mid; + } else { + r = mid - 1; + } + } + return l == 0 ? -1 : l; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/Solution.java b/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/Solution.java index 25f93a56fea62..745e4ebc05c5c 100644 --- a/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/Solution.java +++ b/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/Solution.java @@ -1,36 +1,36 @@ -class Solution { - private String s; - private int n; - - public int maximumLength(String s) { - this.s = s; - n = s.length(); - int l = 0, r = n; - while (l < r) { - int mid = (l + r + 1) >> 1; - if (check(mid)) { - l = mid; - } else { - r = mid - 1; - } - } - return l == 0 ? -1 : l; - } - - private boolean check(int x) { - int[] cnt = new int[26]; - for (int i = 0; i < n;) { - int j = i + 1; - while (j < n && s.charAt(j) == s.charAt(i)) { - j++; - } - int k = s.charAt(i) - 'a'; - cnt[k] += Math.max(0, j - i - x + 1); - if (cnt[k] >= 3) { - return true; - } - i = j; - } - return false; - } +class Solution { + private String s; + private int n; + + public int maximumLength(String s) { + this.s = s; + n = s.length(); + int l = 0, r = n; + while (l < r) { + int mid = (l + r + 1) >> 1; + if (check(mid)) { + l = mid; + } else { + r = mid - 1; + } + } + return l == 0 ? -1 : l; + } + + private boolean check(int x) { + int[] cnt = new int[26]; + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && s.charAt(j) == s.charAt(i)) { + j++; + } + int k = s.charAt(i) - 'a'; + cnt[k] += Math.max(0, j - i - x + 1); + if (cnt[k] >= 3) { + return true; + } + i = j; + } + return false; + } } \ No newline at end of file diff --git a/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/Solution.py b/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/Solution.py index ce1b4f5856c5e..b3b1c101f4b59 100644 --- a/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/Solution.py +++ b/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/Solution.py @@ -1,22 +1,22 @@ -class Solution: - def maximumLength(self, s: str) -> int: - def check(x: int) -> bool: - cnt = defaultdict(int) - i = 0 - while i < n: - j = i + 1 - while j < n and s[j] == s[i]: - j += 1 - cnt[s[i]] += max(0, j - i - x + 1) - i = j - return max(cnt.values()) >= 3 - - n = len(s) - l, r = 0, n - while l < r: - mid = (l + r + 1) >> 1 - if check(mid): - l = mid - else: - r = mid - 1 - return -1 if l == 0 else l +class Solution: + def maximumLength(self, s: str) -> int: + def check(x: int) -> bool: + cnt = defaultdict(int) + i = 0 + while i < n: + j = i + 1 + while j < n and s[j] == s[i]: + j += 1 + cnt[s[i]] += max(0, j - i - x + 1) + i = j + return max(cnt.values()) >= 3 + + n = len(s) + l, r = 0, n + while l < r: + mid = (l + r + 1) >> 1 + if check(mid): + l = mid + else: + r = mid - 1 + return -1 if l == 0 else l diff --git a/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/Solution.cpp b/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/Solution.cpp index cc67a747769d8..1125019efb2e8 100644 --- a/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/Solution.cpp +++ b/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/Solution.cpp @@ -1,32 +1,32 @@ -class Solution { -public: - int maximumLength(string s) { - int n = s.size(); - int l = 0, r = n; - auto check = [&](int x) { - int cnt[26]{}; - for (int i = 0; i < n;) { - int j = i + 1; - while (j < n && s[j] == s[i]) { - ++j; - } - int k = s[i] - 'a'; - cnt[k] += max(0, j - i - x + 1); - if (cnt[k] >= 3) { - return true; - } - i = j; - } - return false; - }; - while (l < r) { - int mid = (l + r + 1) >> 1; - if (check(mid)) { - l = mid; - } else { - r = mid - 1; - } - } - return l == 0 ? -1 : l; - } +class Solution { +public: + int maximumLength(string s) { + int n = s.size(); + int l = 0, r = n; + auto check = [&](int x) { + int cnt[26]{}; + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && s[j] == s[i]) { + ++j; + } + int k = s[i] - 'a'; + cnt[k] += max(0, j - i - x + 1); + if (cnt[k] >= 3) { + return true; + } + i = j; + } + return false; + }; + while (l < r) { + int mid = (l + r + 1) >> 1; + if (check(mid)) { + l = mid; + } else { + r = mid - 1; + } + } + return l == 0 ? -1 : l; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/Solution.java b/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/Solution.java index 25f93a56fea62..745e4ebc05c5c 100644 --- a/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/Solution.java +++ b/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/Solution.java @@ -1,36 +1,36 @@ -class Solution { - private String s; - private int n; - - public int maximumLength(String s) { - this.s = s; - n = s.length(); - int l = 0, r = n; - while (l < r) { - int mid = (l + r + 1) >> 1; - if (check(mid)) { - l = mid; - } else { - r = mid - 1; - } - } - return l == 0 ? -1 : l; - } - - private boolean check(int x) { - int[] cnt = new int[26]; - for (int i = 0; i < n;) { - int j = i + 1; - while (j < n && s.charAt(j) == s.charAt(i)) { - j++; - } - int k = s.charAt(i) - 'a'; - cnt[k] += Math.max(0, j - i - x + 1); - if (cnt[k] >= 3) { - return true; - } - i = j; - } - return false; - } +class Solution { + private String s; + private int n; + + public int maximumLength(String s) { + this.s = s; + n = s.length(); + int l = 0, r = n; + while (l < r) { + int mid = (l + r + 1) >> 1; + if (check(mid)) { + l = mid; + } else { + r = mid - 1; + } + } + return l == 0 ? -1 : l; + } + + private boolean check(int x) { + int[] cnt = new int[26]; + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && s.charAt(j) == s.charAt(i)) { + j++; + } + int k = s.charAt(i) - 'a'; + cnt[k] += Math.max(0, j - i - x + 1); + if (cnt[k] >= 3) { + return true; + } + i = j; + } + return false; + } } \ No newline at end of file diff --git a/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/Solution.py b/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/Solution.py index ce1b4f5856c5e..b3b1c101f4b59 100644 --- a/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/Solution.py +++ b/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/Solution.py @@ -1,22 +1,22 @@ -class Solution: - def maximumLength(self, s: str) -> int: - def check(x: int) -> bool: - cnt = defaultdict(int) - i = 0 - while i < n: - j = i + 1 - while j < n and s[j] == s[i]: - j += 1 - cnt[s[i]] += max(0, j - i - x + 1) - i = j - return max(cnt.values()) >= 3 - - n = len(s) - l, r = 0, n - while l < r: - mid = (l + r + 1) >> 1 - if check(mid): - l = mid - else: - r = mid - 1 - return -1 if l == 0 else l +class Solution: + def maximumLength(self, s: str) -> int: + def check(x: int) -> bool: + cnt = defaultdict(int) + i = 0 + while i < n: + j = i + 1 + while j < n and s[j] == s[i]: + j += 1 + cnt[s[i]] += max(0, j - i - x + 1) + i = j + return max(cnt.values()) >= 3 + + n = len(s) + l, r = 0, n + while l < r: + mid = (l + r + 1) >> 1 + if check(mid): + l = mid + else: + r = mid - 1 + return -1 if l == 0 else l diff --git a/solution/2900-2999/2983.Palindrome Rearrangement Queries/Solution.cpp b/solution/2900-2999/2983.Palindrome Rearrangement Queries/Solution.cpp index 07070bc1b8618..968d7b587e42d 100644 --- a/solution/2900-2999/2983.Palindrome Rearrangement Queries/Solution.cpp +++ b/solution/2900-2999/2983.Palindrome Rearrangement Queries/Solution.cpp @@ -1,69 +1,69 @@ -class Solution { -public: - vector canMakePalindromeQueries(string s, vector>& queries) { - int n = s.length(); - int m = n / 2; - string t = string(s.begin() + m, s.end()); - reverse(t.begin(), t.end()); - s = string(s.begin(), s.begin() + m); - - vector> pre1(m + 1, vector(26)); - vector> pre2(m + 1, vector(26)); - vector diff(m + 1, 0); - for (int i = 1; i <= m; ++i) { - pre1[i] = pre1[i - 1]; - pre2[i] = pre2[i - 1]; - ++pre1[i][s[i - 1] - 'a']; - ++pre2[i][t[i - 1] - 'a']; - diff[i] = diff[i - 1] + (s[i - 1] == t[i - 1] ? 0 : 1); - } - - vector ans(queries.size(), false); - for (int i = 0; i < queries.size(); ++i) { - vector q = queries[i]; - int a = q[0], b = q[1]; - int c = n - 1 - q[3], d = n - 1 - q[2]; - ans[i] = (a <= c) ? check(pre1, pre2, diff, a, b, c, d) : check(pre2, pre1, diff, c, d, a, b); - } - return ans; - } - -private: - bool check(const vector>& pre1, const vector>& pre2, const vector& diff, int a, int b, int c, int d) { - if (diff[a] > 0 || diff[diff.size() - 1] - diff[max(b, d) + 1] > 0) { - return false; - } - - if (d <= b) { - return count(pre1, a, b) == count(pre2, a, b); - } - - if (b < c) { - return diff[c] - diff[b + 1] == 0 && count(pre1, a, b) == count(pre2, a, b) && count(pre1, c, d) == count(pre2, c, d); - } - - vector cnt1 = sub(count(pre1, a, b), count(pre2, a, c - 1)); - vector cnt2 = sub(count(pre2, c, d), count(pre1, b + 1, d)); - - return cnt1 != vector() && cnt2 != vector() && cnt1 == cnt2; - } - - vector count(const vector>& pre, int i, int j) { - vector cnt(26); - for (int k = 0; k < 26; ++k) { - cnt[k] = pre[j + 1][k] - pre[i][k]; - } - return cnt; - } - - vector sub(const vector& cnt1, const vector& cnt2) { - vector cnt(26); - for (int i = 0; i < 26; ++i) { - cnt[i] = cnt1[i] - cnt2[i]; - if (cnt[i] < 0) { - return vector(); - } - } - return cnt; - } +class Solution { +public: + vector canMakePalindromeQueries(string s, vector>& queries) { + int n = s.length(); + int m = n / 2; + string t = string(s.begin() + m, s.end()); + reverse(t.begin(), t.end()); + s = string(s.begin(), s.begin() + m); + + vector> pre1(m + 1, vector(26)); + vector> pre2(m + 1, vector(26)); + vector diff(m + 1, 0); + for (int i = 1; i <= m; ++i) { + pre1[i] = pre1[i - 1]; + pre2[i] = pre2[i - 1]; + ++pre1[i][s[i - 1] - 'a']; + ++pre2[i][t[i - 1] - 'a']; + diff[i] = diff[i - 1] + (s[i - 1] == t[i - 1] ? 0 : 1); + } + + vector ans(queries.size(), false); + for (int i = 0; i < queries.size(); ++i) { + vector q = queries[i]; + int a = q[0], b = q[1]; + int c = n - 1 - q[3], d = n - 1 - q[2]; + ans[i] = (a <= c) ? check(pre1, pre2, diff, a, b, c, d) : check(pre2, pre1, diff, c, d, a, b); + } + return ans; + } + +private: + bool check(const vector>& pre1, const vector>& pre2, const vector& diff, int a, int b, int c, int d) { + if (diff[a] > 0 || diff[diff.size() - 1] - diff[max(b, d) + 1] > 0) { + return false; + } + + if (d <= b) { + return count(pre1, a, b) == count(pre2, a, b); + } + + if (b < c) { + return diff[c] - diff[b + 1] == 0 && count(pre1, a, b) == count(pre2, a, b) && count(pre1, c, d) == count(pre2, c, d); + } + + vector cnt1 = sub(count(pre1, a, b), count(pre2, a, c - 1)); + vector cnt2 = sub(count(pre2, c, d), count(pre1, b + 1, d)); + + return cnt1 != vector() && cnt2 != vector() && cnt1 == cnt2; + } + + vector count(const vector>& pre, int i, int j) { + vector cnt(26); + for (int k = 0; k < 26; ++k) { + cnt[k] = pre[j + 1][k] - pre[i][k]; + } + return cnt; + } + + vector sub(const vector& cnt1, const vector& cnt2) { + vector cnt(26); + for (int i = 0; i < 26; ++i) { + cnt[i] = cnt1[i] - cnt2[i]; + if (cnt[i] < 0) { + return vector(); + } + } + return cnt; + } }; \ No newline at end of file diff --git a/solution/2900-2999/2983.Palindrome Rearrangement Queries/Solution.java b/solution/2900-2999/2983.Palindrome Rearrangement Queries/Solution.java index 2a794c56a061d..56cdfbd17a6e7 100644 --- a/solution/2900-2999/2983.Palindrome Rearrangement Queries/Solution.java +++ b/solution/2900-2999/2983.Palindrome Rearrangement Queries/Solution.java @@ -1,64 +1,64 @@ -class Solution { - public boolean[] canMakePalindromeQueries(String s, int[][] queries) { - int n = s.length(); - int m = n / 2; - String t = new StringBuilder(s.substring(m)).reverse().toString(); - s = s.substring(0, m); - int[][] pre1 = new int[m + 1][0]; - int[][] pre2 = new int[m + 1][0]; - int[] diff = new int[m + 1]; - pre1[0] = new int[26]; - pre2[0] = new int[26]; - for (int i = 1; i <= m; ++i) { - pre1[i] = pre1[i - 1].clone(); - pre2[i] = pre2[i - 1].clone(); - ++pre1[i][s.charAt(i - 1) - 'a']; - ++pre2[i][t.charAt(i - 1) - 'a']; - diff[i] = diff[i - 1] + (s.charAt(i - 1) == t.charAt(i - 1) ? 0 : 1); - } - boolean[] ans = new boolean[queries.length]; - for (int i = 0; i < queries.length; ++i) { - int[] q = queries[i]; - int a = q[0], b = q[1]; - int c = n - 1 - q[3], d = n - 1 - q[2]; - ans[i] = a <= c ? check(pre1, pre2, diff, a, b, c, d) - : check(pre2, pre1, diff, c, d, a, b); - } - return ans; - } - - private boolean check(int[][] pre1, int[][] pre2, int[] diff, int a, int b, int c, int d) { - if (diff[a] > 0 || diff[diff.length - 1] - diff[Math.max(b, d) + 1] > 0) { - return false; - } - if (d <= b) { - return Arrays.equals(count(pre1, a, b), count(pre2, a, b)); - } - if (b < c) { - return diff[c] - diff[b + 1] == 0 && Arrays.equals(count(pre1, a, b), count(pre2, a, b)) - && Arrays.equals(count(pre1, c, d), count(pre2, c, d)); - } - int[] cnt1 = sub(count(pre1, a, b), count(pre2, a, c - 1)); - int[] cnt2 = sub(count(pre2, c, d), count(pre1, b + 1, d)); - return cnt1 != null && cnt2 != null && Arrays.equals(cnt1, cnt2); - } - - private int[] count(int[][] pre, int i, int j) { - int[] cnt = new int[26]; - for (int k = 0; k < 26; ++k) { - cnt[k] = pre[j + 1][k] - pre[i][k]; - } - return cnt; - } - - private int[] sub(int[] cnt1, int[] cnt2) { - int[] cnt = new int[26]; - for (int i = 0; i < 26; ++i) { - cnt[i] = cnt1[i] - cnt2[i]; - if (cnt[i] < 0) { - return null; - } - } - return cnt; - } +class Solution { + public boolean[] canMakePalindromeQueries(String s, int[][] queries) { + int n = s.length(); + int m = n / 2; + String t = new StringBuilder(s.substring(m)).reverse().toString(); + s = s.substring(0, m); + int[][] pre1 = new int[m + 1][0]; + int[][] pre2 = new int[m + 1][0]; + int[] diff = new int[m + 1]; + pre1[0] = new int[26]; + pre2[0] = new int[26]; + for (int i = 1; i <= m; ++i) { + pre1[i] = pre1[i - 1].clone(); + pre2[i] = pre2[i - 1].clone(); + ++pre1[i][s.charAt(i - 1) - 'a']; + ++pre2[i][t.charAt(i - 1) - 'a']; + diff[i] = diff[i - 1] + (s.charAt(i - 1) == t.charAt(i - 1) ? 0 : 1); + } + boolean[] ans = new boolean[queries.length]; + for (int i = 0; i < queries.length; ++i) { + int[] q = queries[i]; + int a = q[0], b = q[1]; + int c = n - 1 - q[3], d = n - 1 - q[2]; + ans[i] = a <= c ? check(pre1, pre2, diff, a, b, c, d) + : check(pre2, pre1, diff, c, d, a, b); + } + return ans; + } + + private boolean check(int[][] pre1, int[][] pre2, int[] diff, int a, int b, int c, int d) { + if (diff[a] > 0 || diff[diff.length - 1] - diff[Math.max(b, d) + 1] > 0) { + return false; + } + if (d <= b) { + return Arrays.equals(count(pre1, a, b), count(pre2, a, b)); + } + if (b < c) { + return diff[c] - diff[b + 1] == 0 && Arrays.equals(count(pre1, a, b), count(pre2, a, b)) + && Arrays.equals(count(pre1, c, d), count(pre2, c, d)); + } + int[] cnt1 = sub(count(pre1, a, b), count(pre2, a, c - 1)); + int[] cnt2 = sub(count(pre2, c, d), count(pre1, b + 1, d)); + return cnt1 != null && cnt2 != null && Arrays.equals(cnt1, cnt2); + } + + private int[] count(int[][] pre, int i, int j) { + int[] cnt = new int[26]; + for (int k = 0; k < 26; ++k) { + cnt[k] = pre[j + 1][k] - pre[i][k]; + } + return cnt; + } + + private int[] sub(int[] cnt1, int[] cnt2) { + int[] cnt = new int[26]; + for (int i = 0; i < 26; ++i) { + cnt[i] = cnt1[i] - cnt2[i]; + if (cnt[i] < 0) { + return null; + } + } + return cnt; + } } \ No newline at end of file diff --git a/solution/2900-2999/2983.Palindrome Rearrangement Queries/Solution.py b/solution/2900-2999/2983.Palindrome Rearrangement Queries/Solution.py index 834abc54a1987..db3034c0158c3 100644 --- a/solution/2900-2999/2983.Palindrome Rearrangement Queries/Solution.py +++ b/solution/2900-2999/2983.Palindrome Rearrangement Queries/Solution.py @@ -1,53 +1,53 @@ -class Solution: - def canMakePalindromeQueries(self, s: str, queries: List[List[int]]) -> List[bool]: - def count(pre: List[List[int]], i: int, j: int) -> List[int]: - return [x - y for x, y in zip(pre[j + 1], pre[i])] - - def sub(cnt1: List[int], cnt2: List[int]) -> List[int]: - res = [] - for x, y in zip(cnt1, cnt2): - if x - y < 0: - return [] - res.append(x - y) - return res - - def check( - pre1: List[List[int]], pre2: List[List[int]], a: int, b: int, c: int, d: int - ) -> bool: - if diff[a] > 0 or diff[m] - diff[max(b, d) + 1] > 0: - return False - if d <= b: - return count(pre1, a, b) == count(pre2, a, b) - if b < c: - return ( - diff[c] - diff[b + 1] == 0 - and count(pre1, a, b) == count(pre2, a, b) - and count(pre1, c, d) == count(pre2, c, d) - ) - cnt1 = sub(count(pre1, a, b), count(pre2, a, c - 1)) - cnt2 = sub(count(pre2, c, d), count(pre1, b + 1, d)) - return bool(cnt1) and bool(cnt2) and cnt1 == cnt2 - - n = len(s) - m = n // 2 - t = s[m:][::-1] - s = s[:m] - pre1 = [[0] * 26 for _ in range(m + 1)] - pre2 = [[0] * 26 for _ in range(m + 1)] - diff = [0] * (m + 1) - for i, (c1, c2) in enumerate(zip(s, t), 1): - pre1[i] = pre1[i - 1][:] - pre2[i] = pre2[i - 1][:] - pre1[i][ord(c1) - ord("a")] += 1 - pre2[i][ord(c2) - ord("a")] += 1 - diff[i] = diff[i - 1] + int(c1 != c2) - ans = [] - for a, b, c, d in queries: - c, d = n - 1 - d, n - 1 - c - ok = ( - check(pre1, pre2, a, b, c, d) - if a <= c - else check(pre2, pre1, c, d, a, b) - ) - ans.append(ok) - return ans +class Solution: + def canMakePalindromeQueries(self, s: str, queries: List[List[int]]) -> List[bool]: + def count(pre: List[List[int]], i: int, j: int) -> List[int]: + return [x - y for x, y in zip(pre[j + 1], pre[i])] + + def sub(cnt1: List[int], cnt2: List[int]) -> List[int]: + res = [] + for x, y in zip(cnt1, cnt2): + if x - y < 0: + return [] + res.append(x - y) + return res + + def check( + pre1: List[List[int]], pre2: List[List[int]], a: int, b: int, c: int, d: int + ) -> bool: + if diff[a] > 0 or diff[m] - diff[max(b, d) + 1] > 0: + return False + if d <= b: + return count(pre1, a, b) == count(pre2, a, b) + if b < c: + return ( + diff[c] - diff[b + 1] == 0 + and count(pre1, a, b) == count(pre2, a, b) + and count(pre1, c, d) == count(pre2, c, d) + ) + cnt1 = sub(count(pre1, a, b), count(pre2, a, c - 1)) + cnt2 = sub(count(pre2, c, d), count(pre1, b + 1, d)) + return bool(cnt1) and bool(cnt2) and cnt1 == cnt2 + + n = len(s) + m = n // 2 + t = s[m:][::-1] + s = s[:m] + pre1 = [[0] * 26 for _ in range(m + 1)] + pre2 = [[0] * 26 for _ in range(m + 1)] + diff = [0] * (m + 1) + for i, (c1, c2) in enumerate(zip(s, t), 1): + pre1[i] = pre1[i - 1][:] + pre2[i] = pre2[i - 1][:] + pre1[i][ord(c1) - ord("a")] += 1 + pre2[i][ord(c2) - ord("a")] += 1 + diff[i] = diff[i - 1] + int(c1 != c2) + ans = [] + for a, b, c, d in queries: + c, d = n - 1 - d, n - 1 - c + ok = ( + check(pre1, pre2, a, b, c, d) + if a <= c + else check(pre2, pre1, c, d, a, b) + ) + ans.append(ok) + return ans diff --git a/solution/2900-2999/2992.Number of Self-Divisible Permutations/Solution2.cpp b/solution/2900-2999/2992.Number of Self-Divisible Permutations/Solution2.cpp new file mode 100644 index 0000000000000..32b8ab0a3f317 --- /dev/null +++ b/solution/2900-2999/2992.Number of Self-Divisible Permutations/Solution2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int selfDivisiblePermutationCount(int n) { + int f[1 << n]; + memset(f, 0, sizeof(f)); + f[0] = 1; + for (int mask = 0; mask < 1 << n; ++mask) { + int i = __builtin_popcount(mask); + for (int j = 1; j <= n; ++j) { + if (((mask >> (j - 1)) & 1) == 1 && (i % j == 0 || j % i == 0)) { + f[mask] += f[mask ^ (1 << (j - 1))]; + } + } + } + return f[(1 << n) - 1]; + } +}; \ No newline at end of file diff --git a/solution/2900-2999/2992.Number of Self-Divisible Permutations/Solution2.go b/solution/2900-2999/2992.Number of Self-Divisible Permutations/Solution2.go new file mode 100644 index 0000000000000..f335466dc9242 --- /dev/null +++ b/solution/2900-2999/2992.Number of Self-Divisible Permutations/Solution2.go @@ -0,0 +1,13 @@ +func selfDivisiblePermutationCount(n int) int { + f := make([]int, 1<>(j-1)&1 == 1 && (i%j == 0 || j%i == 0) { + f[mask] += f[mask^(1<<(j-1))] + } + } + } + return f[(1<> (j - 1)) & 1) == 1 && (i % j == 0 || j % i == 0)) { + f[mask] += f[mask ^ (1 << (j - 1))]; + } + } + } + return f[(1 << n) - 1]; + } +} \ No newline at end of file diff --git a/solution/2900-2999/2992.Number of Self-Divisible Permutations/Solution2.py b/solution/2900-2999/2992.Number of Self-Divisible Permutations/Solution2.py new file mode 100644 index 0000000000000..f5cebb609016f --- /dev/null +++ b/solution/2900-2999/2992.Number of Self-Divisible Permutations/Solution2.py @@ -0,0 +1,10 @@ +class Solution: + def selfDivisiblePermutationCount(self, n: int) -> int: + f = [0] * (1 << n) + f[0] = 1 + for mask in range(1 << n): + i = mask.bit_count() + for j in range(1, n + 1): + if (mask >> (j - 1) & 1) == 1 and (i % j == 0 or j % i == 0): + f[mask] += f[mask ^ (1 << (j - 1))] + return f[-1] diff --git a/solution/2900-2999/2992.Number of Self-Divisible Permutations/Solution2.ts b/solution/2900-2999/2992.Number of Self-Divisible Permutations/Solution2.ts new file mode 100644 index 0000000000000..3d175f5dfb626 --- /dev/null +++ b/solution/2900-2999/2992.Number of Self-Divisible Permutations/Solution2.ts @@ -0,0 +1,22 @@ +function selfDivisiblePermutationCount(n: number): number { + const f: number[] = Array(1 << n).fill(0); + f[0] = 1; + for (let mask = 0; mask < 1 << n; ++mask) { + const i = bitCount(mask); + for (let j = 1; j <= n; ++j) { + if ((mask >> (j - 1)) & 1 && (i % j === 0 || j % i === 0)) { + f[mask] += f[mask ^ (1 << (j - 1))]; + } + } + } + return f.at(-1)!; +} + +function bitCount(i: number): number { + i = i - ((i >>> 1) & 0x55555555); + i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); + i = (i + (i >>> 4)) & 0x0f0f0f0f; + i = i + (i >>> 8); + i = i + (i >>> 16); + return i & 0x3f; +} diff --git a/solution/3000-3099/3001.Minimum Moves to Capture The Queen/Solution.cpp b/solution/3000-3099/3001.Minimum Moves to Capture The Queen/Solution.cpp index c01429a83a927..6eac09a127bb4 100644 --- a/solution/3000-3099/3001.Minimum Moves to Capture The Queen/Solution.cpp +++ b/solution/3000-3099/3001.Minimum Moves to Capture The Queen/Solution.cpp @@ -1,22 +1,22 @@ -class Solution { -public: - int minMovesToCaptureTheQueen(int a, int b, int c, int d, int e, int f) { - int dirs[2][5] = {{-1, 0, 1, 0, -1}, {-1, 1, 1, -1, -1}}; - auto check = [&](int i, int sx, int sy, int bx, int by) { - for (int d = 0; d < 4; ++d) { - for (int k = 1; k < 8; ++k) { - int x = sx + dirs[i][d] * k; - int y = sy + dirs[i][d + 1] * k; - if (x < 1 || x > 8 || y < 1 || y > 8 || (x == bx && y == by)) { - break; - } - if (x == e && y == f) { - return true; - } - } - } - return false; - }; - return check(0, a, b, c, d) || check(1, c, d, a, b) ? 1 : 2; - } +class Solution { +public: + int minMovesToCaptureTheQueen(int a, int b, int c, int d, int e, int f) { + int dirs[2][5] = {{-1, 0, 1, 0, -1}, {-1, 1, 1, -1, -1}}; + auto check = [&](int i, int sx, int sy, int bx, int by) { + for (int d = 0; d < 4; ++d) { + for (int k = 1; k < 8; ++k) { + int x = sx + dirs[i][d] * k; + int y = sy + dirs[i][d + 1] * k; + if (x < 1 || x > 8 || y < 1 || y > 8 || (x == bx && y == by)) { + break; + } + if (x == e && y == f) { + return true; + } + } + } + return false; + }; + return check(0, a, b, c, d) || check(1, c, d, a, b) ? 1 : 2; + } }; \ No newline at end of file diff --git a/solution/3000-3099/3001.Minimum Moves to Capture The Queen/Solution.go b/solution/3000-3099/3001.Minimum Moves to Capture The Queen/Solution.go index 39014a52e806c..b85b4d1447e66 100644 --- a/solution/3000-3099/3001.Minimum Moves to Capture The Queen/Solution.go +++ b/solution/3000-3099/3001.Minimum Moves to Capture The Queen/Solution.go @@ -1,22 +1,22 @@ -func minMovesToCaptureTheQueen(a int, b int, c int, d int, e int, f int) int { - dirs := [2][5]int{{-1, 0, 1, 0, -1}, {-1, 1, 1, -1, -1}} - check := func(i, sx, sy, bx, by int) bool { - for d := 0; d < 4; d++ { - for k := 1; k < 8; k++ { - x := sx + dirs[i][d]*k - y := sy + dirs[i][d+1]*k - if x < 1 || x > 8 || y < 1 || y > 8 || (x == bx && y == by) { - break - } - if x == e && y == f { - return true - } - } - } - return false - } - if check(0, a, b, c, d) || check(1, c, d, a, b) { - return 1 - } - return 2 +func minMovesToCaptureTheQueen(a int, b int, c int, d int, e int, f int) int { + dirs := [2][5]int{{-1, 0, 1, 0, -1}, {-1, 1, 1, -1, -1}} + check := func(i, sx, sy, bx, by int) bool { + for d := 0; d < 4; d++ { + for k := 1; k < 8; k++ { + x := sx + dirs[i][d]*k + y := sy + dirs[i][d+1]*k + if x < 1 || x > 8 || y < 1 || y > 8 || (x == bx && y == by) { + break + } + if x == e && y == f { + return true + } + } + } + return false + } + if check(0, a, b, c, d) || check(1, c, d, a, b) { + return 1 + } + return 2 } \ No newline at end of file diff --git a/solution/3000-3099/3001.Minimum Moves to Capture The Queen/Solution.java b/solution/3000-3099/3001.Minimum Moves to Capture The Queen/Solution.java index b5d21f96bcd21..412041f0ad455 100644 --- a/solution/3000-3099/3001.Minimum Moves to Capture The Queen/Solution.java +++ b/solution/3000-3099/3001.Minimum Moves to Capture The Queen/Solution.java @@ -1,27 +1,27 @@ -class Solution { - private final int[] dirs1 = {-1, 0, 1, 0, -1}; - private final int[] dirs2 = {-1, 1, 1, -1, -1}; - private int e, f; - - public int minMovesToCaptureTheQueen(int a, int b, int c, int d, int e, int f) { - this.e = e; - this.f = f; - return check(dirs1, a, b, c, d) || check(dirs2, c, d, a, b) ? 1 : 2; - } - - private boolean check(int[] dirs, int sx, int sy, int bx, int by) { - for (int d = 0; d < 4; ++d) { - for (int k = 1; k < 8; ++k) { - int x = sx + dirs[d] * k; - int y = sy + dirs[d + 1] * k; - if (x < 1 || x > 8 || y < 1 || y > 8 || (x == bx && y == by)) { - break; - } - if (x == e && y == f) { - return true; - } - } - } - return false; - } +class Solution { + private final int[] dirs1 = {-1, 0, 1, 0, -1}; + private final int[] dirs2 = {-1, 1, 1, -1, -1}; + private int e, f; + + public int minMovesToCaptureTheQueen(int a, int b, int c, int d, int e, int f) { + this.e = e; + this.f = f; + return check(dirs1, a, b, c, d) || check(dirs2, c, d, a, b) ? 1 : 2; + } + + private boolean check(int[] dirs, int sx, int sy, int bx, int by) { + for (int d = 0; d < 4; ++d) { + for (int k = 1; k < 8; ++k) { + int x = sx + dirs[d] * k; + int y = sy + dirs[d + 1] * k; + if (x < 1 || x > 8 || y < 1 || y > 8 || (x == bx && y == by)) { + break; + } + if (x == e && y == f) { + return true; + } + } + } + return false; + } } \ No newline at end of file diff --git a/solution/3000-3099/3001.Minimum Moves to Capture The Queen/Solution.py b/solution/3000-3099/3001.Minimum Moves to Capture The Queen/Solution.py index 486ccf66eb134..a0313777c4e29 100644 --- a/solution/3000-3099/3001.Minimum Moves to Capture The Queen/Solution.py +++ b/solution/3000-3099/3001.Minimum Moves to Capture The Queen/Solution.py @@ -1,18 +1,18 @@ -class Solution: - def minMovesToCaptureTheQueen( - self, a: int, b: int, c: int, d: int, e: int, f: int - ) -> int: - def check(dirs, sx, sy, bx, by) -> bool: - for dx, dy in pairwise(dirs): - for k in range(1, 8): - x = sx + dx * k - y = sy + dy * k - if not (1 <= x <= 8 and 1 <= y <= 8) or (x, y) == (bx, by): - break - if (x, y) == (e, f): - return True - return False - - dirs1 = (-1, 0, 1, 0, -1) - dirs2 = (-1, 1, 1, -1, -1) - return 1 if check(dirs1, a, b, c, d) or check(dirs2, c, d, a, b) else 2 +class Solution: + def minMovesToCaptureTheQueen( + self, a: int, b: int, c: int, d: int, e: int, f: int + ) -> int: + def check(dirs, sx, sy, bx, by) -> bool: + for dx, dy in pairwise(dirs): + for k in range(1, 8): + x = sx + dx * k + y = sy + dy * k + if not (1 <= x <= 8 and 1 <= y <= 8) or (x, y) == (bx, by): + break + if (x, y) == (e, f): + return True + return False + + dirs1 = (-1, 0, 1, 0, -1) + dirs2 = (-1, 1, 1, -1, -1) + return 1 if check(dirs1, a, b, c, d) or check(dirs2, c, d, a, b) else 2 diff --git a/solution/3000-3099/3002.Maximum Size of a Set After Removals/Solution.cpp b/solution/3000-3099/3002.Maximum Size of a Set After Removals/Solution.cpp index 984a11fda0361..d4dd60995cdfb 100644 --- a/solution/3000-3099/3002.Maximum Size of a Set After Removals/Solution.cpp +++ b/solution/3000-3099/3002.Maximum Size of a Set After Removals/Solution.cpp @@ -1,24 +1,24 @@ -class Solution { -public: - int maximumSetSize(vector& nums1, vector& nums2) { - unordered_set s1(nums1.begin(), nums1.end()); - unordered_set s2(nums2.begin(), nums2.end()); - int n = nums1.size(); - int a = 0, b = 0, c = 0; - for (int x : s1) { - if (!s2.count(x)) { - ++a; - } - } - for (int x : s2) { - if (!s1.count(x)) { - ++b; - } else { - ++c; - } - } - a = min(a, n / 2); - b = min(b, n / 2); - return min(a + b + c, n); - } +class Solution { +public: + int maximumSetSize(vector& nums1, vector& nums2) { + unordered_set s1(nums1.begin(), nums1.end()); + unordered_set s2(nums2.begin(), nums2.end()); + int n = nums1.size(); + int a = 0, b = 0, c = 0; + for (int x : s1) { + if (!s2.count(x)) { + ++a; + } + } + for (int x : s2) { + if (!s1.count(x)) { + ++b; + } else { + ++c; + } + } + a = min(a, n / 2); + b = min(b, n / 2); + return min(a + b + c, n); + } }; \ No newline at end of file diff --git a/solution/3000-3099/3002.Maximum Size of a Set After Removals/Solution.go b/solution/3000-3099/3002.Maximum Size of a Set After Removals/Solution.go index 461e507c3473b..0bfb6707a0d16 100644 --- a/solution/3000-3099/3002.Maximum Size of a Set After Removals/Solution.go +++ b/solution/3000-3099/3002.Maximum Size of a Set After Removals/Solution.go @@ -1,27 +1,27 @@ -func maximumSetSize(nums1 []int, nums2 []int) int { - s1 := map[int]bool{} - s2 := map[int]bool{} - for _, x := range nums1 { - s1[x] = true - } - for _, x := range nums2 { - s2[x] = true - } - a, b, c := 0, 0, 0 - for x := range s1 { - if !s2[x] { - a++ - } - } - for x := range s2 { - if !s1[x] { - b++ - } else { - c++ - } - } - n := len(nums1) - a = min(a, n/2) - b = min(b, n/2) - return min(a+b+c, n) +func maximumSetSize(nums1 []int, nums2 []int) int { + s1 := map[int]bool{} + s2 := map[int]bool{} + for _, x := range nums1 { + s1[x] = true + } + for _, x := range nums2 { + s2[x] = true + } + a, b, c := 0, 0, 0 + for x := range s1 { + if !s2[x] { + a++ + } + } + for x := range s2 { + if !s1[x] { + b++ + } else { + c++ + } + } + n := len(nums1) + a = min(a, n/2) + b = min(b, n/2) + return min(a+b+c, n) } \ No newline at end of file diff --git a/solution/3000-3099/3002.Maximum Size of a Set After Removals/Solution.java b/solution/3000-3099/3002.Maximum Size of a Set After Removals/Solution.java index 5aceca3538210..8abb4b4d167c9 100644 --- a/solution/3000-3099/3002.Maximum Size of a Set After Removals/Solution.java +++ b/solution/3000-3099/3002.Maximum Size of a Set After Removals/Solution.java @@ -1,29 +1,29 @@ -class Solution { - public int maximumSetSize(int[] nums1, int[] nums2) { - Set s1 = new HashSet<>(); - Set s2 = new HashSet<>(); - for (int x : nums1) { - s1.add(x); - } - for (int x : nums2) { - s2.add(x); - } - int n = nums1.length; - int a = 0, b = 0, c = 0; - for (int x : s1) { - if (!s2.contains(x)) { - ++a; - } - } - for (int x : s2) { - if (!s1.contains(x)) { - ++b; - } else { - ++c; - } - } - a = Math.min(a, n / 2); - b = Math.min(b, n / 2); - return Math.min(a + b + c, n); - } +class Solution { + public int maximumSetSize(int[] nums1, int[] nums2) { + Set s1 = new HashSet<>(); + Set s2 = new HashSet<>(); + for (int x : nums1) { + s1.add(x); + } + for (int x : nums2) { + s2.add(x); + } + int n = nums1.length; + int a = 0, b = 0, c = 0; + for (int x : s1) { + if (!s2.contains(x)) { + ++a; + } + } + for (int x : s2) { + if (!s1.contains(x)) { + ++b; + } else { + ++c; + } + } + a = Math.min(a, n / 2); + b = Math.min(b, n / 2); + return Math.min(a + b + c, n); + } } \ No newline at end of file diff --git a/solution/3000-3099/3002.Maximum Size of a Set After Removals/Solution.py b/solution/3000-3099/3002.Maximum Size of a Set After Removals/Solution.py index f4fa0f01cc313..4a5905f325f92 100644 --- a/solution/3000-3099/3002.Maximum Size of a Set After Removals/Solution.py +++ b/solution/3000-3099/3002.Maximum Size of a Set After Removals/Solution.py @@ -1,8 +1,8 @@ -class Solution: - def maximumSetSize(self, nums1: List[int], nums2: List[int]) -> int: - s1 = set(nums1) - s2 = set(nums2) - n = len(nums1) - a = min(len(s1 - s2), n // 2) - b = min(len(s2 - s1), n // 2) - return min(a + b + len(s1 & s2), n) +class Solution: + def maximumSetSize(self, nums1: List[int], nums2: List[int]) -> int: + s1 = set(nums1) + s2 = set(nums2) + n = len(nums1) + a = min(len(s1 - s2), n // 2) + b = min(len(s2 - s1), n // 2) + return min(a + b + len(s1 & s2), n) diff --git a/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/Solution.cpp b/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/Solution.cpp index bdd700377b40c..0023c8165d70f 100644 --- a/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/Solution.cpp +++ b/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/Solution.cpp @@ -1,31 +1,31 @@ -class Solution { -public: - int maxPartitionsAfterOperations(string s, int k) { - int n = s.size(); - unordered_map f; - function dfs = [&](int i, int cur, int t) { - if (i >= n) { - return 1; - } - long long key = (long long) i << 32 | cur << 1 | t; - if (f.count(key)) { - return f[key]; - } - int v = 1 << (s[i] - 'a'); - int nxt = cur | v; - int ans = __builtin_popcount(nxt) > k ? dfs(i + 1, v, t) + 1 : dfs(i + 1, nxt, t); - if (t) { - for (int j = 0; j < 26; ++j) { - nxt = cur | (1 << j); - if (__builtin_popcount(nxt) > k) { - ans = max(ans, dfs(i + 1, 1 << j, 0) + 1); - } else { - ans = max(ans, dfs(i + 1, nxt, 0)); - } - } - } - return f[key] = ans; - }; - return dfs(0, 0, 1); - } +class Solution { +public: + int maxPartitionsAfterOperations(string s, int k) { + int n = s.size(); + unordered_map f; + function dfs = [&](int i, int cur, int t) { + if (i >= n) { + return 1; + } + long long key = (long long) i << 32 | cur << 1 | t; + if (f.count(key)) { + return f[key]; + } + int v = 1 << (s[i] - 'a'); + int nxt = cur | v; + int ans = __builtin_popcount(nxt) > k ? dfs(i + 1, v, t) + 1 : dfs(i + 1, nxt, t); + if (t) { + for (int j = 0; j < 26; ++j) { + nxt = cur | (1 << j); + if (__builtin_popcount(nxt) > k) { + ans = max(ans, dfs(i + 1, 1 << j, 0) + 1); + } else { + ans = max(ans, dfs(i + 1, nxt, 0)); + } + } + } + return f[key] = ans; + }; + return dfs(0, 0, 1); + } }; \ No newline at end of file diff --git a/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/Solution.go b/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/Solution.go index 921e1544952d2..849876f7bab66 100644 --- a/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/Solution.go +++ b/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/Solution.go @@ -1,36 +1,36 @@ -func maxPartitionsAfterOperations(s string, k int) int { - n := len(s) - type tuple struct{ i, cur, t int } - f := map[tuple]int{} - var dfs func(i, cur, t int) int - dfs = func(i, cur, t int) int { - if i >= n { - return 1 - } - key := tuple{i, cur, t} - if v, ok := f[key]; ok { - return v - } - v := 1 << (s[i] - 'a') - nxt := cur | v - var ans int - if bits.OnesCount(uint(nxt)) > k { - ans = dfs(i+1, v, t) + 1 - } else { - ans = dfs(i+1, nxt, t) - } - if t > 0 { - for j := 0; j < 26; j++ { - nxt = cur | (1 << j) - if bits.OnesCount(uint(nxt)) > k { - ans = max(ans, dfs(i+1, 1<= n { + return 1 + } + key := tuple{i, cur, t} + if v, ok := f[key]; ok { + return v + } + v := 1 << (s[i] - 'a') + nxt := cur | v + var ans int + if bits.OnesCount(uint(nxt)) > k { + ans = dfs(i+1, v, t) + 1 + } else { + ans = dfs(i+1, nxt, t) + } + if t > 0 { + for j := 0; j < 26; j++ { + nxt = cur | (1 << j) + if bits.OnesCount(uint(nxt)) > k { + ans = max(ans, dfs(i+1, 1<, Integer> f = new HashMap<>(); - private String s; - private int k; - - public int maxPartitionsAfterOperations(String s, int k) { - this.s = s; - this.k = k; - return dfs(0, 0, 1); - } - - private int dfs(int i, int cur, int t) { - if (i >= s.length()) { - return 1; - } - var key = List.of(i, cur, t); - if (f.containsKey(key)) { - return f.get(key); - } - int v = 1 << (s.charAt(i) - 'a'); - int nxt = cur | v; - int ans = Integer.bitCount(nxt) > k ? dfs(i + 1, v, t) + 1 : dfs(i + 1, nxt, t); - if (t > 0) { - for (int j = 0; j < 26; ++j) { - nxt = cur | (1 << j); - if (Integer.bitCount(nxt) > k) { - ans = Math.max(ans, dfs(i + 1, 1 << j, 0) + 1); - } else { - ans = Math.max(ans, dfs(i + 1, nxt, 0)); - } - } - } - f.put(key, ans); - return ans; - } +class Solution { + private Map, Integer> f = new HashMap<>(); + private String s; + private int k; + + public int maxPartitionsAfterOperations(String s, int k) { + this.s = s; + this.k = k; + return dfs(0, 0, 1); + } + + private int dfs(int i, int cur, int t) { + if (i >= s.length()) { + return 1; + } + var key = List.of(i, cur, t); + if (f.containsKey(key)) { + return f.get(key); + } + int v = 1 << (s.charAt(i) - 'a'); + int nxt = cur | v; + int ans = Integer.bitCount(nxt) > k ? dfs(i + 1, v, t) + 1 : dfs(i + 1, nxt, t); + if (t > 0) { + for (int j = 0; j < 26; ++j) { + nxt = cur | (1 << j); + if (Integer.bitCount(nxt) > k) { + ans = Math.max(ans, dfs(i + 1, 1 << j, 0) + 1); + } else { + ans = Math.max(ans, dfs(i + 1, nxt, 0)); + } + } + } + f.put(key, ans); + return ans; + } } \ No newline at end of file diff --git a/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/Solution.py b/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/Solution.py index b5958e0542986..e9670c6cabcf5 100644 --- a/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/Solution.py +++ b/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/Solution.py @@ -1,23 +1,23 @@ -class Solution: - def maxPartitionsAfterOperations(self, s: str, k: int) -> int: - @cache - def dfs(i: int, cur: int, t: int) -> int: - if i >= n: - return 1 - v = 1 << (ord(s[i]) - ord("a")) - nxt = cur | v - if nxt.bit_count() > k: - ans = dfs(i + 1, v, t) + 1 - else: - ans = dfs(i + 1, nxt, t) - if t: - for j in range(26): - nxt = cur | (1 << j) - if nxt.bit_count() > k: - ans = max(ans, dfs(i + 1, 1 << j, 0) + 1) - else: - ans = max(ans, dfs(i + 1, nxt, 0)) - return ans - - n = len(s) - return dfs(0, 0, 1) +class Solution: + def maxPartitionsAfterOperations(self, s: str, k: int) -> int: + @cache + def dfs(i: int, cur: int, t: int) -> int: + if i >= n: + return 1 + v = 1 << (ord(s[i]) - ord("a")) + nxt = cur | v + if nxt.bit_count() > k: + ans = dfs(i + 1, v, t) + 1 + else: + ans = dfs(i + 1, nxt, t) + if t: + for j in range(26): + nxt = cur | (1 << j) + if nxt.bit_count() > k: + ans = max(ans, dfs(i + 1, 1 << j, 0) + 1) + else: + ans = max(ans, dfs(i + 1, nxt, 0)) + return ans + + n = len(s) + return dfs(0, 0, 1)